text:
Q: EF Core: include only instance of many-nav property public class Chat
{
    public string ChatID { get; set; }
    [Required]
    public ICollection<Message> Messages { get; set; }
}

public class Message
{
    public string MessageID { get; set; }
    public DateTime Time { get; set; }
    [Required]
    public Chat Chat { get; set; }
}

How can I load list of chats with included the latest (only) (ordered by Message.Time) message for ICollection<Message> Messages nav property per single request to DB? There is not Include with condition (chat.messages.last()) in EF Core

A: This works in EF6, not sure in EF Core
You can follow @CodeNotFound idea, modify it slightly and maybe still get a single roundtrip to the database, provided that you are only interested in chats that have messages
var chatInfos = db.Chats
    .Where(chat => ...) // filter chats if you need to
    .SelectMany(chat =>

        // INNER JOIN with Messages, ORDER by Time, SELECT TOP 1
        chat.Messages.OrderByDescending(m => m.Time).Take(1),

        // Explicitly load Chat, LastMessage and no more than that
        (chat, msg) => new
        {
            Chat = chat,
            LastMessage = msg
        })

     // Materialize!!
     // EF will fix-up Chat-Message navigation and will know that LastMessage is in the Chat's messages collection
    .ToList()

     // Sort again, you have the last message but not the chats ordered by last message
    .OrderByDescending(x => x.LastMessage.Time)

    // Now you have a list of chats, with last message, sorted by last message time
    .ToList();

foreach (var info in chatInfos)
{
    var chatEntry = db.Entry(info.Chat);
    var messageCollection = chatEntry.Collection(x => x.Messages);

    // Tell EF that the collection is loaded
    // Though the last query only loaded ONE Message entity via Explicit Loading
    messageCollection.IsLoaded = true;
}

// Get the chats, now calls to chat.Messages should not be lazy loaded for these and the collection should contain only one Message
var chats = chatInfos.ConvertAll(x => x.Chat);

I didn't test this code, but have similar code working on EF 6


text:
Q: Angular UI Bootstrap TypeAhead - How to force a user selection If a user enters a partial word that matches a typeAhead result, but doesn't select one of the popup options, how can I make it required that user actually select one of the popup options?
Example: If a possible result is called Penguin, and the user starts typing, p-e-n, and penguin pops up but they don't select the option for whatever reason, and the input field loses its focus; then the popup of options goes away, and the input field says, "pen" which would not have a key pair value.
How can I force a user to go back and continue typing in Penguin to select the option?

A: Add typeahead-editable="false" inside the input element. Then if user does not select any value partially typed values will be removed. In your example "pen" will be removed if user did not select the Penguin.
Eg.
<input type="text" typeahead-editable="false"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: DatabaseError: file is encrypted or is not a database I was trying to connect my .sql database with python version 2.7.9 with this code :
import sqlite3
db = sqlite3.connect("c:\\Users\\afsoon\\Desktop\\ch9learning\\sql\\genres.sql")
cursor = db.cursor()
query = """SELECT * FROM mytable where genre='folk'"""
lines = cursor.execute(query)
data = cursor.fetchall()
db.close()

but I catch this error :
lines = cursor.execute(query)
Traceback (most recent call last):

  File "<ipython-input-10-af02982f9f74>", line 1, in <module>
    lines = cursor.execute(query)

DatabaseError: file is encrypted or is not a database

I'm on windows and I've got sqlite3!
p.s: these are my database first lines
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Dec 23, 2015 at 09:29 AM
-- Server version: 10.1.9-MariaDB
-- PHP Version: 5.6.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `genres`
--
CREATE DATABASE IF NOT EXISTS `genres` DEFAULT CHARACTER SET utf8 COLLATE utf8_persian_ci;
USE `genres`;

-- --------------------------------------------------------

--
-- Table structure for table `mytable`
--

CREATE TABLE `mytable` (
  `genre` varchar(640) COLLATE utf8_persian_ci DEFAULT NULL,
  `track_id` varchar(50) COLLATE utf8_persian_ci DEFAULT NULL,
  `artist_name` varchar(248) COLLATE utf8_persian_ci DEFAULT NULL,
  `title` varchar(248) COLLATE utf8_persian_ci DEFAULT NULL,
  `keyy` decimal(13,10) DEFAULT NULL,
  `modee` decimal(13,10) DEFAULT NULL,
  `duration` decimal(14,10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci;

--
-- Dumping data for table `mytable`

A: You have to import your data into SQLite. Since your file is an export of MySQL there might be import problems and you might have to fix some line manually.
But basically you have to create a new SQLite database file and import your SQL. You need the sqlite3 binary for that. Run on the command line:
sqlite3 your_new_db.sqlite
sqlite> .read genres.sql


text:
Q: Hours aren't working on Stopwatch I'm making a stopwatch with seconds, minutes, and hours.  I want the stopwatch to reset and restart after the hours reach 59.  Also, when minutes reach 59 I want the hour hands to increment.  It doesn't seem to work.  The left hour "hand", if you will, won't increment.. even when I stated that I wanted it to.
PLEASE NOTE SPEED "5" ON SETTIMEOUT.  I SPED IT UP TO TEST HOURS.  SHOULD BE "1000".
HTML:

0

0

:

0

0

:

0

0

JS:
(function() {

    var secLesser = document.getElementById("sec-lesser").value,
    secGreater = document.getElementById("sec-greater").value,
    minLesser = document.getElementById("min-lesser").value,
    minGreater = document.getElementById("min-greater").value,
    hourLesser = document.getElementById("hour-lesser").value,
    hourGreater = document.getElementById("hour-greater").value;

    function stopWatch(){
        secLesser++;
        if(secLesser > 9) {
            secLesser = 0;
            secGreater++;
        } else if(secGreater + secLesser == 14){
            secGreater = 0;
            secLesser = 0;
            minLesser++;
        } else if(minLesser > 9){
            minLesser = 0;
            minGreater++;
        } else if(minGreater + minLesser == 14){
            secGreater = 0;
            secLesser = 0;
            hourLesser++;
        } else if(hourLesser > 9){
            hourLesser = 0;
            hourGreater++;
        } else if(hourGreater + hourLesser == 14){
            alert("It's been 59 hours... leave this page!");
        }

        document.getElementById("sec-lesser").textContent = secLesser;
        document.getElementById("sec-greater").textContent = secGreater;
        document.getElementById("min-lesser").textContent = minLesser;
        document.getElementById("min-greater").textContent = minGreater;
        document.getElementById("hour-lesser").textContent = hourLesser;
        document.getElementById("hour-greater").textContent = hourGreater;
        window.setTimeout(stopWatch, 5);
    }

    stopWatch();
})();

A: the part where you have
} else if(minGreater + minLesser == 14){
            secGreater = 0;
            secLesser = 0;
            hourLesser++;

should be resetting minGreater and minLesser not secGreater/secLesser. Change it to:
} else if(minGreater + minLesser == 14){
            minGreater = 0;
            minLesser = 0;
            hourLesser++;

Oh and look into requestAnimationFrame as better alternative to setTimeout/setInterval.


text:
Q: Roslyn CSharpSyntaxRewriter Get A List of Implemented Interfaces I have a CustomRewriter implementing CSharpSyntaxRewriter.  Within either the VisitClassDeclaration or VisitMethodDeclaration I need to check for ANY Interfaces that the class might implement.
The reason is that VisitMethodDeclaration is looking for methods that make data calls and is adding a parameter to the method.  This is working.  However, if modifies a method signature I need it to check if the Method altered comes from an implemented interface and if it does then modify the Interface as well.
I cannot figure out a way to get this information from Class & Method DeclarationNode parms nor the Syntax Tree or Syntax Nodes.  I also added Compilation as a Constructor Parm in an effort to use it to get the SchematicModel and somehow go from there, but without any luck.
public class DetermineIfInterfaceMethodRewriter : CSharpSyntaxRewriter
{
    private string Test = string.Empty;
    private Compilation comp;
    public DetermineIfInterfaceMethodRewriter(Compilation compilation)
    {
        this.comp = compilation;
    }
    public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        return base.VisitClassDeclaration(node);
    }
    public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
    {
        var tree = node.SyntaxTree;
        var root = tree.GetRoot();

        return node;
    }
}

A: You need to use the semantic model:

*

*Call GetDeclaredSymbol(classDeclarationSyntax) to get the ITypeSymbol for the class.

*Call AllInterfaces to get all of its implemented interfaces.

A: This information is available from the INamedTypedSymbol for the Class which can be obtained through the SemanticModel GetDeclaredSymbol Method.  Once you have the Symbol for the Class you can call AllInterfaces to get a collection of implemented interfaces.
    public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        var tree = node.SyntaxTree;
        var root = tree.GetRoot();
        var sModel = comp.GetSemanticModel(node.SyntaxTree);
        var classSymbol = sModel.GetDeclaredSymbol(root.DescendantNodes().OfType<ClassDeclarationSyntax>().First());

        var implementedInterfaces = classSymbol.AllInterfaces;

        return base.VisitClassDeclaration(node);
    }


text:
Q: z-index not working, image behind div I am trying to add a menu to css but its working image is falling back of the div. I think some css problem, tried a lot but not working, even z-index have no effect, I also tried to attached a image but reputation problem, images explain a lot. Anyway, the question may sound simple, but don't know why its not working, M using firefox 19.
The css
ul.gelbuttonmenu{
    position:relative;
    padding: 0;
    margin: 0;
    margin-bottom:1em;
    text-align: center; /*set value to "left", "center", or "right"*/
    }

ul.gelbuttonmenu li{
    display: inline;
    z-index:10;
    }

ul.gelbuttonmenu li a{
    color: black;
    font-weight:bold;
    padding: 10px; /*make sure padding is sufficient that the height of the link is enough to fully show the gel button*/
    margin-right: 20px; /*spacing between each menu link*/
    text-decoration: none;
    z-index:10;
    }

ul.gelbuttonmenu li.active{ /*style of LI that gets dynamically added to menu to create background effect*/
    position:absolute;
    width:0;
    background:lightblue;
    z-index:10;
    background:url(gelbuttonleft.gif) top left no-repeat, url(gelbuttonright.gif) top right no-repeat, url(gelbuttoncenter.gif) top center repeat-x;
    }
