text:
Q: Redux initial value null while clicking on edit button I am trying to edit form. After first rendering I am not getting existing data from database. Because of state is null. If I click on second button first data is appearing. ( Because of state is null. If I click on second button first data is appearing. )
Reducer:
const intialState ={ channel:null}

Please click here for the image

//form Component
    import React, { Fragment } from "react";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";

const FormChannel = ({ channelData, ouSubmit, open }) => {
  let [formData, setFromData] = React.useState({
    channel: channelData ? channelData.channel : "",
    channelName: channelData ? channelData.channelName : "",
    introduction: channelData ? channelData.introduction : "",
    language: channelData ? channelData.language : "",
    keywords: channelData ? channelData.keywords : ""
  });
  const { channel, channelName, introduction, language, keywords } = formData;

  const handleClose = () => {
    ouSubmit(formData);
    setFromData({
      channel: "",
      channelName: "",
      introduction: "",
      language: "",
      keywords: ""
    });
  };

  const handleChange = channel => e => {
    setFromData({ ...formData, [channel]: e.target.value });
  };

  const view = (
    <Fragment>
      <Dialog
        open={open}
        onClose={handleClose}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Create Channel</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            value={channel}
            onChange={handleChange("channel")}
            id="channel"
            label="Name"
            type="emachannelil"
            margin="normal"
            variant="outlined"
            fullWidth
          />
          <TextField
            value={channelName}
            onChange={handleChange("channelName")}
            id="channelName"
            label="Channel Name"
            type="text"
            margin="normal"
            variant="outlined"
            fullWidth
          />
          <TextField
            label="Language"
            id="language"
            value={language}
            onChange={handleChange("language")}
            type="text"
            margin="normal"
            variant="outlined"
            fullWidth
          />
          <TextField
            value={introduction}
            onChange={handleChange("introduction")}
            id="introduction"
            label="Introduction"
            type="text"
            margin="normal"
            variant="outlined"
            fullWidth
          />
          <TextField
            value={keywords}
            onChange={handleChange("keywords")}
            id="kewords"
            label="Keywords"
            type="text"
            margin="normal"
            variant="outlined"
            fullWidth
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} color="primary">
            Cancel
          </Button>
          <Button onClick={handleClose} color="primary" variant="contained">
            Create
          </Button>
        </DialogActions>
      </Dialog>
    </Fragment>
  );
  return <Fragment>{view}</Fragment>;
};
export default FormChannel

Edit
import React, { Fragment } from "react";
import { connect } from "react-redux";
import { Button } from "@material-ui/core";
import FormChannel from "./Form";
const EditChannel = ({ channels: { channel }, open, setOpen }) => {
  console.log(channel);
  return (
    <Fragment>
      <FormChannel
        open={open}
        channelData={channel}
        ouSubmit={formData => {
          setOpen(false);
          console.log(formData);
        }}
      />
    </Fragment>
  );
};
const mapStateToProps = (state, props) => {
  console.log(state);
  return {
    channels: state.channels
  };
};
export default connect(mapStateToProps)(EditChannel);

card
import React, { Fragment } from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Typography, Button } from "@material-ui/core";
import Avatar from "@material-ui/core/Avatar";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { channelFollow, channelFetchById } from "../../../redux/action/channel";
import EditChannel from "../../Channels/List/Edit";

const useStyles = makeStyles(theme => ({
  card: {
    flexGrow: 1
  },
  img: {
    height: "60%",
    overflow: "hidden",
    width: "100%"
  },

  link: {
    textDecoration: "none",
    color: "black"
  },
  link1: {
    textDecoration: "none",
    color: "white"
  },
  root: {
    display: "flex",
    "& > *": {
      margin: theme.spacing(0.5)
    },
    justifyContent: "center"
  },
  button: {
    display: "flex",
    justifyContent: "center"
  },
  text: {
    fontWeight: "bold",
    fontSize: 15
  },
  text1: {
    color: "gray",
    fontSize: 15
  },
  bigAvatar: {
    width: 140,
    height: 140
  },
  buttons: {
    marginRight: 5
  }
}));

const ChannelCard = props => {
  const classes = useStyles();
  const { channel, channelFetchById } = props;
  const [open, setOpen] = React.useState(false);
  const handleClickOpen = () => {
    setOpen(true);
  };
  const view = (

      <Link to={`/channels/${channel._id}`} className={classes.link}>

          <Avatar
            alt="Remy Sharp"
            src={channel.avatar}
            className={classes.bigAvatar}
          />

          <Typography
            variant="subtitle1"
            align="center"
            className={classes.text}
          >
            {channel.channelName}
          </Typography>
          <Typography variant="body2" align="center">
            {channel.introduction}
          </Typography>

      </Link>
      <Typography variant="body2" align="center" className={classes.text1}>
        {channel.follows ? channel.follows.length : 0} followers

        Language:{channel.language}
      </Typography>

            <Button
              variant="contained"
              color="primary"
              onClick={() => {
                channelFetchById(channel._id);
                handleClickOpen();
              }}
            >
              Edit
            </Button>
            {open ? <EditChannel setOpen={setOpen} open={open} /> : ""}

            <Button color="primary" variant="contained">
              Delete
            </Button>

  );
  return <Fragment>{view}</Fragment>;
};
export default connect(null, { channelFollow, channelFetchById })(ChannelCard);

Reducer
    import {
  CHANNEL_FETCH,
  CHANNEL_FETCH_BY_ID,
  CHANNEL_UNFOLLOWED,
  CHANNEL_EDIT
} from "../action/typeof";
const initialState = {
  channels: [],
  channel: null,
  loading: true
};
export default (state = initialState, action) => {
  const { payload } = action;
  switch (action.type) {
    case CHANNEL_FETCH:
      return { ...state, channels: payload, loading: false };
    case CHANNEL_FETCH_BY_ID:
      return {
        ...state,
        channel: payload,
        loading: false
      };
    case CHANNEL_UNFOLLOWED:
      return {
        ...state,
        channelUnfollowedUser: payload,
        loading: false
      };
    case CHANNEL_EDIT:
      const channelEdit = state.channes.map(single =>
        single._id === payload.id ? { single, ...payload.data } : single
      );
      return {
        ...state,
        channels: channelEdit,
        loading: false
      };

    default:
      return state;
  }
};


text:
Q: Out-of-core computations in Julia I consider switching from R, Python and SAS to Julia and wondering whether Julia has convenient tools for out-of-core operations. I intend to use Julia on datasets of the size 10-20 Gb, so I would like to be able to manipulate them without loading them into RAM. Is there any package in Julia, allowing Julia to 'just work' with larger-than-RAM data the way SAS functions work?

A: JuliaDB is a dataframe package in Julia which allows for out-of-core computations, online (streaming) statistics, and parallelism.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to put a unique number code in all  of my arrays Say I have 3 arrays of arrays and when I write in any of them my counter goes up by one every insertion I do.How can I show on screen the data I inserted the same order I inserted them with that unique code it was printed when I was inserting them?
array ar1=new array[3];
array2 ar2=new array2[3];
array3 ar3=new array3[3];
I'm working on C# with 6 files. My main calls methods from the other 3 files. My base abstract class calls a counter (named code) from a constructor, which is being inserted on every array.My main is without Heredity, but calls the variables from the 3 files that are connected with heredity to the abstract base class.
This is my main and how I fill my first array.Same with different variables on the other two arrays.
i ++;
     ar1[i] = new array();
{
 Console.WriteLine("Inserting on first array");
 Console.WriteLine("\n\nCode :{0}",code);

 ar1[i].Inserting_data();  // this is the method where I fill my arrays

}
And this is how I try to call my previous insertions using a method again.
for (int x = 0; x <= i; x++)
{
    Console.WriteLine("code :{0}",code); //trying to print the unique code but it prints total.
    ar1[x].Print_data(); //the method for printing my insertions

}
If I leave the program like this when I insert data(up to 3 on every array) My counter is working fine and when I print them on screen, it prints them on the correct order but in the Console.WriteLine that there should be the unique code I want for every insertion (from 1 to 9 on that example, if I fill them all),my counter shows me the total insertions I have.
If I try rather than printing my counter, printing each variable from the For command,I get numbers from 0 to 2 max since that's what I put on my For. I can't unite my 3 arrays since each of them holds different variables and is on 3 different files.
Hope that helped.

A: I found the problem at last..
I had to add another variable on the base abstract class.Inside the constructor I had to write that the new variable (say s)was (s=+1+count++) and add it with a property(set,get) on my main.It worked fine.
Thanks for the time it took you to see this topic and ask some questions to help me.


text:
Q: How does one work with cdefined metaclasses in cython? Below is an example of the cython files i'm trying to compile:
foobar.pxd
cdef extern from 'object.h':
    ctypedef class __builtin__.type [object PyHeapTypeObject]:
        pass

cdef class _A(type):
    pass

cdef class A #Forward Declaration

cdef class B(A):
    pass

foobar.pyx
cdef class _A(type):
    def __init__(metaself, name, **args):
        super(_A, metaself).__init__(name, *args)
        print name

A = _A('A', (object,), {})

cdef class B(A):
    pass

