text:
Q: Дважды записывает данные в бд, почему? Доброго времени суток!
Значит так, речь идет о платежной системе (для личных нужд). Передаются на страницу "success" зашифрованный $_GET с параметрами, я сравниваю параметры, если все хорошо, то сохраняю в базу данных, вот только он сохраняет дважды, почему так может происходить?
Если коротко, то код примерно следующий:
if( $params['status'] == 1){
    $email = $params['email'];
    $link = mysqli_connect("localhost", "xxx", "xxx", "xxx");
    $insert = 'INSERT INTO xxx (email) VALUES ("'.$email.'")';
    $query = mysqli_query($link, $insert) or die(mysqli_error($link));
}

Как можно проверить, отправились ли данные, чтобы не отправлять дважды? Спасибо!

A: Используйте PDO
$link = new PDO("mysql:host=$db_host;port=$db_port;dbname=$db_database", $db_user, $db_pass);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$link->exec("set names utf8");

$stmt = $link->prepare("INSERT INTO xxx (`email`) VALUES (:email)");
$stmt->bindValue(':email', $email);
$stmt->execute();


text:
Q: How to plot with different colors I am trying to plot a spiral with 8 turns. In each turn it is supposed to have a different color.
t = -1*pi*1:0.02:pi*1;

plot3(sin(t),cos(t),-1*pi*1:0.02:pi*1,'g')

t1 = -1*pi*2:0.02:pi*2;

plot3(sin(t1),cos(t1),-2*pi*1:0.02:pi*2,'r')

For now i am only plotting two turns, but it just turns out red. I have tried using hold on and hold off but its not working. Any suggestions?

A: check this
plot3(sin(t),cos(t),-1*pi*1:0.02:pi*1,'g-',sin(t1),cos(t1),-2*pi*1:0.02:pi*2,'r--')

A: The problem is that your red plot actually plots overtop of your previous one you should increase BOTH the lower bound and upper bound.
numberOfColors = 5;

for n = 0:numberOfColors-1
    t = -pi + n*2*pi:0.02:pi + n*2*pi;
    plot3(sin(t),cos(t),t,'Color',rand(3,1))
    hold on
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: MVC3 Data binding I have a partial view which I pass a model to and it displays checkboxs which the user can select and this eventually gets posted with my form so that I can query their checked state and insert data into DB as required.
I want to change my partial view so that instead of taking a model that contains a list of models it take the list of models directly thus decoupling it and making it more useful as a partial view. The problem is when I do this it doesn't seem to bind the data correctly. Below is an example of the code before (working correctly and after not working).
I would very much appreciate if somebody is able to shed some light as to why my changes are not taking affect, i.e. in the after code when I inspect the posted data the list is null and in the before it is populated correctly:
Before:
Call the partial view:
<fieldset>
    <legend>Facilities</legend>

            @{Html.RenderPartial("Partial/FacilityPartial", Model);}

</fieldset>

Partial view:
@model namespace.Models.SchoolRegisterModel
@for (var i = 0; i < Model.Facilities.Count; i++)
{
    @Html.HiddenFor(x => x.Facilities[i].name)
    @Html.HiddenFor(x => x.Facilities[i].facility_id)
    @Html.LabelFor(x => x.Facilities[i].@checked, Model.Facilities[i].name);
    @Html.CheckBoxFor(
            x => x.Facilities[i].@checked,
        new
        {
            id = Model.Facilities[i].facility_id,
            @class = "RightSpacing",
            description = Model.Facilities[i].description
        }
    )
}

After:
Call the partial view:
<fieldset>
    <legend>Facilities</legend>

            @{Html.RenderPartial("Partial/FacilityPartial", Model.Facilities);}

</fieldset>

Partial view:
@model IEnumerable<namespace.Models.facility>
@for (int i = 0; i < Model.Count(); i++)
{
    @Html.HiddenFor(x => x.ElementAt(i).name)

    @Html.HiddenFor(x => x.ElementAt(i).name)
    @Html.HiddenFor(x => x.ElementAt(i).facility_id)
    @Html.LabelFor(x => x.ElementAt(i).@checked, Model.ElementAt(i).name);
    @Html.CheckBoxFor(
            x => x.ElementAt(i).@checked,
        new
        {
            id = Model.ElementAt(i).facility_id,
            @class = "RightSpacing",
            description = Model.ElementAt(i).description
        }
    )
}

Thanks in advance!
Joe
Finished Code (Working)
Model:
public class SchoolRegisterModel
{
    // ... Lots of data
    public string Data { get; set; }

    [Display(Name = "Facilities")]
    public IEnumerable<FacilityViewModel> Facilities { get; set; }
}

namespace namespace.Models
{
    public class FacilityViewModel
    {
        public FacilityViewModel()
        {
        }

        public FacilityViewModel(facility facil, bool bSelected = false)
        {
            this.Facility = facil;
            this.Selected = bSelected;
        }

        public facility Facility { get; set; }
        public bool Selected { get; set; }
    }
}

Editor Template:
@model namespace.Models.FacilityViewModel
@Html.HiddenFor(x => x.Facility.facility_id)
@Html.HiddenFor(x => x.Facility.name)
@Html.LabelFor(x => x.Selected, Model.Facility.name)
@Html.CheckBoxFor(x => x.Selected,
    new
    {
        id = Model.Facility.facility_id,
        @class = "RightSpacing",
        description = Model.Facility.description
    }
)

Controller:
// GET: /School/Register

public ActionResult Register()
{
    var viewModel = new SchoolRegisterModel();

    PopulateFacilityCollection(ref viewModel);
    return View(viewModel);
}

private void PopulateFacilityCollection(ref SchoolRegisterModel viewModel)
{
    List<FacilityViewModel> FacilityCollection = new List<FacilityViewModel>();
    foreach (facility facil in DBModel.facilities)
    {
        FacilityCollection.Add(new FacilityViewModel(facil));
    }

    viewModel.Facilities = FacilityCollection;
}

View:
<fieldset>
    <legend>Facility</legend>

            @Html.EditorFor(x => x.Facilities)

</fieldset>

All seems to work well now, I hope that this helps somebody else!

A: The issue is that you seem to be using Partial Views when you should be using Editor Templates. When using Partials, you will need to pass around the full Model in order for the Html Helpers to retain the full object hierarchy in the names/ids it generates. Since the Model Binder uses those names during deserialization, if the hierarchy is lost... the data cannot be re-saturated.
I would suggest using an Editor Template instead, this will allow you to keep the Razor code in your Partial View the same while passing only the object needed in the top level model... in your case the list.
Here is a pretty good tutorial on how to use them: http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/


text:
Q: react state not working as it is supposed I started doing this tutorial and reached to the point where it is about making a sidebar, instructor made a hook and also made a context provider and then his button does its toggle functionality as it is supposed but after introducing the hooks my sidebar is gone.
I should get something like this where the humburger menu toggle the sidebar, I haven't done hamburger menue yet, in mine it's just a X button in the side bar which it is supposed to toggle it but instead I don't even see my sidebar:

All I see is this:

This is my sidebar component:

import React from 'react'
import { Link, NavLink } from 'react-router-dom';
import { SiShopware } from 'react-icons/si'
import { MdOutlineCancel } from 'react-icons/md'
import { TooltipComponent } from '@syncfusion/ej2-react-popups'
import { links } from '../data/dummy';
import { useStateContext } from '../contexts/ContextProvider';
const Sidebar = () => {
  const { activeMenu, setActiveMenu } = useStateContext();
  const activeLink = 'flex items-center w-40 gap-5 pl-4 pt-3 pb-2.5 rounded-lg text-white text-md m-2';
  const normalLink = 'flex items-center w-40 gap-5 pl-4 pt-3 pb-2.5 rounded-lg text-lg hover:bg-gray-200 text-gray-700 dark:text-gray-200 dark:hover:text-black m-2';
  return (

      {activeMenu && (<>

          <Link to ="/" onClick={() => { setActiveMenu(false) }} className="flex inline-flex items-center gap-3 ml-3 mt-4
           flex text-xl font-extrabold tracking-tight dark:text-white text-slate-900">
            <SiShopware /> Shoppy
          </Link>

          <TooltipComponent content="Menu" position="BottomCenter">
            <button type="button"
            onClick={() => setActiveMenu(prevActiveMenu => !prevActiveMenu)}
            className="text-xl rounded-full hover:bg-light-grayblock md:hidden">
              <MdOutlineCancel />
            </button>
          </TooltipComponent>

          {links.map((item) => (

                {item.title}

              {item.links.map((link) => (

                <NavLink to={`/${link.name}`}
                key={link.name}
                onClick={() => {}}
                className={({ isActive }) =>
                  isActive ? activeLink : normalLink
                }
                >

                  {link.icon}

                  {link.name}

                </NavLink>

              ))}

          ))}

        </>)}

  )
}

export default Sidebar

This is the contextProvide.js:

import React from 'react'
import { Link, NavLink } from 'react-router-dom';
import { SiShopware } from 'react-icons/si'
import { MdOutlineCancel } from 'react-icons/md'
import { TooltipComponent } from '@syncfusion/ej2-react-popups'
import { links } from '../data/dummy';
import { useStateContext } from '../contexts/ContextProvider';
const Sidebar = () => {
  const { activeMenu, setActiveMenu } = useStateContext();
  const activeLink = 'flex items-center w-40 gap-5 pl-4 pt-3 pb-2.5 rounded-lg text-white text-md m-2';
  const normalLink = 'flex items-center w-40 gap-5 pl-4 pt-3 pb-2.5 rounded-lg text-lg hover:bg-gray-200 text-gray-700 dark:text-gray-200 dark:hover:text-black m-2';
  return (

      {activeMenu && (<>

          <Link to ="/" onClick={() => { setActiveMenu(false) }} className="flex inline-flex items-center gap-3 ml-3 mt-4
           flex text-xl font-extrabold tracking-tight dark:text-white text-slate-900">
            <SiShopware /> Shoppy
          </Link>

          <TooltipComponent content="Menu" position="BottomCenter">
            <button type="button"
            onClick={() => setActiveMenu(prevActiveMenu => !prevActiveMenu)}
            className="text-xl rounded-full hover:bg-light-grayblock md:hidden">
              <MdOutlineCancel />
            </button>
          </TooltipComponent>

          {links.map((item) => (

                {item.title}

              {item.links.map((link) => (

                <NavLink to={`/${link.name}`}
                key={link.name}
                onClick={() => {}}
                className={({ isActive }) =>
                  isActive ? activeLink : normalLink
                }
                >

                  {link.icon}

                  {link.name}

                </NavLink>

              ))}

          ))}

        </>)}

  )
}

export default Sidebar

This is the index.js

import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';
import App from './App';
import { ContextProvider } from './contexts/ContextProvider';//TODO:HERE
ReactDOM.render(
    <React.StrictMode> //TODO:HERE
    <ContextProvider>
      <App />
    </ContextProvider>
  </React.StrictMode>,//TODO:HERE
    document.getElementById('root')
    );

And the app.js:

import React, { useEffect } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { FiSettings } from 'react-icons/fi'
import { TooltipComponent } from '@syncfusion/ej2-react-popups';

import { Navbar, Footer, Sidebar, ThemeSetting } from './components';
import { ECommerce, Orders, Calendar, Employees, Stacked, Pyramid, Customers, Kanban, Area, Bar, Pie, Financial, ColorPicker, ColorMapping, Editor }
from './pages'
import { useStateContext } from './contexts/ContextProvider';