body{}
            .head{height:50px}
            .foot{height:90px}

            .wrap{width:80%;margin-left: 10%;background-color: #74e0ea;
            text-align: center;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
            -webkit-box-shadow: #666 0px 2px 50px;
            -moz-box-shadow: #666 0px 2px 50px;
            box-shadow: #666 0px 2px 50px;
            background: #74E0EA;
            background: -webkit-gradient(linear, 0 0, 0 bottom, from(#74E0EA), to(#CCF1F5));
            background: -webkit-linear-gradient(#74E0EA, #CCF1F5);
            background: -moz-linear-gradient(#74E0EA, #CCF1F5);
            background: -ms-linear-gradient(#74E0EA, #CCF1F5);
            background: -o-linear-gradient(#74E0EA, #CCF1F5);
            background: linear-gradient(#74E0EA, #CCF1F5);
            }

The HTML

Home

CSS Codes

Forums

Tools

JavaScript

CSS Gallery

Thanks and regards

A: You can use the simple css menu with the below code:

  ul {list-style: none;padding: 0px;margin: 0px;}
  ul li {display: block;position: relative;float: left;border:1px solid #000}
  li ul {display: none;}
  ul li a {display: block;background: #000;padding: 5px 10px 5px 10px;text-decoration: none;
           white-space: nowrap;color: #fff;}
  ul li a:hover {background: #f00;}
  li:hover ul {display: block; position: absolute;}
  li:hover li {float: none;}
  li:hover a {background: #f00;}
  li:hover li a:hover {background: #000;}
  #drop-nav li ul li {border-top: 0px;}

Support

Web Design

HTML

CSS

JavaScript

Content Management

Joomla

Drupal

WordPress

Concrete 5

Contact

General Inquiries

Ask me a Question


text:
Q: Map latitude and longitude to state in SAS I have about 100,000 latitude and longitude pairs (to 4 decimals) and I would like to assign each pair to a US state.  Does anyone know how to do this in SAS?  Is it possible to import shapefiles into SAS for this task?

A: Note: the following answer assumes you have a license for SAS Graph and the Maps library is properly set up on your installation. This will not work on SAS University Edition. If you need to download the MAPS files they are here: http://support.sas.com/rnd/datavisualization/mapsonline/index.html
You don't need to import the SHP file for the US, SAS already has these built in. You can use PROC GINSIDE to determine what state and/or county the points are located.
An example is located here:
https://support.sas.com/documentation/cdl/en/grmapref/69722/HTML/default/viewer.htm#p0qjcc8hugcjb2n1x3bmuaar16f0.htm
And copied here, for SO rules.
goptions reset=global border;
data gpscounties;
  input longitude latitude site $;
  x=longitude*arcos(-1)/180;
  x=x*(-1);
  y=latitude*arcos(-1)/180;
datalines;
-77.0348 40.0454 a
-78.4437 39.1623 b
-78.4115 39.3751 c
-78.7646 40.6354 d
;
run;
proc ginside data=gpscounties map=mapssas.counties out=gpscounties;
  id state county;
run;
proc sort data=gpscounties;
  by site;
run;

proc print data=gpscounties;
  var site state county x y;
run;
quit;


text:
Q: Data manipulation for heatmap I have a dataset that has 15 minute interval data. What I need to do is group the data by day/hour, averaging the 4 (15 min intervals) for each hour.
For example, take the 6:00, 6:15, 6:30, 6:45 values and average them to make one 6 AM value.
I'm looking for a general strategy on how to approach this and/or examples that may be me get on the right track (using JS, and/or lodash, moment)
[
{date:"2019-07-02T06:00:00.000Z",value:1271.22}
{date:"2019-07-02T06:15:00.000Z",value:1771.41},
{date:"2019-07-02T06:30:00.000Z",value:1780.83},
{date:"2019-07-02T06:45:00.000Z",value:1788.13},
{date:"2019-07-02T07:00:00.000Z",value:1805.31},
{date:"2019-07-02T07:15:00.000Z",value:1781.83},
{date:"2019-07-02T07:30:00.000Z",value:1764.17},
{date:"2019-07-02T07:45:00.000Z",value:1721.44},
{date:"2019-07-02T08:00:00.000Z",value:1712.92},
{date:"2019-07-02T08:15:00.000Z",value:1764.63},
{date:"2019-07-02T08:30:00.000Z",value:1759.03},
{date:"2019-07-02T08:45:00.000Z",value:1754.27},
{date:"2019-07-02T09:00:00.000Z",value:1745.81}
....
]

example data set here:
Full example dataset here
yAxis will be [
'Saturday',
'Friday',
'Thursday',
'Wednesday',
'Tuesday',
'Monday',
'Sunday'
]
yAxis labels will be the times of day: (12 AM, 1 AM, 2 AM, 3 AM, etc)
like this:
[img]https://i.stack.imgur.com/zk7jf.jpg[/img]
final data structure should look like this. This is broken down by hour (the average of the four points listed above), day of week, and value
[
[1, 6, 553],
[2, 6, 777],
[3, 6, 654],
[4, 6, 613],
[5, 6, 551],
[6, 6, 668],
[7, 6, 647],
[8, 6, 725],
[9, 6, 703],
[10, 6, 661],
[11, 6, 745],
[12, 6, 670],
[13, 6, 770],
[14, 6, 763],
[15, 6, 705],
[16, 6, 713],
[17, 6, 693],
[18, 6, 724],
[19, 6, 724],
[20, 6, 701],
[21, 6, 710],
[22, 6, 656]
....]

The last value is the average of the hour of that day. For example,
{date:"2019-07-02T06:00:00.000Z",value:1271.22} {date:"2019-07-02T06:15:00.000Z",value:1771.41}, {date:"2019-07-02T06:30:00.000Z",value:1780.83}, {date:"2019-07-02T06:45:00.000Z",value:1788.13}

On July 2nd, the 6AM average value would equal the average of the 4 values above
So for the entry in the final data structure it would be something like:
[hour of day, day of week, the average of the four intervals within that hour]

A: For approaching it first what we need to do is to groupBy the period of time it means Day-Hour, we do it with the following code->
let byHour = {};

const groups = (() => {
const byDay = (item) => moment(item.date).format('MMM DD YYYY'),
    forHour = (item) => moment(item.date).format('MM/DD/YYYY HH:ss');
return {
    byDay,
    forHour
};
})();
const currentGroup = 'forHour';
let obj = _.groupBy(values, groups[currentGroup]);
let valuesGrouped = Object.values(obj)

For doing it we need moment and Lodash, what we do is we format the dates incoming and group them by Day-hour, we make them as keys, after we group them what we want is their values, once we have the values, format it as []
 let answerArr = valuesGrouped.map((a,i,arr)=>{

 return [moment(a[0].date).format('hh a'),moment(a[0].date).format('DD'),a.reduce((x, y) => parseInt(x) + parseInt(y.value),0) / a.length]
 })
 console.log(answerArr)

PS: Rembember that you are using ISO8601 as format once you format wich moment you will format it to your local timeZone.
Offtopic
In my case when I formatted it it started since june 30 22:00
CodePen link

A: You can also try to use this logic to achieve wanted output:
let finalOutput = [],
        curOutput = 0,
        startDay = 1,
        startHour = 4;

values.forEach((v, i) => {
    curOutput += v.value;
    i = i + 1;
    if (i % 4 === 0) {
        console.log(i)
        finalOutput.push([startHour, startDay, curOutput / 4])
        startHour += 1;
        curOutput = 0;

        if (startHour === 24) {
            startDay += 1;
            startHour = 0;
        }
    }
})

console.log(finalOutput)

Demo: https://jsfiddle.net/BlackLabel/ut1yzx6s/


text:
Q: glxinfo shows different versions in the same machine on different runs I am trying to get my OpenGL version. Most of the time, I am shown OpenGL Core Profile is 3.3 but sometimes it shows 4.3. Any idea why it would happen? Also, how to fix permanently to 4.3?
soham@soham-machine:~$ glxinfo | grep version
server glx version string: 1.4
client glx version string: 1.4
GLX version: 1.4
    Max core profile version: 4.3
    Max compat profile version: 3.0
    Max GLES1 profile version: 1.1
    Max GLES[23] profile version: 3.1
OpenGL core profile version string: 4.3 (Core Profile) Mesa 18.0.5
OpenGL core profile shading language version string: 4.30
OpenGL version string: 3.0 Mesa 18.0.5
OpenGL shading language version string: 1.30
OpenGL ES profile version string: OpenGL ES 3.1 Mesa 18.0.5
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.10

soham@soham-machine:~$ glxinfo | grep version
server glx version string: 1.4
client glx version string: 1.4
GLX version: 1.4
    Max core profile version: 3.3
    Max compat profile version: 3.0
    Max GLES1 profile version: 1.1
    Max GLES[23] profile version: 3.1
OpenGL core profile version string: 3.3 (Core Profile) Mesa 18.0.5
OpenGL core profile shading language version string: 3.30
OpenGL version string: 3.0 Mesa 18.0.5
OpenGL shading language version string: 1.30
OpenGL ES profile version string: OpenGL ES 3.0 Mesa 18.0.5
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.00

My machine is the following:
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.7 LTS
Release:    16.04
Codename:   xenial

The Graphics is Intel integrated graphics:
OpenGL vendor string: Intel Open Source Technology Center
OpenGL renderer string: Mesa DRI Intel(R) Haswell Mobile

A: I had to update my kernel version to 4.15 to fix the problem:
sudo apt-get install --install-recommends linux-generic-hwe-16.04

After this, I restarted the system, now I have OpenGL 4.5:
server glx version string: 1.4
client glx version string: 1.4
GLX version: 1.4
    Max core profile version: 4.5
    Max compat profile version: 3.0
    Max GLES1 profile version: 1.1
    Max GLES[23] profile version: 3.1
OpenGL core profile version string: 4.5 (Core Profile) Mesa 18.0.5
OpenGL core profile shading language version string: 4.50
OpenGL version string: 3.0 Mesa 18.0.5
OpenGL shading language version string: 1.30
OpenGL ES profile version string: OpenGL ES 3.1 Mesa 18.0.5
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.10


text:
Q: CanCan, setting up a nested resource? I have the following models:
Group (id)
Poll (id, group_id)
PollVote (id, poll_id)

I don't want to do deep nesting, meaning I don't want /group/:id/poll/:id/poll_vote/:id
I want to set it up so my routes:
/group/:id
/poll/:id
/poll/:id/poll_vote/:poll_vote_id

I have poll working, but I can't figure out how to get PollVote working... So far I have:
class PollVotesController < ApplicationController

  # Authorization w Devise & CanCan
  before_filter :authenticate_user! # Devise, signed in users only
  load_and_authorize_resource :poll # CanCan
  load_and_authorize_resource :poll_vote, :through => :poll

  # We need to pass along the wall
    def current_ability
        @current_ability ||= Ability.new(current_user, @poll.group_id)
    end

Then in ability.rb
can [:manage], Poll do |poll|
    This returns TRUE is the user is a group member of the poll
end

What do I use in PollVotes, to have PollVotes check CanCan using Poll?
Thanks

A: You haven't shown your User <-> Group association, so if User has_and_belongs_to_many :groups then:
can :manage, [ Poll ] { |poll| user.groups.include?(poll.group) }

Of course, you probably want to lock that down to only votes associated with the user.
Edit - here are examples for restricting access to creating and editing poll votes:
can :read, PollVote # not needed if you have e.g. can :read, :all
can :create, [ PollVote ] { |poll_vote| user.groups.include?(poll_vote.poll.group) }
can [ :edit, :destroy ], [ PollVote ] { |poll_vote| poll_vote.user_id == user.id }


text:
Q: How to restore changes from commit in git? I know there are tons of questions like this, but none solution worked out for me. Here is what happened:
I tried to add a new feature in my app, so I created a new branch to implement this feature.
After I was done I merged it to master, deleted the branch that I tested the new feature and pushed the changes to the repository (bitbucket btw).
The code was normal.
Then I needed to add other feature tho.
I then created a new branch again, but now I tested this other new feature in master, and let the other branch with the "right" code.
The new feature didn't work, so I tried going to the other branch and merging it to master, to delete the changes I made, it gave me a merge conflict tho, I tried everything, but I just wasn't able to do it.
I than switched back to master and deleted the branch with the right code.
I was with the wrong code in master.
I hadn't pushed the changes yet, only commited, so I tried searching on how to fix this, none worked.
I then ran this command: git checkout NUMBER OF THE COMMIT
I checked the last pushed commit, which had the right code.
My project changed to the right code, and I thought everything was ok, I thought it restored the changes.
I ran git status and that was the output:
HEAD detached at f49fb28
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)

modified:   .DS_Store
modified:   Homework.xcworkspace/xcuserdata/Henrique.xcuserdatad/UserInterfaceState.xcuserstate

no changes added to commit (use "git add" and/or "git commit -a")

I then ran git add -A along with git commit -m "some message" and pushed it to the repo thinking that the code would get there fixed. It didn't tho, now my repo AND project has the same code, the wrong code. Is it possible that I checkout the commit I made with the RIGHT feature, not the wrong one and my code restores to this exact commit? If not, my only salvation will be to redo everything.
PLEASE HELP ME!
EDIT: I RAN git status AND THE OUTPUT WAS DIFFERENT NOW:
HEAD detached from f49fb28
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)

modified:   Homework.xcworkspace/xcuserdata/Henrique.xcuserdatad/UserInterfaceState.xcuserstate

no changes added to commit (use "git add" and/or "git commit -a")

A:
Is it possible that I checkout the commit I made with the RIGHT feature

First of all read the attached full answer in the comments.
To summary what you can now is simply use the git reflog to checkout the desired commit.
Here is how a reflog will look like:


text:
Q: How to redirect to parent virtual directory for Razor Pages? I have a web application which consists from two parts the first is in an IIS virtual directory MainFolder the second is in a virtual directory MainFolder/RazorFolder. The second application is .Net Core Web Application with Razor Pages. I have a page MainFolder/Default.aspx and a page MainFolder/RazorFolder/MyRazorPage.
When I go to from default.aspx to MyRazorPage I use
Response.Redirect("RazorFolder/MyRazorPage")

However I do not know how to get back. The only working way is (in an action method)
return Redirect("http://localhost/MainFolder/Default.aspx");

which is valid in my testing environment only.
Other attempts:
return Redirect("~/Default.aspx");

redirects to http://localhost/MainFolder/RazorFolder/Default.aspx
Url.Content("~/Default.aspx")

returns "/MainFolder/RazorFolder/Default.aspx"
Hopefull (see ResolveUrl/ResolveClientUrl equivalents for Asp.Net Razor?
)
@Href("../default.aspx")

returns "../default.aspx"
So I either need to be able to redirect to parent virtual directory or get full page URL to parse it. Or should I smuggle (with a shame) the return address from the webforms application?

A: It seems that there is no method which allows to use double dot (/..) syntax. So it is necessary to get absolute URL, parse it, remove unwanted part and build it again.
Methods allowing to complete the task are in Microsoft.AspNetCore.Http.Extensions nuget.

*

*Full URL: Request..GetDisplayUrl()

*Parse it: UriHelper.FromAbsolute

*Build again processed URL UriHelper.BuildAbsolute
So the complete extension method (be aware that the parameter parentRelativeUri has to start with '/'):
public static string GetParentUri(this HttpRequest request, string parentRelativeUri)
{
    string scheme;
    HostString host;
    PathString path;
    QueryString query;
    FragmentString fragment;

    UriHelper.FromAbsolute(request.GetDisplayUrl(), out scheme, out host, out path, out query, out fragment);

    var pathBase = request.PathBase.ToString();

    return UriHelper.BuildAbsolute(scheme, host,
        pathBase.Substring(0, pathBase.LastIndexOf("/")),
        parentRelativeUri);
}

And finally the redirection to parent is:
return Redirect(Request.GetParentUri("/Default.aspx"));


text:
Q: ROracle error ORA-12592 when insert a lot of rows When i use dbWriteTable for dataframe with millions rows sometimes get ORA-12592 error.
With small dataframe - all works fine.
Is there way to customize dbWriteTable for commit every X rows? Or other way to minimaze error?
option bulk_write = 1000L change nothing
Version:

ROracle_1.3-1
DBI_1.0.0


text:
Q: Make prettier less uglier - prevent split tags Prettier in VS Code is great, except in this case where it seems to make things less readable. Here's an example of prettier's wrapping behavior in a Vue template file:

Notice the opening tag's end bracket is placed as start of second line, and closing tag is split between end of line 2 and 3. In my mind, this is more pretty:

Now the tags are complete on their own lines and the content is alone on line 2.
I've been unable to find a way to configure this in the prettier docs. Any ninjas know how?

A: Try to set htmlWhitespaceSensitivity property to ignore in your prettier config.

A: I agree your opinion. This Linter rule will help you.
eslint-plugin-vue/html-closing-bracket-newline.md at master · vuejs/eslint-plugin-vue
I setting up rules in .eslintrc.js below.
"vue/html-closing-bracket-newline": [2, { multiline: "never" }]

and I setting up .vscode/setting.json below
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.formatOnSave": false
  },
  "[vue]": {
    "editor.formatOnSave": false
  }
}


text:
Q: Odd crash in Xamarin.iOS after dismissing keyboard So I'm building an MVVM app in Xamarin. I'm working on the iOS view for a certain viewmodel right now, and the view contains a few RadioGroups to select items from lists, as well as some EntryElements to take text data from the keyboard. Now it works when you select items from lists, and then enter keyboard data. However, if you enter the keyboard data first, and then try to select items from the RadioGroup, I get a crash in Main.cs at this line:
UIApplication.Main(args, null, "AppDelegate");
Here's the error description:
MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown.  Name: NSInvalidArgumentException Reason: -[__NSCFString setRestorableResponder:]: unrecognized selector sent to instance 0x16744d90
  at at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
  at MonoTouch.UIKit.UIApplication.Main (System.String[] args, IntPtr principal, IntPtr delegate) [0x00005] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:62
  at MonoTouch.UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0001c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:45
  at GreenRideGlobalMeterReading.iOS.Application.Main (System.String[] args) [0x00008] in /Users/developers/Desktop/GreenRideGlobalMeterReading/GreenRideGlobalMeterReading.iOS/Main.cs:17
I can't figure out what the hell is causing this - some weird MvvmCross or MonoTouch related framework error? Anyone else encountered this before or have an idea of how to fix it?

A: It looks like you are forgetting to call the "ResignFirstResponder" of the keyboard. If the keyboard is up, and you try to click an element in another control, you need to first dismiss the keyboard using the:
textBox.ResignFirstResponder();

You can also add a delegate when initiating the textBox like this:
tbDescription = new UITextField ();
tbDescription.Placeholder = "Description...";
tbDescription.ReturnKeyType = UIReturnKeyType.Done;
tbDescription.ShouldReturn += (textField) =>
{
    tbDescription.ResignFirstResponder ();
    return true;
};

Try that out. I hope it helps. Good luck!


text:
Q: Howto hide a Listings or Verbatim environment using a \newif enable command Due to make life easier I want to create a Exercise sheet for a lecture including the corresponding solutions. Therefore I defined a \newif to control whether the solution should be included or not. That worked fine until I need a lstlisting or a verbatim environment in it.  The following code is the minimal example for the error, it works with verbatim too.
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\newif\ifsolution
\solutionfalse

\ifsolution
\newcommand{\solution}[1]{#1}
\else
\newcommand{\solution}[1]{}
\fi

\begin{document}
This is always shown.
\solution{The listing is only shown if ifsolution is true.
\begin{lstlisting}
 Test
\end{lstlisting}
}
\end{document}

Setting solution to true produces the error. How can I defined a command or an environment with this function?

A: My first assessment was wrong, but like Gonzalo kindly noted

verbatim material cannot appear in the argument of standard commands

A solution that does work is, not using any arguments:
\ifsolution
\def\solution{\relax}
\else
\newcommand{\solution}[1]{}
\fi

But you can also use the comment package. It provides the ability to easily define a certain environment as comment.
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\usepackage{comment}
\excludecomment{solution}
%\includecomment{solution}

\begin{document}
This is always shown.
\begin{solution}
    The listing is only shown if ifsolution is true.
\begin{lstlisting}
 Test
\end{lstlisting}
\end{solution}

\end{document}

With \excludecomment{solution} the solutions won't be shown and when you write \includecomment{solution} instead, they will be shown.


text:
Q: Python multiprocessing start more processes than cores Say I start 10 process in a loop using Process() but I only have 8 cores available. How does python handle this?

A: While best practice is to use as many threads as you have virtual cores available, you don't have to stick to that. Using less means you could be under-utilizing your available processor capacity. Using more means you'll be over-utilizing your available processor capacity.
Both these situations mean you'll be doing work at a slower rate than would otherwise be possible. (Though using more threads than you have cores has less of an impact than using fewer threads than your have cores.)


text:
Q: How to dynamically add the rows in the MUI for user to edit and add? Here is my example, where I am reading the values i.e. normRules and then applying it to dynamically generate the rows. However, I want the user to be able to add a new row and
edit the values when the add button is pressed. In the add submit click, I am simply appending the array with an empty object. However, I see that it simply adding an empty object i.e. a blank row. How can I add a row that a user is mandated to add the values in that row when a user clicks the add button? Here is my sandbox.
https://codesandbox.io/s/react-mui-forked-c8hf16?file=/Test.js


text:
Q: Spearman correlation between two matrices of same dimensions I have two matrices of equal dimensions (p and e) and I would like to make a spearman correlation between columns of the same name. I want to have the output of pair correlations in a matrix (M)
I used the corr.test() function from library Psych and here is what I did:
library(psych)
M <- data.frame(matrix(ncol=3,nrow=ncol(p)))
M[,1] <- as.character()
G <- colnames(p)
for(rs in 1:ncol(p){
      M[rs,1] <- G[rs]
      cor <- corr.test(p[,rs],e[,rs],method="spearman",adjust="none")
      M[rs,2] <- cor$r
      M[rs,3] <- cor$p
}

But I get an error message:
Error in 1:ncol(y) : argument of length 0

Could you please show me what is wrong? or suggest another method?

A: No need for all this looping and indexing etc:
# test data
p <- matrix(data = rnorm(100),nrow = 10)
e <- matrix(data = rnorm(100),nrow = 10)

cor <- corr.test(p, e, method="spearman", adjust="none")
data.frame(name=colnames(p), r=diag(cor$r), p=diag(cor$p))

#  name           r         p
#a    a  0.36969697 0.2930501
#b    b  0.16363636 0.6514773
#c    c -0.15151515 0.6760652
# etc etc

If the names of the matrices don't already match, then match them:
cor <- corr.test(p, e[,match(colnames(p),colnames(e))], method="spearman", adjust="none")

A: Since the two matrices are huge, it would take very long system.time to execute the function corr.test() on all possible pairs but the loop that finally worked is as follow:
    library(psych)
    M <- data.frame(matrix(ncol=3,nrow=ncol(p)))
    M[,1] <- as.character()
    G <- colnames(p)
    for(rs in 1:ncol(p){
          M[rs,1] <- G[rs]
          cor <- corr.test(as.data.frame(p[,rs]),as.data.frame(e[,rs]),
method="spearman",adjust="none")
          M[rs,2] <- cor$r
          M[rs,3] <- cor$p
    }


text:
Q: Datatable - How to search and export data only when the search is not null This is the approach I have tried so far:
$("#ExportPDF").on("click", function() {
    var datatable = $('#myTable').DataTable();
    if (! datatable.data().any()) {
        console.log( 'the table is actually empty' );
    }
    else{
        var table = $('#myTable').DataTable().search('something');
        table.button( '.buttons-pdf' ).trigger();
    }
});

When my table is empty, it does not export anything, which is perfect for me.
Now when the table contains elements, I do a search on a keyword something; if items are found they export them. But when no information is found it still exports an empty PDF.
How to avoid exporting an empty PDF?

A: Check the returned array before triggering the button :
else {
  var table = $('#myTable').DataTable().search('something');
  if( table != "" ){
    table.button('.buttons-pdf').trigger();
  }
}

A: $('#tableid').dataTable({
    "fnDrawCallback": function () {
        var table = $('#tableid').DataTable();
        if (table.data().length === 0)
            table.buttons('.buttons-html5').attr('disabled', true);
        else
            table.buttons('.buttons-html5').attr('disabled', false);

    }
});


text:
Q: Elasticsearch helm chart gives AccessDenied exception It is a common issue still seems unresolved:
ElasticsearchException[failed to bind service]; nested: AccessDeniedException[/usr/share/elasticsearch/data/nodes];
Likely root cause: java.nio.file.AccessDeniedException: /usr/share/elasticsearch/data/nodes

I am trying to run it on a cluster setup by RKE. I started to use it in an outofabox manner, means only using it as a dependency :
dependencies:
  - name: elasticsearch
    version: 7.6.2
    repository: https://helm.elastic.co

It just fails right away.
I am aware and have followed the corresponding github issues like:
https://github.com/elastic/helm-charts/issues/429
https://github.com/elastic/helm-charts/issues/137
https://github.com/elastic/helm-charts/issues/388
https://github.com/elastic/helm-charts/issues/258
I have also tried to cmod-ing it by hand in 'initresources' , I have played with fsgroup, and I have also tried to use Rancher Local Path Provisioner(menioned in issue 429).
No success at all ,same exception comes every time.
Any idea?

A: Pasting here the answer I gave at https://github.com/elastic/helm-charts/issues/258
Basically, I've fixed this issue by grabbing the values.yaml from the helm chart and adding a securityContext. The configure-sysctl initContainer that comes with the chart itself does this (privileged + runAsUser):
extraInitContainers:
   - name: file-permissions
     image: busybox
     command: ['chown', '-R', '1000:1000', '/usr/share/elasticsearch/']
     volumeMounts:
     - mountPath: /usr/share/elasticsearch/data
       name: elasticsearch-master
     securityContext:
       privileged: true
       runAsUser: 0


text:
Q: How to pass header in Axios post request Here is my code:
const data = {
      listing: listing,

    };

    await axios.post('https://app.jghfjgf.com/m/api/helper/helper', qs.stringify(data) ,{
      headers:{
        'Cookie':cookie,
        'content-type': 'application/x-www-form-urlencoded'
      }}
    ).then(response =>{
      console.log(response);
      alert(response.data);
    }).catch(error => {
      console.log(error);
      alert(error);
    });

I am trying to make HTTP request using Axios library and I tried most of the suggestions available on the web. I don't know what mistake I am doing. I am new to React Native application so don't have enough practice with Axios.
Note: The issue is value "cookie" in header is not passing along with the API so I am facing error.


text:
Q: Is it free to create an Ubuntu One Account? I just created an Ubuntu One account, but I am unsure; is the account ITSELF free?

A: Refer to the Fees and payment section of the Ubuntu One TOS at https://login.ubuntu.com/terms/#fees-and-payment:

The Ubuntu One services consist of a free and paid subscriptions. An
  Ubuntu One subscription is required for all services and a valid
  credit card is required for paid subscriptions.

You have a free subscription. Without providing a credit card, you can't get a paid subscription.

If you purchase content or applications from us, payment for content
  or applications is due at the time you purchase the content or
  application. You will be asked to enter your credit card number and we
  will charge your credit card at the time of purchase.

You'll know if you get charged since payment won't happen silently.

A: The Ubuntu One account itself is free.
I have retained an Ubuntu One account since 2013, without a credit card attached, as well as without a charge.
Ubuntu One has a number of free services that I use (haven't explored their pay services).
The ones that I use are for web authentication, such as provided by many social sites such as Facebook, Google, Launchpad, and a few others.
While I prefer not to use social sites for login authentications, but the actual site that I'm logging into, I do use it for some sites such as:

*

*ubuntuforums.org

*launchpad.net

*pastebin.ubuntu.com

... and a few others.
An Ubuntu One account is a requirement for logging into the official Ubuntu Web forum. (Note: Askubuntu.com is presented by http://www.ubuntu.com as one of their official support sites.)
You can explore many of the services both free and paid services by visiting http://www.ubuntu.com and clicking on one of the menu links included in the first to line header of the site.  Some of the link names include:

*

*Design

*Hardware

*Partners

*Shop

*cloud

*Server

... and more.
Your account itself is free.  You would only pay for something that you explicitly order as a paid product or service.


text:
Q: Pass Property to User Defined Function Trying to read up on feeding arguments to a function in VBA (just started looking at VBA), and cannot find any examples that help me understand the specific scenario I want.
I have a function:
Public Function myFunction()
  With ActiveSheet.Shapes.Range(Array("Chart1", "Chart2", "Chart3""))
    .Visible = Not .Visible
  End With
End Function

Which I then call like this:
Sub myMacro()
  trigger = myFunction()
End Sub

What I want to do instead of having ".visible" and "Not .visible" properties passed to my function from my Sub. For example if I have multiple functions:
Public Function myFunction1(visibility)
  With ActiveSheet.Shapes.Range(Array("Chart1", "Chart2", "Chart3""))
    .Visible = visibility
  End With
End Function

Public Function myFunction2(visibility)
  With ActiveSheet.Shapes.Range(Array("Chart4", "Chart5", "Chart6""))
    .Visible = visibility
  End With
End Function

Sub myMacro1()
  Dim showit
  showit = .Visible
  Dim hideit
  hideit = Not .Visible

 showCharts = myFunction1(showit)
 HideCharts = myFunction2(hideit)
End Sub

Sub myMacro2()
  Dim showit
  showit = .Visible
  Dim hideit
  hideit = Not .Visible

 showCharts = myFunction1(hideit)
 HideCharts = myFunction2(showit)
End Sub

How do I achieve this? If I wrap "showit" and "hideit" values in quotation marks, it will be passed with the quotation marks. If I do like above and don't have quotation marks, it does not pass it at all
Update: I made it work with the "As Variant" declaration and the information about using True and False suggested by @Viktor. Solution posted below.

A: I see your problem. I hope this solution is flexible enough to use.
In myMacro you can put the names of the charts following by their required visibility (true or false).
The function SetVisibility try to set the visibility. If it fails, returns false, that can be used for displaying a message.
Sub myMacro()
    If Not SetVisibility("Chart1", False) Then MsgBox "Setting visibility failed"
    If Not SetVisibility("Chart2", False) Then MsgBox "Setting visibility failed"
    If Not SetVisibility("Chart3", False) Then MsgBox "Setting visibility failed"
    If Not SetVisibility("Chart4", False) Then MsgBox "Setting visibility failed"
End Sub

Function SetVisibility(psShapeName As String, pbVisibility As Boolean) As Boolean
    SetVisibility = True
    On Error GoTo errHandler
        ActiveSheet.Shapes(psShapeName).Visible = pbVisibility
    Exit Function
errHandler:
    SetVisibility = False
End Function

A: Update: I made it work with the "As Variant" declaration and the information about using True and False suggested by @Viktor
Public Function myFunction1(visibility As Variant)
  With ActiveSheet.Shapes.Range(Array("Chart1", "Chart2", "Chart3"))
    .Visible = visibility
  End With
End Function

Public Function myFunction2(visibility As Variant)
  With ActiveSheet.Shapes.Range(Array("Chart4", "Chart5", "Chart6"))
    .Visible = visibility
  End With
End Function

Sub myMacro1()
  Dim showit
  showit = True
  Dim hideit
  hideit = False

  showCharts = myFunction1(showit)
  hideCharts = myFunction2(hideit)
End Sub

Sub myMacro2()
  Dim showit
  showit = True
  Dim hideit
  hideit = False

  showCharts = myFunction2(showit)
  hideCharts = myFunction1(hideit)
End Sub

Not sure this is the best way of doing it, but it works fine!
As I will have even more sets of charts I want to show/hide, I can just create a function for the different sets, and add a "hide" for all of the ones that are not the ones that should be shows (so each sub will call one "show" function, and pass "hide" to all the rest). Simple enough for readability.


text:
Q: Refreshing a post via the "change" notice causes the question notice to disappear I noticed a minor bug today. If a question has a post notice, that notice disappears if any of the answers (or the question itself) are refreshed. By "refreshed" I mean by clicking on the little gray bar at the top of the post that says something like "this post has changed... click this to refresh it".
Here is sample post, with the notice:

And this is what happened when I refreshed the answer post:

I noticed this on MSO just shortly prior; I also noticed this behavior on SO with a question close notice (not 100% sure on the latter though).
I should add that the notice disappearing is temporary. It comes back when the entire page is reloaded (e.g., pressing F5).


text:
Q: How to elegantly check if a dictionary has a given structure?
I have a dictionary with the following structure:
D = {
   'rows': 11,
   'cols': 13,
   (i, j): {
              'meta': 'random string',
              'walls': {
                  'E': True,
                  'O': False,
                  'N': True,
                  'S': True
              }
           }
}
# i ranging in {0 .. D['rows']-1}
# j ranging in {0 .. D['cols']-1}

I want to write a function that takes an arbitrary object as argument and checks if it has that structure. This is what I wrote:
def well_formed(L):
    if type(L) != dict:
        return False
    if 'rows' not in L:
        return False
    if 'cols' not in L:
        return False

    nr, nc = L['rows'], L['cols']

    # I should also check the int-ness of nr and nc ...

    if len(L) != nr*nc + 2:
        return False

    for i in range(nr):
        for j in range(nc):
            if not ((i, j) in L
                and 'meta' in L[i, j]
                and  'walls' in L[i, j]
                and type(L[i, j]['meta']) == str
                and type(L[i, j]['walls'])  == dict
                and     'E' in L[i, j]['walls']
                and     'N' in L[i, j]['walls']
                and     'O' in L[i, j]['walls']
                and     'S' in L[i, j]['walls']
                and type(L[i, j]['walls']['E']) == bool
                and type(L[i, j]['walls']['N']) == bool
                and type(L[i, j]['walls']['O']) == bool
                and type(L[i, j]['walls']['S']) == bool):
                return False

    return True

Although it works, I don't like it at all. Is there a Pythonic way to do it?
I'm allowed to use just the standard library.

A: In Python, the exact identity of the types involved is less important than how the values behave. For a defined use of such an object, would the object suffice? This means L doesn't have to be a dict, it just has support __getitem__; L[(i,j)]['meta'] doesn't have to be a str, it just has to support conversion to a string via str(L[(i,j)]['meta']); etc.
Given that relaxation, I would simply try to catch any errors raised by attempting such actions, and return False if any occur. For example,
def well_formed(L):
    try:
        nr = L['rows']
        nc = L['cols']
    except KeyError:
        return False

    try:
        for i in range(nr):
            for j in range(nc):
                str(L[(i,j)]['meta'])
                walls = L[(i,j)]['walls']
                for direction in walls:
                    # Necessary?
                    if direction not in "ENOS":
                        return False
                    if walls[direction] not in (True, False):
                        return False
    except KeyError:
        return False

    return True

Given that any object has a boolean value, it seemed pointless to attempt bool(walls[direction]); rather, if having exactly True or False as a value isn't a hard requirement, I would just any test of the value altogether. Likewise, additional walls may or may not be an issue, and don't have to be explicitly tested for.

A: You can compose validation like this (idea from Scala extractors). The advantage is that the validator structure is similar to the structure to test.
A disadvantage is that the many function calls may make it much slower.
class Mapping:
    def __init__(self, **kwargs):
        self.key_values = [KeyValue(k, v) for k, v in kwargs.items()]

    def validate(self, to_validate):
        if not isinstance(to_validate, dict):
            return False

        for validator in self.key_values:
            if not validator.validate(to_validate):
                return False
        return True

class KeyValue:
    def __init__(self, key, value):
        self.key = key
        self.value = value

    def validate(self, to_validate):
        return self.key in to_validate and self.value.validate(to_validate[self.key])

class Boolean:
    def validate(self, to_validate):
        return isinstance(to_validate, bool)

class Integer:
    def validate(self, to_validate):
        return isinstance(to_validate, int)

class String:
    def validate(self, to_validate):
        return isinstance(to_validate, str)

class CustomValidator:
    def validate(self, to_validate):
        if not Mapping(rows=Integer(), cols=Integer()).validate(to_validate):
            return False
        element_validator = Mapping(meta=String(), walls=Mapping(**{k: Boolean() for k in "EONS"}))
        for i in range(to_validate['rows']):
            for j in range(to_validate['cols']):
                if not KeyValue((i, j), element_validator).validate(to_validate):
                    return False
        return True

d = {
    'rows': 11,
    'cols': 13,
}
d.update({(i, j): {
    'meta': 'random string',
    'walls': {
        'E': True,
        'O': False,
        'N': True,
        'S': True
    }
} for i in range(11) for j in range(13)})

assert CustomValidator().validate(d)

Same thing with overriding isinstance(tested with Python 3.5)
class IsInstanceCustomMeta(type):
    def __instancecheck__(self, instance):
        return self.validate(instance)

def create_custom_isinstance_class(f):
    class IsInstanceCustomClass(metaclass=IsInstanceCustomMeta):
        validate = f
    return IsInstanceCustomClass

def Mapping(**kwargs):
    key_values = [KeyValue(k, v) for k, v in kwargs.items()]

    def validate(to_validate):
        if not isinstance(to_validate, dict):
            return False

        for validator in key_values:
            if not isinstance(to_validate, validator):
                return False
        return True

    return create_custom_isinstance_class(validate)

def KeyValue(key, value):
    return create_custom_isinstance_class(lambda to_validate: key in to_validate and isinstance(to_validate[key], value))

def my_format_validation(to_validate):
    if not isinstance(to_validate, Mapping(rows=int, cols=int)):
        return False
    element_validator = Mapping(meta=str, walls=Mapping(**{k: bool for k in "EONS"}))
    for i in range(to_validate['rows']):
        for j in range(to_validate['cols']):
            if not isinstance(to_validate, KeyValue((i, j), element_validator)):
                return False
    return True

MyFormat = create_custom_isinstance_class(my_format_validation)

d = {
    'rows': 11,
    'cols': 13,
}
d.update({(i, j): {
    'meta': 'random string',
    'walls': {
        'E': True,
        'O': False,
        'N': True,
        'S': True
    }
} for i in range(11) for j in range(13)})

assert isinstance(d, MyFormat)

A: If your format were simpler, I'd agree with the other answer/comments to use existing schema validation libraries, like schema and voluptuous. But, given your specific case of having to check a dictionary with tuple keys, and those tuples' values depending on the values of other members of your dict, I think you'd be better off writing your own validator than trying to coax a schema to fit your format.

A: Firstly, I think the more 'Pythonic' thing might be to ask forgiveness rather than permission - to check when you needed a property whether the data structure had that property.
But on the other hand, that doesn't help if you've been asked to create something to check it's well-formed. :)
So if you need to check, you can use something like the schema library to define what your data structure should look like, and then check other data structures against that schema.

A: from itertools import product

def isvalid(d):
    try:
        for key in product(range(d['rows']), range(d['cols'])):
            sub = d[key]
            assert (isinstance(sub['meta'], str) and
                    all(isinstance(sub['walls'][c], bool)
                        for c in 'EONS'))
    except (KeyError, TypeError, AssertionError):
        return False
    return True

If Python 2 compatibility is important or it's necessary to assert that there are no additional keys, let me know.

A: If you use something like this:
def get_deep_keys(d, depth=2):
    """Gets a representation of all dictionary keys to a set depth.

    If a (sub)dictionary contains all non-dictionary values, a list of keys
    will be returned.

    If a dictionary contains a mix of types, a dictionary of dicts/lists/types
    will be returned.
    """
    if isinstance(d, dict):
        if depth > 0 and any(isinstance(v, dict) for v in d.values()):
            return {k: get_deep_keys(v, depth=depth - 1) for k, v in d.items()}
        else:
            return set(d.keys())

    else:
        return type(d)

Then you can do:
assert get_deep_keys(D[i, j]) == {
    'meta': str, 'walls': {'E', 'N', 'O', 'S'}}

Inside a loop over i, j. This is pretty easy to modify to return the types of the bottom level elements instead:
def get_deep_keys(d, depth=2):
    """Gets a representation of all dictionary keys to a set depth, with types.
    """
    if isinstance(d, dict) and depth > 0:
        return {k: get_deep_keys(v, depth=depth - 1) for k, v in d.items()}

    return type(d)

get_deep_keys(D)
 # {'meta': str, 'walls': {'E': bool, 'O': bool, 'N': bool, 'S': bool}}


text:
Q: How to disable nuget package restore with msbuild command line options? I want to disable NuGet package restore on build and use the individual command for that. Is this possible?
My idea is to use something like this:
nuget.exe restore
msbuild.exe /p:NuGetRestorePackages=false

Update:

*

*the package updating can be disabled by MSBuild.exe ... /p:RestorePackages=false

*and it looks like .nuget\nuget.exe restore solution.sln restores the packages

A: You can use "MSBuild    /p:RestorePackages=false" to disable package restore on build command.

A: Nowadays, I suggest making your CLI approach more comprehensive and reliable.
Short plan

*

*Install Visual Studio Build Tools 2017

*Find proper MSBuild

*Clean solution

*Restore packages with nuget using correct MSBuild

*Build solution

Details

*

*Using Build Tools will give you independence from Visual Studio installation.
Download Build Tools for Visual Studio 2017 from Visual Studio Downloads page (direct link)
Command-line arguments documented here: Use command-line parameters to install Visual Studio 2017
All workloads and components are listed here: Visual Studio Build Tools 2017 component directory

*Use PowerShell module VSSetup. And choose x86 or x64 MSBuild version
Download it or install from here: Github: Microsoft/Visual Studio Setup PowerShell Module

*Run MSBuild with clean target

*Help nuget.exe to use proper MSBuild
nuget.exe restore -MSBuildPath "C:\..."

*Run MSBuild with build target (you can add additional required parameters)

# 1. Find MS Build

Import-Module $PSScriptRoot\VSSetup\VSSetup.psd1

$msBuildPath = (Get-VSSetupInstance | Select-VSSetupInstance -Version 15.0 -Product Microsoft.VisualStudio.Product.BuildTools).InstallationPath

if ([System.IntPtr]::Size -eq 8)
{
    $global:msbuildPath = Join-Path $msBuildPath 'MSBuild\15.0\Bin\amd64'
}
else
{
    $global:msbuildPath = Join-Path $msBuildPath 'MSBuild\15.0\Bin'
}

Write-Output "Using MSBuild from $global:msbuildPath"
Write-Output "MSBuild /version"

$msbuild = Join-Path $global:msbuildPath msbuild

& $msbuild /version

# 2. Clean

& $msbuild "$sln_file" /t:Clean /v:q /nologo

# 3. Restore

$nuget = Join-Path $PSScriptRoot "\.nuget\nuget.exe"
& $nuget restore -MSBuildPath $global:msbuildPath

# 4. Build

& $msbuild "$sln_file" /t:Build /v:q /nologo

As the result, you will not have any filesystem, PATH or Visual Studio dependencies. And your solution will be reusable on the local machine and a build server.


text:
Q: State disappear after Component Update I made little Poll App
with Home Component and New component
Home Render state with question and vote option
in New Component You can Make new poll with vote option.
After goes to New component by "Add poll" button, old state disappear,
So I cad add only one Poll.
How can I maintain this state disappearing?

import React, {Component} from 'react';
import {Link} from 'react-router-dom';
import Poll from './Poll'

class Home extends Component {
  state = {
    question:"",
    tag:[],
  }

componentDidMount() {
  if (this.props.location.state !== undefined) {
    const tag = this.props.location.state.tag;
    const que= this.props.location.state.question;
      this.setState({
      tag: [...this.state.tag, tag],
      question: [...this.state.question, que]
    })
  }
}

  render() {
    return (

        <Poll
          question={this.state.question}
          tag={this.state.tag}
        />

          <Link to='/New'>
            <button
            style={{width:"100px", height:"80px", cursor:"pointer" }}>
              Add Poll
            </button>
          </Link>

    )
  };
}

export default Home;

Edit:
I passing State from New Component By

<Link to={this.state.question && this.state.tag[0] ?
              { pathname: '/', state: {
              question: this.state.question,
              tag : this.state.tag
              } }
             :
             { pathname: '/New'}}>
              <button style={{padding:"8px", marginTop:"10px"}}>
                Add new poll
              </button>
            </Link>

<BrowserRouter>
        <Switch>
          <Route exact path ="/" component={Home}/>
          <Route path ="/New" component={New} />
        </Switch>
      </BrowserRouter>

A: React component loses the state once the component gets unmount. If you want to maintain the state even after component unmount, then try using Redux.

A: You could separate your components to a container (Home) and presentional components (Poll List, New).
I.e Home would maintain the state and would render the list or new component. Thus you would never loose the state.
The add button would only change kinda flag in your state and according to that flag you would render one of the component.


text:
Q: Using multiple classes I am trying to make a simple program that asks the user to enter an integer. Once the program receives the input it takes and stores it and then counts from 1 to the input integer and sums the total of the count. Then it displays the results in a meaningful way to the user and prompts them if they would like to process another number. The point of this program is to use loops and multiple classes. I know that I am really close to the desired end product but cannot figure out why the AccumulateValue() method is not working properly. It does not seem to be going into the conditional while statement that I made. If anyone could give me some insight to my problem that would be great!
Here is my code:
AccumulatorApp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project
{
    class AccumulatorApp
    {

        static void Main(string[] args)
        {
            string loopControl = "Y";
            int sum;
            int enteredValue;
            DisplayTitle();

            while (loopControl == "Y" || loopControl == "YES")
            {
                enteredValue = InputInteger(0);
                Accumulator number = new Accumulator(enteredValue);
                sum = number.AccumulateValues();
                DisplayOutput(sum, enteredValue);
                Console.Write("\tWould you like to process another number? \n\t\t<Y or N>: ");
                loopControl = Console.ReadLine().ToUpper();
            }

        }

        public static void DisplayTitle()
        {
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.Clear();
            Console.WriteLine();
            Console.WriteLine("\tProgramming Assignment 05 - Accumulator - Robert");
            DrawLine();

        }

        public static int InputInteger(int enteredValue)
        {

            Console.Write("\tPlease enter a positive integer: ");
            enteredValue = Convert.ToInt32(Console.ReadLine());
            if (enteredValue > 0)
            {
                return enteredValue;
            }
            else
            {
                Console.WriteLine("\tInvalid input. Please enter a POSITIVE integer: ");
                enteredValue = Convert.ToInt32(Console.ReadLine());
            }
            return enteredValue;

            /*
            Console.Write("Please enter a positive integer: ");
            int enteredValue = Convert.ToInt32(Console.ReadLine());
            return enteredValue;
             * */
        }

        public static void DisplayOutput(int sum, int inputValue)
        {
            Console.WriteLine("\tThe inputed integer is: {0}", inputValue);
            Console.WriteLine("\tThe sum of 1 through {0} = {1}", inputValue, sum);
            DrawLine();
        }

        public static void DrawLine()
        {
            Console.WriteLine("\t______________________________________________________");
            Console.WriteLine();
        }

    }
}

Accumulator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project
{
    class Accumulator
    {
        int integerEntered;

        public Accumulator()
        {
        }

        public Accumulator(int integerEntered)
        {
            int enteredInteger = integerEntered;
        }

        public int AccumulateValues()
        {
            int accumulatedValue = 0;
            int counterValue = 1;
            while (counterValue <= integerEntered)
            {
                Console.WriteLine("\tPasses through loop = {0}", accumulatedValue);
                accumulatedValue = accumulatedValue + counterValue;
                counterValue = counterValue + 1;
            }
            return accumulatedValue;
        }

    }
}

A: When you are instantiating a new instance of Accumulator through it's constructor containing one int argument you were setting the passed value equal to the field within the class (Setting them both to 0.)
Your accumulator class should look like this:
class Accumulator
{
    int integerEntered;

    public Accumulator()
    {
    }

    public Accumulator(int passedInteger)
    {
        //Local field is equal to passedInteger, not the other way around.
        integerEntered = passedInteger;
    }

    public int AccumulateValues()
    {
        int accumulatedValue = 0;
        int counterValue = 1;
        while (counterValue <= integerEntered)
        {
            Console.WriteLine("\tPasses through loop = {0}", accumulatedValue);
            accumulatedValue = accumulatedValue + counterValue;
            //Increment does the same thing you were doing
            counterValue++;
        }
        return accumulatedValue;
    }

}

A: It looks like the problem may actually be with your value constructor. When this line is called:
    Accumulator number = new Accumulator(enteredValue);
A new Accumulator is being made with your value constructor:
public Accumulator(int integerEntered)
{
    int enteredInteger = integerEntered;
}

The problem is that integerEntered isn't really saved anywhere and once enteredInteger goes out of scope (end of constructor), the value that was entered is essentially lost as far as the Accumulator object is concerned. I think what you want is:
public Accumulator(int integerEntered)
{
    integerEntered = integerEntered;
}

As a heads up, you may have to do this.integerEntered = integerEntered;
Also I think you want to subtract 1 from integerEntered each iteration of your while loop in AccumulateValues().

A: There 2 -3 things needs to be changed
1) you are not assigning values to integerEntered in your constructor so I have changed it
2) you should integerEntered as a property so i have changed it to  public int integerEntered { get; set; }
3) the logic of calculating to count AccumulateValues .. actually mathematical formula is the sum up to integer n is = (n * (n+1))/2 so i have changed it too
try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project
{
    class Accumulator
    {

        public int integerEntered { get; set; }

        public Accumulator()
        {
        }

        public Accumulator(int integerPassed)
        {
            integerEntered = integerPassed;
        }

        public int AccumulateValues()
        {
            int accumulatedValue = 0;
            if(integerEntered > 0)
            {
                accumulatedValue = (integerEntered * (integerEntered + 1))/2;
            }
            return accumulatedValue;

        }

    }
}


text:
Q: Is the regular representation of a fusion ring a direct sum of all its irreducible representations? For groups, the regular representation contains each irrep with multiplicity equal to the irrep's dimension.
For (not necessarily commutative) fusion rings, is there any analogous statement for the regular representation (= fusion matrix)?


text:
Q: Laravel Password Hashing I have a external service which wishes to create user via a bespoke API that I have created in my Laravel application.
Rather than the remote end sending me the password in plain text I would like the remote end to hash the password first however I am unsure on how of the hashing using.
The remote end is using ASP.NET to make things slightly more complicated.
I am guessing Laravel is using CRYPT_BLOWFISH as that is the strongest available on the server but unsure how the salt works. Could anyone advise?

A: http://php.net/manual/en/function.crypt.php

CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithmeter and must be in range 04-31, values outside this range will cause crypt() to fail. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".

Example hash from Laravel:
$2y$10$RXyfF5/5qdBeGbwKgU5NR.p1OcgT5t3N.M5ql5PHm.UoxYGOogDWi

*

*2y = blowfish prefix

*10 = cost parameter

*RXyfF5/5qdBeGbwKgU5NR. = 22 char salt

*p1OcgT5t3N.M5ql5PHm.UoxYGOogDWi = bcrypt hash


text:
Q: CSS transition of fill color not working on hover out I have the fill color of the SVG path set to transition on hover. It works fine when you hover over the graphic, but the color snaps back when you hover out instead of transitioning back. What's going on?

body {
  background: rgb(0, 185, 228);
}

a.facebookIcon {
  display: inline-block;
  margin: 20px;
}

a.facebookIcon svg {
  width: 42px;
  height: 42px;
}

a.facebookIcon svg path {
  fill: rgb(255, 255, 255);
}

a.facebookIcon:hover svg path {
  fill: rgb(182, 52, 187);
  transition: fill 3000ms;
}

  <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1017.78" viewBox="0 0 1024 1017.78">
  <path d="M1024,512C1024,229.23,794.77,0,512,0S0,229.23,0,512c0,255.55,187.23,467.37,432,505.78V660H302V512H432V399.2C432,270.88,508.44,200,625.39,200c56,0,114.61,10,114.61,10V336H675.44c-63.6,0-83.44,39.47-83.44,80v96H734L711.3,660H592v357.78C836.77,979.37,1024,767.55,1024,512Z"/>
</svg>

A: The transition is only added to the :hover state, so when your mouse comes off it forgets about the transition. Add the transition to the initial state.
a.facebookIcon svg path{
  fill: rgb(255,255,255);
  transition: fill 3000ms; //HERE
}

A: put transition: fill 3000ms; into a.facebookIcon svg path like this
a.facebookIcon svg path{
    fill: rgb(255,255,255);
  transition: fill 3000ms;
}
a.facebookIcon:hover svg path{
    fill: rgb(182,52,187);
}

and not
a.facebookIcon svg path{
    fill: rgb(255,255,255);
}
a.facebookIcon:hover svg path{
    fill: rgb(182,52,187);
    transition: fill 3000ms;
}


text:
Q: Algorithm to generate all nonnegative solutions to x1 + x2 + ....xk = n. (Stars and bars) What is an algorithm to generate every solution to  x1 + x2 + ....xk = n, xi >= 0? I am aware it is some form of backtracking but I am not sure how to implement this.

A: Straightforward recursion will work here. The first element of the solution can take any value xi from 0 to n. To find the second and subsequent values, find the possible partitions for (n−xi, k−1). The recursion stops when k=1, in which case the final element must be equal to the remaining value of n.
I hope that makes sense. Perhaps the following Python code will help:
def get_partitions(n, k, p=[]):
    # End point. If k=1, then the last element must equal n
    # p[] starts as an empty list; we will append values to it
    # at each recursive step
    if k <= 1:
        if k == 1 and n >= 0:
            yield(p + [n])
        return
        # If k is zero, then there is no solution
        yield None
    # Recursively loop over every possible value for the current element
    for i in range(0,n+1):
        yield from get_partitions(n-i, k-1, p+[i])

>>> for p in get_partitions(4,3):
...     print(p)
...
[0, 0, 4]
[0, 1, 3]
[0, 2, 2]
[0, 3, 1]
[0, 4, 0]
[1, 0, 3]
[1, 1, 2]
[1, 2, 1]
[1, 3, 0]
[2, 0, 2]
[2, 1, 1]
[2, 2, 0]
[3, 0, 1]
[3, 1, 0]
[4, 0, 0]

A: Without recursion, quicky modified from my answer with non-zero partitions, implements stars and bars principle
from itertools import combinations

#print(parts(7,4))

def partswithzeros(n,r):
    result = []
    for comb in combinations(range(n+r-1), r-1):
        zpart = [comb[0]] + [comb[i]-comb[i-1]-1 for i in range(1,r-1)] + [n+r-2 - comb[-1]]
        result.append(zpart)
    return(result)

print(partswithzeros(5,3))

>>>[[0, 0, 5], [0, 1, 4], [0, 2, 3], [0, 3, 2], [0, 4, 1], [0, 5, 0], [1, 0, 4],
    [1, 1, 3], [1, 2, 2], [1, 3, 1], [1, 4, 0], [2, 0, 3], [2, 1, 2], [2, 2, 1],
    [2, 3, 0], [3, 0, 2], [3, 1, 1], [3, 2, 0], [4, 0, 1], [4, 1, 0], [5, 0, 0]]


text:
Q: Exercise on saturated Tits system I'm trying to work through the following exercise in Bourbaki, Lie Groups and Lie Algebras.

For part (a), we are assuming $b \in B$ normalizes $N$, and we are supposed to show that $bnb^{-1}n^{-1} \in T = B \cap N$ for all $n \in N$.  The hint is to write $bn = (bnb^{-1})b$ use Theorem 1, which says that
$$w \mapsto BwB$$
is an injective on $N/T$.  Already $bnb^{-1}n^{-1}$ lies in $N$.  Thus, if we can show that $Bbnb^{-1}n^{-1}B = B$, it will follow that $bnb^{-1}n^{-1} \in B \cap N$.  I'm probably just tired but I can't get anywhere on this problem.  I would appreciate any further hints.

A: (a): First, assume that $b \in B \cap \hat{N}$.  We will show that $bnbn^{-1} \in B \cap N$ for all $n \in N$.  Let $n \in N$.  Since $b \in \hat{N} = \mathcal N_G(N)$, we have $bnb^{-1}  = n'$ for some $n' \in N$. Then $bn = n'b$, so $BnB = Bn'B$.  This implies that $n \equiv n' \pmod{T}$, so $n'n^{-1} = b_0$ for some $b_0 \in T$.  Then $$bnbn^{-1} = n'n^{-1} \in T = B \cap N$$ as required.
Next, let's show that if $b \in B \cap \hat{N}$, then $b \in \hat{T} = \bigcap\limits_{n \in N} nBn^{-1}$.  By what we just showed, we have for each $n \in N$, that $bnbn^{-1} = b_0$ for some $b_0 \in B \cap N$.  Then $$b = b_0nb^{-1}n^{-1} = n(n^{-1}b_0n)b^{-1}n^{-1}$$
which is in $nBn^{-1}$, since $N$ normalizes $B \cap N$.
Finally, let's show that $\hat{T} \cap N = T$.  Since $\hat{T} \subseteq B$, we have $\hat{T} \cap N \subseteq B \cap N = T$.  Conversely, if $b_0 \in T = B \cap N$, then already $b_0 \in N$, so we just need to show that $b_0 \in nBn^{-1}$ for every $n \in N$.  But
$$b_0 = n(n^{-1}b_0n)n^{-1}$$
with $n^{-1}b_0n \in B$.


text:
Q: Found array with 0 sample(s) (shape=(0, 1)) while a minimum of 1 is required by MinMaxScaler I was trying to use MinMax scaler on multiple data frames using the following code.
for file in glob.glob('*csv'):
    name = check_output(['basename',file,'.csv']).decode().strip()
    df = pd.read_csv(file, index_col=0)
    scaler = MinMaxScaler()
    df[['col']] = scaler.fit_transform(df[['col']])

But it was throwing the following error
Found array with 0 sample(s) (shape=(0, 1)) while a minimum of 1 is required by MinMaxScaler


text:
Q: How to separate whole number and decimal number to two different variable I am  trying to separate whole number and decimal number
two int variable
#include <iostream>
#include <iomanip>
#include<math.h>

using namespace std;
int main()
{
    double initialAmount = 42800.13;
    double fractionalPart = initialAmount - floor(initialAmount);
    cout<<int(initialAmount)<<"\n"<<fractionalPart<<"\n";

}

Present output is
42800
0.13

expected output
42800
13

It can be more than two decimal places .
any easy way to do that

A: Maybe not the best solution, but at least it is simple :)
Store your double initialAmount in a int - which will truncate the decimal part. Then you have the number before the decimal point. Then subtract that from the initial value and you'll be left with just the part after the decimal point. Multiply that by however many powers of 10 that you deem significant and then again store that in a int and you'll have your two values.

A: As suggested in the comments, it could help to convert the number into a string.  Here's one possibility:
#include <sstream>
#include <iostream>
#include <vector>
#include <string>

int main() {
  double d = 42800.13;
  std::vector<std::string> numbers_s;
  std::string s;
  std::istringstream numberAsString(std::to_string( d ));
  while (getline(numberAsString, s, '.')) {
    numbers_s.push_back(s);
  }
  std::cout << "whole number:" << numbers_s[0] << std::endl;
  //[ remove trailing zeros from fractional part:
  numbers_s[1].erase(numbers_s[1].find_last_not_of('0') + 1, std::string::npos);
  //]
   std::cout << "fractional part:" << std::stoi(numbers_s[1]) << std::endl;
}

Error checks should be added to capture cases when the number does not contain a decimal point.


text:
Q: Use StaticResource in XAML root element I want to use StaticResource in the root element of a xaml document.
But MSDN says:

Static resource references from within
  a resource dictionary must reference a
  resource that has already been defined
  lexically before the resource
  reference. Forward references cannot
  be resolved by a static resource
  reference.

And this:

The lookup process then traverses the
  logical tree upward, to the parent
  element and its resource dictionary.
  This continues until the root element
  is reached.

Should I define my resource in the application or create it from code?

A: If you really need to access a ResourceDictionary from the root element, you may be able to reference it as a DynamicResource rather than a StaticResource - I'm not sure if it will work, but it could be worth a try.

A: You can actually set any property as an element as well as an attribute, including ones as simple as Window.Left.
This means you can set the value of Left after you declare your resources.
<Window.Resources>
    <app:LeftConverter
        x:Key="LeftConverter" />
</Window.Resources>

<Window.Left>
    <Binding
        Path="UnconvertedLeft"
        Converter="{StaticResource LeftConverter}" />
</Window.Left>


text:
Q: HP MSR 30-10a Router - Route Traffic over Default Route We have a brand new HP MSR 30-10a Router. We have a fairly simple routing situation - we have two IP blocks, one which has a route out. We need things on the first block to go through the router, and out. I have an old Cisco 2801 router doing the job right now.
For our example -
IP Block 1:
50.203.110.232/29, Router interface on this block is 50.203.110.237, route out is 50.203.110.233.
IP Block 2: 50.202.219.1/27, Router interface on this block at 50.202.219.20.
I have a static route created for:
0.0.0.0 0.0.0.0 50.203.110.233
The router seems to understand this. When on the CLI via serial cable, I can ping 8.8.8.8 and hear responses from Google DNS. Woo hoo!
The issue arrives when any client sits on the IP Block 2 side. I configured my client with a static IP of 50.202.219.15/27, default gateway 50.202.219.20. I can ping myself. I can ping the near side of the router (50.202.219.20), and I can ping the far side of the router (50.203.110.237. I cannot ping anything else in IP block 1, nor can I ping 8.8.8.8.
Here is my configuration file:
<HP>display current-configuration
#
 version 5.20.106, Release 2507, Standard
#
 sysname HP
#
 domain default enable system
#
 dar p2p signature-file flash:/p2p_default.mtd
#
 port-security enable
#
 undo ip http enable
#
 password-recovery enable
#
vlan 1
#
domain system
 access-limit disable
 state active
 idle-cut disable
 self-service-url disable
#
user-group system
 group-attribute allow-guest
#
local-user admin
 password cipher $c$3$40gC1cxf/wIJNa1ufFPJsjKAof+QP5aV
 authorization-attribute level 3
 service-type telnet
#
cwmp
 undo cwmp enable
#
interface Aux0
 async mode flow
 link-protocol ppp
#
interface Cellular0/0
 async mode protocol
 link-protocol ppp
#
interface Ethernet0/0
 port link-mode route
 ip address 50.203.110.237 255.255.255.248
#
interface Ethernet0/1
 port link-mode route
 ip address 50.202.219.20 255.255.255.224
#
interface NULL0
#
 ip route-static 0.0.0.0 0.0.0.0 50.203.110.233 permanent
#
 load xml-configuration
#
 load tr069-configuration
#
user-interface tty 12
user-interface aux 0
user-interface vty 0 4
 authentication-mode scheme
#

My guess right now is there is some sort of "permission" needed to use the default route. The manuals haven't turned up a lot in this area that don't make the situation much more complicated (but maybe it needs to be more complicated?)
Background: we use HP switches, and I love the CLI. I bought HP thinking the command line interface would be similar, or at least speak the same language. Whoops!
I'd be happy to provide more information or perform any additional tests. Thanks in advance!
Update 1: The manual mentions routing rules. I hadn't previously added these (since our Cisco 2801 seems to route anything by default). I added:
ip ip-prefix 1 permit 0.0.0.0 0 less-equal 32
alas, still no dice.

A: I contacted HP Support. The word is - the configuration is great and the router will work set up like this! My pings aren't coming back because while my route out is correct, our incoming system doesn't have a route back (it goes to the live router which this one will be replacing).
To get this router to route traffic, I have two options:

*

*Call Comcast. Ask them to change the our route in

*Give this new router the same internal and external IP address (this is what I'll do).

Makes sense! A simple solution, and it's good to be affirmed that I set the router up correctly. I hope this helps someone else!
-Stead


text:
Q: Doubt regarding spring force on strings
Here, it has been said that the tension $T$ acting on the string is $3mg$ due to the masses $2m$ and $m$. But there is also a spring connected. Why don't we take that into account while finding $T$?

A: You can.
The small mass $m$ is at rest. The small mass experiences gravity, and upward tension from the spring, in balance, so $mg = S$, where $S$ is the tension of the spring.
The large mass $2m$ is at rest. The large mass experiences gravity and downward tension from the spring, balanced with upward tension from the string, so
$$2mg + S = T$$
$S = mg$, so $T = 3mg$. This does take into account the spring.
You can either choose:

*

*to think of the two masses separately, considering the effect of the small mass on the string through the spring,

or

*

*you can choose to think of the two masses combined, ignoring the
spring.

You cannot add $mg$ from the small mass and $mg$ from the spring at
the same time, as that would be double-counting. Both are different ways of looking at the effect of the small mass.

A: The tension $T$ isn't so useful in this case, because it suddenly changes when the spring breaks (suddenly becoming $T_+=0$).  The force exerted by the spring, however, is useful.  It isn't suddenly changed by the spring breaking -- the force exerted by a spring is proportional to how much it is stretched/compressed, and nothing more.  That stretching doesn't change when the string breaks.
Accordingly, you can solve this in two steps:

*

*First, find the force that the spring must exert in order to keep the second mass up in the steady state solution.  This is, of course, $F_{spring}=mg$

*Second, find the acceleration of the first mass after the spring has snapped.  After the spring has snapped $T=0$, but $F_{spring}$ is still present, and still equal to $mg$ because the spring hasn't had the opportunity to shrink.  Thus, the forces on the first block are gravity, $(2m)g$ and the spring force, $mg$, both in the downward direction.  These, of course, sum to $3mg$.

*

*This is not necessarily attributable to the $T=3mg$ tension force on the wire, although it happens to line up in this case.  It is entirely due to gravity and the spring force.  This particular problem happens to have an answer that is the same as the answer to "what is the tension force in the string," but in general, focus on the forces that exist after the sudden change to the system.


text:
Q: using sscanf(), read string to array of int? i have this string:
12 4 the quick 99 -1 fox dog \

what i want in my program:
myArray[] = {12, 4, 99, -1};

how i do a multiple number scanning?

A: See my answer to your other question here. It's a relatively simple matter to replace the strtok section to recognize non-numeric words and neither increment the count (in the first pass) nor load them into the array (in the second pass).
The code has changed as follows:
Using an input file of:
12 3 45 6 7 8
3 5 6 7
7 0 -1 4 5
12 4 the quick 99 -1 fox dog \

it produces output along the lines of:
0x8e42170, size = 6:
   12 3 45 6 7 8
0x8e421d0, size = 4:
   3 5 6 7
0x8e421e0, size = 5:
   7 0 -1 4 5
0x8e42278, size = 4:
   12 4 99 -1

Here's the code that produced that output:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

// This is the linked list of integer arrays.

typedef struct _tIntArray {
    int size;
    int *array;
    struct _tIntArray *next;
} tIntArray;
static tIntArray *first = NULL;
static tIntArray *last = NULL;

// Check that argument is numeric, optional minus sign followed by
// zero or more digits (you may want one or more).

static int isAllNumeric (char *word) {
    char *s = word;
    if (*s == '-')
        s++;
    for (; *s != '\0'; s++)
        if ((*s < '0') || (*s > '9'))
            return 0;
    return 1;
}

// Add a line of integers as a node.

static int addNode (char *str) {
    tIntArray *curr;  // pointers for new integer array.
    char *word;       // word within string.
    char *tmpStr;     // temp copy of buffer.
    int fldCnt;       // field count for line.
    int i;

    // Count number of fields.

    if ((tmpStr = strdup (str)) == NULL) {
        printf ("Cannot allocate duplicate string (%d).\n", errno);
        return 1;
    }
    fldCnt = 0;
    for (word = strtok (tmpStr, " "); word; word = strtok (NULL, " "))
        if (isAllNumeric (word))
            fldCnt++;
    free (tmpStr);

    // Create new linked list node.

    if ((curr = malloc (sizeof (tIntArray))) == NULL) {
        printf ("Cannot allocate integer array node (%d).\n", errno);
        return 1;
    }

    curr->size = fldCnt;
    if ((curr->array = malloc (fldCnt * sizeof (int))) == NULL) {
        printf ("Cannot allocate integer array (%d).\n", errno);
        free (curr);
        return 1;
    }
    curr->next = NULL;

    for (i = 0, word = strtok (str, " "); word; word = strtok (NULL, " "))
        if (isAllNumeric (word))
            curr->array[i++] = atoi (word);

    if (last == NULL)
        first = last = curr;
    else {
        last->next = curr;
        last = curr;
    }

    return 0;
}

int main(void) {
    int lineSz;       // current line size.
    char *buff;       // buffer to hold line.
    FILE *fin;        // input file handle.
    long offset;      // offset for re-allocating line buffer.
    tIntArray *curr;  // pointers for new integer array.
    int i;

    // Open file.

    if ((fin = fopen ("qq.in", "r")) == NULL) {
        printf ("Cannot open qq.in, errno = %d\n", errno);
        return 1;
    }

    // Allocate initial line.

    lineSz = 2;
    if ((buff = malloc (lineSz+1)) == NULL) {
        printf ("Cannot allocate initial memory, errno = %d.\n", errno);
        return 1;
    }

    // Loop forever.

    while (1) {
        // Save offset in case we need to re-read.

        offset = ftell (fin);

        // Get line, exit if end of file.

        if (fgets (buff, lineSz, fin) == NULL)
            break;

        // If no newline, assume buffer wasn't big enough.

        if (buff[strlen(buff)-1] != '\n') {
            // Get bigger buffer and seek back to line start and retry.

            free (buff);
            lineSz += 3;
            if ((buff = malloc (lineSz+1)) == NULL) {
                printf ("Cannot allocate extra memory, errno = %d.\n", errno);
                return 1;
            }
            if (fseek (fin, offset, SEEK_SET) != 0) {
                printf ("Cannot seek, errno = %d.\n", errno);
                return 1;
            }
            continue;
        }

        // Remove newline and process.

        buff[strlen(buff)-1] = '\0';
        if (addNode (buff) != 0)
            return 1;
    }

    // Dump table for debugging.

    for (curr = first; curr != NULL; curr = curr->next) {
        printf ("%p, size = %d:\n  ", curr, curr->size);
        for (i = 0; i < curr->size; i++)
            printf (" %d", curr->array[i]);
        printf ("\n");
    }

    // Free resources and exit.

    free (buff);
    fclose (fin);
    return 0;
}


text:
Q: CA2213 code analysis rule and auto-implemented properties I use static code analysis in our projects to check for code violations. One of extensively used rules is CA2213, which checks for correct disposing of disposable fields.
I noticed CA2213 does not check disposing of auto implemented properties.
Furthermore CA2213 does not check disposing of neither fields nor auto implemented properties if the class inherits from class which implements IDisposable and does not override the Dispose method.
Practical example:
public sealed class Good : IDisposable {
    private Font font;
    public Font Font {
        get { return font; }
        set { font = value; }
    }
    public Good() { font = new Font("Arial", 9); }
    public void Dispose() { /* Do nothing */ }       // CA2213
}

public sealed class Bad : IDisposable {
    public Font Font { get; set; }
    public Bad() { Font = new Font("Arial", 9); }
    public void Dispose() { /* Do nothing */ }       // No warning
}

Has anyone else encountered this behavior? Is this by design or bug in CA2213 rule?

A: Code analyzers do have limitations, the one present in this code is that it needs to generate an actionable warning.  One that the programmer can actually follow up on to fix his code.  A key problem with the current code analyzer is that it does not analyze source code, it works from the assembly that's generated by the compiler.  Which is nice, it works for any .NET language.  But nobody will like this warning:

CA2213  Disposable fields should be disposed
  'Bad' contains field k__BackingField that is of IDisposable type: 'Font'. Change the Dispose method on 'Bad' to call Dispose or Close on this field.

Yikes, of course there is no such field in the program.  To generate a better message, the analyzer would have to figure out that the k__BackingField field in the metadata is in fact associated with the auto-implemented Font property.  There is nothing available in the metadata that makes that connection unambiguously.  The field only carries the [CompilerGenerated] attribute and the auto-generated field name is a compiler implementation detail.  Different language compilers generate different names.
It is the kind of problem that requires source-code analysis, not IL analysis as currently implemented.  Opportunity is knocking on the door, source-code analysis is going to be a lot easier to implement with Roslyn available today. VS2015 is the first VS version that supports "Live Code" analysis.  I don't know yet whether it looks for CA2213 style errors, soon.

A: Static analysis tools are tuned for a good trade-off between generating too many false-positives (i.e. emitting issues on perfectly fine code) and too many false-negatives (i.e. missing real issues in the code).
Let's take a simple example:
// CA2213 detects an issue
class OwnsTheField : IDisposable
{
    private MemoryStream f = new MemoryStream();
    public void Dispose() {}
}

It is clear in this case that an issue should be reported, and that is indeed the case.
Now, let's make things slightly more complicated:
// CA2213 does not detect
class FieldIsInjected : IDisposable
{
    private MemoryStream f;
    public FieldIsInjected(MemoryStream p)
    {
        f = p;
    }
    public void Dispose() { }
}

In this case, there might not be an issue with not disposing f. If pis properly disposed by the caller, then everything works as expected:
using (var p = new MemoryStream())
{
    using (var x = FieldIsInjected(p)) { /* ... */ }
} // p is properly disposed

More often than not, the exact behavior (including the handling of all corner cases) will not be documented, as an exhaustive documentation would be too costly to maintain over time. For example, this exception is explicitly mentioned in https://msdn.microsoft.com/en-us/library/ms182328.aspx

A: The rule is from .net framework 2, and auto properties are from C# 3, which was added to the language specification after the rule was created. The rule is defined in terms of fields not properties, so it seems like it is due for an update but working as currently specified.
This Question on disposing properties seems to show that properties that implement IDisposable aren't consistent in the framework.

A: The analysis engine is perfectly capable of walking between the property and its backing field. It just doesn't have the logic to do it, and so misses an opportunity for a warning. Worse, it emits a false warning if a properly disposed property is get-only.


text:
Q: ssh, nohup, then copy results back I want a script which automates the running of big mathematical computing jobs on a remote machine. Currently I do this:

*

*ssh into remote machine; run matlab script

*periodically check in to see if job is done yet

*when job is done, I manually scp the files containing the results back to my home machine.

I tried to use these kind of lines in my script to do this job (note the script runs on my machine):
ssh nohup matlab -r theScript; exit;
scp remote@~/files ~/files

This doesn't work. After a while the ssh session ends and the script just proceeds to do the scp, even though the job is not finished yet and the files don't exist yet.
I think what I need to do is check periodically whether the job is done, perhaps by ssh'ing in periodically and reading the nohup.out file looking for a DONE! signal using grep. Then when I see that, copy the files back. But this seems complicated and I don't know how to get the DONE! message back to my computer to run a conditional on (if you see the DONE signal, do this stuff...) any ideas?

A: There seems to be a way to configure this in your ssh_config.
This page explain how: http://nileshbansal.blogspot.com/2007/02/prevent-timeouts-in-ssh.html

A: Yeah, the ssh could time out or something. So yeah, you best option is to poll. e.g.
RUN="$(date +%Y%m%d-%H%M%S)"
ssh remote " nohup bash -c \"( matlab -r theScript; echo \$? > $RUN.done ) >$RUN.log 2>&1 </dev/null &\" "
DONE=""
while [ -z "$DONE" ]
do
    sleep 60
    DONE="$(ssh cat $RUN.done 2>/dev/null)"
done
if [ $DONE -eq 0 ]
then
    scp ...
else
    # Optionally fetch logfile
    # scp $RUN.log@remote ...
    echo "ERROR in remote matlab...."
fi

A: Try setting the ServerAliveInterval in you ssh_config file. That way, your SSH session will not close until the remote command finishes.
See here.


text:
Q: EXC_BAD_ACCESS and MPMusicPlayerController I wrote an app that I haven't worked on in awhile.  It started in Xcode 7.3.1, but worked fine in Xcode 8.3.3.  I'm getting EXC_BAD_ACCESS when I try to run it on an iPhone 8 with iOS 11.4.1 (I wish I never updated the iOS, but now I'm stuck).  But the app still runs fine on my old iPhone 5 with iOS 10.3.3.
My Mac runs Sierra and has Xcode 8.3.3 and 9.2.  I did copy the appropriate support files into the correct folder in each Xcode app (something I learned on this site).  That trick had worked for awhile!
I decide to build a little "Hello World" app under Xcode 9.2 just to simplify things.  If I remove the MPMusicPlayerController() below, the app installs and runs fine.  But, with that code, it crashes on self.myMPMusicPlayerController.playbackState == .stopped.
Can anyone suggest anything?  Thank you very much ahead of time.
import UIKit
import MediaPlayer

class ViewController: UIViewController {

@IBOutlet var myLabel: UILabel!
@IBOutlet var nowPlaying: UIButton!

var myMPMusicPlayerController = MPMusicPlayerController()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // The following is a tiny bit of an app
    // My mac is running Sierra so it can only take Xcode 8.3.3 or 9.2
    // I will be updating my mac at least to High Sierra soon, so it will be able to take Xcode 9.4.1
    // I have copied in the appropriate support file folders accordingly. So I have the 11.4 (15F79) folder in place

    // The following line, worked fine using Xcode 8.3.3 and an iPhone8 running 11.2 and an iPhone5 running 10.3.3
    // The following line, crashes on an iPhone8 running 11.4.1 but RUNS FINE on the iPhone5 running 10.3.3

    // I'm getting the error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x70)
    if self.myMPMusicPlayerController.playbackState == .stopped {

        // Hide the nowPlaying button.
        nowPlaying.isHidden = true
    } else {

        // Show the nowPlaying button.
        nowPlaying.isHidden = false
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// I added this just for a simple test
@IBAction func nowPlayingButton(_ sender: Any) {
    self.myLabel.text = "Hello"
}

}

A: I tried to run your code, unfortunately I am on Xcode 10.1 but I am having a compile error in the initialization of MPMusicPlayerController and shows the following error:

From Apple's Documentation of the MPMusicPlayerController class you may try initializing with
MPMusicPlayerController.systemMusicPlayer or MPMusicPlayerController.applicationMusicPlayer depending on your use case. I have tried this and ran on 11.4.1 and didn't run into any crashes.