When i try to compile them, i get an AnalyseDeclarationsTransform error. What is the appropriate syntax, or are there any workarounds?

A: As far as I know, you can't have an extension (cdef) class with a metaclass which is not type. Note however, that a usual class with a cdef metaclass is perfectly correct. I'm not sure about what you are trying to achieve but the following is ok:
cdef extern from 'object.h':
    ctypedef class __builtin__.type [object PyHeapTypeObject]:
        pass

cdef class _A(type):
    pass

and
cdef class _A(type):
    def __init__(metaself, name, **args):
        super(_A, metaself).__init__(name, *args)
        print name

A = _A('A', (object,), {})

class B(A):   # use a non cdef class
    pass

You can find a real life example of that in the classcall_metaclass of sage


text:
Q: Kotlin. Возобновление таймера в функции CountDownTimer Таймер
 var milliseconds: Long = 180000

 var timer = object :   CountDownTimer(milliseconds, 1000) {
     override fun onTick(seconds: Long) {
         milliseconds = seconds / 1000
         textView4.text = String.format("%02d:%02d", seconds / 60000, seconds % 60000 / 1000)
     }

После остановки таймера через команду
timer.cancel()

И после возобновления через команду timer.start()
Таймер сбрасывается и начинает идти заново, как можно сделать так, чтобы после остановки таймера и возобновления он продолжал идти с места остановки, мне казалось, что 1 переменная milliseconds изменяясь после каждого тика, будет сохранять результат, но она всегда статична

A: Ты должен снова инициализировать объект timer, чтобы он возобновил работу с того момента.
Если снова не инициализировать , то milliseconds не будет меняться и будет 180к.
Если хочешь возобновить:
    var timer = object : CountDownTimer(milliseconds, 1000) {
      ...
     }


text:
Q: postgresql, key is not present in table error, but key present in the table I have tables providers, and provider_groups.
providers:
create table providers
(
    id integer not null constraint providers_pkey primary key,
    available         boolean not null,
);

and provider_groups

create table provider_groups
(
    id integer  not null provider_groups_pkey primary key,
    provider_id integer not null constraint fk_237d25c5d3e1ebb8
            references providers on delete cascade,
    type              varchar(100) not null
);

create index idx_237d25c5d3e1ebb8
    on provider_groups (provider_id);

and my application (which using of doctrine ORM) trying to update data for some provider and his related group. I'm sure both provider and group exists in database, but for some reason it's failing with error
  SQLSTATE[23503]: Foreign key violation: 7 ERROR:  insert or update on table "provider_groups" violates foreign key constraint "fk_237d25c5d3e1ebb8"\n
    DETAIL:  Key (provider_id)=(28007) is not present in table "providers".

but as I mentioned it's there, I can see it through database UI.
What I'm doing wrong??? Can it be related to some cache on DB side, as it's a pretty old logic running for a while and that error apears only now... Thanks in advice!


text:
Q: In R, how do I get all possible combinations of the values of some vectors? The background: I have a function which takes some parameters. I want to have the result of the function for all possible parameter combinations.
A simplified example:
f <- function(x, y) { return paste(x, y, sep=",")}
colors = c("red", "green", "blue")
days = c("Monday", "Tuesday")

I want my result to look like
     color    day         f
[1,] "red"    "Monday"    "red,Monday"
[2,] "red"    "Tuesday"   "red,Tuesday"
[3,] "green"  "Monday"    "green,Monday"
[4,] "green"  "Tuesday"   "green,Tuesday"
[5,] "blue"   "Monday"    "blue,Monday"
[6,] "blue"   "Tuesday"   "blue,Tuesday"

My idea is to create a matrix with the columns color and day, fill it using the existing vectors colors and days, initialize an empty column for the results, then use a loop to call f once per matrix row and write the result into the last column. But I don't know how to easily generate the matrix from the colors and days vector. I tried searching for it, but all results I got were for the combn function, which does something different.
In this simplified case, the colors and days are factors, but in my real example, this is not the case. Some of the parameters to the function are integers, so my real vector may look more like 1, 2, 3 and the function will require that it is passed to it as numeric. So please no solutions which rely on factor levels, if they can't somehow be used to work with integers.

A: I think you just want expand.grid:
> colors = c("red", "green", "blue")
> days = c("Monday", "Tuesday")
> expand.grid(colors,days)
   Var1    Var2
1   red  Monday
2 green  Monday
3  blue  Monday
4   red Tuesday
5 green Tuesday
6  blue Tuesday

And, if you want to specify the column names in the same line:
> expand.grid(color = colors, day = days)
  color     day
1   red  Monday
2 green  Monday
3  blue  Monday
4   red Tuesday
5 green Tuesday
6  blue Tuesday


text:
Q: Knitr/Kable: Html Table Width I have one html table with a bunch of cols. I would like to expand the table as much as I can to fit in this columns. My output and code are below. As you can see theres' a low of white space between the table. I would like to use such space.
d %>%
kable( align = c( 'l', rep( 'c', 23  )), escape = F, full_width = F ) %>%
kable_styling(bootstrap_options = c("striped", 'condensed' ), font_size = 10 )

A: Try setting the full_width option to full_width = T


text:
Q: Как правильно описывать типы данных в typescript? Вообщем, пишу я на Angular 1.x с использованием Typescript.
Суть вопроса заключается в том где и как правильно описывать тип данных (классов).
Есть допустим у typescript @types, там описывают типы в файлах d.ts.
Еще можно описывать интерфейсами рядом с классом и экспортируют.
Как бы это все разумно совместить что бы не нагородить гавнокода.
Может я чего-то еще не понимаю.
Пример 1, использовать интерфейс вот так
interface ICommentController {
    add: (...args) => any;
    vote: (...args) => any;
}

class CommentController implements ICommentController {
    vote: (...args) => any;
    add: (...args) => any;
}

Пример 2, вынести интерфейс в d.ts
declare module application {

    namespace comment {
        interface ICommentController {
            add: (...args) => any;
            vote: (...args) => any;
        }
    }
}

а использовать вот так
class CommentController implements application.comment.ICommentController {}

я то понимаю что в d.ts описывают типы, но ведь суть почти та же ? тот же интерфейс, только в 1 случаи если использовать интерфейс его нужно импортировать, а во 2 - не нужно

A: Declaration files создаются для того, чтобы поставлять их вместе с собранными .js файлами для их использования в другом проекте из TypeScript кода. Если вы планируете использовать эти типы только внутри своего проекта, нет нужды объявлять их в отдельных d.ts файлах.


text:
Q: Referencing on photo How can I make it when I click number for referencing to go on picture NOT on caption text.
I hope you get what I want haha, when I click 1 (for ex) to go on picture/figure 1 not on caption text.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage[american]{circuitikz}
\usetikzlibrary{calc}
\usepackage{hyperref}

\title{text}

\date{May 2020}

\begin{document}

Here you can find somewhat \ref{fig:fig1} for figure1

\newpage

\begin{figure}
\centering
%width=170mm, height=70mm
\begin{tikzpicture}
    \draw (-2,0) -- (2,0);
\filldraw [gray] (0,0) circle (2pt);
\draw (-2,-2) .. controls (0,0) .. (2,-2);
\draw (-2,2) .. controls (-1,0) and (1,0) .. (2,2);
  \end{tikzpicture}
\caption{Talasni oblik uzorkovanog i izvornog analognog signala}
\label{fig:fig1}
\end{figure}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

\newpage
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

\end{document}

A: Just use caption package with hypcap=true. Hope it works as desired!
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[hypcap=true]{caption}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepackage[american]{circuitikz}
\usetikzlibrary{calc}
\usepackage{hyperref}

\title{text}
\author{derviswebdev }
\date{May 2020}

\begin{document}

Here you can find somewhat \ref{fig:fig1} for figure1

\newpage

\begin{figure}
\centering
%width=170mm, height=70mm
\begin{tikzpicture}
\draw (-2,0) -- (2,0);
\filldraw [gray] (0,0) circle (2pt);
\draw (-2,-2) .. controls (0,0) .. (2,-2);
\draw (-2,2) .. controls (-1,0) and (1,0) .. (2,2);
  \end{tikzpicture}
\caption{Talasni oblik uzorkovanog i izvornog analognog signala}
\label{fig:fig1}
\end{figure}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem    Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

\newpage
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

\end{document}


text:
Q: Values variables inside "this" class differ when created and during OnPress I am using a custom class to visualize DesignCards that are shown inside a dropdown menu after a button is pressed. The values are correct when these Cards are displayer, which I am sure of since they show the right image. However, after I call the "OnSelected" function trough the default "OnPress" event from Unity's Button component, it shows me in the log that it will always use the default values of this class (CardType being "Powersupply" and PartType being "A").
DesignCard Class:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;

public class DesignCard : MonoBehaviour {

    public enum CardType { Powersupply, Sensor, Weapon, Module}
    CardType cardType = CardType.Powersupply;

    public enum PartType { A, B, C, D, E}
    PartType partType = PartType.A;

    private int inStock;
    private Transform MasterObject, contentList;
    private Sprite sprite;

    void Start ()
    {
        MasterObject = GameObject.Find("Master").transform;
    }

    public DesignCard (CardType mCardType, PartType mPartType, int mInStock)
    {
        cardType = mCardType;
        partType = mPartType;
        inStock = mInStock;
    }

    public void CreateCard(Transform mContentList)
    {
        Debug.Log("Created card with type: " + this.GetType().ToString() + " and model: " + this.GetModel().ToString());
        contentList = mContentList;
        GameObject go = (GameObject)Instantiate(Resources.Load("TowerDesignScene/Card"), contentList);
        go.transform.localScale = new Vector3(1, 1, 1);
        sprite = GetImage(this);
        go.GetComponent<Image>().sprite = sprite;
    }

    public CardType GetType()
    {
        return (cardType);
    }

    public PartType GetModel()
    {
        return (partType);
    }

    public Sprite GetSprite()
    {
        return (sprite);
    }

    public void AddToStock()
    {
        inStock++;
    }

    public int GetStock()
    {
        return (inStock);
    }

    public void OnSelected ()
    {
        Debug.Log("Pressed on card with type: " + this.GetType().ToString() + " and model: " + this.GetModel().ToString());
        MasterObject.GetComponent<TowerDesignMasterScript>().SetCard(this);
    }

    private Sprite GetImage(DesignCard mCard)
    {
        DesignCard.CardType cardType = mCard.GetType();
        DesignCard.PartType partType = mCard.GetModel();
        sprite = null;
        string imagePath = "TowerDesignScene/DesignCards/";
        if (cardType == DesignCard.CardType.Module) imagePath += "Module/";
        else if (cardType == DesignCard.CardType.Powersupply) imagePath += "Powersupply/";
        else if (cardType == DesignCard.CardType.Sensor) imagePath += "Sensor/";
        else if (cardType == DesignCard.CardType.Weapon) imagePath += "Weapon/";
        if (partType == DesignCard.PartType.A) imagePath += "Type A";
        else if (partType == DesignCard.PartType.B) imagePath += "Type B";
        else if (partType == DesignCard.PartType.C) imagePath += "Type C";
        else if (partType == DesignCard.PartType.D) imagePath += "Type D";
        else if (partType == DesignCard.PartType.E) imagePath += "Type E";

        sprite = Resources.Load<Sprite>(imagePath);
        return sprite;
    }

}

Log when created a dropdown menu filled with Powersupplies and pressing each of the 5 buttons in the same order they are created:
(cleaned up the unneccesary lines)
Created card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Powersupply and model: B
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Powersupply and model: C
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Powersupply and model: D
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Powersupply and model: E
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Log when created a dropdown menu filled with Modules and pressing each of the 5 buttons in the same order they are created:
(cleaned up the unneccesary lines)
Created card with type: Module and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Module and model: B
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Module and model: C
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Module and model: D
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Module and model: E
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

I'm pretty sure this isn't some sort of bug, but I'm running out of ideas of where the source of my issue may be.
Thanks.


text:
Q: classification technique My BE final year project is about sign language recognition. I'm terribly confused in choosing the right classification technique for patterns seen in the video of signs generated by a dumb user. I learned neural nets(NN) are better than hidden markov model in several aspects but fine tuning the parameters of NN requires a lot of time. Further, some reports say that Support Vector Machine are better in performance than NN.   What do I choose among these alternatives or are there any other better alternatives so that it would be feasible to complete my project within 4-5 months and  I could continue with that field in my masters?

A: Actually the system will be fed with real time video and we intend to recognize the hand postures and spatiotemporal gestures. So, its the entire sentences I'm trying to find.
On the basis of studies till now, I'm making my mind to use
 1. Hu moments & eigenspace size functions to represent hand shapes
 2. SVM for posture classification &
 3. Threshold HMM for spatiotemporal gesture recognition.
What would u comment in these decisions?


text:
Q: Download file from StreamWriter How I can get byte[] from StreamWriter and download the file with what is written to streamwriter?
string document = @"C:\TestArea\Destination\SUP000011\ATM-1B4L2KQ0ZE0-0001\Sample.docx";
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
    string docText = null;

    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
    }
    Regex regexText = new Regex("Hello world!");
    docText = regexText.Replace(docText, "Hi Everyone!");

    using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
    {
        sw.Write(docText);
    }
}