import './App.css'

const App = () => {
  const { activeMenu } = useStateContext;
  return (

        <BrowserRouter>

                    <TooltipComponent content="Settings" position="Top">
                        <button type="button" className="text-3xl p-3 hover:drop-shadow-xl hover:bg-light-gray text-white "
                        style={{background:'blue', borderRadius: '50%'}}
                        >

                        <FiSettings />
                        </button>
                    </TooltipComponent>

                { activeMenu ? (

                        <Sidebar />

                ) : (

                         <Sidebar />

                )}

                        <Navbar />

                    <Routes>
                        {/*Dashboard*/}
                        <Route path="/" element={<ECommerce />}/>
                        <Route path="/ecommerce" element={<ECommerce />}/>
                        {/*Pages */}
                        <Route path="/orders" element={<Orders />}/>
                        <Route path="/employees" element={<Employees />}/>
                        <Route path="/customers" element={<Customers />}/>
                        {/*Apps*/}
                        <Route path="/kanban" element={<Kanban />}/>
                        <Route path="/editor" element={<Editor />}/>
                        <Route path="/calendar" element={<Calendar />}/>
                        <Route path="/color-picker" element={<ColorPicker />}/>
                        {/*Charts*/}
                        {/*
                        <Route path="/line" element={<Line />}/>
                        <Route path="/area" element={<Area />}/>
                        <Route path="/bar" element={<Bar />}/>
                        <Route path="/pie" element={<Pie />}/>
                        <Route path="/financial" element={<Financial />}/>
                        <Route path="/color-mapping" element={<ColorMapping />}/>
                        <Route path="/pyramid" element={<Pyramid />}/>
                        <Route path="/stacked" element={<Stacked />}/>
                    */}
                    </Routes>

        </BrowserRouter>

  )
}

export default App

this is the link to what I did In case someone wants to see it live:
GitPod Link
this is the main repo:
Main Repo

A: Problem in use of useStateContext, you forget to use as function
App.js
const { activeMenu } = useStateContext();


text:
Q: Codeigniter connecting to multiple databases I have been using these lines of code for connecting multiple databases in codeigniter but getting error. My new db connection is for new_group.
$this->new_group = $this->CI->load->database('new_group', TRUE);
$q = $this->new_group->query("SELECT* FROM mytable ORDER BY id DESC");

Call to a member function database() on a non-object.
Waiting for response. Thanks

A: Try this http://codeigniter.com/forums/viewthread/145901/
$db['new_group']['pconnect'] = FALSE;

I didnt try...

A: remove ->CI from the load command
$this->new_group = $this->load->database('new_group', TRUE);
$q = $this->new_group->query("SELECT* FROM mytable ORDER BY id DESC");

or you have to load the CI object first:
$this->CI =& get_instance();
$this->new_group = $this->CI->load->database('new_group', TRUE);
$q = $this->new_group->query("SELECT* FROM mytable ORDER BY id DESC");