Downloading code snippet -
  byte[] bytearraydata = Encoding.ASCII.GetBytes(doctext);
 if (bytearraydata != null)
                {
                    Response.ContentType = "Application/msword";
                    Response.AppendHeader("Content-disposition",
                            "attachment; filename=" + "Sample.docx");
                    Response.AppendHeader("content-length", bytearraydata.Length.ToString());
                    Response.BinaryWrite(bytearraydata);
                    Response.End();
                }

A: Despite its name, StreamWriter actually writes characters, not bytes. If you want to write unencoded bytes use BinaryWriter.
To read unencoded bytes use BinaryReader.


text:
Q: What does it mean "whenever sqlerror exit 9"? What does whenever sqlerror exit 9 mean?
And does the number 9 represent anything? I was thinking maybe it's a sqlerror code but I couldn't find a sqlerror code with a number 9.

A: Typically exiting 0 means success and non-zero means an error.  The number of the exit code refers to where the error occurred, and is programmer-defined.  Perhaps your program would exit 1 if login failed, 2 if a query returned no rows where at least one was expected, etc.  A wrapper program can call this one, then use the return code to see if it ran successfully or not.  If not, you know where in the code it failed by the number.  Used as you are dealing with, they are called magic numbers.  Who knows what they mean as apparently the original developer never at least defined them in a comment.  Now you know why magic numbers should be avoided.  Instead, define return codes as constants with a meaningful name at the top of your program, then refer to them by that name when used.  Whoever maintains the code after you will sing your praises instead of cursing your existence!  In Oracle PL/SQL for instance, I'd do something like this:
...
-- Define return codes.
ERR_NOLOGIN       CONSTANT INTEGER := 1;
ERR_NOROWS        CONSTANT INTEGER := 2;
ERR_TOO_MANY_ROWS CONSTANT INTEGER := 3;
...
-- Then in your error handing:
WHENEVER ERROR EXIT ERR_NOLOGIN;  -- No magic number makes for
                                  -- easier to read code.
...


text:
Q: BAT: how to run Python Script and restart the process after 1 hour I want to run and restart a specific python script on X time.
I'm aware of the following code but I'm unaware of how to make it kill the ongoing python process and start it over again after X time.
@echo off
python main.py

Any help is appreciated!

A: You can schedule it as a cron job or a periodic job.
Library
pip install apscheduler

Import
from apscheduler.schedulers.blocking import BlockingScheduler

Cron Job:
scheduler = BlockingScheduler()

def hello():
    print("HELLO")

scheduler.add_job(hello, 'cron', hour="*/1")
scheduler.start()

Or you can schedule it to run every one hour
scheduler = BlockingScheduler()

def hello():
    print("HELLO")

scheduler.add_job(hello, 'interval', hours=1)
scheduler.start()


text:
Q: Getting Chid elements in DOM I have a code which is similar to the following snippet

 /* this ul has many nested children */

I would like to get all tags inside the "main" div and set them new id if they already has one. I have a javascript like one below
        var InfoMsg = "";
        var nodes = element.getElementsByTagName('*');
        for (var i = 0; i < nodes.length; i++)
        {
            InfoMsg += nodes[i]
        }
        alert(InfoMsg);

I get the following alert
 [object HTMLDivElement][object HTMLUListElement][object HTMLLIElement]
 [object HTMLTableElement][object HTMLTableSectionElement]
 [object HTMLTableRowElement][object HTMLTableCellElement]
 [object HTMLImageElement][object HTMLTableCellElement]
 [object HTMLTableCellElement]

Why does the inner ul  and its children are not getting retrieved by the  getElementsByTagName()  method, Or is there any other way to do so;
Note :
     At run time i will know only the "main" div id. All the children are dynamic and can run to any length.
Thanks in advance!!


text:
Q: FSM doesn't work when I run aiogram with fastapi I have a problem with fsm using aiogram with Fastapi. I ran the code from aiogram_fsm_example, but changed the long-polling to the Fastapi implementation. Here's the code I've got:
import logging
from fastapi import FastAPI, Request
import aiogram.utils.markdown as md
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import ParseMode
from aiogram.utils import executor

logging.basicConfig(level=logging.INFO)

API_TOKEN = "here's the bot token"

bot = Bot(token=API_TOKEN)

# For example use simple MemoryStorage for Dispatcher.
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)

# States
class Form(StatesGroup):
    name = State()  # Will be represented in storage as 'Form:name'
    age = State()  # Will be represented in storage as 'Form:age'
    gender = State()  # Will be represented in storage as 'Form:gender'

@dp.message_handler(commands='start')
async def cmd_start(message: types.Message):
    """
    Conversation's entry point
    """
    # Set state
    await Form.name.set()

    await message.reply("Hi there! What's your name?")

@dp.message_handler(state=Form.name)
async def process_name(message: types.Message, state: FSMContext):
    """
    Process user name
    """
    async with state.proxy() as data:
        data['name'] = message.text

    await Form.next()
    await message.reply("How old are you?")

# Check age. Age gotta be digit
@dp.message_handler(lambda message: not message.text.isdigit(), state=Form.age)
async def process_age_invalid(message: types.Message):
    """
    If age is invalid
    """
    return await message.reply("Age gotta be a number.\nHow old are you? (digits only)")

@dp.message_handler(lambda message: message.text.isdigit(), state=Form.age)
async def process_age(message: types.Message, state: FSMContext):
    # Update state and data
    await Form.next()
    await state.update_data(age=int(message.text))

    # Configure ReplyKeyboardMarkup
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True)
    markup.add("Male", "Female")
    markup.add("Other")

    await message.reply("What is your gender?", reply_markup=markup)

@dp.message_handler(lambda message: message.text not in ["Male", "Female", "Other"], state=Form.gender)
async def process_gender_invalid(message: types.Message):
    """
    In this example gender has to be one of: Male, Female, Other.
    """
    return await message.reply("Bad gender name. Choose your gender from the keyboard.")

@dp.message_handler(state=Form.gender)
async def process_gender(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['gender'] = message.text

        # Remove keyboard
        markup = types.ReplyKeyboardRemove()

        # And send message
        await bot.send_message(
            message.chat.id,
            md.text(
                md.text('Hi! Nice to meet you,', md.bold(data['name'])),
                md.text('Age:', md.code(data['age'])),
                md.text('Gender:', data['gender']),
                sep='\n',
            ),
            reply_markup=markup,
            parse_mode=ParseMode.MARKDOWN,
        )

    # Finish conversation
    await state.finish()

# my changes
app = FastAPI()

@app.get("/")
async def root():
    return "ok"

@app.post("/")
async def process_update(request: Request):
    update = await request.json()
    update = types.Update(**update)
    print("incoming", update)
    await dp.process_update(update)

But when I run that with uvicorn (uvicorn main:app) and send /start command to the bot, the backend throws this error:
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 373, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/starlette/routing.py", line 61, in app
    response = await func(request)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/fastapi/routing.py", line 226, in app
    raw_response = await run_endpoint_function(
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/fastapi/routing.py", line 159, in run_endpoint_function
    return await dependant.call(**values)
  File "/home/oleh/projects/tg_bot_test_fsm/./main.py", line 124, in process_update
    await dp.process_update(update)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 257, in process_update
    return await self.message_handlers.notify(update.message)
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/oleh/projects/tg_bot_test_fsm/./main.py", line 38, in cmd_start
    await Form.name.set()
  File "/home/oleh/projects/tg_bot_test_fsm/.venv/lib/python3.8/site-packages/aiogram/dispatcher/filters/state.py", line 56, in set
    state = Dispatcher.get_current().current_state()
AttributeError: 'NoneType' object has no attribute 'current_state'

As far as I understood: there's a state in the dispatcher that is not created somewhy when I use the dp.process_update() function.
When I run that with long_polling - everything works fine, but I need so much to run it with Fastapi.
Is there a way to set up the state manually? Or I just do not process it correctly?
P.S. I run it in the WSL Ubuntu 20.04 LTS. Python version is 3.8.10, aiogram - 2.15, uvicorn - 0.15.0 and Fastapi - 0.70.0.
SOLVED: if you're using Fastapi with aiogram and trying FSM, you need to set state in another way, with state.set_state(Form.name) function. My working code of start method looks like that:
@dp.message_handler(commands='start', state="*")
async def cmd_start(message: types.Message, state: FSMContext):
    """
    Conversation's entry point
    """
    # Set state
    await state.set_state(Form.name)

    await message.reply("Hi there! What's your name?")

A: It's enough to set current context for Dispatcher
dp = Dispatcher(bot, storage=storage)
Dispatcher.set_current(dp)


text:
Q: Breaking up a string by comparing characters/combinations of characters against a dictionary What I would like to do is something like this:
testdictionary = {"a":1, "b":2, "c":3, "A":4}
list1 = []
list2 = []
keyval = 200
for char in string:
    i = 0
    y = "".join(list1)
    while y in testdictionary:
        list1.append(string[i])
        i +=1
    list2.append(y[:-1])
    testdictionary[y] = keyval
    keyval +=1
    string = string[((len(list1))-1):]
    list1 = []

So for a string "abcacababa" the desired output would be:
['ab', 'ca', 'cab', 'aba']

Or "AAAAA" would be
['A', 'AA'. 'AA']

Take abcacababa. Iterating through we get a which is in testdictionary so we append list1 again. This time we have ab which is not in the dictionary, so we add it as a key to testdictionary with a value of 200. Then doing the same process again, we add ca to testdictionary with a value of 201. Then since we have already added ca, the next value appended to list2 would be cab and so on.
What I am trying to do is take a string and compare each character against a dictionary, if the character is a key in the dictionary add another character, do this until it is not in the dictionary at which point add it to the dictionary and assign a value to it, keep doing this for the whole string.
There's obviously a lot wrong with this code, it also doesn't work. The i index being out of range but I have no idea how to approach this iteration. Also I need to add in an if statement to ensure the "leftovers" of the string at the end are appended to list2. Any help is appreciated.

A: I think I get it now @Boa. This code I believe works for abcacababa at least. As for leftovers, I think it's only possible to have a single 'leftover' key when the last key is in the test dictionary, so you just have to check after the loop if curr_key is not empty:
testdictionary = {"a":1, "b":2, "c":3, "A":4}
word = 'abcacababa'

key_val = 200
curr_key = ''

out_lst = []
let_ind = 0

for let in word:
    curr_key += let
    if curr_key not in testdictionary:
        out_lst.append(curr_key)
        testdictionary[curr_key] = key_val
        key_val += 1
        curr_key = ''

leftover = curr_key
print(out_lst)
print(testdictionary)

Output:
['ab', 'ca', 'cab', 'aba']
{'a': 1, 'A': 4, 'c': 3, 'b': 2, 'aba': 203, 'ca': 201, 'ab': 200, 'cab': 202}

Please let me know if anything is unclear. Also I think your second example with AAAAA should be ['AA', 'AAA'] instead of ['A', 'AA', 'AA']


text:
Q: How to create VPN connection In Jessie 8.5 I am trying to create a VPN connection in Debian Jessie 8.5. To do this, I first installed OPENVPN by typing these commands in bash:
sudo apt-get install openvpn
sudo apt-get install network-manager-openvpn-gnome
But, as we see in the picture below, the save button is not active, even after entering all the data I was supposed to provide in order to create the connection:

My problem now is that the save button is not active to let me create and use the connection. Would you please tell me how to make it responsible and working?

A: openvpn requires an ssl cert, even if you don't want to have certs for user auth, or for tls firewall.
Import the ssl cert from openvpn, then you can save the profile.
openvpn certs;
ca.crt (must have)
user.crt (optional: user auth)
user.key (optional: user auth)
ta.crt (optional: firewall)

sample config using all 3x cert:
client
dev tun
proto udp
remote 192.168.0.2
persist-key
persist-tun
ca ca.crt
cert user.crt
key user.key
auth-user-pass tmp.ovpn
comp-lzo yes
nobind
auth-nocache
script-security 2
reneg-sec 21600
tls-auth ta.key 1
cipher AES-256-CFB8
tls-cipher TLS-DHE-RSA-WITH-AES-256-CBC-SHA
remote-cert-tls server
auth SHA512


text:
Q: How do I store the value of a javascript variable (without a server) externally? Lets say I am asking users (on my local machine) to input their email address to sign up for a raffle.
<!DOCTYPE HTML>
<title>Raffle</title>

<input id="Email" name="Email" type="email">
<input type="Submit" id="submit" name="submit" onclick="foo();">

Fiddle
When the user hits submit, the email address pops up in front of them. Is there any way to simultaneously store the variable email in an external file (.php, .txt etc.)

A: Without a server, the only persistence you're going to get from JavaScript is through cookies, local storage, or one of the client-side DB methods. (There are ways to write data to files but they are often more hassle than they're worth for such simple cases).
Simplest is local storage. This will keep a comma-separated string of all emails users have entered:
if (!localStorage.emails)
    localStorage.emails = email;
else
    localStorage.emails += ',' + email;

And then at subsequent page visits, you can retrieve the emails that users entered through the localStorage.emails variable.

A: in your code you have make minor changes as i understand it
<!DOCTYPE HTML>
<title>Raffle</title>

<input id="Email" name="Email" type="email">
<input type="Submit" id="submit" name="submit" onclick="foo();">

in another way you can show this value as to the user in your jquery script

<input id="Email" name="Email" type="email">
<input type="Submit" id="submit" name="submit" onclick="foo();">

hopefully it may help you

A: As I mentioned in the comments, you can use localStorage to persist values in a single browser.
If you want to store a list of e-mail addresses, your best bet is to store them as an array, and serialize that into localstorage
<!DOCTYPE HTML>
<title>Raffle</title>

<input id="Email" name="Email" type="email">
<input type="Submit" id="submit" name="submit" onclick="foo();">

DEMO


text:
Q: HTML: What determines the 'move the focus to the next control when Enter is hit' behavior A basic HTML question. Is it possible on an HTML page to declaratively achieve a behavior when pressing Enter in a textbox moves the focus to the next control? How do you achieve it and how do you turn it off? Or maybe the dynamic javascript part should be involved here?
For exaple, the following HTML in IE7 does not allow to move to the focus to the next textbox with enter:

<form>

<input type="text" name="i1"/>

<input type="text" name="i2"/>

</form>

I have a page where I need to get rid of this 'move the focus to the next control when Enter is pressed' behavior.
@Edit: The example above turns out to be incorrect. The control the focus jumps to when I press enter on the page I want to avoid this behavior on is actually of type submit. The strange thing is that this "submit" is a part of a Telerik tree control and is not a submit button but an arrow used to collapse and expand the tree structure.
So I assume the focus jumps to the next submit control which the Browser expects to be a normal submit button which is not true in my case.
So I suppose I should look for a Telerik pecific solution here.

A: In most browsers, pressing Enter when focused within a form will submit the form. If you need to change this behavior so that pressing Enter moves to the next textbox you will need to use javascript.
Try this: (courtesy of javascript.internet.com)
http://javascript.internet.com/forms/tab-key-emulation.html

A: <input type="text" name="i1" Tabindex="[order number]"/>
I usually lookup these things on:
http://start.gotapi.com/


text:
Q: Control airflow task parallelism per dag for specific tasks? Is there a way to control the parallelism for particular tasks in an airflow dag? Eg. say I have a dag definition like...
for dataset in list_of_datasets:
    # some simple operation
    task_1 = BashOperator(task_id=f'task_1_{dataset.name}', ...)
    # load intensive operation
    task_2 = BashOperator()
    # another simple operation
    task_3 = BashOperator()

    task_1 >> task_2 >> task_3

Is there a way to have something where task_1 can have, say, 5 of its kind running in a dag instance, while only 2 instances of task_2 may be running in a dag instance (also implying that if there are 2 instances of task_2 already running, then only 3 instances of task_1 can run)? Any other common ways to work around this kind of requirement (I imagine this must come up often for pipelines)?

A: From discussions on the apache airflow email list...
You can use pools (https://airflow.apache.org/docs/stable/concepts.html#pools) to limit how many tasks can be run in parallel for given pool.
So you can create named "pools" with task count limits (via the webserver admin menu)

and then assign those tasks to those pools in a dag definition file when they are created
for dataset in datasets:
high_load_task = BashOperator(
            task_id='high_load_task_%s' % dataset["id"],
            bash_command='some_command',
            pool='example_pool',
            trigger_rule=TriggerRule.ALL_SUCCESS,
            dag=dag)

Also...

There is another way to limit parallelism of tasks - applicable for example in cases where you have different kinds of machines with different capabilities (for example with/without GPU). You can have some affinities defined between tasks and actual machines that are executing them - in Celery executor you can define queues in your celery configuration and you can assign your task to one of the queues. Then you can have a number of workers/slots defined for all machines in the queue and as effect you can also limit parallelism of the tasks this way: https://airflow.apache.org/docs/stable/concepts.html#queues


text:
Q: Java Timer doesn't fire at Websphere server I am using java.Util.Timer library for schedule my job.
I wanna call my function at 22:00 every sunday. So my code is like :
rspServer = new RSPServer();

Calendar scheduleStartTime = Calendar.getInstance();
scheduleStartTime.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
scheduleStartTime.set(Calendar.HOUR_OF_DAY, 22);
scheduleStartTime.set(Calendar.MINUTE, 0);
scheduleStartTime.set(Calendar.SECOND, 0);
scheduleStartTime.set(Calendar.MILLISECOND, 0);

rspServer.startScheduler(Class.forName("xx.xx.xx.xx.RSP.RSPServer"),rspServer, "PopulateModels", scheduleStartTime, 7 * 24 * 60 * 60 * 1000);

I deployed that code and restarted websphere server at thursday. I was expecting that function will be start at sunday. But it didn't fire. There is no error or out log in the server.
I tried that
I updated the start time as monday 11:00 am. And restarted server at 10:40 am on monday. After 20 minutes, my function worked at 11:00 am as expected. But if I restart my server at thursday and set the start time as sunday it did not fire.
Is there a kind of idle thread kill time or sth else in webshere server?
What could be the reason for this?
here is my startScheduler function
public void startScheduler(final Class<?> serverClass, final Object server,
        final String methodName, Calendar _startAfterTime, int _repeatAfterTime) {
    timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        private java.lang.reflect.Method method;

        @Override
        public void run() {
            try {
                method = serverClass.getMethod(methodName);
                method.invoke(server);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.err.println("Error!");
                e.printStackTrace();
            }
        }
    };
    timer.schedule(timerTask, _startAfterTime.getTime(), _repeatAfterTime);
}

A: There is no idle thread killing mechanism in WebSphere Application Server, so there should not be any reason the timer does not run.  I would suggest taking a core thread dump to see that your thread is still running (perhaps immediately after it was scheduled), and perhaps a core dump to inspect the field values to ensure they have expected values.  My best guess would be that this logic to start the timer is not actually running for some reason.
That said, why are you using java.util.Timer in the first place?  That is not recommended in any Java EE server.  If you're using WebSphere 8.0 or later, I would recommend using an EJB scheduled time, which you can configure with cron-like syntax.  Otherwise, if upgrading isn't an option, I would suggest using a WebSphere Scheduler.

A: In websphere default java time configurations, the week starts with sunday. In Turkey the week starts with monday. So when I set the date to Sunday at Wednesday by the code :
scheduleStartTime.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

It sets next Sunday in my local but in websphere it sets previous Sunday.
In timer function, if your set start date is smaller than current date, timer function does not fire. It is library restrict. So I fixed my problem like
Calendar scheduleStartTime = Calendar.getInstance();
scheduleStartTime.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
scheduleStartTime.set(Calendar.HOUR_OF_DAY, 11);
scheduleStartTime.add(Calendar.DAY_OF_YEAR, 7); // added this line to set next sunday
scheduleStartTime.set(Calendar.MINUTE, 0);
scheduleStartTime.set(Calendar.SECOND, 0);
scheduleStartTime.set(Calendar.MILLISECOND, 0);


text:
Q: How can I get the aliens to start doing abductions again? I find it a lot of fun to pause my store progression at the Gollop chamber and just pass the in-game months fighting aliens, minmaxing my soldiers and experimenting with different teams; however I am finding that the game is missing something - I am no longer offered alien abductions to deal with. The Wikia site for the game says that abductions don't happen in countries with satellite coverage and stop altogether when most countries are covered with satellites, which is a good lead, but not nearly specific enough. What exact conditions stop alien abductions? Can I get alien abductions back after getting rid of them?

A: I can confirm this works.
I left one country (Egypt) in my home continent (Africa) without a satellite hoping to continue getting abduction missions. This didn't work however.
I then let a UFO escape and a Battleship turned up later and I left this alone too. It shot down the satellite over Russia.
Russia went up to a panic level of 5 because of this. Shortly afterwards however I got a Bomb disposal mission in Russia which reduced panic levels and then an UFO landing.
The next mission after that was an Abduction mission as you can see:

This leads me to think when playing Iron-man it may be worth leaving the remaining countries in your home continent without satellites. The extra cash, meld and rewards would be a decent boost. That is assuming they don't replace normal UFO missions which they may well do.

A: If you let a UFO go by without intercepting it, it's likely a battleship will come by later and shoot down a satellite.
If you have at least two countries uncovered by satellites, you'll get abduction missions.
So, you can wait for the aliens to shoot down two of your satellites and then abduction missions should start appearing again.


text:
Q: How to set values in local storage of the browser using node js express backend Till now, I was using cookies to save some preferences, for my websites. But with time, this has gone very big, and now it is exceeding the limit of 4096 chars.
So I have to find an alternate way of storing the data. Here I find, using local-storage can serve my purpose. But I couldn't find any example, how I can save some value in local storage of the browser from node js. Previously I used to send the cookie value with response, to save the cookie, can we do something similar for local storage.
I see some of the npm modules like node-localstorage etc. , but not sure, how I can save the data to the browser.

A: I would at first suggest using some kind of persistent data handler. Maybe a database on the server, or if you want to avoid server-handling, maybe you could use something like Firebase to handle your persistent data.
There is probably a ton of npm modules to save to local storage, but I guess it depends on what you're using it for, but maybe this module can help? Otherwise if you're using the cookie to send information between different requests, maybe you could use query-strings on your requests instead?
So instead of saving preferences to a cookie, you send a querystring with the preferences on each request using
encodeURIComponent & decodeURIComponent()


text:
Q: Running a remote protractor webdriver manager doesn't work We are trying to run a test suite through the protractor chrome web driver,
all the tests ran successfully manually on our CI server (windows server 2012).
But when we run the protractor web driver manager through a service the tests get stuck in the middle of their work without any error information.
We suspect it has something to do with the chrome ran by the web driver 'GUI-less', but couldn't find really the root of the problem.
Is there something we missing ? like a special parameter the web driver should be started with when running without the GUI?


text:
Q: php prepared statement multiple possible querys I'm using prepared statement for MySQLi PHP which is all working. However, the application that I'm using this in has 108 different possible statements all very similar that can be run either without condition:
select * from table1

or with
select * from table 1 where user_level = 1)