text:
Q: Continuous JS Slider For this "photo image" slider, I'm almost there: http://jsfiddle.net/4z4Lok9y/1/
When I get to slide 3 and hit "next" I would like it to return to slide 1.  (Without the jumping through slide 2, the "jerky motion).
Same for when I'm on slide 1 and hit "prev" I would like to go to slide 3 without the jumping around.
What is the minimal, easiest way to fix my jsfiddle for this motion?
$(document).ready(function(){
    var slides = $('.js-slide');
    var i = 0;
    $('.navigation a.nav-right').click(function(){
    i = ++i % slides.length;
    $('.slide-wrapper').animate(
    {
        'left' : -(slides.eq(i).position().left)},300);
    });
    $('.navigation a.nav-prev').click(function(){
    i = --i % slides.length;
    $('.slide-wrapper').animate(
    {
        'left' : -(slides.eq(i).position().left)},300);
    });
});

Thanks,

A: maybe like this http://jsfiddle.net/4z4Lok9y/2/
$(document).ready(function(){
        var slides = $('.js-slide');
        var i = 0;
        $('.navigation a.nav-right').click(function(){
            i = ++i % slides.length;

            if(i==0)
            {
                var l=0
                $('.slide-wrapper').css('left',l);
                return;
            }

            $('.slide-wrapper').animate({
                'left' : -(slides.eq(i).position().left)},300);
        });

        $('.navigation a.nav-prev').click(function(){
            i = --i % slides.length;

            if(i==-1)
            {
                var l=-slides.eq(i).position().left
                $('.slide-wrapper').css('left',l);
                return;
            }

            $('.slide-wrapper').animate({
                'left' : -(slides.eq(i).position().left)},300);
            });

});

A: I'm assuming you want it to animate between the first and last slide, but do not show the slides in between. This allows you to have as many slides as you want (within reason), and still keep the smooth animation effect.
To do this you need to hide the slides in between and then animate. Then directly after the animation un-hide all the slides.
JSFiddle Demo
$(document).ready(function(){
        var slides = $('.js-slide');
        var i = 0;
        $('.navigation a.nav-right').click(function(){
            i = ++i % slides.length;

            //if we're going from the last slide to the first, hide all the slides
            //and re-position the slide-wrapper
            if (i ==0) {
                $('.module-body').not(':first').not(':last').css('display','none');
                $('.slide-wrapper').css('left', -(slides.eq(-1).position().left));
            }

            $('.slide-wrapper').animate(
            {
                'left' : -(slides.eq(i).position().left)
            },300, function() {
                //After we finish animating be sure to show the slides again
                //you could wrap this in a if statement if you wanted, to only try displaying
                //the slides if i is 0. Might save a bit, but for the example I didn't bother with
                //optimizations.
                $('.module-body').not(':first').not(':last').css('display','block');
            });
        });
        $('.navigation a.nav-prev').click(function(){
            i = --i % slides.length;

            if (i == -1) {
                $('.module-body').not(':first').not(':last').css('display','none');
                $('.slide-wrapper').css('left', -(slides.eq(0).position().left));
            }

            $('.slide-wrapper').animate(
            {
                'left' : -(slides.eq(i).position().left)
            },300, function() {
                $('.module-body').not(':first').not(':last').css('display','block');
                if (i == -1) {
                    $('.slide-wrapper').css('left', -(slides.eq(-1).position().left));
                }
            });
        });
});


text:
Q: Tell Linux what to use swap for I am using Ubuntu 20.04 Server edition.
I have a 512GB of RAM, with about 130GB typically used for a process running on the machine. I also have two ramdisks (tmpfs) both configured as 500GB.
As tmpfs disks expand and contract the amount of RAM they use, depending on how full they are, typically the ramdisks use very little maybe 200GB in total.
I have swap on a fast NVMe drive, about 1000GB. Occasionally, for brief periods of time the usage of RAM spikes, just for a few seconds.
During these moments, how do I tell Linux it should ALWAYS give the ram to the process and use the swap for the drives?

A: To the best of my knowledge (and FelixJN's link seems to agree), all things in RAM are equally swappable, and the decision what to swap is made on freshness, not on type of data. My guess is that this is a good heuristic, even for your use case!
However, you can trick around, a bit, at least.
Assuming your 512GB RAM machine is a NUMA machine:
You can assign (see man tmpfs:mpol) your tmpfs to specific node's memory, and will at least concentrate all the memory on one node.
Honestly, though: instead of tmpfs'ing 200 GB (!) of data, wouldn't be putting that directly on SSD, but using very large file system buffers and very low pressure to flush these to storage work? The moment your processes run out of memory, the kernel will start flushing the buffers to SSD, and throttling access to the files that you formerly put into tmpfs, which implements what you want: your temporary files get stored onto SSD when memory pressure is high, and gets handled in RAM if there's plenty of free memory.


text:
Q: What is the most efficient way to sum all columns whose name starts with a pattern? My goal is to sum all values in columns that start with the prefix skill_ in a data.table. I would prefer a solution using data.table but I am not picky.
My solution up to now:
> require(data.table)
> DT <- data.table(x=1:4, skill_a=c(0,1,0,0), skill_b=c(0,1,1,0), skill_c=c(0,1,1,1))
> DT[, row_idx := 1:nrow(DT)]
> DT[, count_skills :=
          sapply(1:nrow(DT),
                 function(id) sum(DT[row_idx == id,
                                     grepl("skill_", names(DT)), with=FALSE]))]

> DT
   x skill_a skill_b skill_c row_idx count_skills
1: 1       0       0       0       1            0
2: 2       1       1       1       2            3
3: 3       0       1       1       3            2
4: 4       0       0       1       4            1

But this becomes very slow when DT is very large. Is there a more efficient way to do this?

A: Solution using data.table and .SDcols.
require(data.table)

DT <- data.table(x=1:4, skill_a=c(0,1,0,0), skill_b=c(0,1,1,0),
                 skill_c=c(0,1,1,1))

DT[, row_idx := 1:nrow(DT)]

DT[, count_skills := Reduce(`+`, .SD), .SDcols = patterns("skill_")]
DT

A: A question about efficiency and performance always deserves benchmarks...
The size of your data is important as growth rate makes a huge difference...

Relative Benchmark Timings between 2^4 and 2^24.
Sizes along floor( 2^logb(10^( seq( 4, 24, .5 ) ), 10 ) )
Excerpt of benchmarks at 1 million rows...
## Unit: milliseconds
##             expr    min     lq median    uq   max neval
##    dplyr.sol(DT) 21.803 50.260 51.765 52.45 73.30   100
##  rowSums.sol(DT) 20.759 50.224 51.418 52.56 96.28   100
##   SDCols.sol(DT)  7.250  8.916 37.699 38.50 52.69   100
##     eval.sol(DT)  6.883  7.007  7.916  9.45 50.91   100

eval.sol is an answer that takes advantage of data.table's handling of expressions, in the below source...
library(compiler)
library(data.table)
suppressMessages(library(dplyr))
library(microbenchmark)

buildDT <- function(reps) {
  data.table(x=seq_len(reps*4),
               skill_a=rep(c(0,1,0,0),reps),
               skill_b=rep(c(0,1,1,0),reps),
               skill_c=rep(c(0,1,1,1),reps))
}

OP.sol <- function(DT) {
  DT[, row_idx := 1:nrow(DT)]
  DT[, count_skills :=
          sapply(1:nrow(DT),
                 function(id) sum(DT[row_idx == id,
                                     grepl("skill_", names(DT)), with=FALSE]))]
}

dplyr.sol <- function(DT)
  DT %.% select(starts_with("skill_")) %.% rowSums()

SDCols.sol <- function(DT)
  DT[, Reduce(`+`, .SD),
     .SDcols = grep("skill_", names(DT), value = T)]

rowSums.sol <- function(DT)
  rowSums(DT[,grep("skill_", names(DT)),with=FALSE])

eval.sol <- function(DT) {
  cmd <- parse(text=paste(colnames(DT)[grepl("^skill_", colnames(DT))],collapse='+') )
  DT[,eval(cmd)]
}

DT <- buildDT(1)
identical(OP.sol(DT)$count_skills, dplyr.sol(DT))

## [1] TRUE

identical(OP.sol(DT)$count_skills, rowSums.sol(DT))

## [1] TRUE

identical(OP.sol(DT)$count_skills, SDCols.sol(DT))

## [1] TRUE

identical(OP.sol(DT)$count_skills, eval.sol(DT))

## [1] TRUE

DT<-buildDT(2500)
nrow(DT)

## [1] 10000

microbenchmark( # OP.sol(DT), forget this method.
                dplyr.sol(DT),
                rowSums.sol(DT),
                SDCols.sol(DT),
                eval.sol(DT),
                times=100)

## Unit: microseconds
##             expr   min    lq median    uq   max neval
##    dplyr.sol(DT) 760.1 809.0  848.2 951.5  2276   100
##  rowSums.sol(DT) 580.5 605.3  627.6 745.7 28481   100
##   SDCols.sol(DT) 559.8 610.5  638.8 694.0  2016   100
##     eval.sol(DT) 636.4 677.7  692.4 740.5  2021   100

DT<-buildDT(25000)
nrow(DT)

## [1] 100000

microbenchmark( # OP.sol(DT), forget this method.
                dplyr.sol(DT),
                rowSums.sol(DT),
                SDCols.sol(DT),
                eval.sol(DT),
                times=100)

## Unit: milliseconds
##             expr   min    lq median    uq   max neval
##    dplyr.sol(DT) 2.668 3.744  4.045 4.573 33.87   100
##  rowSums.sol(DT) 2.455 3.339  3.756 4.235 34.19   100
##   SDCols.sol(DT) 1.253 1.401  2.179 2.392 31.72   100
##     eval.sol(DT) 1.294 1.427  2.116 2.484 32.02   100

DT<-buildDT(250000)
nrow(DT)

## [1] 1000000

microbenchmark( # OP.sol(DT), forget this method.
                dplyr.sol(DT),
                rowSums.sol(DT),
                SDCols.sol(DT),
                eval.sol(DT),
                times=100)

## Unit: milliseconds
##             expr    min     lq median    uq   max neval
##    dplyr.sol(DT) 21.803 50.260 51.765 52.45 73.30   100
##  rowSums.sol(DT) 20.759 50.224 51.418 52.56 96.28   100
##   SDCols.sol(DT)  7.250  8.916 37.699 38.50 52.69   100
##     eval.sol(DT)  6.883  7.007  7.916  9.45 50.91   100

identical(dplyr.sol(DT), rowSums.sol(DT))

## [1] TRUE

identical(dplyr.sol(DT), SDCols.sol(DT))

## [1] TRUE

identical(dplyr.sol(DT), eval.sol(DT))

## [1] TRUE

A: Here is a dplyr solution:
library(dplyr)

DT %>% mutate(count = DT %>% select(starts_with("skill_")) %>% rowSums())

A: Why not to use rowSums, It is generally efficient:
DT[, rowSums(.SD), .SDcols=patterns("skill_")]


text:
Q: Error of using epsfig I having an error below

\begin{figure}[ht!]
\begin{minipage}[h]{1.08\columnwidth}
\centering
 \centerline{\epsfig{figure/test123.eps,width=1\columnwidth}}
    \end{minipage}
    \end{figure}

A: The actual error message is because you have the incorrect syntax for \epsfig the image name should be given as file=figure/test123.eps and you have omitted the file= key.
However epsfig was written just to help convert documents that were old at the time (1993) to standard latex there is no reason to use it now.
Also minipage does not have an [h] option (unknown options are silently ignored) but you don't need a minipage here anyway as the figure environment already acts as a containing box, so you just need:
\begin{figure}[htp]
\includegraphics[width=\columnwidth]{figure/test123}
\end{figure}


text:
Q: Where does the thumb/handle/button in TrackBar come from? When I have a Forms.TrackBar (aka "Slider") in a Window that is shown with a "Windows Classic" desktop, the old gray pointy thumbs are rendered.
When I start the same application with Aero activated, it renders the thumb in the selected Aero style.
For the case where VisualStyles are enabled (Aero), there is
TrackBarRenderer.DrawRightPointingThumb
for example, which renders the thumb accoring to the new styles engine.
Without VisualStyles, one can use ControlPaint methods to draw certain gui elements, but no the thumb for a slider.
My questions now are: Does anyone know where the classic slider thumb is located? Is it a Bitmap or does it get painted in some OnPaint code? Why is there no method to paint it with ControlPaint?
Maybe there is something special about this piece of grafix, but I can't see why.


text:
Q: How to change the structure of a table if a variable is null I'm selecting a table from a stored procedure which returns different columns if one of my variables is null vs. when it isn't.  How do I declare a table differently based on one of my inputs?  The code below communicates what I'm trying to do, but I get an error that I'm declaring the table twice if I try to do it this way.
IF @Input IS NOT NULL BEGIN
DECLARE @tbl AS TABLE (
    Var1 FLOAT,
    Var2 DATETIME,
    VAR3 INt,
    ...
)
END
ELSE
DECLARE @tbl AS TABLE(
    Var1 INT,
    Var2 FLOAT,
    Var3 DATETIME,
    ...
)

A: Use two different table variables ... @stage  ,  @stage1 .

A: This is the only way I can think of to do what you're after, and it isn't friendly. You need to jump scope to declare the same variable table:
DECLARE @Input VARCHAR(5),@TableFields VARCHAR(1000)
SET @Input = NULL
BEGIN
IF @Input IS NOT NULL
 SET @TableFields = 'Var1 FLOAT,Var2 DATETIME,VAR3 INt'
ELSE
 SET @TableFields = 'Var1 INT,Var2 FLOAT,Var3 DATETIME'
EXEC ('DECLARE @tbl AS TABLE ('+@TableFields+')
      INSERT INTO @tbl VALUES (''1'','''','''')
      SELECT * FROM @tbl

    ')
END

Easier to use 2 table variables and point to each based on your IF logic, imo.


text:
Q: Getting migration Errors I am getting migration errors.i tried deleting my previous migrations.error tells it's failed to write/create migration files errors are give below.
Traceback (most recent call last):
 File "manage.py", line 15, in <module>
 execute_from_command_line(sys.argv)
 File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages         /django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
 File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
 self.execute(*args, **cmd_options)
 File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
  output = self.handle(*args, **options)
  File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
  res = handle_func(*args, **kwargs)
  File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 184, in handle
  self.write_migration_files(changes)
  File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 222, in  write_migration_files
   migration_string = writer.as_string()
  File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/db/migrations/writer.py", line 151, in as_string
    operation_string, operation_imports = OperationWriter(operation).serialize()
   File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/db/migrations/writer.py", line 110, in serialize
_write(arg_name, arg_value)
 File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/db/migrations/writer.py", line 62, in _write
arg_string, arg_imports = MigrationWriter.serialize(item)
 File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/db/migrations/writer.py", line 279, in serialize
  return serializer_factory(value).serialize()
  File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/db/migrations/serializer.py", line 37, in serialize
  item_string, item_imports = serializer_factory(item).serialize()
  File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/db/migrations/serializer.py", line 197, in serialize
  return self.serialize_deconstructed(path, args, kwargs)
  File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/db/migrations/serializer.py", line 85, in serialize_deconstructed
arg_string, arg_imports = serializer_factory(arg).serialize()
File "/home/clifton/Documents/all_venvs/unica/lib/python3.6/site-packages/django/db/migrations/serializer.py", line 149, in serialize
raise ValueError("Cannot serialize function %r: No module" % self.value)
 ValueError: Cannot serialize function <built-in method time of datetime.datetime object at 0x7f1ec51abb40>: No module

A: You had this issue with using time in the custom field definition.
It is than hard to spot as it is not listed in traceback and the error is not raised on the particular model which uses such custom field.
But, try to add auto_now_add=True in the Time field in your model


text:
Q: Running windows server 2012 and windows 8 on VM to do DHCP lab I have windows server 2012 installed on a VM along with windows 8 to do DHCP lab (I am new to networking), but the server cannot assign an IP address to windows 8.
I am using a wireless router.
In the server's powershell, I type ipconfig /all to see my IP address and subnet mask and my default gateway,
which is IP address:

10.0.2.15    255.255.255.0    10.0.2.2

I went to network to set static IP address the same as above and the preferred DNS server is 10.0.2.15.
Then I create a DHCP range: 10.0.2.100 to 10.0.2.200 and DNS server is and I can see my scope in the DHCP view.
I boot up windows 8 on my VM to see it works.
I go back to server to refresh the address release but nothing happens.
In windows 8 , I command prompt the ipconfig /all

Ipaddress : 10.0.2.15 (which is server address?) subnet mask: 255.255.255.0 default gateway: 10.0.2.2 DNS server : 192.168.1.1

What am I doing wrong? Is the problem with my DNS configuration?

A: Hmm...It's not quite clear what steps you took to set up your server :(.
Exactly why is your DNS server (192.168.1.1) in a different Network? Are you using a relay Agent?
I will assume you have already installed DHCP server role and feature and
hence have DHCP manager up and running.
Go through the checklist below.

*

*did you activate the scope?

*did you specify the domain name server (006) IP and  Router (003) IP?

*did you check the 'Address Lease' column to see if DHCP is leasing any Add?

*did you make sure DHCP guard is not enabled?

Install Network monitor to view DHCP transaction between Client and Server.
You should try runnning ipconfig /release and ipconfig /renew on client instead of server.
The site link below might also help.
https://technet.microsoft.com/en-us/library/hh831538.aspx

A: Since DHCP server is using broadcast method to release IP address, you might run into the situation where you have more than 1 DHCP server in your network. Run the IPCONFIG /ALL again to make sure you got the IP from the right DHCP server.


text:
Q: RabbitMQ delayed exchange plugin loads and resources We are using rabbitmq (3.6.6) to send analysis (millions) to different analyzers. These are very quick and we were planning on use the rabbit-message-plugin to schedule monitorizations over the analyzed elements.
We were thinking about rabbitmq-delayed-exchange-plugin, already made some tests and we need some clarification.
Currently:

*

*We are scheduling millions of messages

*Delays range from a few minutes to 24 hours

*As previously said, these are tests, so we are using a machine with one core and 4G of RAM which has also other apps running on it.

What happened with a high memory watermark set up at 2.0G:

*

*RabbitMQ eventually (a day or so) starts consuming 100% (only one core) and does not respond to the management interface nor rabbitmqctl. This goes on for at least 18 hours (always end up killing, deleting mnesia delayed file on disk - about 100 / 200 MB - and restarting).

What happened with a high memory watermark set up at 3.6G:

*

*RabbitMQ was killed by kernel, because of high memory usage (4 GB hardware) about a week after working like this.

*Mnesia file for delayed exchange is about 1.5G

*RabbitMQ cannot start anymore giving to the below trace (we are assuming that because of being terminated by a KILL messages in the delay somehow ended up corrupted or something
{could_not_start,rabbit,
rabbitmq-server[12889]: {{case_clause,{timeout,['rabbit_delayed_messagerabbit@rabbitNode']}},
rabbitmq-server[12889]: [{rabbit_boot_steps,'-run_step/2-lc$^1/1-1-',1,

And right now we are asking ourselves: Are we a little over our heads using rabbit delayed exchange plugin for this volumes of information? If we are, then end of the problem, rethink and restart, but if not, what could be an appropiate hardware and/or configuration setup?

A: RabbitMQ delayed exchange plugin is not properly designed to store millions of messages.
It is also documented to the plugin page

Current design of this plugin doesn't really fit scenarios with a high
  number of delayed messages (e.g. 100s of thousands or millions). See
  72 for details.

Read also here: https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/issues/72

This plugin is often used as if RabbitMQ was a database. It is not.


text:
Q: Followed default options in installation, now have a tiny drive I spent a small fortune (6k) and made five server racks.
I have purchased Five m.2 samsung drives that run nearly at 2250 MBps.
I followed basic directions of the latest ubuntu os when installing it.
Something is wrong, the drives I have installed have 128GB capacity where as this is what my df prints out.
    Filesystem                   1K-blocks     Used Available Use% Mounted on
    udev                          16402568        0  16402568   0% /dev
    tmpfs                          3282848   320392   2962456  10% /run
    /dev/mapper/server5--vg-root  89780400 59506456  25690316  70% /
    tmpfs                         16414228        0  16414228   0% /dev/shm
    tmpfs                             5120        0      5120   0% /run/lock
    tmpfs                         16414228        0  16414228   0% /sys/fs/cgroup
    /dev/sda1                       240972   240139         0 100% /boot
    tmpfs                          3282848        0   3282848   0% /run/user/1000

Note that each machine also has 32 GB ram.
Also some of my info from the start up screen
    System load:  1.16               Processes:           173
      Usage of /:   65.8% of 85.62GB   Users logged in:     0
      Memory usage: 24%

So why is only 89 gigs allocated? How do I increase the partition size? This is a problem as I am starting to run out of disk space across all my machines.

A: Because you only chose to allocate that much when you installed.  To increase it now you can do:
sudo lvresize -L 100g server5-vg/root
sudo resize2fs /dev/server5-vg/root


text:
Q: two different uses of : which is the best solution for accessibility? I want to substitute a piece of text with an image (for example, the word "call" with a phone icon) along some other text in a web page. I want this to work for normal user, without penalizing people who disable css (or don't have css active) and blind people that cannot see images [addendum]. Which is the better solution between the following two ones?
1.

2.     call

with:
.s1 {
    display:inline-block;
    background: url("call.png") no-repeat scroll 0 0 transparent;
    width:24px;
}
.s2 {
    overflow:hidden;
    text-indent: 30px;
}

P.S.: no  alternative, please.

A: Between the two alternatives given, 2 is evidently the right answer, i.e. it is clearly less detrimental to accessibility. When CSS is off, the element reduces to the word "call", whereas alternative 1 reduces to the empty string. There is no guarantee that some software is able to announce the value of the title attribute. Consider, for example, the use of a normal graphic browser in purely visual mode, with no screen reader (with e.g. settings that override page CSS and enforce large enough font suitable for the user).
Even alternative 2 is bad for accessibility. When CSS is enabled, the word "call" is replaced by an icon. But there is no guarantee that the user can see it at all. And there is no way to specify alt text for a background image as you can do for content images. Moreover, what would you use as a phone icon? Most such icons are old-style, like ☎ or ✆, and there are more and more people who never used such a device.

A: SPAN is a very generic element, and should be used when no better markup element is suited for the purpose. In your case, the A (anchor) is just what you need, assuming your "call" element is something the user agent should distinguish from pure text. Even if you don't use href, it's still an anchor - just bind it to a mouse event with JavaScript.
Also, using background images here is misplaced. Background images are for backgrounds. In fact, user agents shouldn't even alow clicking on these as part of active user interface (only as a very secondary interaction) If it's a "Call" button you're after, use CSS content property instead. You are right about img though - that's for images that carry page content, not navigation. I.e. buttons, anchors and the like shouldn't use the img tag. You can also use input or button, depending on context (cannot tell from your question).
If you really want to make your pages accessible, you are on the right track, but I really think the following is a better alternative:
 Call

 .s1
 {
     content: url(call.png);
 }

You can adjust the size of your anchor that is marked with the s1 class using CSS width and height. I would use an SVG instead though. If your graphic is vector, it is definitely a much better idea. Pixels are for photos and pixel-art :-)
If you want to add some text after your element, you can use CSS :after:
.s1:after
{
    content: "Call";
}


text:
Q: Can you find an element of order 10 in $\mathbb{Z}_{31}^{*}$ I'm stuck on that question, because I'm trying to find a simple way to solve it.
I'm pretty sure there exists such elements because the group is cyclic and $|\mathbb{Z}_{31}^{*}| = 30$, hence there exists a sub-group of any order dividing $30$. So I know there is a sub-group of order $10$ and it's cyclic because any sub-group of a cyclic group is cyclic, and it's generator is an elements of order $10$.

Now, how can I proceed from here? How can one find the generator of this sub-group?

A: Let's see: $2^5 = 32 \equiv 1 \mod 31$ so that's no good.  Ah, but then $(-2)^5 \equiv -1 \mod 31$, so $(-2)^{10} \equiv 1$, and the order of $-2$ is not $2$ or $5$...

A: Choose a random element $b\neq 0$ and cube it $\,a = b^{\large 3}.\,$ Then $\,a^{\large 10} = b^{\large 30} = 1.\,$ By the Order Test below,  it follows that $a$ has order $10$ iff $\,a^{\large 2}\neq 1\neq a^{\large 5}.\,$ Keep testing till you find one of order $10$.
Order Test $\,\ \,a\,$ has order $\,n\iff a^{ n} = 1\,$ but $\,a^{n/p} \not= 1\,$ for every prime $\,p\mid n.\,$
Proof $\ (\Leftarrow)\ $ If $\,a\,$ has $\,\rm\color{#c00}{order\ k}\,$ then $\,k\mid n.\,$  If $\,k < n\,$ then $\,k\,$ is proper divisor of $\,n\,$ therefore $\,k\,$ must omit at least one prime $\,p\,$ from the unique prime factorization of $\,n,\,$ hence $\,k\mid n/p,\,$ say $\, kj = n/p,\,$ so $\,a^{n/p} = (\color{#c00}{a^k})^j= \color{#c00}1^j= 1,\,$ contra hypothesis. $\ (\Rightarrow)\ $ By definition of order.


text:
Q: GitLab Community Edition with Google OAuth does not allow main GitLab login page to appear can only use Google to login We have Google OAuth setup in our GitLab CE 8.17.2 instance.  Our organization's users are all Google Accounts so if was an easy decision to set up Google OAuth.
Google OAuth is the only OAuth provider we have set.
We have sent email to external users to sign up for an account in our GitLab CE instance.  Before we turned on/configured OAuth, these external users would see the main GitLab login/register page.
When that external user attempts to access our site, they are presented with the Google Login Page and no way to get around it to have the main Login/Register page appear for GitLab.  There is no "Skip" or "Back" or "Cancel" links to get around this Google login page.  The external user would have to create a Google account just to register which is confusing to me.
We have had external users try different browsers with the cache completely cleared (history, passwords, auto complete forms, etc.) -- Firefox, IE, Chrome -- and they still get this Google login page:

I thought that the main GitLab Login/Register page would appear where you can login or register, and the Google logo would be visible to use as the authenticator.  From how it works for us, you have to have a Google Account to access and cannot get around the Google login page.
Here are the gitlab.rb OAuth settings:
## For setting up omniauth
## see https://docs.gitlab.com/ce/integration/omniauth.html
gitlab_rails['omniauth_enabled'] = true
gitlab_rails['omniauth_allow_single_sign_on'] = ['google_oauth2']
gitlab_rails['omniauth_auto_sign_in_with_provider'] = 'google_oauth2'
gitlab_rails['omniauth_block_auto_created_users'] = false
gitlab_rails['omniauth_auto_link_ldap_user'] = true
# gitlab_rails['omniauth_auto_link_saml_user'] = false
# gitlab_rails['omniauth_external_providers'] = ['google_oauth2']
gitlab_rails['omniauth_providers'] = [
  {
    "name" => "google_oauth2",
    "app_id" => "(the app id)",
    "app_secret" => "(the app secret)",
    "args" => { "access_type" => "offline", "approval_prompt" => "" }
  }
]

If there is a setting we are missing, please let us know.  If not, I get the feeling Google OAuth may not work for us.

A: We commented/remarked out:
gitlab_rails['omniauth_auto_sign_in_with_provider'] = 'google_oauth2'

in our gitlab.rb file.
The section now looks like this:
## For setting up omniauth
## see https://docs.gitlab.com/ce/integration/omniauth.html
gitlab_rails['omniauth_enabled'] = true
gitlab_rails['omniauth_allow_single_sign_on'] = ['google_oauth2']
# gitlab_rails['omniauth_auto_sign_in_with_provider'] = 'google_oauth2'
gitlab_rails['omniauth_block_auto_created_users'] = false
gitlab_rails['omniauth_auto_link_ldap_user'] = true
# gitlab_rails['omniauth_auto_link_saml_user'] = false
# gitlab_rails['omniauth_external_providers'] = ['google_oauth2']
gitlab_rails['omniauth_providers'] = [
  {
    "name" => "google_oauth2",
    "app_id" => "(the app id)",
    "app_secret" => "(the app secret)",
    "args" => { "access_type" => "offline", "approval_prompt" => "" }
  }
]


text:
Q: Простые unit-тесты на проверку пароля Помогите переделать Unit-тест. На форме AdForm  имеется textbox, на который нужно написать два простых unit-теста.
На проверку правильности ввода, и не правильности ввода пароля т.е. два отдельных unit-теста.

Код который хочу тестировать:
 public void button5_Click(object sender, EventArgs e)
        {
            if (maskedTextBox4.Text == "qwerty") // вот это тестить хочу
            {
                AdForm adForm = new AdForm(this);
                adForm.Show();
                this.Hide();
            }
        }

Мой корявый наброски Unit-тестов:
[TestMethod()]
public void login()
{
    AdForm n = new AdForm ();
    string rez = n.insCl("qwerty");
    string exp = "Успешно";
    Assert.AreEqual(rez, exp);
}

[TestMethod]
public void login()
{
    adForm  n = new adForm ();
    n.Text(true,"qwerty");
}

[TestMethod()]
public void login()
{
    AdForm test1 = new AdForm ();
    int a = test1.conv("qwerty");
    Assert.AreEqual(a, 0);
}

P.S. Если кто поможет, буду благодарен. Мне бы один правильный вариант Unit-теста на проверку. Дальше сам. Не ругайтесь.
Код формы:
namespace roza
{
    public partial class AuthForm : Form
    {
        public AuthForm()
        {
            InitializeComponent();
        }

            public void button5_Click(object sender, EventArgs e)
            {
                if (maskedTextBox4.Text == "qwerty") // вот это тестить хочу
                {
                    AdForm adForm = new AdForm(this);
                    adForm.Show();
                    this.Hide();
                }
            }
        }
    }
}

Вот так должна выглядеть работа Unit-теста

Тест-->Выполнить-->Все тесты

A: Вся проблема в том, что вы не отделили классы UI (ваши формочки) и бизнес-логику.
Это очень стандартная ошибка новичков: фигачить бизнес-логику прямо в buttonN_click.
Поэтому сначала вы должны научаться разделять логику предметной области от UI - и потом уже писать юнит-тесты на них.
А пока это у вас не будет юнит-тест, это будет что-то ближе к интеграционному тесты, либо юнит-тест, но хрупкий, который зависит и от UI и от фаз луны и от чего-нибудь ещё.
Посмотрите вот мои примеры юнит-тестов: у меня в проекте ни одной формы нет, а тесты есть.
Как вам нужно поступить в вашем случае. У вас есть некий класс формы, вам нужно объявить, что этот класс имеет зависимость от некоторого класса, реализующего интерфейс проверки пароля.
Было:
public partial class AuthForm : Form
{
    public AuthForm()
    {
        InitializeComponent();
    }

    public void button5_Click(object sender, EventArgs e)
    {
        if (maskedTextBox4.Text == "qwerty") // вот это тестить хочу
        {
            AdForm adForm = new AdForm(this);
            adForm.Show();
            this.Hide();
        }
    }
}

Стало:
public partial class AuthForm : Form
{
    public AuthForm(IPasswordCheckerService passwordCheckerService)
    {
        this.PasswordCheckerService = passwordCheckerService;
        InitializeComponent();
    }

    private IPasswordCheckerService PasswordCheckerService { get; set; }

    public void button5_Click(object sender, EventArgs e)
    {
        if (this.PasswordCheckerService.IsPasswordValid(maskedTextBox4.Text)) // вот это тестить хочу
        {
            AdForm adForm = new AdForm(this);
            adForm.Show();
            this.Hide();
        }
    }
}

public interface IPasswordCheckerService
{
    bool IsPasswordValid(string password)
}

И вот с этим уже можно работать.
Вы можете создать кучу классов, которые реализуют данный интефейс - от простых, которые возвращают всегда true или которые проверяют что пароль равен какой-либо захардкоженной строке до очень сложных, которые лезут в реестр виндовс, базу данных, облако и т.п.
Вот простой пример класса, реализующего интерфейс:
public class SimplePasswordChecker : IPasswordCheckerService
{
    public bool IsPasswordValid(string password)
    {
        return true;
    }
}

А вот простой тест:
[Test]
public void IsPasswordValid_PasswordMatch_ReturnsTrue()
{
    // Arrange
    var checker = new SimplePasswordChecker();

    // Act
    var result = checker.IsPasswordValid("qwerty");

    // Assert
    Assert.IsTrue(result);
}

[Test]
public void IsPasswordValid_PasswordMismatch_ReturnsFalse()
{
    // Arrange
    var checker = new SimplePasswordChecker();

    // Act
    var result = checker.IsPasswordValid("asdf");

    // Assert
    Assert.IsFalse(result);
}

Разумеется, этот тест "не пройдёт". Как и полагается в TDD мы сначала написали красный тест, потом исправляем код класса SimplePasswordChecker на тот, который пройдёт тест.
Получившиеся классы никак не завязаны на то, какой у вас интерфейс - сегодня это winforms, завтра wpf, веб или мобильное приложение. А бизнес-логика остаётся отдельным проектом в решении, которое не имеет никаких зависимостей. Поэтому все эти классы бизнес-логики сразу отселяйте в отдельный проект и начинайте структурировать своё приложение - это и есть архитектура приложения, когда у вас слои разделяют обязанности, а не валят всё в одну кучу.
PS Как передавать зависимость на конструктор - оставляю вам на самостоятельную проработку. В идеале вообще такие вещи делаются при помощи DI.

A: Допустим, у вас есть сервис для проверки пароля
public class LoginService
{
    public bool Login(string secret)
    {
        return secret == "qwerty";
    }
}

И вы используете его на своей форме
public class LoginForm : Form
{
    LoginService _loginService;

    public LoginForm(LoginService loginService)
    {
        _loginService = loginService;

        var passwordBox = new TextBox();
        var loginButton = new Button() { Text = "Login", Top = 50 };

        loginButton.Click += (sender, args) =>
        {
            var text = passwordBox.Text;
            if (loginService.Login(text))
                MessageBox.Show("Login sucessed");
            else
                MessageBox.Show("Login failed");
        };

        this.Controls.Add(passwordBox);
        this.Controls.Add(loginButton);
    }
}

Создание формы выглядит так:
var service = new LoginService();
var form = new LoginForm(service);
form.ShowDialog();

Результат выглядит так:

Тесты писать надо будет для сервиса, так как только он содержит логику, определяющую, правильный был передан пароль или нет. Пример 2 тестов - позитивный и негативный:
[TestMethod()]
public void login_failed()
{
    var loginService = new LoginService();
    var actual = loginService.Login("wrong password");
    var expected = false;
    Assert.AreEqual(actual, expected);
}

[TestMethod()]
public void login_sucessed()
{
    var loginService = new LoginService();
    var actual = loginService.Login("qwerty");
    var expected = true;
    Assert.AreEqual(actual, expected);
}


text:
Q: Entity Framework LINQ - Using additional Where clause with Join significantly slows down query The addition of the last line slows requests from a second to 5 seconds plus, and making requests seconds apart causes hangs of over 10 seconds:
from b in db.Books
join u in
    (from x in db.UsersBooks where x.UserID == userID select x) on b.ID equals u.BookID into gj
from subpet in gj.DefaultIfEmpty()
select new
{
    ID = b.ID,
    BookName = b.Name,
    UsersRating = subpet.Rating,
    UsersComment = subpet.Comment,
    Awards = db.Awards.Where(a => (a.bookID == b.ID))
};

I'm considering returning the Awards using a separate API call for each book, though this seems a bit ridiculous, is such a hang expected with this kind of query?


text:
Q: How can I block the user from using the page while ASP.NET MVC Ajax unobtrusive form is loading? When you using MVC Ajax in a razor view like this
@using (Ajax.BeginForm("Something", new { id = Model.Id }, new AjaxOptions
{
    UpdateTargetId = "something + Model.Id,
    InsertionMode = InsertionMode.ReplaceWith,
    LoadingElementId = "loading"
}))
{
    Html.RenderPartial("Something", foto);
}

How can I create in bootstrap a overlay to show progress and prevent the user to use the page while the page is loading?

A: You can create a hidden bootstrap overlay and modal with infinite loading progressbar like this for example:

Processando...


text:
Q: Как правильно создать функцию Delphi Я хочу написать 10 функций в отдельном .pas файле, а потом вызывать их по мере необходимости. Делаю так:
unit Unit5;

interface

uses
  System.SysUtils, System.Classes, myTypes;

type
  RGetInfo = record
    function GetGroups(ClientName: String): XGroups;
    function GetLanguages(ClientName: String): XLanguages;
    function GetSettings(ClientName: String): XSettings;
  end;

implementation

...
end.

Вызываю так:
var
  GetInfo: RGetInfo;
  Groups: XGroups;
begin
  Groups := GetInfo.GetGroups('Client1');

Может есть, более грамотный, способ? Например вместо record.

A: Статические методы класса:
RGetInfo = class
public
  class function GetGroups(ClientName: String): XGroups;
  class function GetLanguages(ClientName: String): XLanguages;
  class function GetSettings(ClientName: String): XSettings;
end;

var
  Groups: XGroups;
begin
  Groups := RGetInfo.GetGroups('Client1');

или просто отдельные функции:
interface

  function GetGroups(ClientName: String): XGroups;
  function GetLanguages(ClientName: String): XLanguages;
  function GetSettings(ClientName: String): XSettings;

implementation

function GetGroups(ClientName: String): XGroups;
begin
  result := ...
end;

var
  Groups: XGroups;
begin
  Groups := GetGroups('Client1');


text:
Q: Integrate Fabric Android app With iOS App in Digit When Integrating two apps it's essential to add Digit Key and secret key. In swift there is a function to do this like :-
 // Swift
 Digits.sharedInstance().startWithConsumerKey("your_key", consumerSecret: "your_secret")

So I searched in the documentation to find the equivalent code for the android. But didn't find the code yet. So how can I ad iOS app Digits secret key and consumer key in my android app ?

A: I asked this from the Fabric team.Problem is that they didn't clearly mention that we can use digit key and secret in TwitterAuthConfig. and they told me :-

you should use your Twitter or Digits consumer key and secret in TwitterAuthConfig("consumerKey", "consumerSecret")
  I'll let the team know that this was confusing.

So you can simply add your Digit consumer key and consumer secret in here :-
TwitterAuthConfig authConfig =  new TwitterAuthConfig("consumerKey", "consumerSecret");
Fabric.with(this, new TwitterCore(authConfig), new Digits());


text:
Q: tweaking jquery-ui menu widget Working on making a very standard dropdown menu with the new jquery ui 1.9 menu widget, but having some problems due to the newness of the widget and the presence of only a single extremely basic example at jqueryui.com
Specifically, can anyone here help me to:

*

*Initialize a widget with no icons for submenus?  (Default is a right-facing carat and I can't get rid of it)

*Make a menu where user has to click on the top menu item (as opposed to just hovering) to make the submenu appear?  Any deeper submenus should then expand when the user's pointer hovers over them.  This is typical dropdown behavior, e.g., user clicks "edit" to make options appear like "select" or "undo", but any further choices under (for example) "select" would apper just by hovering over "select". I hope that's clear.
Thanks

A: I don't know how to do the second part of your question but I can answer the first question.
You can change the default icon by setting the icon option of the menu option.
First add a class to your CSS file like this.
.no-icon { display:none;}

Then set the icon option when you create the menu.
$( "#menu" ).menu(
    { icons: { submenu: "no-icon" } }
);

You won't have any icons.
Here is a fiddle


text:
Q: Implementing rebate Classic scenario, where an order has order lines.
The client wants to be able to apply a rebate to the entire order, that is either a fixed amount or a percentage.
What would be the best way to implement that?
I am thinking storing two fields on the order-object:

*

*Rebate fixed amount

*Rebate percentage

And then I can calculate the total rebate - and make the rebate an order line, that I re-calc every time the rebate-fields or order lines are changed.
Caveats, hints, best practices?

A: Take a look into using something like the composite pattern.
The rebates should not be stored within the objects themselves but should be applied as an external entity. Think about providing enough flexibility for realistic changes.

A: There's more flexibility in keeping the rebate logic separate from the order. For example, business rules might change to have a more flexible rebate strategy, e.g. rebates only apply to some order lines based on whether there is a promotion for those items. That's more akin to a strategy pattern (which might or might not be overkill for your scenario and business environment).
In that scenario, the order would have a foreign key into a rebate table which identified the rebate strategy and any associated data such as percentage or fixed amount.

A: Did you think of adding rebates to all order lines. If no rebate - it`s a zero rebate. Any rebate can be added.
Pattern you should use in this case depends on how are you going to use rebates. If single rebate on the order - strategy is very well.
If rebates can work with each other (rebate for first buy, 10000 client and discount card) you should look at decorator as other way you`ll be have to implement as much strategies as rebates combination.


text:
Q: The configuration section 'entityFramework' cannot be read because it is missing a section declaration I've been working on this project for quite a while. But now it just crashed after I added Identity. The error is as according:
The configuration section 'entityFramework' cannot be read because it is missing a section declaration
It's some IIS error I think, because that's what the page is saying.
My web.config file:
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\WebFormsIdentity.mdf;Initial Catalog=WebFormsIdentity;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v12.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

I hope someone can help me resolving this problem.. Thanks in advance!

A: You are missing a section as the error says:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
   type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
 </configuration>

https://msdn.microsoft.com/en-us/data/jj556606.aspx


text:
Q: Php dynamic subpage and nginx address rewriting I created a website based on ajax tech. and now I want to achieve similar effects using php (nginx). The problem is I don't want to create (even dynamically) .php documents for every user or offer or anything. I have templates for every pages like userTemplate.php and it works fine with $_GET method, which fill it with proper data BUT the address is not acceptable, hoe can I convert that requestexample.com/userTemplate.php?id=1 to example.com/users/1. I tried with rewriting it in config files, but then it redirects me to the path /users/1 which is ofc wrong... Is it possible? Please I've already spent hours looking for any answer.

A: Try this:
location / {
    try_files $uri $uri/ =404;
}
location ~* /users/(\d+) {
    try_files $uri /userTemplate.php?id=$1;
}
location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    #
    # With php5-cgi alone:
    # fastcgi_pass 127.0.0.1:9000;
    #
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}

If you want to go for an alternative approach, have a look at Creating NGINX Rewrite Rules. If you need different, more complicated regular expressions, perhaps start here.


text:
Q: Why Wordpress AJAX returns undefined however it works fine when I add static url instead of dynamic function? Code from functions.php
function university_files()
{
   wp_localize_script('main-university-js', 'universityData', array(
        'root-url' => get_site_url()
    ));
};

add_action('wp_enqueue_scripts', 'university_files');

Code from JS
getResults() {
    $.getJSON(
      universityData.root_url +
        "/wp-json/wp/v2/posts?search=" +
        this.searchField.val(),
      (posts) => {
        this.resultsDiv.html(`

General Information

          ${
            posts.length
              ? `<ul class="link-list min-list">`
              : `No General Information Marched your search`
          }
            ${posts
              .map(
                (item) =>
                  `<li><a href="${item.link}">${item.title.rendered}</a></li>`
              )
              .join("")}
          ${posts.length ? `</ul>` : ""}

        `);
        this.isSpinnerVisible = false;
      }
    );
  }

A: Because you have:
universityData.root_url

But you localised:
'root-url' => get_site_url()

root_url != root-url


text:
Q: ASP.NET WebAPI and Angular POST I have a WebAPI controller
public class MyController : ApiController
{
    [HttpPost]
    public SomeResult MyAction(string name, string message)
    {
        return SomeResult.???;
    }
}

I have an angular controller calling this method
$http
    .post("/api/My/MyAction", { name: "bob", message: "hello" })
    .then(function(xhr) { ... }, function(xhr) { ... });

I get this result

Server Error in '/' Application.
The resource cannot be found.

What did I do wrong?
P.S. It's not the URL...It works when I use HttpGet and append the parameters to the query string.

A: I've faced that problem, if you google there are different ways to solve it. One of the easiest requires to use only one input object in you WebApi controller, so in you case just crate a class
public class InputData {
    public string name { get; set; }
    public string message { get; set; }
}

Then change your input to the new create object with [FromBody] prefix (maybe not mandatory, see @ADyson comment)
public SomeResult MyAction([FromBody]InputData inputData)

A: For more than one attribute for post requests, you can use [FromBody] in your controller and make a ViewModel class. Example:
[HttpPost]
        public HttpResponseMessage UpdateNumber([FromBody]UpdateNumberViewModel model)
        {
           //To do business
            return Request.CreateResponse(HttpStatusCode.OK);
        }

UpdateViewModel:
public class UpdateViewModel
    {
        public int Id{ get; set; }
        public string Title{ get; set; }

    }

Angular:
var model = {
                    Id: 1,
                    Title: 'Vai filhão'
                }

    $http.post('/api/controller/updateNumber/',model).then(function () { alert("OK"); }, function () {alert("something wrong"); });

You can see more details about how web api it works here: https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api


text:
Q: view-model to entity binder I have a question that I don't know how to ask it. See; I have an entity like this:
public class Person{
    public int Id {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

and also have a view-model with same properties as entity:
public class PersonModel{
    public int Id {get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

My question is: how can I create a auto convertor for reading properties from one of them, and create a new another one and write it properties from the first? see:
// DAL
public class Repository{
    public void Save(Person person){
        // saving a person entity
    }
}

// BLL
public class Service{
    public void CreatePerson(PersonModel model){
        var person = new Person{
            Id = model.Id,
            FirstName = model.FirstName,
            LastName = model.LastName
        };
        new Repository().Save(person);
    }
}

I have to repeat this code for converting all view-models to entities when I want to pass them from service to repository. I know about explicit and implicit, I don't want to use them. I mean I'm searching a way to auto binding them via reflection and generics. for example something like this:
public class Binder{
    public TOut Bind<TIn, TOut>(TIn inObject){ }
}

Has everybody any idea that where I should start or where can I find some resources to learning this? Thanks in advanced.

A: AutoMapper - Best Way
Look at this. It's perfect for your problem:
AutoMapper
Example:
public User Create(User obj) {
    var rep = UnitOfWork.Create<User>();
    var usr = Mapper.Map(obj, rep.Create());
    rep.Add(usr);

    return usr;
}

If you want to ignore some properties while mapping:
Mapper.CreateMap<User, User>()
    .ForMember(dest => dest.ID, opt => opt.Ignore()) // Dont map the ID.

Reflection - Slow way
If you want to use reflection, then here is an example. But for the record. This is just a small sample how it could work. If it's a Generic Type, an array or something else, it doesn't work!
var modelProperties = this.GetType().GetProperties();
foreach(var prop in usr.GetType().GetProperties()) {
    var thisProp = modelProperties.FirstOrDefault(n => n.Name == prop.Name);
    if(thisProp != null) {
        var value = prop.GetValue(usr, null);
        thisProp.SetValue(this, value, null);
    }
}

A: You can use Extension Methods to copy the properties to another object:
public static class ConvertPersonToPersonModel
{
    public static PersonModel ConvertToPersonModel(this Person person)
    {
        PersonModel p= new PersonModel(); //assign the properties
        p.Id = person.Id;
        p.FirstName = person.FirstName;

        return p;
    }

    public static IEnumerable<PersonModel> ConvertPeopleToPeopleModels(this List<Person> people)
    {
        List<PersonModel> ps= new List<PersonModel>();
        foreach (var person in people)
        {
            ps.Add(ConvertToPersonModel(person));
        }
        return ps.AsEnumerable<PersonModel>();
    }
}

The ConvertPersonToPersonModel() method will now show up on your Person object e.g.
Person p = new Person
p.ConvertToPersonModel();


text:
Q: Why is my print function giving the wrong output in my program to print strings? The expected outcome is for example:
a
word
a sentence

This is the outcome tho:
 aword
word
a sentence

Here's the code:
#include <stdlib.h>
#include <stdio.h>

int main() {
    char letter[1], word[20], sentence[100];

    scanf("%s", letter);

    scanf("%s", word);

    scanf(" %[^\n]s", sentence);

    printf("\n %s", letter);
    printf("\n %s", word);
    printf("\n %s", sentence);

    return 0;
}

A: At least these problems
No width limit
Never use scanf() to read user input into a string lacking a width in the format.  The width should be less than the array count.
char letter[1],word[20],sentence[100];
// scanf("%s", letter);
// scanf("%s", word);
// scanf(" %[^\n]s", sentence);
scanf("%0s", letter);          // "%0s" not valid.  See below
scanf("%19s", word);
scanf(" %99[^\n]s", sentence); // See below also

Buffer too small for "%s"
char letter[1] only big enough for a null string "".
To read 1 character into a string, increase size
char letter[2];
scanf("%1s", letter);

s not needed
s serves no point in " %[^\n]s".  Who or whatever text suggested an s is a poor source of coding in C practice.
// scanf(" %99[^\n]s", sentence);
scanf(" %99[^\n]", sentence);

Check return value
Test the return value from all scanf().
// scanf("%1s", letter);
if (scanf("%1s", letter) != 1) {
  fprintf(stderr, "Failed to read into letter");
  return EXIT_FAILURE;
}


text:
Q: Asp.Net Core 3.0 API app requires restart frequently on IIS Windows Server 2016 I have hosted my Asp.Net Core API project on IIS on Windows Server 2016 and also installed hosting bundle for Asp.Net core apps on that; have to restart my application after few hours. Please help me to solve this.

A: What is the problem? Is there any error message? You need to be more specific on your issue.


text:
Q: openldap give group write access to subtree I have
dn: ou=people,dc=example,dc=com
objectClass: organizationalUnit
ou: people

and group of admins for it:
dn: cn=people-admins,ou=groups,dc=example,dc=com
objectClass: groupOfUniqueNames
cn: admins of people group
uniqueMember: uid=admin1,ou=people,dc=example,dc=com

and I add such rules to allow people-admins add/delete/modify users in people groups
dn: olcDatabase={1}hdb,cn=config
changetype: modify
delete: olcAccess
-
add: olcAccess
olcAccess: to attrs=userPassword,shadowLastChange by self write by dn="cn=admin,dc=example,dc=com" write by anonymous auth by * none
olcAccess: to dn.one="ou=people,dc=example,dc=com" by group.exact=cn=people-admins,ou=groups,dc=example,dc=com write by self write by dn="cn=admin,dc=example,dc=com" write by * none
olcAccess: to dn.base="ou=people,dc=example,dc=com" by group.exact=cn=people-admins,ou=groups,dc=example,dc=com write by self write by dn="cn=admin,dc=example,dc=com" write by * none
olcAccess: to dn.children="ou=people,dc=example,dc=com" by group.exact=cn=people-admins,ou=groups,dc=example,dc=com write by self write by dn="cn=admin,dc=example,dc=com" write by * none
olcAccess: to dn.subtree="ou=people,dc=example,dc=com" by group.exact=cn=people-admins,ou=groups,dc=example,dc=com write by self write by dn="cn=admin,dc=example,dc=com" write by * none
olcAccess: to * by self write by dn="cn=admin,dc=example,dc=com" write by * none

then I try to add new user to people group using credentials of admin1, and got this:
ldapadd -x -H ldap://127.0.0.1:3000/  -D "uid=admin1,ou=people,dc=example,dc=com" -W
dn: uid=test1,ou=people,dc=example,dc=com
objectClass: inetOrgPerson
uid: test1
sn: test
givenName: test1
cn: test test1
displayName: Test1
userPassword: test1
adding new entry "uid=test1,ou=people,dc=example,dc=com"
ldap_add: Insufficient access (50)
        additional info: no write access to parent

Here similar question, but it receive wrong answer, because of dn.entry does not exists in openldap.

A: The problem was that group.exact not work with groupOfUniqueNames.
I solved it by changing this rule:
by group.exact=cn=people-admins,ou=groups,dc=example,dc=com write

to this rule:
by group/groupOfUniqueNames/uniqueMember=cn=people-admins,ou=groups,dc=example,dc=com write

A: If you're just starting out, I recommend switching to using groupOfNames rather than groupOfUniqueNames.
Most systems that interact with OpenLDAP for group membership expect groupOfNames by default, including OpenLDAP itself. While they can generally be modified to use groupOfUniqueNames/uniqueMember (e.g. sssd-ldap ldap_group_member or your own use in OpenLDAP's olcAccess), this will save you from having to adjust the defaults.

There are differences between distinguishedNameMatch, used by member and uniqueMemberMatch used by uniqueMember, but the former is usually sufficient.
$ ldapadd <<EOF
dn: cn=testgroup,ou=groups,dc=example,dc=com
> objectclass: groupofnames
> member: uid=testuser,ou=people,dc=example,dc=com
> member: uid=testuser,ou=people,dc=example,dc=com
> EOF
SASL/GSSAPI authentication started
SASL username: self@EXAMPLE.COM
SASL SSF: 56
SASL data security layer installed.
adding new entry "cn=testgroup,ou=groups,dc=example,dc=com"
ldap_add: Type or value exists (20)
    additional info: member: value #0 provided more than once

$ ldapsearch cn=testgroup
dn: cn=testgroup,ou=groups,dc=example,dc=com
objectClass: groupOfNames
objectClass: posixGroup
cn: testgroup
gidNumber: 12345
member: uid=testuser,ou=people,dc=example,dc=com

$ ldapmodify <<EOF
dn: cn=testgroup,ou=groups,dc=example,dc=com
add: member
member: uid=testuser,ou=people,dc=example,dc=com
EOF

SASL/GSSAPI authentication started
SASL username: self@EXAMPLE.COM
SASL SSF: 56
SASL data security layer installed.
modifying entry "cn=testgroup,ou=groups,dc=example,dc=com"
ldap_modify: Type or value exists (20)
    additional info: modify/add: member: value #0 already exists


text:
Q: How to use MPI to organize asynchronous communication? I plan to use MPI to build a solver that supports asynchronous communication. The basic idea is as follows.
Assume there are two parallel processes. Process 1 wants to send good solutions it finds periodically to process 2, and ask for good solutions from process 2 when it needs diversification.

*

*At some point, process 1 uses MPI_send to send a solution to process 2. How to guarantee there is an MPI_Rev matching this MPI_Send, since this send is triggered dynamically?

*When process 1 needs a solution, how can it send a request to process 2, and process 2 will notice its request in time?

A: There are three ways to achieve what you want, although it is not truly asynchronous communication.
1) Use non-blocking send/recvs. Replace your send/recv calls with irecv/isend and wait. The sender can issue an isend and continue working on the next problem. At some point, you will have to issue a mpi-wait to make sure your previous send was received. Your process2 can issue a recv ahead of time using irecv and continue doing its work. Again, at some point you will call mpi-wait to make sure your irecv was received. this may be a bit cumbersome if I understand you requirement correctly.
2) A Elegant way would be to use One-Sided communication. MPI_Put, Get.
3) Restructure your algorithm in such a way that at certain intervals of time, process 1 & 2 exchange information and state.

A: Depending on the nature of the MPI_* function you call, the send will block until a matching receive has been called by another process, so you need to make sure that's going to happen in your code.
There are also non-blocking function calls MPI_Isend f.ex, which gives you a request-handle which you can check on later to see if the process' send has been received by a matching receive.
Regarding your issue, you could issue a non-blocking receive (MPI_Irecv being the most basic) and check on the status every n seconds depending on your application. The status will then be set to complete when a message has been received and is ready to be read.
If it's time sensitive, use a blocking call while waiting for a message. The blocking mechanism (in OpenMPI at least) uses a spinning poll however, so the waiting process will be eating 100% cpu.


text:
Q: Rename multiple files in folder I have some files in my folder like:
asd55.png
qwe55.png
zxc55.png

I want to remove the 55 and get the result:
asd.png
qwe.png
zxc.png

I tried with:
ren *55.png *.png

but doesnt work.

A: Test this on a folder of test files.
@echo off
for %%a in (*.png) do ren "%%a" "???%%~xa"

A: I solved this finally looking the example and applied to my case:
@echo off
setlocal enabledelayedexpansion

for /r %%G in (*55.*) do (
set new=%%~nG
set new=!new:~0,-2!
ren "%%~G" "!new!%%~xG"
)


text:
Q: AES encryptions/decryptions differs between Python and C#? i am using AES encryption/decryption in Python3 using the pip pycryptodome package on Linux (Debian, ubuntu).
now i needed to implement the same program for Windows by using C#.
but the encryption results differs between the two platforms (slightly).

*

*AES encryptions from Python (Linux) cannot decrypted on C# (Windows),
i get an exception because of wrong padding

*AES encryptions from C# (Windows) cannot always decrypted on Python (Linux).

*but it is always possible to decrypt encryptions from the same programming language when it was encrypted with the same language.

EDIT: i installed python 3.11 and pip pycryptodome on the windows system and there the test.py parogram behaves the same as on the linux system. but using python there is no option. i have to stick on C# on the windows system.
AES encryptions/decryptions on python:
t:'TEST+++TEST+++TEST' -> e:'dMTh7CVOf/1PkhTEWRsnv68j'     -> d:'TEST+++TEST+++TEST'
AES encryptions/decryptions on C#:
t:'TEST+++TEST+++TEST' -> e:'dMTh7CVOf/1PkhTEWRsnv68jdQ==' -> d:'TEST+++TEST+++TEST'
what i am doing wrong here?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import base64

# pip install pycryptodome
from Crypto.Cipher import AES

KEY   = b'\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41'
IV    = b'\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41'
MODE  = AES.MODE_CFB
BLOCK = 128

def en(plain_text):
    crypto = AES.new(key=KEY, mode=MODE, iv=IV)
    crypto.block_size = BLOCK
    b_plain = plain_text.encode('utf-8')
    b_encrypted = crypto.encrypt(b_plain)
    base64_encrypted_text = base64.b64encode(b_encrypted).decode('utf-8')
    return base64_encrypted_text

def de(base64_encrypted_text):
    crypto = AES.new(key=KEY, mode=MODE, iv=IV)
    crypto.block_size = BLOCK
    b_encrypted = base64.b64decode(base64_encrypted_text)
    b_plain = crypto.decrypt(b_encrypted)
    plain_text = b_plain.decode('utf-8')
    return plain_text

t = 'TEST+++TEST+++TEST'
e = en(t)
d = de(e)
print(f"t:'{t}' -> e:'{e}' -> d:'{d}'")
# t:'TEST+++TEST+++TEST' -> e:'dMTh7CVOf/1PkhTEWRsnv68j' -> d:'TEST+++TEST+++TEST'

// C# .NET 6.0 Console
//

using System.Security.Cryptography;

byte[] KEY = { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 };
byte[] IV = { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 };
CipherMode MODE = CipherMode.CFB;
int BLOCK = 128;

string en(string plain_text)
{
    string base64_encrypted_text;
    using (var crypto = Aes.Create())
    {
        crypto.Mode = MODE;
        crypto.BlockSize = BLOCK;
        crypto.Key = KEY;
        crypto.IV = IV;
        using (var s_encrypted = new MemoryStream())
        {
            using (var s_crypto = new CryptoStream(s_encrypted, crypto.CreateEncryptor(KEY, IV), CryptoStreamMode.Write))
            {
                using (var s_plain = new StreamWriter(s_crypto))
                {
                    s_plain.Write(plain_text);
                }
            }
            base64_encrypted_text = Convert.ToBase64String(s_encrypted.ToArray());
        }
    }
    return base64_encrypted_text;
}

string de(string base64_encrypted_text)
{
    string plain_text;
    using (var crypto = Aes.Create())
    {
        crypto.Mode = MODE;
        crypto.BlockSize = BLOCK;
        crypto.Key = KEY;
        crypto.IV = IV;
        var b_encrypted = Convert.FromBase64String(base64_encrypted_text);
        using (var s_encrypted = new MemoryStream(b_encrypted))
        {
            using (var s_crypto = new CryptoStream(s_encrypted, crypto.CreateDecryptor(KEY, IV), CryptoStreamMode.Read))
            {
                using (var s_plain = new StreamReader(s_crypto))
                {
                    plain_text = s_plain.ReadToEnd();
                }
            }
        }
    }
    return plain_text;
}

var t = "TEST+++TEST+++TEST";
var e = en(t);
var d = de(e);
Console.WriteLine($"t:'{t}' -> e:'{e}' -> d:'{d}'");
// t:'TEST+++TEST+++TEST' -> e:'dMTh7CVOf/1PkhTEWRsnv68jdQ==' -> d:'TEST+++TEST+++TEST'

A: PyCryptoDome correctly implements the CFB(Cipher feedback) mode, where the size of a cipher text is the same as the size of the corresponding plain text and padding is not required. But the System.Security.Cryptography of .NET framework prior to 6.0 does not support encrypting without padding in the CFB mode.
If you are using .NET 6.0 or later, you can disable padding like this(with attribution to 'beta-tester').
string en(string plain_text)
{
    string base64_encrypted_text;
    using (var crypto = Aes.Create())
    {
        crypto.Mode = MODE;
        crypto.Padding = PaddingMode.None;
        byte[] ptBytes = Encoding.UTF8.GetBytes(plane_text);
        using (var s_encrypted = new MemoryStream())
        {
            using (var s_crypto = new CryptoStream(s_encrypted, crypto.CreateEncryptor(KEY, IV), CryptoStreamMode.Write))
            {
                s_crypto.Write(ptBytes);
            }
        }
        Byte[] ctBytes = s_encrypted.ToArray();
        base64_encrypted_text = Convert.ToBase64String(ctBytes);
    }
    return base64_encrypted_text;
}

And if you are using .NET prior to 6.0(including Mono), you can truncate the cipher text like this.
using System.Text;
...
string en(string plain_text)
{
    string base64_encrypted_text;
    using (var crypto = Aes.Create())
    {
        crypto.Mode = MODE;
        byte[] ptBytes = Encoding.UTF8.GetBytes(plane_text);
        using (var s_encrypted = new MemoryStream())
        {
            using (var s_crypto = new CryptoStream(s_encrypted, crypto.CreateEncryptor(KEY, IV), CryptoStreamMode.Write))
            {
                s_crypto.Write(ptBytes);
            }
        }
        Byte[] ctBytes = new Byte[ptBytes.Length];
        Buffer.BlockCopy(s_encrypted.ToArray(), 0, ctBytes, 0, ptBytes.Length);
        base64_encrypted_text = Convert.ToBase64String(ctBytes);
    }
    return base64_encrypted_text;
}

And as a side note, you don't need to set the BlockSize property of a cipher. (For example, the block size of AES algorithm is 128 bit by definition.)

A: thank you @relent95 for the hint.
now it works with setting the crypto.Padding = PaddingMode.None;.
(it was set to PaddingMode.PKCS7 by default)
BTW.: the order of settings are very important.
e.g.: setting the crypto.Mode will alter other settings.
NOTE: this is only working in .NET 6.0.
in .NET 4.7 or .NET 4.8 it is still not working!!!
// C# .NET 6.0 Console
// C# .NET 6.0 WPF App
//

using System.Security.Cryptography;

byte[] KEY = { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 };
byte[] IV = { 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 };
CipherMode MODE = CipherMode.CFB;
PaddingMode PADDING = PaddingMode.None;

string en(string plain_text)
{
    string base64_encrypted_text;
    using (var crypto = Aes.Create())
    {
        crypto.Mode = MODE;
        crypto.Padding = PADDING;
        crypto.Key = KEY;
        crypto.IV = IV;
        using (var s_encrypted = new MemoryStream())
        {
            using (var s_crypto = new CryptoStream(s_encrypted, crypto.CreateEncryptor(KEY, IV), CryptoStreamMode.Write))
            {
                using (var s_plain = new StreamWriter(s_crypto))
                {
                    s_plain.Write(plain_text);
                }
            }
            base64_encrypted_text = Convert.ToBase64String(s_encrypted.ToArray());
        }
    }
    return base64_encrypted_text;
}

string de(string base64_encrypted_text)
{
    string plain_text;
    using (var crypto = Aes.Create())
    {
        crypto.Mode = MODE;
        crypto.Padding = PADDING;
        crypto.Key = KEY;
        crypto.IV = IV;
        var b_encrypted = Convert.FromBase64String(base64_encrypted_text);
        using (var s_encrypted = new MemoryStream(b_encrypted))
        {
            using (var s_crypto = new CryptoStream(s_encrypted, crypto.CreateDecryptor(KEY, IV), CryptoStreamMode.Read))
            {
                using (var s_plain = new StreamReader(s_crypto))
                {
                    plain_text = s_plain.ReadToEnd();
                }
            }
        }
    }
    return plain_text;
}

var t = "TEST+++TEST+++TEST";
var e = en(t);
var d = de(e);
Console.WriteLine($"t:'{t}' -> e:'{e}' -> d:'{d}'");
// t:'TEST+++TEST+++TEST' -> e:'dMTh7CVOf/1PkhTEWRsnv68jdQ==' -> d:'TEST+++TEST+++TEST'


text:
Q: principal curvature of the flat torus I am looking at the Hopf-fibration and I am looking at the preimage of the equator in $\mathbb{S}^2$. I think that I have proved that this is just the flat torus and now I want to calculate the principal curvatures of this torus. My general approach to the problem has been:
I consider $\mathbb{R}^4$ as $\mathbb{C}^2$ and $\mathbb{S}^3$ to be "the unit circle" in this "plane", every point on the circle determines a line through the origion. And the lines through the origion intersects the sphere in a unique circle. Mapping $\mathbb{S^3}$ to the space of lines through the origion gives me an onto map to $\mathbb{C}\mathbb{P}^1$ which I diffeomorphically identify with $\mathbb{S}^2$. The preimage of any point $(z_1:z_2)$ in $\mathbb{S}^3$ is just the circle $\frac{z_1}{z_2}=z$. Hence the preimage of the equator is all circles satisfying $\frac{|z_1|}{|z_2|}=1$, i.e $|z_1|=|z_2|$, hence the preimage is a product of two circles, i.e a torus.
Since my torus is just $S^1\times S^1$ in $\mathbb{C}\times \mathbb{C}$ it is equipped with the product metric, and hence in this case flat.
I am now stuck, here is two ways I would like to go forward:
Calculating the Weingarten map.
Using the parametrization $(e^{i\theta },e^{i\psi })$, what is the normal direction inside of $\mathbb{S}^3$?
I have also tried to look at the normal curvature of curves in $S^1\times S^1$ are these just "circles wrapping around the torus" the smaller ones curving more then the bigger? This way of thinking would give me principal curvature $1$ and something depending on where on the torus I am being $-1$ in "the inner circle"?

A: One (of the possible two ones) unit normal vector of $\mathbb{S}^1 \times \mathbb{S}^1 \subset \mathbb{S}^3$ at the point $(e^{i \theta},e^{i\psi})$ is the vector $$\eta(\theta,\psi) := \frac{(e^{i \theta},-e^{i\psi})}{\sqrt{2}} \, .$$ Indeed, the scalar dot product of two vectors $\mathbb{v} = (v_1,v_2) ,\mathbb{w} = (w_1,w_2) $ in $\mathbb{C}^2$ is given by $$\mathbb{v} \cdot \mathbb{w} = real(v_1 \bar{w_1} + v_2.\bar{w_2}) \,. $$
To see that $\eta(\theta,\psi)$ do the job just notice that the normal space of $\mathbb{S}^1 \times \mathbb{S}^1 \subset \mathbb{C} \times \mathbb{C} =\mathbb{C}^2$ at the point $(\theta,\psi)$ is spaned by the two vectors $$(e^{i\theta},0) \, \, , \, \, (0,e^{i\psi})$$
so you just need to look for a linear combination of this two perpendicular to the normal of the sphere which is the position vector $\mathbf{p} = (e^{i \theta},e^{i\psi})$.


text:
Q: How create a P2P web-chat without any server? is there a way to create a P2P web-chat without any server ?

A: Malte Uble's excellent UniversalComet article does exactly that as a proof of concept. Even works with Iphone and Android phones.

A: Yes, but you must decide on a place to meet.
If your friend send his ip over to you, you can connect. Then you only need to tell some more people to join. After some time you will get bigger and bigger. Then, if some link on the net fail, the cloud will be broken up in two clouds(netsplit). Then everyone need to know how to get back to being "one cloud".
Some one in the cloud always have to play the server, that is done with voting. If all agreed on who is the server, then it's decided. If not agreed, shoot one down and vote again.
You have to host your own web-server to serve up the web-interface, I guess.
I have not tried this. But I think it would work.

A: If you're willing to use Flash, check out Adobe Stratus, which allows for peer to peer data and video streaming. http://labs.adobe.com/technologies/stratus/


text:
Q: Accordion panels I am not good with jQuery. I found the following accordion panel script. This script hides all panels on load and open one when I click on it. However, I want to have all panels open on load and only click the one I want to hide.  don't want to hide all when I click on it.
// accordion
    $('.accordion h5').click(function () {
        $('.accordion h5').removeClass('open');
     // close all slides
        $('.accordion ul ul').slideUp('normal');
        if ($(this).next().is(':hidden') == true) {
            $(this).addClass('open');
            $(this).next().slideDown('normal');
        }
    });
    $('.accordion h5').mouseover(function () {
        $(this).addClass('hover');
    }).mouseout(function () {
        $(this).removeClass('hover');
    });
    $('.accordion ul ul').show();

A: Following should give behavior you want.
 $('.accordion h5').click(function () {
        $(this).toggleClass('open').next().slideToggle();
 }).hover(function(){
       $(this).toggleClass('hover');
 });

Provide some markup if this needs to be modified


text:
Q: ODataController, if the model is incorrect, it gets null on post If there is any wrong property (For example if I send the payload data, Person_ instead of Person), model fully gets as null (Post([FromBody] Request data))
public class Person
{
   public Guid Id { get; set; }

   public string? Firstname { get; set; }

   public string? Lastname { get; set; }
}

public class Request
{
   public Guid Id { get; set; }

   public Guid? Personid { get; set; }

   public virtual Person? Person { get; set; }
}

public IActionResult Post([FromBody] Request data)
{
   ...
}

curl --location --request POST 'https://localhost:7124/v2/request?$expand=Person($select=Id,Firstname,Lastname)/Request&@odata.context=%27https://localhost:7124/v2/$metadata' \
--header 'Content-Type: application/json' \
--data-raw '{
    "Id": "a436677a-fa4b-465e-8e70-211a1a3de8e9",
    "Personid": "be9b53ad-4dfb-4db5-b269-32669f7c4e2d",
    "Person_" : {
        "Firstname": "JOHN",
        "Lastname": "SMITH",
    }
}'

I need to get the model even though some properties not correct according to model schema.
What could be the reason for it being null?

A: The problem is the declaration of Person  in the class Request, It should be public Person Person_ { get; set; }.
You can declare it as public virtual Person? Person_ { get; set; } also if you don't want to change the declaration.
The only catch here is the suffix underscore before Person.
If you don't want to change the declaration then you can use JsonProperty
[JsonProperty("Person_")]
public virtual Person? Person { get; set; }

A: One of the main issues is that the type argument forms a strong contract that the OData subsystem tries to enforce. If the Deserializer cannot match the expected type fully, then it returns null, not a partially constructed object, or an empty object if none of the properties matched.

What you are expecting was a lazy implementation that we often took for granted in previous versions of OData and JSON.Net, but the OData Entity Serializer doesn't work this way any more.

When the argument is null, the ModelState should provide detailed information on the reason for the failure.
OData has support for allowing additional members, it is called Open-Type Support. Similar to the catch all solutions in other deserialization methods, we designate a dictionary to route all un-mapped properties so that you can inspect them after deserialization. This was a good walkthrough in .Net FX but basically we add the property:
public class Request
{
   public Guid Id { get; set; }
   public Guid? Personid { get; set; }
   public virtual Person? Person { get; set; }
   public IDictionary<string, object> DynamicProperties { get; set; }
}

Then in your model builder you need to declare the type as open:
builder.Entity<Request>("request").EntityType.IsOpen();

This is alone is still going to be hard to use though because your additional member is a complex type, so the type cannot be easily resolved automatically.
You could implement your own deserializer, but that is a lot more universal to all of your controllers and endpoints, you should take a little bit more care because it really opens a back door and cancels out a lot of functionality if you don't do it right. In your example the _person is omitted entirely, which might not be your intention.

Other solutions are a bit more permanent and messy, like adding additional properties to your model to capture the input and re-assign it internally. The best advice however is to respond to the client with an adequate error message so that they update the call.

There is another way that we can also cheat by using the JToken type, instead of the expected concrete type. This will universally ingest the payload from the request, then we can use good old JSON.Net to resolve the object:
/// <summary>
/// Inserts a new item into this collection
/// </summary>
/// <param name="item">The item to insert</param>
/// <returns>CreatedODataResult</returns>
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Format | AllowedQueryOptions.Select)]
public virtual async Task<IActionResult> Post([FromBody] Newtonsoft.Json.Linq.JToken x)
//public virtual async Task<IActionResult> Post(TEntity item)
{
    TEntity item = x.ToObject<TEntity>();

    ... insert custom logic to resolve the badly formed properties

    // Tell the client that the request is invalid, if it is still invalid.
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    //EvalSecurityPolicy(item, Operation.Insert);
    await ApplyPost(item);
    //UpdateRelationships(item, Operation.Insert);

    await _db.SaveChangesAsync();

    return Created(item);
}

/// <summary>
/// Inheriting classes can override this method to apply custom fields or other properties from dynamic members in the posted item, base class will apply TenantId only if it has not already been applied
/// </summary>
/// <remarks>This process is called after the usual validation overriding just this process means you do not have to replicate the existing internal logic for the afore mentioned tasks.</remarks>
/// <param name="item">The new item that has been uploaded</param>
/// <returns>Promise to add the item to the underlying table store</returns>
public virtual Task ApplyPost(TEntity item)
{
    GetEntitySet().Add(item);
    return Task.CompletedTask;
}

This is a base class implementation of ODataController Inheriting controller classes only override ApplyPost if needed. I've commented out some more advanced logic routines to give you other hints on how you might use this pattern.
Is a good practice? I'm undecided but it works and will allow your API to be resilient to schema changes that the client hasn't yet been updated to support,  you can also inspect and handle the invalid ModelState in your controller before you return to the caller, or can easily add your own custom mapping logic if needed.

A: I have found a solution. I have used a custom ODataResourceDeserializer to handle the exception of doesn't exist properties and, included a try/catch block in the ApplyNestedProperty method's content. So the web service cannot throw an exception for not exists properties while deserialization process.
public class CustomResourceDeserializer : ODataResourceDeserializer
{
    public CustomResourceDeserializer(IODataDeserializerProvider deserializerProvider) : base(deserializerProvider)
    {
    }

    public override void ApplyNestedProperty(object resource, ODataNestedResourceInfoWrapper resourceInfoWrapper, IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext)
    {
        try
        {
            base.ApplyNestedProperty(resource, resourceInfoWrapper, structuredType, readContext);
        }
        catch (System.Exception)
        {

        }

    }
}