The question that I'm asking: Is there a way that I can create the statement that covers all possibilities such as
select * from table 1 where user_level = {special input}

that will give the same outcome as
select * from table1

Otherwise I'm looking at a lot of repetition.

A: You would use parameter binding. See https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php.


text:
Q: A closed-form expression for the inverse of a block-matrix Let $\bf A$ be an $n \times n$ non-singular  matrix over $\mathbb{F}$.
Let $x$ be a non-zero element of $\mathbb{F}$.
Suppose that  ${\bf 1}_{n}$ is a symbol for  the all-one  vector  of length $n$ over $\mathbb{F}$.
Now consider the following  $(n+1) \times (n+1)$ matrix and assume that $\bf B$ is a invertible matrix over $\mathbb{F}$.
$$
{\bf B}=
\left(
 \begin{array}{cc}
x &{\bf 1}^T_{n} \\
 {\bf 1}_{n} & {\bf A}
 \end{array}
 \right).
 $$
My question: Is there a closed-form expression for the inverse of $\bf B$, denoted with ${\bf B}^{-1}$?
Thanks for any help.

A: Say that
$$B^{-1}=:\begin{pmatrix} b & X^T \\ Y & M \end{pmatrix}.$$
Then using Schur's complement formula (thanks to Nathaniel), $b=(x-{\bf1}^TA^{-1}{\bf1})^{-1}$ and $M=(A-x^{-1}{\bf11}^T)^{-1}$. From this, you can compute the vectors
$$Y=-x^{-1}M{\bf1},\qquad X^T=-b{\bf1}^TA^{-1}.$$


text:
Q: free elements from array Probably, this is a very basic question, but here goes anyways. I have an array of size say 10. But, while assigning integers to that array I give only 8 elements. Can I free the memory of 2 elements that are not used ?

A: No, you can't. For dynamic allocation, you can only free or delete memory that was allocated with malloc or new. The exact same amount with the exact same pointer. For automatic variables, the memory will be freed automatically.
But since this is C++, use a std::vector instead. Please.

A: It depends on how you got your array in the first place.
If it is an array that is allocated in the automatic or static storage (i.e. a local or a global) there is nothing you can free, because you did not allocate anything (the compiler did it for you).
If this is a dynamically allocated array, you can achieve the same effect by creating a smaller array with only eight elements, copying the original values into it, and then freeing the original array. This does not guarantee that the amount of memory allocated to your program would necessarily go down, because the allocator of the eight-element array is allowed to allocate space for more elements. If the numbers are 10000 and 8000, on the other hand, you will almost certainly get some savings (although the standard does not guarantee it either).


text:
Q: ActionLink is not passing parameter to the Controller -- asp.Net MVC 4 Please i am having an issue with one of my controllers for hours now. I have succesfully use similar metothos through out the project. However, for some reason this controller's paramterer is always null. Below is my controller.
[Authorize(Roles = "Employer")]
public class EmployerController : Controller
{
  [HttpGet]
  public ActionResult Index(long? id)
  {

  }

}
My Action Link is below

@Html.ActionLink("View jobs", "Index", "Employer", new { id = userid})

I used a break point and confirmed that my userid is not null.
Below is my routing.
 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
               name: null,
               url: "{controller}/Page{page}",
               defaults: new { Controller = "Home", action = "Index" }
               );
            routes.MapRoute(
                name: null,
                url: "{Controller}",
                defaults: new { Controller = "Home", action = "Index" }
                );

          routes.MapRoute(
          name: null,
          url: "{controller}/{action}/{id}/{title}",
          defaults: new
          {
              controller = "Home",
              action = "Index",
              title=UrlParameter.Optional,
              id = UrlParameter.Optional
          }
          );
            routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
            );
            routes.MapRoute(null, "{controller}/{action}");
        }
    }

I am expecting my action to be served by route four .
routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new
                {
                    controller = "Home",
                    action = "Index",
                    id = UrlParameter.Optional
                }

Previously my controller parameter was employerId, then i though that may be the cause of my error because i use id in route. I changed to id and yet still is passing empty. My url is returning something like.
Employer?Length=8

Where do the LEnghth came from ? Please where do i go wrong? Any help would be appreciated.

A: The problem is that you are using a wrong overload of @Html.ActionLink.
Instead of

@Html.ActionLink("View jobs", "Index", "Employer", new { id = userid })

Try

@Html.ActionLink("View jobs", "Index", "Employer",new { id = userid }, null)

OR

@Html.ActionLink("View jobs", "Index", "Employer",new { id = userid }, new{})

A: You have to use this overload:
@Html.ActionLink("View jobs", "Index", "Employer", new { id = userid}, null)

You are currently using the wrong overload which assumes the controller name as the route values. (It's a sequence of 8 chars)


text:
Q: How to get hosted nodejs website to run on cordova? I have a website(HTML5 Game) that uses NodeJS to manage a database among other things, i am trying to port it too android and IOS using Cordova, but i do not know how to get Cordova to load the website using a URL, i need it to load into the URL because of all the server side stuff. Does anyone have any advise on how to do this?
I've looked at countless articles/posts but every time i test it out by clicking on index.HTML it doesn't redirect/show my website.
I have tried several plugins and even just using simple javascript to load the website but nothing has been working.
i get the following error on when i open the index.html
Content Security Policy: The page's settings blocked the loading of a resource at inline ("default-src").

my config.xml:
<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloCordova</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="http://mysite.us*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>
<cordova>
    <access origin="http://mysite.us*"/>
</cordova>

My index.js
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function() {
        this.receivedEvent('deviceready');
            window.location="http://mysite.us";
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

app.initialize();

A: Here is the code I use:
  <plugin name="cordova-plugin-whitelist" source="npm" />
  <allow-navigation href="https://example.org/*" />
  <allow-intent href="https://example.org/*" />
  <access origin="https://example.org/*" />

It doesn't need to be in a platform tag and you will obviously need to replace the url with your own.
If you need you select everything in a folder or domain, you can use the wildcard: * (Like shown above)
EDIT:
Keep in mind that you will also need to whitelist like that all resources loaded by your webapp like for example:
If you load jQuery via a cdn, then you will need to whitelist that url or the cdn's whole domain name.
Remember too that if outside urls were blacklisted in the first place is to prevent Xss injection. If you whitelist too much urls, people may be able to load a script from a source you have whitelisted so to deceive a user via your app.
EDIT 2:
You can also simply use an iframe instead of using window.location
<iframe src="https://example.com/nodejs-webapp/" style="border: 0; width: 100%; height: 100%">Your browser doesn't support iFrames.</iframe>

And this goes in the head tag
<style>body{margin:0;}</style>


text:
Q: Vectorising a code using xor in Matlab I have an mxn array r in Matlab with elements that are zeros or ones.
I want to construct a vector p of dimension mxn such that for i=1,...,m
p(i,1)=r(i,1)
p(i,2)=r(i,2)XOR r(i,1)
p(i,3)=r(i,3) XOR r(i,2)
...
p(i,n)=r(i,n) XOR r(i,n-1)
This code does what I want but it is slow for m,n large. Could you suggest something faster?
m=4;
n=5;
r=[1 1 1 1 1; ...
   0 0 1 0 0; ...
   1 0 1 0 1; ...
   0 1 0 0 0];

p=zeros(m,n);

for i=1:m
    p(i,1)=r(i,1);
    for j=2:n
        p(i,j)=xor(r(i,j),r(i,j-1));
    end
end

A: Sure:
p            = zeros(m,n);
p(:,1)       = r(:,1);
p(:,2:end)   = xor(  r(:,1:(end-1)),   r(:,2:n)   );

What we're doing here is:

*

*Pre-allocating the array. Same as your code.

*Fill in the first column of p with the first column of r

*Fill in the 2nd - last columns of p with the desired XOR operation. As inputs to the XOR we are using two large sections of r. The first is the 1st - (last-1)th columns. The second is the 2nd through last columns.


text:
Q: jupyter nbconvert sticky bit runtime warning When I run jupyter nbconvert --execute --to html toy_notebook.ipynb with jupyter version 4.3.0 and python 3.6 on macOS 10.12.5,  I get the following warning:

[NbConvertApp] Converting notebook toy_notebook.ipynb to html
  [NbConvertApp] Executing notebook with kernel: python3
  /Users/zblanton/anaconda/lib/python3.6/site-packages/jupyter_client/connect.py:157:
  RuntimeWarning: Failed to set sticky bit on
  '/var/folders/nr/1n4j77yx7g93kzr2mrwwdlgm0000gq/T': [Errno 1]
  Operation not permitted:
  '/var/folders/nr/1n4j77yx7g93kzr2mrwwdlgm0000gq/T'   RuntimeWarning,
  /Users/zblanton/anaconda/lib/python3.6/site-packages/jupyter_client/connect.py:157:
  RuntimeWarning: Failed to set sticky bit on
  '/var/folders/nr/1n4j77yx7g93kzr2mrwwdlgm0000gq/T': [Errno 1]
  Operation not permitted:
  '/var/folders/nr/1n4j77yx7g93kzr2mrwwdlgm0000gq/T'   RuntimeWarning,

A stack trace is here. I think it's an issue with setting sticky bits on temporary connection files that are being created?

File
  "/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/exporters/exporter.py",
  line 172, in from_filename
  return self.from_file(f, resources=resources, **kw)
  File
  "/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/exporters/exporter.py",
  line 190, in from_file
return self.from_notebook_node(nbformat.read(file_stream, as_version=4), resources=resources, **kw)

File
  "/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/exporters/html.py",
  line 84, in from_notebook_node
return super(HTMLExporter, self).from_notebook_node(nb, resources, **kw)                File "/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/exporters/templateexporter.py",

line 268, in from_notebook_node
nb_copy, resources = super(TemplateExporter, self).from_notebook_node(nb, resources, **kw)

File
  "/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/exporters/exporter.py",
  line 132, in from_notebook_node
nb_copy, resources = self._preprocess(nb_copy, resources)                               File

"/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/exporters/exporter.py",
  line 309, in _preprocess
nbc, resc = preprocessor(nbc, resc)        File "/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/preprocessors/base.py",

line 47, in call
return self.preprocess(nb,resources)       File "/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/preprocessors/execute.py",

line 237, in preprocess
cwd=path)                                  File "/Users/zblanton/anaconda/lib/python3.6/site-packages/nbconvert/preprocessors/execute.py",

line 217, in start_new_kernel
km.start_kernel(**kwargs)                  File "/Users/zblanton/anaconda/lib/python3.6/site-packages/jupyter_client/manager.py",

line 238, in start_kernel
self.write_connection_file()               File "/Users/zblanton/anaconda/lib/python3.6/site-packages/jupyter_client/connect.py",

line 431, in write_connection_file
kernel_name=self.kernel_name               File "/Users/zblanton/anaconda/lib/python3.6/site-packages/jupyter_client/connect.py",

line 157, in write_connection_file
RuntimeWarning,                            File "/Users/zblanton/anaconda/lib/python3.6/warnings.py", line 99, in

_showwarnmsg
      msg.file, msg.line)                        File "dodo.py", line 16, in warn_with_traceback
      traceback.print_stack(file=log)

For what it's worth, the notebook I was using looks like this:
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "be nice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n"
     ]
    }
   ],
   "source": [
    "print(3 * 3)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}


text:
Q: How to do AutoFocus on angular dynamic form i have a dynamic form and add element  on my button,
but I want to add focus on new element
//Html

+

                  <textarea class="form-control" [(ngModel)]="mission.description" name="description_{{i}}_{{j}}"
                            placeholder="Description"  cols="20" rows="3"></textarea>

// TS
  public addMission(i: number) {
    this.mission = new Mission();
    this.mission.id = null;
    this.mission.description = '';
    this.service.list_experience[i].missions.push(this.mission);
    this.service.list_experience[i].focus();;
  }

I looking for a fings like that

A: You could try to add a custom id for each "mission" based on its index.
For instance
<textarea class="form-control" [(ngModel)]="mission.description" name="description_{{i}}_{{j}}" placeholder="Description"  cols="20" rows="3" id="{{ 'missionNumber_' + j }}"></textarea>

Then you can request each element inside your component :
  public addMission(i: number) {
    this.mission = new Mission();
    this.mission.id = null;
    this.mission.description = '';
    this.service.list_experience[i].missions.push(this.mission);

    const lastMission = this.document.getElementById("#missionNumber_" + i);

    lastMission.focus();;
  }

A: //Html

+

                  <textarea id="missionNumber_{{i}}_{{j}}" class="form-control" [(ngModel)]="mission.description" name="description_{{i}}_{{j}}"
                            placeholder="Description"  cols="20" rows="3"></textarea>

// TS
  public addMission(i: number) {
    this.mission = new Mission();
    this.mission.id = null;
    this.mission.description = '';
    this.service.list_experience[i].missions.push(this.mission);
    this.service.list_experience[i].focus();
    onst j = this.cvService.list_experience[i].missions.length -1;
    setTimeout(()=>{ // this will make the execution after the above boolean has changed
      this.renderer2.selectRootElement('#missionNumber_'+i +'_'+ j).focus();
    },0);

Add renderer2 on constructor
it's work like that. but if you have the best answer to fill in to replace the timeout, I'll take it.


text:
Q: Transform YYYYMM to DD-MM-YYY SQL Server I have a column in sql server like 201801. How can I transform this in DD-MM-YYYY?
Thank you!

A: Assuming date column has varchar type, then you can do :
select convert(varchar(12), cast(col+'01' as date), 105)
from table t;


text:
Q: Migradoc and PDfSharp add line after text till the end of the page I have this so far:
Table table = CreateBaseTable();
Row row = table.AddRow();
    {
        row.Cells[0].AddParagraph().AddFormattedText(text, bold);
    }

I would like to have a line after this text, for example:
This Is a Header ------------------------------------------------------------------------------------
but not dotted.
Thanks

A: If you want a line to the right of your text: use a tab stop with a line as filling (that's how it looks like in your question but I presume this is not what you want).
If you want to have the line below the text: set the border of the table cell (or table row). In your case, set the bottom border width to the desired width, set the width of other borders (top, left, right) to 0.
For the row, try code like this:
row.Borders.Bottom.Visible = true;
row.Borders.Bottom.Width = 1;

Edit: Here's sample code for the tab stop:
paragraph = section.AddParagraph("Hello, World!");
paragraph.Format.TabStops.ClearAll();
paragraph.Format.TabStops.AddTabStop("16cm", TabAlignment.Right, TabLeader.Lines);
paragraph.AddTab();

I should have tested that before pointing that option out. The line is drawn at the base, so it looks like
The Header_____________________
TabLeader also offers Dashes (which you don't want) or MiddleDots (which you didn't ask for either).
So I'm afraid there is no simple solution to get exactly what you want.


text:
Q: Unable to boot ArchLinux on Macbook Pro 7.1 - drops to recovery shell My MBP fails to boot Arch.
This is what I did to install ArchLinux.
Install rEFIT.
Partition using disk utility such that first one is Mac partition, second is Arch & the third ie the last one is windows.
Then put Windows 7 CD, select it from rEFIT and install it.
Similar, install ArchLinux just as I did for windows.
Then finally to install the GRUB, I issued the command $grub-install --root-directory=/mnt/arch --recheck /dev/sda3 (after mounting my /dev/sda3 to /mnt/arch).

This is the exact error and then it drops to recovery:

Error after typing exit:

I have tried rootfstype too. No success.
My menu.lst (I have tried /dev/sda3 too):

A: Removed autodetect HOOK and created the kernel image & now it boots.

A: I think you have put a wrong entry in grub...put the  correct entry for root section of the grub entry.You said arch is in 2nd partition right?? Then it should read like below
root (hd0,1)
Grub is not able find you disk partition containing Arch install;so drop you to a recovery shell.
The error msg also said that no /dev/sda3 partition exist!!! how did you install Arch??


text:
Q: How can I create a "duck-typed" grpc protobuf Message at runtime in Go? I'm using grpc protobuf Message definitions and implementing them in Go.
My ultimate goal is for my rpc to retrieve some json on a user and return a Profile Message with optional, nested Messages to be used for unmarshalling a subset of the json.
using this rpc:
  rpc GetUser (GetUserRequest) returns (Profile) {
    option (google.api.http) = {
      get: "/user/{id=*}"
    };
  }

and assuming the following json:
{
  "profile": {
     "foo": {
        "name": "tim"
        "age": 22
      },
     "bar": {
       "level": 5
     }
  }
}

I want to return a Profile Message containing  only "foo", "bar", or both, as nested Messages based on an incoming runtime scope parameter of the grpc request (currently, scope would be a list of strings containing the Message names to be used for subsetting the json into respective Messages e.g. ["Foo","Bar"]).
given these Message definitions:
message Profile {
  //both Foo & Bar are optional by default
  Foo foo = 1 [json_name="foo"];
  Bar bar = 2 [json_name="bar"];
}

message Foo {
  string name = 1 [json_name="name"];
  int32 age = 2 [json_name="age"];
}

message Bar {
  string level = 1 [json_name="level"];
}

then in the case that scope is ["Foo"], I'd like the rpc to return:
Profile{
  Foo: // Foo Message unmarshalled from json
}

or if "scope" is ["Foo","Bar"] then:
Profile{
  Foo:
  Bar:
}

The problem seems to boil down to "duck-typing" a Message type.
Attempt 1
I got close to finding a solution using protoreflect & protoregistry by doing:
import(
    "google.golang.org/protobuf/reflect/protoregistry"
    "google.golang.org/protobuf/reflect/protoreflect"
)

var scope protoreflect.FullName = "Foo"
var types = new(protoregistry.Types)
var message, errs = types.FindMessageByName(scope)
var almost_foo = message.New()

// using `myJson` object without top level "profile" key to make testing more simple at the moment
var myJson = `{ "foo": { .. }, "bar", { ... } }`
err = json.Unmarshal([]byte(myJson), almost_foo)

but when I attempt to create Profile Message using almost_foo:
var profile = &pb.Profile{almost_foo}

I get error: cannot use almost_foo (type protoreflect.Message) as type *package_name.Foo in field value
Attempt 2
using
import(
  "github.com/jhump/protoreflect/desc"
  "github.com/jhump/protoreflect/dynamic"
)

I try to dynamically create the message again:
var fd, errs = desc.LoadFileDescriptor("github.com/package/path/..")
var message_desc = fd.FindMessage("Foo")
var almost_foo = dynamic.NewMessage(message_desc)

and a similar error occurs:
cannot use almost_foo (type *dynamic.Message) as type *package_name.Foo in field value
Both attempts almost create a Message but the type system still doesn't allow either to actually be used.
Any help is appreciated.

A: I managed to solve this by whittling down the json to what I want first and then putting it through Unmarshal.
I created a top level Message that takes Profile as a field:
message GetUserResponse {
  Profile profile = 1;
}

and redefined the response:
rpc GetUser (GetUserRequest) returns (GetUserResponse)

To build the allowed/scoped json, I use:
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"

I copy the json dictated by the scope paths (dot-delimited e.g. ["profile.foo"]) over to an initially empty, output, response_json string, and build up only the allowed json to be returned.
var response_json string

var scopes = []string{"profile.foo"}

for _, scope := range scopes {
    // copy allowed json subset in raw form
    value := gjson.Get(myJson, scope + "|@ugly")

    // if scope didn't copy a value, skip
    if value.String() == "" {
        continue
    } else {
        // write value to output json using SetRaw since value can be an object
        response_json, _ = sjson.SetRaw(response_json, scope, value.Raw)
    }
}

response_json looks like:
{
  "profile": {
     "foo": {
        "name": "tim"
        "age": 22
      }
  }
}

and then Unmarshal:
response = &pb.VerifyUserResponse{}
err = json.Unmarshal([]byte(response_json), response)


text:
Q: Django redirect error 500 to 404 when language not found I noticed that, when a language is referred in settings.py without proper pages in the website, it generates 500 pages.
For exemple :
    LANGUAGES = (
    ('en', gettext('English')),
    ('fr', gettext('French')),
    ('it', gettext('Italian')),
    ('es', gettext('Spanish')),
    ('de', gettext('German')),
    ('el', gettext('Greek')),
    ('tr', gettext('Turkish')),
    ('ja', gettext('Japanese')),
    ('pt', gettext('Portuguese')),
    ('ar', gettext('Arabic')),
)

So, on my website, en fr es de and ja are translated and present on the website. Others aren't.
Then, if you try to reach : example.org/el/whatever it's raising a 500 error.
I would like to have a 404 in order to let the user in the website.
Does anyone has a clue about this problem ? Or do I have to remove the languages from the settings ?
many thanks.
Edit : here is the report I have with this error :
 Internal Server Error: /it/blog/
Traceback (most recent call last):
  File "/var/www/webapps/lib/python3.4/site-packages/cms/views.py", line 34,
 in _handle_no_page
    resolve('%s$' % request.path)
  File
 "/var/www/webapps/lib/python3.4/site-packages/django/core/urlresolvers.py", line 494, in resolve
    return get_resolver(urlconf).resolve(path)
  File
 "/var/www/webapps/lib/python3.4/site-packages/django/core/urlresolvers.py", line 358, in resolve
    raise Resolver404({'tried': tried, 'path': new_path})
django.core.urlresolvers.Resolver404: {'tried': [[<RegexURLResolver <module
 'autocomplete_light.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/autocomplete_light/urls.py'> (None:None) ^autocomplete/>],
 [<RegexURLResolver <module 'djangocms_contact.urls' from
 '/var/www/webapps/proj_website/app/djangocms_plugins/djangocms_contact/urls.py'> (None:None)
 ^api/contact_plugin/>], [<RegexURLResolver <module 'taggit_autosuggest_select2.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/taggit_autosuggest_select2/urls.py'>
 (None:None) ^taggit_autosuggest_select2/>], [<RegexURLPattern None
 ^sitemap\.xml$>], [<RegexURLPattern None ^sitemap-(?P<section>.+)\.xml$>],
 [<LocaleRegexURLResolver <RegexURLPattern list> (None:None) ^it/>, <RegexURLPattern
 None ^share/>], [<LocaleRegexURLResolver <RegexURLPattern list> (None:None)
 ^it/>, <RegexURLResolver <module 'djangocms_job.urls' from
 '/var/www/webapps/proj_website/app/djangocms_plugins/djangocms_job/urls.py'> (None:None)
  ^api-job_plugin/>], [<LocaleRegexURLResolver <RegexURLPattern list>
 (None:None) ^it/>, <RegexURLResolver <RegexURLPattern list> (admin:admin)
 ^admin/>], [<LocaleRegexURLResolver <RegexURLPattern list> (None:None) ^it/>,
 <RegexURLResolver <module 'cms.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/cms/urls.py'> (None:None) ^>, <RegexURLPattern pages-details-by-slug
 ^(?P<slug>[0-9A-Za-z-_.//]+)/$>], [<LocaleRegexURLResolver <RegexURLPattern
 list> (None:None) ^it/>, <RegexURLResolver <module 'cms.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/cms/urls.py'> (None:None) ^>,
 <RegexURLPattern pages-root ^$>], [<RegexURLResolver <module 'rosetta.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/rosetta/urls.py'> (None:None)
 ^rosetta/>]], 'path': 'it/blog/$'}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File
 "/var/www/webapps/lib/python3.4/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/var/www/webapps/lib/python3.4/site-packages/cms/views.py", line
 118, in details
    return _handle_no_page(request, slug)
  File "/var/www/webapps/lib/python3.4/site-packages/cms/views.py", line 38,
 in _handle_no_page
    raise exc
django.http.response.Http404: {'tried': [[<RegexURLResolver <module
 'autocomplete_light.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/autocomplete_light/urls.py'> (None:None) ^autocomplete/>], [<RegexURLResolver
 <module 'djangocms_contact.urls' from
 '/var/www/webapps/proj_website/app/djangocms_plugins/djangocms_contact/urls.py'> (None:None) ^api/contact_plugin/>],
 [<RegexURLResolver <module 'taggit_autosuggest_select2.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/taggit_autosuggest_select2/urls.py'>
 (None:None) ^taggit_autosuggest_select2/>], [<RegexURLPattern None
 ^sitemap\.xml$>], [<RegexURLPattern None ^sitemap-(?P<section>.+)\.xml$>],
 [<LocaleRegexURLResolver <RegexURLPattern list> (None:None) ^it/>, <RegexURLPattern None
 ^share/>], [<LocaleRegexURLResolver <RegexURLPattern list> (None:None)
 ^it/>, <RegexURLResolver <module 'djangocms_job.urls' from
 '/var/www/webapps/proj_website/app/djangocms_plugins/djangocms_job/urls.py'> (None:None)
 ^api-jo
 b_plugin/>], [<LocaleRegexURLResolver <RegexURLPattern list> (None:None)
 ^it/>, <RegexURLResolver <RegexURLPattern list> (admin:admin) ^admin/>],
 [<LocaleRegexURLResolver <RegexURLPattern list> (None:None) ^it/>,
 <RegexURLResolver <module 'cms.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/cms/urls.py'> (None:None) ^>, <RegexURLPattern pages-details-by-slug
 ^(?P<slug>[0-9A-Za-z-_.//]+)/$>], [<LocaleRegexURLResolver <RegexURLPattern list>
 (None:None) ^it/>, <RegexURLResolver <module 'cms.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/cms/urls.py'> (None:None) ^>, <RegexURLPattern
 pages-root ^$>], [<RegexURLResolver <module 'rosetta.urls' from
 '/var/www/webapps/lib/python3.4/site-packages/rosetta/urls.py'> (None:None) ^rosetta/>]],
 'path': '/it/blog/'}

And it continues like this (I have 2 more big paragraphes) starting with :
Traceback (most recent call last):
  File "/var/www/webapps/lib/python3.4/site-packages/cms/views.py", line 34,

and :
Traceback (most recent call last):
  File
 "/var/www/webapps/lib/python3.4/site-packages/django/core/handlers/base.py", line 150, in get_response
    response = callback(request, **param_dict)
  File "/var/www/webapps/proj_website/app/proj/views.py", line 84, in
 custom_page_not_found

A: It seems that something goes wrong in your views.py.
So you need to do the following in your view that is getting problem:
from django.http import Http404

def your_view(request):
    try:
       code_that_must_work_but_can_fail="goes here"
    except Exception, e:
       raise Http404

So what we've doing here is just wrapping all of code within view in try: except: so if somethng will go wrong in try block it will move to except block and there is raise instruction which will return 404 page.
Please create 404.html and 500.html in your templates to have nice pages even with 500


text:
Q: Can I use CSS Flexbox to remove columns? Is there some way CSS flexbox will remove columns (flex items) when the available real estate is small - similar to the functionality provided by FooTable?

A: The element will tighten up to 0px if needed. Hiding the content can be handled by using overflow: hidden, but beware that this may create problems in other scenarios.
Check the following snippet to see the result:

.container {
    display: flex;
}

.child1, .child3 {
    flex: 1 0 50%;
}

.child2 {
    flex: 1;
    overflow: hidden;
}

child1

child2

child3

Other suggestions:

*

*Use media queries to hide the content depending on the window size;

*Use media queries to apply the overflow property depending on the window size;

*If you don't want to hide it, go with flex-wrap to spread your flex items into 2+ rows