text:
Q: How to replace global variables in Python I was hoping someone could give me some advice on how to improve my code so that I don't need to use global variables. (I've slightly simplified/shortened the code below to focus on the problem)
The code works as follows: there are two process (pan and tilt), both of them use the function pid_process which will calculate an error number. if both pan and tilt error states are below 10 (both true), I want to do something.
I've got it working with global variables but it seems not to be the best way in Python and was wondering if someone could help me write better code.
tilt_error = False
pan_error = False

def checkErrorMargin(action, error):
    global tilt_error
    global pan_error

    if 'tilt' in action:
        if error < 10:
            tilt_error = True
        else:
            tilt_error = False
        return tilt_error
    else:
        if error < 10:
            pan_error = True
        else:
            pan_error = False
        return pan_error

def pid_process(action, error):
    global tilt_error
    global pan_error

    # in original code - error number will be calculated here

    if 'tilt' in action:
        tilt_error = checkErrorMargin(action, error)
    else:
        pan_error = checkErrorMargin(action, error)

    if tilt_error and pan_error:
        print("do something")

for x in range(0,3):
    pid_process("pan", x+8)
    pid_process("tilt", x+1)

A: thanks for the help. it's working now
def checkErrorMargin(action, error):

    if 'tilt' in action:
        if error < 10:
            tilt_error = True
        else:
            tilt_error = False
        return tilt_error
    else:
        if error < 10:
            pan_error = True
        else:
            pan_error = False
        return pan_error

def pid_process(action, error):

    if 'tilt' in action:
        tilt_error = checkErrorMargin(action, error)
        return tilt_error
    else:
        pan_error = checkErrorMargin(action, error)
        return pan_error

for x in range(0,3):

    pan_error = pid_process("pan", x+8)
    tilt_error = pid_process("tilt", x+1)

    if tilt_error and pan_error:
        print("fire")


text:
Q: Error save data in database I have page that related with two table using the same database. the problem is when i try to save data into table #A, the data also save in table #B, i want the data only save in table #A but i got id from table #B.
Model for table #A
@JoinColumn(name = "VACANCYNAME", referencedColumnName = "ID")
@ManyToOne
private Vacancy vacancyname;

Model for table #B
@OneToMany(mappedBy = "vacancyname")
private List<ApplicantVacancy> applicantVacancyList;

jsp for table #A

    Vacancy Name
    <form:input path="vacancyname.vacancyname" value="${param.name}" readonly="true"/>

jsp for table #B
Webpage URL : http://localhost:8080/hrms/applicantvacancy/index.htm

A: I don't know your implementation, but this readOnly="true" dont't seems very well to persist the object in db.
Try to put it false.

    Vacancy Name
    <form:input path="vacancyname.vacancyname" value="${param.name}" readonly="false"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to mask a floating-point image in OpenCV? I have a Nx1 matrix of floating-point values. I wish to get the average of only those values starting from the 22nd to the Nth item.  I have created a binary mask of Nx1 dimensions, put 0s in the range [0,21] and 1s in the rest. Applying that mask while calculating the average (using inbuilt functions for maximum speed) gives an error. The code snippet is given below.
The error is:

sizes on input arguments do not match in cvSvg()"

What should be the correct mask? I have tried using floating-points instead of integers in the mask, still not working.
CvMat mask;
int i;
int N = img->width;
IplImage* W = cvCreateImage( cvSize(N, 1), IPL_DEPTH_32F , 1 );
IplImage* A = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F , 1 );
cvConvertScale(img, A);
int* vals = (int*)malloc(N*sizeof(int));

for(i=0; i<N; i++)
{
    if(i<22)
        vals[i] = 0;
    else
        vals[i] = 1;
}
cvInitMatHeader(&mask, N, 1, CV_8U, vals);

cvSVD(A, W, NULL, NULL, CV_SVD_MODIFY_A);

CvScalar mean = cvAvg(W, &mask);

A: Here is how I computed the mask with a contrived example, but it appears to work just fine.
int main(int argc, char* argv[])
{
    int N = 50;
    CvMat* a = cvCreateMat(1, N, CV_32FC1);
    CvMat* mask = cvCreateMat(1, N, CV_8UC1);

    float* aData = a->data.fl;
    uchar* maskData = mask->data.ptr;

    for(int i = 0; i < a->cols; i++)
    {
        aData[i] = (float)i;

        if(i < 22)
        {
            maskData[i] = 0;
        }
        else
        {
            maskData[i] = 1;
        }
    }

    CvScalar avg = cvAvg(a);
    cout << "Average without mask: " << avg.val[0] << endl;

    avg = cvAvg(a, mask);
    cout << "Average with mask: " << avg.val[0] << endl;

    cvReleaseMat(&a);
    cvReleaseMat(&mask);
    return 0;
}

This produces the following output:
Average without mask: 24.5
Average with mask: 35.5

So, it is working for this simple example. Hopefully that will get you going again.

A: the image you use as mask does not have to be double, but Uint, the code is fine I think, not really sure about the initialization of the mask.
still you must declare W as follow
IplImage* W = cvCreateImage( cvSize(N, 1), IPL_DEPTH_8U, 1 );


text:
Q: Selecting an id from database using razor pages? I am the following. As a user registers his account name and password are put into an existing table. Then his id gets read from that table and another table is made using that id as the tablename.
Now inserting works great but reading the Id from that table seems to give me some problems.
Now it would be great if I was even able to get that id to display on my webpage. i feel like when I am able to do that I can just do something like CREAT TABLE + @Id + etc.
This is what I have so far
var gebruikersnaam = Request.Form["registnaam"];
var wachtwoord = Request.Form["registpassword"];

if (IsPost && Request.Form["registreren"] == "Registreren")
{
    var insertCommand = db.Execute("INSERT INTO Accounts (gebruikersnaam, wachtwoord) VALUES(@0, @1)", gebruikersnaam, wachtwoord);
    var id = db.Query("SELECT * FROM Accounts WHERE gebruikersnaam = @0", gebruikersnaam);
    Response.Write(@id);
}

And this is what the Response.Write(@id) shows me on the webpage:
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]

A: Try merging the create and select query into one.
INSERT INTO Accounts (gebruikersnaam, wachtwoord)
OUTPUT Inserted.Id
VALUES('value1', 'value2')

Getting the Id using a separate query could be a problem in the future especially if the data becomes large, doing this optimize the speed of data retrieval in DB like getting the Id of an inserted record.


text:
Q: Modern C++ version of the expression tree https://gist.github.com/2934374   https://gist.github.com/2934374
So I was intrigued by this comparison and also by the awful C++ solutions that appeared in the comments, but I must admit I'm having trouble to write a nice solution myself :-)
My current attempt looks like this, the problems are:

*

*the environment is copied when the tree is created, I would like the variables to be changeable after the tree is created

*it still looks pretty ugly

So how could I squish it a bit and bind the variables so they would be affected by changes?
#include <map>
#include <string>
#include <iostream>
#include <functional>
using namespace std;

/* environ */
map<string,int> variables = { { "a" , 3 }, { "b", 4 }, { "c", 5 } };

function<int(int,int)> add = [] (int lp, int rp) { return lp + rp; };
function<int(int,int)> mlt = [] (int lp, int rp) { return lp * rp; };

/* impl */
struct Var {
    Var(int v) : p_v(v) {};
    int eval() { return p_v; };

private:
    int p_v;
};

template <typename LP, typename RP>
struct Op {
    Op(function<int(int,int)> op, LP lp, RP rp) : p_op(op), p_l(lp), p_r(rp) {};
    int eval() { return p_op(p_l.eval(), p_r.eval()); }
private:
    function<int(int,int)> p_op;
    LP p_l;
    RP p_r;
};

Var var(int val) { return Var(val); }

template <typename LP, typename RP>
auto op(function<int(int,int)> op, LP lp, RP rp) -> Op<LP,RP>
{
    return Op<LP,RP>(op,lp,rp);
}

Var operator "" _var(const char *key, size_t length)
{ return Var(variables[key]); }

/* gcc is failing me
Var operator "" _num(int val)
{ return Var(val); }
*/

int main()
{
    auto tree = op ( add, "a"_var, op ( mlt, var ( 2 ), "b"_var ));
    cout << tree.eval() << endl;
}

A: You're re-inventing the Standard bind mechanism. There's no need for any glue code to be written by the user.
auto tree = bind(plus<int>(), ref(variables["a"]), bind(multiplies<int>(), 2, ref(variables["b"])));
cout << tree();

http://liveworkspace.org/code/f06fd83b5d7bcbf4829306d4e590da38
std::ref makes it a reference, not a value- this means that you could bind a mutating operation.


text:
Q: создание формы для добавления данных в таблицу Есть метки задач с задачами

На главной странице нужно создать форму для добавления задач, причем нужно иметь возможность выбрать метку для этой задачи. В итоге должно получиться что-то типа такого.

Код для контроллера для добавления задачи
class TodoItemsController < ApplicationController
before_action :set_todo_list
def create
    @todo_item = @todo_list.todo_items.create(todo_item_params)
    if @todo_item.save
        redirect_to @todo_list
    end
end

def destroy
    @todo_item = @todo_list.todo_items.find(params[:id])
    if @todo_item.destroy
        flash[:success] = "Задача была удалена!"
    else
        flash[:error] = "Задача не была удалена, повторите попытку снова!"
    end
    redirect_to @todo_list
end

private

def set_todo_list
    @todo_list = TodoList.find(params[:todo_list_id])
end

def todo_item_params
    params[:todo_item].permit(:text)
end
end

Сколько я бы не мучился, не получается это сделать, от слова совсем, буду очень рад любой помощи.

A: Собственно сам ответ, спустя несколько часов:)

          <%= form_for :todo, url: todos_path do |form| %>
            <%= form.text_field :text, placeholder: 'Название задачи' %>
            <%= form.select(:project_id, Project.all.collect{|p| [ p.title, p.id ] }, {include_blank: 'None'}) %>

            <%= form.submit %>
            ОТМЕНА
          <% end %>


text:
Q: Why does /proc/cpuinfo say "cpu cores: 2" on an AMD FX-4100 Quad-Core Processor I'm trying to figure out how to interpret my /proc/cpuinfo. I've got an AMD FX-4100 quad-core and cpuinfo gives, as it should, 1 'physical id', 4 'core id's and 4 'siblings', but why does 'cpu cores' say 2 instead of 4? Also, the FX-4100 specs say 4MB L2 cache yet cpuinfo says 2MB.
Included below is the text for processor 0.
processor       : 0
vendor_id       : AuthenticAMD
cpu family      : 21
model           : 1
model name      : AMD FX(tm)-4100 Quad-Core Processor
stepping        : 2
microcode       : 0x600063d
cpu MHz         : 1400.000
cache size      : 2048 KB
physical id     : 0
siblings        : 4
core id         : 0
cpu cores       : 2
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc $
bogomips        : 7248.64
TLB size        : 1536 4K pages
clflush size    : 64
cache_alignment : 64
address sizes   : 48 bits physical, 48 bits virtual
power management: ts ttp tm 100mhzsteps hwpstate cpb

A: It says that you've 2 CPU cores because you have 2 CPU cores. The AMD FX-4100 has 2 cores and 2 modules.
From answers.yahoo.com

Your FX is closer to a dual core. To be precise, it's two modules.
  Bulldozer uses modules, and each module consists of one FP scheduler
  and 2 int schedulers.
This is AMD's answer to "hyperthreading" - it's cheaper to
  manufacture, can potentially result in faster overall performance at a
  marginal manufacturing cost, and it lets them get away with selling
  crappy cpus to people who don't understand or read benchmarks/reviews
  etc.
In the end, Bulldozer was a flop. The per-core performance is what
  matters and it loses to Intel by a significant margin.  Even when all
  core are loaded, Bulldozer doesn't compare very well to Intel, but can
  pull ahead ever so slightly in some highly-threaded apps.
Finally, hyperthreading doesn't need to be enabled on the modern CPUs
  that do support it (yours does not).


text:
Q: Format Change Event for Excel VBA I'm trying to prevent people from modifying (most) of my spreadsheet while still alowing them to use the sort function of the AutoFilter. What I've done so far is used the Worksheet_Change event and Application.Undo to automatically undo any values entered into cells that I don't want to be modified. This works great, except that it can't detect changes in formatting. Does anyone know of a means to trigger an event when the format (text/background color) of a cell is changed?
Thanks!

A: The events you are limited to at the worksheet level are as follows:
Activate
BeforeDoubleClick
BeforeRightClick
Calculate
Change
Deactivate
FollowHyperLink
PivotTableUpdate
SelectionChange

I suppose you could try something at the SelectionChange event.  If someone changes the formatting of a cell and then moves to a different cell that event will be called.
Whatever code you have in that area will constantly be called, so it would be a good idea to preface whatever you do with some quick checks to make sure the cells are in a certain range, have data, etc.  Your sheet could get pretty sluggish otherwise as users move from cell to cell.

A: i found it pretty simple:
At ThisWorkbook:
Public Sub Workbook_Open()
Set SelectLast = Range("A1")
SelectVal = Range("A1").Value
SelectColor = Range("A1").Interior.Color
End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Excel.Range)
Dim LastVal As String
Dim LastColor As String
LastVal = ""
LastColor = ""
For i = 1 To SelectLast.Columns.Count
    For y = 1 To SelectLast.Rows.Count
        LastVal = LastVal & SelectLast.Cells(y, i).Value
        LastColor = LastColor & SelectLast.Interior.Color
    Next
Next
If ((LastVal <> SelectVal) Or (LastColor <> SelectColor)) Then MsgBox ("Something happend")
SelectVal = ""
SelectColor = ""
For i = 1 To Target.Columns.Count
    For y = 1 To Target.Rows.Count
        SelectVal = SelectVal & Target.Cells(y, i).Value
        SelectColor = SelectColor & Target.Interior.Color
    Next
Next
Set SelectLast = Target
End Sub

and at Module1
Global SelectLast As Excel.Range
Global SelectVal As String
Global SelectColor As String

It possible watch anything with slight modification.


text:
Q: How do I load my Solana wallet using my private key file? I'm attempting to use the private key I generated using the Solana command-line to create a wallet in JavaScript / Node.
I want to use the web3.Keypair.fromSeed() method.
Here are the steps I've take so far.

*

*created a solana wallet : solana-keygen new -o keyfile.json

*display what is in that file -- it's a 64 byte array (this is a test key so no worries that this is the private key

[237,158,92,107,132,192,1,57,8,20,213,108,29,227,37,8,3,105,196,244,8,221,184,199,62,253,98,131,33,165,165,215,14,7,46,23,221,242,240,226,94,79,161,31,192,163,13,25,106,53,34,215,83,124,162,156,8,97,194,180,213,179,33,68]
However, the call to fromSeed() only wants 32 bytes.
3. check the solana address so I know when everything is working properly  :
>  solana address -->
wm4MapPtFaUoSsyBJppVnChYMGvHzTeAL6BNZ5GmSqH

That's the public key
How do I call web3.Keypair.fromSeed() to load that private key and get my public address (aka public key)?

A: let web3 = require('@solana/web3.js');
let splToken = require('@solana/spl-token');

// load up the first 32 bytes of the 64 byte array that was in our keyfile.json
// Only need the first 32 bytes so I use slice() just to make sure it's the correct length
let firstWinPrivKey = [237,158,92,107,132,192,1,57,8,20,213,108,29,227,37,8,3,105,196,244,8,221,184,199,62,253,98,131,33,165,165,215,14,7,46,23,221,242,240,226,94,79,161,31,192,163,13,25,106,53,34,215,83,124,162,156,8,97,194,180,213,179,33,68]
    .slice(0,32);
  // print the length of the array so we know it is correct
  // the fromSeed() method requires 32 bytes

 console.log(firstWinPrivKey.length);
  let firstWinWallet = web3.Keypair.fromSeed(Uint8Array.from(firstWinPrivKey));
  console.log(firstWinWallet.secretKey);
  console.log(firstWinWallet.publicKey.toString());

Notice that you have to cast the array to a Uint8Array (Uint8Array.from())
When we print out the secretKey, you'll see the same bytes you passed in.
And finally when we print out the publicKey you'll see that same value that we saw with the command line
> solana address
Now you can use the wallet in code.
Here's the final output from this short script:
32
Uint8Array(64) [
  237, 158,  92, 107, 132, 192,   1,  57,   8,  20, 213,
  108,  29, 227,  37,   8,   3, 105, 196, 244,   8, 221,
  184, 199,  62, 253,  98, 131,  33, 165, 165, 215,  14,
    7,  46,  23, 221, 242, 240, 226,  94,  79, 161,  31,
  192, 163,  13,  25, 106,  53,  34, 215,  83, 124, 162,
  156,   8,  97, 194, 180, 213, 179,  33,  68
]
wm4MapPtFaUoSsyBJppVnChYMGvHzTeAL6BNZ5GmSqH

A: If you want to use ".json" file, you can do something like this:
import Fs from "@supercharge/fs";
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";

const decodedKey = new Uint8Array(
JSON.parse(
  //replace with actual path from home dir. For example '.config/solana/devnet.json'
  Fs.readFileSync(Fs.homeDir("path to key.json")).toString();
));

let keyPair = Keypair.fromSecretKey(decodedKey);

I use additional package https://www.npmjs.com/package/@supercharge/fs for working with files.

A: import { Keypair } from "@solana/web3.js";
import fs from "fs";

function loadKeypairFromFile(filename: string): Keypair {

  const secret = JSON.parse(fs.readFileSync(filename).toString()) as number[];
  const secretKey = Uint8Array.from(secret);
  return Keypair.fromSecretKey(secretKey);
}


text:
Q: SQL Server CASE statement with multiple THEN clauses I have seen several similar questions but none cover what I need. I need to put another THEN statement after the first one. My column contains int's. When it returns NULL I need it to display a blank space, but when I try the below code, I just get '0'.
CASE
    WHEN Column1 IS NULL
    THEN ''
    ELSE Column1
END

If I try to put a sting after THEN then it tells me that it cannot convert it from int. I need to convert it to varchar and then change its output to a blank space afterwards, such as:
e.g.
CASE
    WHEN Column1 IS NULL
    THEN CONVERT(varchar(10), Column1)
    THEN ''
    ELSE Column1
END

Is there a way of doing this?
Thanks
Rob

A: A case expression returns a single value -- with a given type.  If you want a string result, then you need to be sure that all paths in the case return strings:
CASE WHEN Column1 IS NULL
     THEN ''
     ELSE CAST(Column1 AS VARCHAR(255))
END

This is more simply written using COALESCE():
COALESCE(CAST(Column1 as VARCHAR(255)), '')

You cannot display an integer as a "blank" (other than using a NULL value).


text:
Q: Should I design with MDBootstrap or Material 2 in designing a responsive app for all platforms I have been recently designing a basic site and learning angular 2.
I have created a basic site (navbar, landing page, 404) with Angular 2 Material ( https://material.angular.io/ ) and its fine although im having alot of trouble with making it correctly responsive with window size.
Is MD Bootstrap ( https://mdbootstrap.com ) a better solution currently because Material 2 is still in heavy development or is Material 2 what I should get used to in creating modern web applications and becoming the industry standard.
I am open to whatever and dont have any bias with what 'should be used' according to company or brand loyalty, I just want to know as a web developer pretty new to Angular 2 web app design what would be the best to learn for me and for my future in webdev?
Thanks!
Side note Why should I start using Google Material Design Lite instead of Twitter Bootstrap or Foundation I read through this and its information and answers are outdated? It seems that MDBootstrap supports Typescript, angular 2 and no jquery as of now so should i not even bother with Material 2 for the time being?
Any feedback is greatly appreciated for a new programmer like myself :)

A: All these frameworks you mentioned will serve you. This fight for which framework to use is 70% personal preference. I would advice you go for anyone that has enough user base and has been tested and trusted, because when you need help(don't we all need help), the number of people using it will come into play for your advantage.
Apart from that, pick the one you fancy and throw shades to your friends about using something else. LOL.


text:
Q: swapping string in c using pointer Need help
this is my code
void swapstringfun()
{
   int i=0,j=0;
   char *str=(char *)malloc(sizeof(char)*15);
   char *mystr=(char *)malloc(sizeof(char)*15);
   system("cls");
   printf("Please enter first string :\t");
   scanf("%s",str);
   printf("Please enter second string :\t");
   scanf("%s",mystr);
   while(*(str+i)!='\0' && *(mystr+i)!='\0')
   {
     *(str+i) ^=*(mystr+i);
     *(mystr+i) ^=*(str+i);
     *(str+i) ^=*(mystr+i);
     i++;
   }
   printf("%s swapped to %s",str,mystr);
   getch();
   main();
}

I wrote the above code to swap the string using XOR operator. The problem with this code is. when my input is lets say.. RAJESH and ASHISH. Then, it shows output ASHISH and RAJESH. And, that is expected.
But, when input is let say.. ABHISHEK and CODER .Then, output is CODERHEK and ABHIS. But, the expected output is CODER and ABHISHEK. Anyone help me to solve this problem. I will appreciate.

A: You iterate and swap until you reach the end of the shorter string
while(*(str+i)!='\0' && *(mystr+i)!='\0')

(or both, if the lengths are equal). To iterate until you reach the end of the longer string, you need an || instead of the && and be sure that 1. both pointers point to large enough memory blocks, and 2. the shorter string ends with enough 0 bytes. So you should calloc the memory, not malloc.
However, you should swap the pointers, really,
char *tmp = str;
str = mystr;
mystr = tmp;

A: You also need to swap the terminating 0, as its part of what is called a string in C.
The 0 is the stopper element in the character array, describing the string.

A: You need to XOR the entire length of both strings. Since in your second example, the strings are different lengths, your algorithm won't work.
This is the statement you'll have to reconsider:
while(*(str+i)!='\0' && *(mystr+i)!='\0')


text:
Q: Migrate User from production DB of ASP.NET MVC app to Rails I'm having a production MVC Website with 500 registered users in the database (MS SQL). I'm thinking of rewrite the app in Rails for many reasons.
The question that popup first is that how can I move username/password from MS SQL to MySQL without knowing that the password is ( the passwords in database are hashed).

A: Since password hashing is practically irreversible by design, you only have two options:

*

*Replicate the hashing algorithm used in your ASP.NET MVC app.
 Move the database without changes.

*Nullify these hashes.
 On any login attempt prompt the user to reset password if the password hash is nil (NULL, or "does not exist").

I have seen option (2) in action a lot of times, namely on Logitech website.


text:
Q: git garbage colleciton using git version 1.8.3.1 and slow git.log I would like to know if the git.gc().setAggressive(true).call(); actually worked correctly on the siteRepo. How can I measure its effect programatically? I am using git version 1.8.3.1
// aggressively optimize the publication repository

siteRepo = new File(gitLocation+publication);
if (siteRepo.exists()){
                git = Git.open(siteRepo);
                git.gc().setAggressive(true).call();
                println("*** garbage collection for repo :" +gitLocation+publication);
              }

I was able to measure it using du -h --max-depth=0 *
146M    ius -> using git.gc on the repo
3.7G    ius -> without git.gc on the repo

git.log unfortunatelly takes a long time on this repo even after git.gc. Is there an additional way to optimizes git.log?


text:
Q: Vertical skip between p{...} rows of tabular I want to increase a bit the vertical spacing in my tabular table.  I did something like this:
\documentclass{article}

\begin{document}

\begin{tabular}{p{4cm}p{4cm}}
  Lorem ipsum dolor sit amet consectetur & adipisicing elit \\[6pt]
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
\end{tabular}

\end{document}

but to my surprise, it doesn't work - it seems that the extra vertical space from [12pt] is somehow eaten by the space beneath the (shorter) parbox.  What should I do?

A: You could put a strut in the first column.
\documentclass{article}
\begin{document}
\begin{tabular}{p{4cm}p{4cm}}
  Lorem ipsum dolor sit amet consectetur\rule[-6pt]{0pt}{6pt} & adipisicing elit \\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
\end{tabular}
\end{document}

A: The \\ mechanism can be used, but one has to account for the height of the \parbox, either manually or automatically.  The other option, if all rows are to be adjusted, is to use the \extrarowheight parameter of the array package, or else \arraystretch as was mentioned in the comments.
\documentclass{article}
\usepackage{array}
\begin{document}

ORIGINAL

\begin{tabular}{p{4cm}p{4cm}}
  Lorem ipsum dolor sit amet consectetur & adipisicing elit \\[6pt]
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
\end{tabular}

\hrulefill

CAN DO A SINGLE ROW, MANUALLY ACCOUNT FOR \verb|\parbox| HEIGHT

\begin{tabular}{p{4cm}p{4cm}}
  Lorem ipsum dolor sit amet consectetur & adipisicing elit \\[18pt]%
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
\end{tabular}

\hrulefill

CAN DO A SINGLE ROW,AUTO- ACCOUNT FOR \verb|\parbox| HEIGHT

\def\x{Lorem ipsum dolor sit amet consectetur}
\setbox0=\hbox{\parbox[t]{4cm}{\x}}

\begin{tabular}{p{4cm}p{4cm}}
  \x & adipisicing elit \\[\dimexpr\dp0+6pt\relax]%
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
\end{tabular}

\hrulefill

AFFECTS EVERY ROW:

\setlength\extrarowheight{6pt}
\begin{tabular}{p{4cm}p{4cm}}
  Lorem ipsum dolor sit amet consectetur & adipisicing elit \\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
\end{tabular}

\end{document}

A: If you do not have vertical lines, then this can be solved by
\noalign{\vspace{6pt}}

Full example:
\documentclass{article}

\begin{document}
  \begin{tabular}{p{4cm}p{4cm}}
    Lorem ipsum dolor sit amet consectetur & adipisicing elit\\
  \noalign{\vspace{6pt}}%
    sed do eiusmod tempor incididunt ut labore & et dolore magna aliqua.\\
  \end{tabular}
\end{document}

With \noalign vertical mode material can be added that is not subjected to the current table alignment.
The main disadvantage of this approach is that vertical lines get interrupted:

Therefore LaTeX uses this implementation for negative lengths. Then the problem with the vertical lines is much smaller, because they just overlap in most cases.
If the value is positive, then LaTeX adds an invisible rule. Height and width are zero, the depth is the sum of the given value and the depths of the standard tabular line, the depth of a strutbox increased by \arraystretch.
A better implementation would have keep track of the maximum depth of all cells in the row. The increased memory usage and slower run time might have been an noticeable issue in the early days of LaTeX. Nowadays implementing such a feature is no fun at all, because 99% of the implementation would have to deal with package compatibility (array, colortbl and many, many other table packages).


text:
Q: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1 . Welcome,
I have several pictures, when I click on one it should take me to another window of this picture.
But this does not happen, but I get this window with this error message:

The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[FirstProject.Models.student]', but
this dictionary requires a model item

I will put the codes related to the problem:
HomeController
using FirstProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FirstProject.Controllers
{
    public class HomeController : Controller
    {
        level_8_coursesEntities db = new level_8_coursesEntities();
        public ActionResult Index()
        {
            List<level_8_courses> list = db.level_8_courses.ToList();
            return View(list);
        }
        public ActionResult Numberofstudents()
        {
            List<level_8_courses> list = db.level_8_courses.ToList();
            return View(list);
        }

        public ActionResult Students(int? id)
        {
            List<student> studentlist = null;
            if (id.HasValue)
            {
                studentlist = db.students.Where(x => x.corId == id).ToList();
            }
            else
            {
                // Set the `studentlist` to some default value when `id` doesn't defined or not a number.
                studentlist = null;
    }
            return View(studentlist);
        }

Number of students.chtml
    @{
        ViewBag.Title = "Numberofstudents";
    }

    @using FirstProject.Models;
    @model List<level_8_courses>

Numberofstudents

                @foreach (var item in Model)
                {

@item.corName

                }

Students.chtml
@using FirstProject.Models;
@model List<student>

        @foreach (var item in Model)
        {

@item.sName

@item.sEmail

        }

Thanks

A: fix students action,  if you don't have any students create an empty list as a model, and remove  studentlist = null;
List<student> studentlist = null

if (id!=null && id > 0)
        studentlist = db.students.Where(x => x.corId == id).ToList();

if(studentlist==null) studentslist= new List<student>();

return View(studentlist);


text:
Q: find duplicate words in a comma separated strings in a panda column and add various prefixes to them I have a dataframe column that looks like the following but larger:
df=  pd.DataFrame(["Mina,is,good", "Dania,is,good,good", "Alice,is,good,good,good"]
                 columns=['a'])

I want the output to look like:
df_output=  pd.DataFrame(["Mina,is,good", "Dania,is,A-good,Y-good", "Alice,is,A-good,Y-good,Z-good"]
          columns=['a'])

So I want to add a prefix if a word is repeated, but there are also three different prefixes:
if a word is repeated once, I want to add ("A-", "Y-"), and if a word is repeated twice, I want to add ("A-", "Y-", "Z-")
Thank you in advance

A: You may need a custom function as below using cumcount:
def fun(x):
    d = {0:'A-',1:'Y-',2:'Z-'} # mapping dictionary
    s = pd.Series(x.split(',')) #split each row as list and treat as series
    mask = s.duplicated(keep=False) #check for cases only which are duplicated
    s[mask] = s[mask].groupby(s).cumcount().map(d) + s[mask]
    return ','.join(s)

df['a'].apply(fun)

0                     Mina,is,good
1           Dania,is,A-good,Y-good
2    Alice,is,A-good,Y-good,Z-good
Name: a, dtype: object


text:
Q: How can I to download a QR Code to user device using Flutter? I have a app that shows a QR Code that stores a simple string, using the qr_flutter package.
But beyond showing the QR Code, I want that when user taps a button, a image of that QR Code is downloaded to device too.
I have searched and didn't find any package that can make this.

A: I did recently using screenshot plugin with pretty_qr_code
ScreenshotController screenshotController = ScreenshotController();

Screenshot(
  controller: screenshotController,
  child: PrettyQr(
    image:AssetImage(AppConfig.placeholder),
    typeNumber: 4,
    size: 300,
    elementColor: Color(0xff596DFF),
    data: invitationCode,
    errorCorrectLevel: QrErrorCorrectLevel.Q,
    roundEdges: false
  ),
)

Future<void> _captureAndSharePng() async {
  screenshotController.capture().then((File image1) async {
    //Capture Done
    List<int> bytes1 = await image1.readAsBytes();

    await Share.file("Code",
      'title' + ".jpg", bytes1, 'image/jpg',
      text: "Join Group by scanning this code"
    );
  }).catchError((onError) {
    print(onError);
  });
}

Share image using esys_flutter_share


text:
Q: in an `async` function are the input parameters preserved over an `await` I have some browser code which has been showing some mysterious errors when running over a slow link. I am coming to the conclusion that the event.detail parameter is getting corrupted.
So I have an async function (as a method on a class) a bit like the following:
async doUpdate(e) {
  e.stopPropagation();
  const response = await readSomethingFromRemoteDatabase(this.id, e.detail.anotherid);
  const myentity = this.entities.find(x => x.id === e.detail.anotherid)
  if (typeof myentity !== 'undefined') {
    //do something to update local data
  }
}

I expect myentity to be found, but occasionally it isn't.
I have since changed the code to become the following:
async doUpdate(e) {
  e.stopPropagation();
  const data = e.detail
  const response = await readSomethingFromRemoteDatabase(this.id, e.detail.anotherid);
  const myentity = this.entities.find(x => x.id === data.anotherid)
  if (typeof myentity !== 'undefined') {
    //do something to update local data
  }
}

and the issue has gone away.
I'm coming to the conclusion that with the slow link, its possible for doUpdate to get called twice, the second time before the readSomthingFromRemoteDatabase has responded, and the second call has come in with different data.
What that implies is that the const data is within the scope of the called function for the entire scope of its execution, but that the parameter variable e is not.
However, I can find no documented information about whether my assumption is true. Can someone point me to where I can find out if my assumption is true?
UPDATE in response to some of the comments.
Firstly, doUpdate is an event listener which is called via lit-element. Elsewhere in this class is a Lit render function, a bit like this
render() {
 return html`
  ${this.entities.map(entity => html`
    <entity-editor .entity=${entity} @entity-changed=${this.doUpdate}></entity-editor>
  `)}
 `;
}

The event detail is an object constructed from parts, so not a reference elsewhere. Normally made something like this (inside the entity-editor custom element.
this.dispatchEvent(new CustomEvent('entity-changed', {
  bubbles: true,
  composed: true,
  detail: {
   anotherid: this.id,
   moreinfo: this.moreinfo
  )
}));

readSomethingFromRemoteDatabase does little more than translate the object passed into a fetch POST request to the server, where the object passed is JSON.stringify'ed into the body of the request.
Sorry that I can't point you at real code - but this is a massive PUA I personally have been building since 2016 advancing through Polymer and now Lit to replace a Microsoft Access Application. It's private work for a company so is in a private repository.
At this stage it's 100s of elements in a client, and 100s of components in a Node.js api-server (proxied by NGINX)


text:
Q: What if a moving radioactive nucleus decays? (while moving) If a radioactive nucleus decays while moving (consider alpha decay), will the energy of the decay products (consider thorium and helium when uranium decays) alter? I mean, according to energy conservation law, the initial kinetic energy of the radioactive nucleus can't be destroyed, so it must have converted into the  kinetic energy of the decay products! Am I correct?

A: Both energy, linear and angular momentum are conserved. This means that the total inner energy + kinetic energy  of the nucleus and the total linear and angular momentum is transformed into the  kinetic (inner) energy, linear momentum and angular momentum of the  decay products. The radioactive nucleus is in a metastable state that contains substantial inner (potential) energy that is converted (disregarding angular momentum) into kinetic energy and linear momentum  of the alpha particle and the kinetic energy and momentum (including recoil effects) of the remaining nucleus.


text:
Q: Can I send a message to a device (instead of browser) in firebase? I'm using firebase in javascript. It works fine for sending messages to a user while the browser is open, using the id from messaging.getToken. Obviously, the user stops getting these messages if they close the browser tab. Is it at all possible (without creating a separate app) to send these messages to a device after the browser has closed?

A: That is possible, servicer workers to the rescue! Service workers will allow you to send the user push notifications even after the browser tab is closed. The firebase documentation has a section on this  here


text:
Q: Select number of closed ticket in mysql I'm new in mysql and php. I want to count the numbers and get the sum of closed ticket each date. I need to get the right queries of counting and adding of closed ticket. I'm very much appreciated of your help. Thanks
Here's my queries:
 SELECT ticket.tn, ticket.id, MAX(ticket_history.change_time) AS closed
 FROM ticket_history
 LEFT JOIN ticket_history_type ON (ticket_history_type.id = ticket_history.history_type_id)
 LEFT JOIN ticket ON (ticket.id = ticket_history.ticket_id)
 LEFT JOIN ticket_state ON (ticket_state.id = ticket_history.state_id)
 LEFT JOIN ticket_state_type ON (ticket_state_type.id = ticket_state.type_id)
 WHERE ticket_history_type.name = "StateUpdate" AND ticket_state_type.name="closed"
 GROUP BY ticket.tn;

Here's the output:
tn                |    id         |    closed
2010080210123456  |    1          |    2013-10-21 09:45:43
.
.
.
.
.
And here's my queries for counting the closed
SELECT case when (select count(*) from ticket_history where ticket.tn, ticket.id,
MAX(ticket_history.change_time) AS closed
FROM ticket_history
LEFT JOIN ticket_history_type ON (ticket_history_type.id = ticket_history.history_type_id)
LEFT JOIN ticket ON (ticket.id = ticket_history.ticket_id)
LEFT JOIN ticket_state ON (ticket_state.id = ticket_history.state_id)
LEFT JOIN ticket_state_type ON (ticket_state_type.id = ticket_state.type_id)
WHERE ticket_history_type.name = "StateUpdate" AND ticket_state_type.name="closed"
GROUP BY ticket.tn;


text:
Q: Use moment.js to figure out if a unix timestamp was within the last week How do i use unix timestamp to work out if an event was within the last week?
I tried
moment().subtract('weeks', 1).unix()<item.start

but it is returning unexpected results.  thanks so much
edit:  thanks so much for the question feedback here is an example of my response
1537858386
1540197758000

A: You can create the point of time which represents the lowest valid value as you did before. When you have this point in time, you can check with momentjs if a given date is older.
const weekAgo = moment().subtract(1, 'weeks') // This is the time to check

const ts = 1519945200000 // any unix timestamp. This is 2018-03-01
const m1 = moment(ts) // Use a unixtimestamp to create a moment object

const m2 = moment().subtract(8, 'days') // further test data
const m3 = moment().subtract(6, 'days') // further test data

console.log(weekAgo.isBefore(m1)) // true
console.log(weekAgo.isBefore(m2)) // true
console.log(weekAgo.isBefore(m3)) // false

A: You can check this answer for date range checking

You can use one of the moment plugin -> moment-range to deal with date
  range:

 var startDate = new Date(2013, 1, 12)   , endDate   = new Date(2013,
 1, 15)   , date  = new Date(2013, 2, 15)   , range =
 moment().range(startDate, endDate);

 range.contains(date); // false

A: Will be using moment.diff function
Follow these Steps

*

*Convert unix timestam to moment object

*Format date

*use moment.diff
function dateDiff (date) {
    // date is unix timestamp date
    let d = moment(date);

    if ( d.isValid() ) {
        d.format("YYYY-MM-DD");

        // moment() gives current date-time
        return moment().diff(d, 'weeks', true);
        // If past date then result will be positive if future date then negative.
    }
    else
       return null;
}

console.log( dateDiff( 1519945200000 ) );  // 30.648079404761905   // 30 weeks ago
console.log( dateDiff( 1534395200000 ) );  // 6.755883640873016   // 6 weeks ago
console.log( dateDiff( 1529945200000 ) );  // 14.113687873677248   // 14 weeks ago
console.log( dateDiff( 1541945200000 ) );  // -5.7275819675925925  // 5 weeks in future

A: As @be-ndee said it was just milliseconds vs seconds so i just edited it to
moment().subtract('weeks', 1).unix()


text:
Q: Load TLB at runtime in C# .net 4.0 I have a tlb file from a third party library. There are many versions of this library, however the functions that I use within the tlb are constant i.e. do not change from one version to the next.
I have added the tlb file to the project as a COM Reference. I can successfully build and call the functions from the third party library.
When I deploy my application, I cannot guarantee that the user will have the same version of the third party installed on their PC as me. When this scenario arises, they get an access violation error (0xc0000005) as soon as a function within the third party library is called.
How can I load the tlb file that is located on the user's PC at run-time?

A: You should be able to use C# 4's dynamic along with Type.GetTypeFromProgID to load the COM object and use it via dynamic binding.
 dynamic obj = Activator.CreateInstance(Type.GetTypeFromProgID(comTypeName));

 // Use object via dynamic binding directly
 obj.Foo();

This avoids the need for anything about the COM object version to be compiled into your assembly.  As long as you use the correct API, and the methods/etc you use exist, it will function with any version.


text:
Q: Exec imagemagick convert via C# When I open a command window in windows and use the imagemagick convert command:
convert /somedir/Garden.jpg /somedir/Garden.png
It works as expected.
What I am trying to do is executing the same command as above using C#.
I tried using  System.Diagnostics.Process, however, no foo.png gets created.
I am using this code:
      var proc = new Process
      {
          StartInfo =
          {
              Arguments = string.Format("{0}Garden.jpg {1}Garden.png",
              TEST_FILE_DIR,
              TEST_FILE_DIR),
              FileName = @"C:\xampp\ImageMagick-6.5.4-Q16\convert",
              UseShellExecute = false,
              CreateNoWindow = true,
              RedirectStandardOutput = false,
              RedirectStandardError = false
          }
      };

      proc.Start();

No exception gets thrown, but no .png is written, either.

A: My guess is that TEST_FILE_DIR contains a space - so you have to quote it.
Try this:
Arguments = string.Format("\"{0}Garden.jpg\" \"{1}Garden.png\"",
                          TEST_FILE_DIR,
                          TEST_FILE_DIR)

You might also want to give the filename including the extension, e.g.
FileName = @"C:\xampp\ImageMagick-6.5.4-Q16\convert.exe"


text:
Q: Recursive evenness check returns undefined There is an exercise in Eloquent JavaScript whose wording is:

Recursion
We've seen that % (the remainder operator) can be used to test whether
  a number is even or odd by using % 2 to check whether it's divisible by
  two. Here's another way to define whether a positive whole number is
  even or odd:

*

*Zero is even.

*One is odd.

*For any other number N, its evenness is the same as N - 2.

  Define a recursive function isEven corresponding to this description. The
  function should accept a number parameter and return a Boolean.
Test it on 50 and 75. See how it behaves on -1. Why? Can you think
  of a way to fix this?

They provide a solution, and I've already written a working implementation, but another always returns undefined; why is this?
var isEven = function ( a ) {
    var r = false;
    if ( a === 0 || a === 1 ) {
        a === 0 ? r = true : r ;
        return r;
    } else
        a < 0 ? isEven(-1 * a) : isEven(a - 2);
};

console.log(isEven(50));

When the number is not 0 or 1, the else branch seems to work fine; the problem, I think, is in the if branch.

A: You need a return statement in the else branch. As it is you're just evaluating the expression and discarding the result.

A: Any reason you are not using a simple even odd check?
var isEven = function ( a ) {
    return (a % 2 === 0) ? true : false;
}

A: a < 0 ? isEven(-1 * a) : isEven( a-2);

This line is missing a return. So you could write it this way:
var isEven = function ( a ) {
    var r = false;
    if ( a === 0 || a === 1 ) {
        a === 0 ? r = true : r ;
        return r;
    }else
        return a < 0 ? isEven(-1 * a) : isEven( a-2);
}

But this way works too:
function isEven(a) {
    return a % 2 === 0;
}

You can expand that to use recursion without making things as complicated, e.g.
function isEven(a) {
    return (
        a === 0 ? true       :
        a === 1 ? false      :
        a < 0   ? isEven(-a) : isEven(a - 2));
}

because setting r = true in a ? operator isn't actually functional, if that was the point. I'd still use the operator, though, since it works on ±Infinity and NaN.

A: Thanks to your answers I got what is going wrong.
In a recursive case, if you want to pass the result of the base case to the calls which are waiting for a response, is essential using result, anyway nothing will do it. If the call of the case base end without any result, what do you expect to happen? Nothing is returned and so on.
Another thing I learnt is that you cannot use the result with the ternary operator.
So, finally, one solution can be this one:
var isEven = function ( a ) {
    var r = false;
    if ( a === 0 || a === 1 ) {
        a === 0 ? r = true : r ;
        return r;
    }else if ( a < 0)
        return isEven(-a);
    else
        return isEven(a-2);
}

which works perfectly.
If anyone wants to know the solution provided by the book, is this one:
function isEven(n) {
  if (n == 0)
    return true;
  else if (n == 1)
    return false;
  else if (n < 0)
    return isEven(-n);
  else
    return isEven(n - 2);

}


text:
Q: 0-10V LED driver dimming with Raspberry Pi and FET I'm a beginner, so please be gentle!
I'm trying to dim the linked LED light fixture driver using a Raspberry Pi (RPi). I want to dim using PWM in conjunction with a FET. Before dimming I am trying to simply turn the fitting on/off. I was hoping it would work on the basis of the top answer to this post.
I have gotten some BS170 FETs and tested them for turning on/off a single LED using an RPI GPIO, they work fine.
I then connected the LED driver to the FET, connecting the +DIM of the driver to the drain, the -DIM to the source, and the gate to the RPi GPIO pin as with the single LED. I attempted to set the GPIO high, then low, as worked with the single LED but I get no change, only a dimmed fixture. Fixture goes to full brightness when I disconnect the +/-DIM wires from the FET, opening the circuit.
I perhaps have the FET oversized for the task? I'm guessing that it is allowing current to flow (with low resistance) from +DIM to -DIM regardless of voltage on the gate??
Any help, tips or advice appreciated.


text:
Q: Xcode Table View Sections not updating I have created a new Xcode 9.4.1 Master-Detail project. I have implemented a custom cell programmatically and all works as expected. My app is a database of Ham Radio Repeaters. I am creating the app for practice. I am now trying to implement sections that groups repeater entries by state. My add/delete functions work fine from the TableView page. The entries get added/removed from the proper sections. I have it setup to perform repeater entry updates in the detail view. The issue is that the tableview does not change the entry grouping when I change the state in the detail view then go back to the master view. I have implemented a self.tableView.reloadData() under the WillAppear function.
Here is the code in for my MasterViewController:
import UIKit
import CoreData

class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate{

    let cellTableIdentifier = "Cell"

    var detailViewController: DetailViewController? = nil
    var managedObjectContext: NSManagedObjectContext? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(CustomCell.self,forCellReuseIdentifier: cellTableIdentifier)

        // Do any additional setup after loading the view, typically from a nib.
        navigationItem.leftBarButtonItem = editButtonItem

        let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
        navigationItem.rightBarButtonItem = addButton
        if let split = splitViewController {
            let controllers = split.viewControllers
            detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
        super.viewWillAppear(animated)
        // reload the data into the TableView
        self.tableView.reloadData()
        //self.tableView.reloadSections([1,2,3], with: .none )
    }

    // Adds Repeaters to Table View, saves in Core Data
    @objc
    func insertNewObject(_ sender: Any)
    {
        // create an Alert with a textFields
        let alertController = UIAlertController(title: "Add Repeater",
                                                message: "",
                                                preferredStyle: UIAlertControllerStyle.alert)

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="State"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="County"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="City"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="Call Sign"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="Input Frequency"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="Output Frequency"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="Uplink Tone"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="Downlink Tone"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="Offset"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // add the textField to the Alert. Create a closure to handle the configuration
        alertController.addTextField(configurationHandler: {(textField: UITextField!) in
            textField.placeholder="Use"
            textField.keyboardType=UIKeyboardType.emailAddress
        })

        // create a default action for the Alert
        let defaultAction = UIAlertAction(
            title: "Create",
            style: UIAlertActionStyle.default,
            handler: {(alertAction: UIAlertAction!) in
                // get the input from the alert controller
                let context = self.fetchedResultsController.managedObjectContext
                let newRepeater = Repeaters(context: context)

                newRepeater.state = (alertController.textFields![0]).text!
                newRepeater.county = (alertController.textFields![1]).text!
                newRepeater.location = (alertController.textFields![2]).text!
                newRepeater.call = (alertController.textFields![3]).text!
                newRepeater.input_Freq = (alertController.textFields![4]).text!
                newRepeater.output_Freq = (alertController.textFields![5]).text!
                newRepeater.uplink_Tone = (alertController.textFields![6]).text!
                newRepeater.downlink_Tone = (alertController.textFields![7]).text!
                newRepeater.offset = (alertController.textFields![8]).text!
                newRepeater.use = (alertController.textFields![9]).text!

                // Save the context.
                do {
                    try context.save()
                } catch {
                    let nserror = error as NSError
                    fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
                }

                // reload the data into the TableView
                self.tableView.reloadData()
        })
        // cancel button
        let cancelAction = UIAlertAction(
            title: "Cancel",
            style: UIAlertActionStyle.cancel,
            handler:nil)

        // add the actions to the Alert
        alertController.addAction(defaultAction)
        alertController.addAction(cancelAction)

        // generate test data
        gernerateTestData(alertController: alertController)

        // display the Alert
        present(alertController, animated: true, completion: nil)
    }

    // Creates test data in Alert Controller
    func gernerateTestData(alertController:UIAlertController)
    {
        // increment count
        //count += 1
        // get the textfields and assign test data
        (alertController.textFields![0]).text = "Ohio"
        (alertController.textFields![1]).text = "Lake"
        (alertController.textFields![2]).text = "Mentor"
        (alertController.textFields![3]).text = "N8BC"
        (alertController.textFields![4]).text = "147.165"
        (alertController.textFields![5]).text = "147.765"
        (alertController.textFields![6]).text = "110.9"
        (alertController.textFields![7]).text = "110.9"
        (alertController.textFields![8]).text = "+"
        (alertController.textFields![9]).text = "OPEN"
    }

    // MARK: - Segues

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
            let object = fetchedResultsController.object(at: indexPath)
                let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
                controller.detailItem = object
                controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
                controller.navigationItem.leftItemsSupplementBackButton = true
            }
        }
    }

    // MARK: - Table View

    override func numberOfSections(in tableView: UITableView) -> Int {
        return fetchedResultsController.sections?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        //return "Section \(section)"
        //return "Ohio"
        if let sections = fetchedResultsController.sections {
            let currentSection = sections[section]
            return String(currentSection.name)
        }
        return nil
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionInfo = fetchedResultsController.sections![section]
        return sectionInfo.numberOfObjects
    }

    // *** Save, allows you to revert to standard cell
//    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
//        let repeater = fetchedResultsController.object(at: indexPath)
//        //configureCell(cell, withEvent: event)
//        configureCell(cell, withEvent: repeater)
//        return cell
//    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellTableIdentifier, for: indexPath) as! CustomCell
        let repeater = fetchedResultsController.object(at: indexPath)
        cell.call = repeater.call!
        //cell.state = repeater.state!
        cell.city = repeater.location!
        return cell
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let context = fetchedResultsController.managedObjectContext
            context.delete(fetchedResultsController.object(at: indexPath))

            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "showDetail", sender:tableView)
    }

    func configureCell(_ cell: UITableViewCell, withEvent repeater: Repeaters) {
                cell.textLabel!.text = repeater.call!.description
    }

    // MARK: - Fetched results controller

    var fetchedResultsController: NSFetchedResultsController<Repeaters> {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
    }
        let fetchRequest: NSFetchRequest<Repeaters> = Repeaters.fetchRequest()

        // Set the batch size to a suitable number.
        fetchRequest.fetchBatchSize = 20

        // Edit the sort key as appropriate.
        let sortDescriptor = NSSortDescriptor(key: "call", ascending: false)

        fetchRequest.sortDescriptors = [sortDescriptor]

        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: "state", cacheName: "Master")
        aFetchedResultsController.delegate = self
        _fetchedResultsController = aFetchedResultsController

        do {
            try _fetchedResultsController!.performFetch()
        } catch {
             // Replace this implementation with code to handle the error appropriately.
             // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
             let nserror = error as NSError
             fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }

        return _fetchedResultsController!
    }
    var _fetchedResultsController: NSFetchedResultsController<Repeaters>? = nil

    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.beginUpdates()
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
        switch type {
            case .insert:
                tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
            case .delete:
                tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
            default:
                return
        }
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
            case .insert:
                tableView.insertRows(at: [newIndexPath!], with: .fade)
            case .delete:
                tableView.deleteRows(at: [indexPath!], with: .fade)
            case .update:
                //configureCell(tableView.cellForRow(at: indexPath!)!, withEvent: anObject as! Repeaters)
                print()
            case .move:
                //configureCell(tableView.cellForRow(at: indexPath!)!, withEvent: anObject as! Repeaters)
                //tableView.moveRow(at: indexPath!, to: newIndexPath!)
                print()
        }
    }

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.endUpdates()
    }

    /*
     // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.

     func controllerDidChangeContent(controller: NSFetchedResultsController) {
         // In the simplest, most efficient, case, reload the table view.
         tableView.reloadData()
     }
     */
}

A: You can try to reload table by adding proper delegate to cell, for example
protocol DetailsCellDelegate: class {
    func updateTable(with: Data)
}

And perform this delegate with your Data by calling delegate?.updateTable(with: data)


text:
Q: Periodically generating CustomObject entries we have created a CustomObject MonthlyItem as child of Contract (Master/Detail Relationship). Now we want to generate new MonthlyItems at the end of each month for the next respective month.
Something like:
For each active Contract
   Create a new MonthlyItem for the contract
     Field-Begin: 1/next-month/this-year
     Field-Budget: some-contract-field

What is the preferred technology for this Task?

A: The above scenario can be implemented using batch apex.
Also you need to implement scheduled apex to run the batch class at the end of month.


text:
Q: How do I use an Enum in another Java class? I have a Java file which is solely an enum:
public enum MyEnum {
    ONE, TWO, THREE;
}

And I want to access this enum in a different file e.g. MyClass.java. Do I use MyEnum.TWO, or what?

A: Exactly. You can do such:
MyEnum x = MyEnum.TWO;

Don't forget to import MyEnum if it is in another package.

A: Yes. for example:
MyEnum enumVar = MyEnum.TWO;


text:
Q: How to find exact duration between two Unix dates (in days) using MomentJS? I am trying to find difference between 2 dates, using MomentJS library. However the requirement is to use Unix timestamps as date values.
Currently I have the following code, which returns inaccurate value:
var start = 1536873321; // 13 September 2018
var end = 1537228800 ; // 18 September 2018

var diff = moment.unix(end).diff(moment.unix(start), 'days');
console.log(diff); //4 (expected 5, or 6 if last day is included)

Is there any solution for that, or using plain JavaScript is more suggested to get more precise result?
Please see the fiddle if needed.

A: Moment is returning 4 days because there are not quite 5 days between those two timestamps.
start = 1536873321; // 13 September 2018 (9:15pm)
end = 1537228800 ; // 18 September 2018 (12:00am)

So the exact time in days between them is 4.114340277777778 days.
Try
start = moment.unix(1536873321);
end = moment.unix(1537228800 );
var diff = Math.ceil(moment.duration(start.diff(end)).asDays());

A: You don't have to use Unix timestamps. Try this:
var start  = moment("20180913", "YYYYMMDD");
var end = moment("20180918", "YYYYMMDD");

var diff = end.diff(start, "days");
console.log(diff);

That makes the syntax a little cleaner too.

A: Just call startOf('day') on both so it will calculate the diff between the dates:
var diff = moment.unix(end).startOf('day').diff(moment.unix(start).startOf('day'), 'days');


text:
Q: Does Interlocked.CompareExchange use a memory barrier? I'm reading Joe Duffy's post about Volatile reads and writes, and timeliness, and i'm trying to understand something about the last code sample in the post:
while (Interlocked.CompareExchange(ref m_state, 1, 0) != 0) ;
m_state = 0;
while (Interlocked.CompareExchange(ref m_state, 1, 0) != 0) ;
m_state = 0;
…

When the second CMPXCHG operation is executed, does it use a memory barrier to ensure that the value of m_state is indeed the latest value written to it? Or will it just use some value that is already stored in the processor's cache? (assuming m_state isn't declared as volatile).
If I understand correctly, if CMPXCHG won't use a memory barrier, then the whole lock acquisition procedure won't be fair since it's highly likely that the thread that was the first to acquire the lock, will be the one that will acquire all of following locks. Did I understand correctly, or am I missing out on something here?
Edit: The main question is actually whether calling to CompareExchange will cause a memory barrier before attempting to read m_state's value. So whether assigning 0 will be visible to all of the threads when they try to call CompareExchange again.

A: There seems to be some comparison with the Win32 API functions by the same name, but this thread is all about the C# Interlocked class. From its very description, it is guaranteed that its operations are atomic. I'm not sure how that translates to "full memory barriers" as mentioned in other answers here, but judge for yourself.
On uniprocessor systems, nothing special happens, there's just a single instruction:
FASTCALL_FUNC CompareExchangeUP,12
        _ASSERT_ALIGNED_4_X86 ecx
        mov     eax, [esp+4]    ; Comparand
        cmpxchg [ecx], edx
        retn    4               ; result in EAX
FASTCALL_ENDFUNC CompareExchangeUP

But on multiprocessor systems, a hardware lock is used to prevent other cores to access the data at the same time:
FASTCALL_FUNC CompareExchangeMP,12
        _ASSERT_ALIGNED_4_X86 ecx
        mov     eax, [esp+4]    ; Comparand
  lock  cmpxchg [ecx], edx
        retn    4               ; result in EAX
FASTCALL_ENDFUNC CompareExchangeMP

An interesting read with here and there some wrong conclusions, but all-in-all excellent on the subject is this blog post on CompareExchange.
Update for ARM
As often, the answer is, "it depends". It appears that prior to 2.1, the ARM had a half-barrier. For the 2.1 release, this behavior was changed to a full barrier for the Interlocked operations.
The current code can be found here and actual implementation of CompareExchange here. Discussions on the generated ARM assembly, as well as examples on generated code can be seen in the aforementioned PR.

A: MSDN says about the Win32 API functions:
"Most of the interlocked functions provide full memory barriers on all Windows platforms"
(the exceptions are Interlocked functions with explicit Acquire / Release semantics)
From that I would conclude that the C# runtime's Interlocked makes the same guarantees, as they are documented withotherwise identical behavior (and they resolve to intrinsic CPU statements on the platforms i know). Unfortunately, with MSDN's tendency to put up samples instead of documentation, it isn't spelled out explicitly.

A: Any x86 instruction that has lock prefix has full memory barrier. As shown Abel's answer, Interlocked* APIs and CompareExchanges use lock-prefixed instruction such as lock cmpxchg. So, it implies memory fence.
Yes, Interlocked.CompareExchange uses a memory barrier.
Why? Because x86 processors did so. From Intel's Volume 3A: System Programming Guide Part 1, Section  7.1.2.2:

For the P6 family processors, locked operations serialize all outstanding load and store operations (that is, wait for them to complete). This rule is also true for the Pentium 4 and Intel Xeon processors, with one exception. Load operations that reference weakly ordered memory types (such as the WC memory type) may not be serialized.

volatile has nothing to do with this discussion. This is about atomic operations; to support atomic operations in CPU, x86 guarantees all previous loads and stores to be completed.

A: The interlocked functions are guaranteed to stall the bus and the cpu while it resolves the operands. The immediate consequence is that no thread switch, on your cpu or another one, will interrupt the interlocked function in the middle of its execution.
Since you're passing a reference to the c# function, the underlying assembler code will work with the address of the actual integer, so the variable access won't be optimized away. It will work exactly as expected.
edit: Here's a link that explains the behaviour of the asm instruction better: http://faydoc.tripod.com/cpu/cmpxchg.htm
As you can see, the bus is stalled by forcing a write cycle, so any other "threads" (read: other cpu cores) that would try to use the bus at the same time would be put in a waiting queue.

A: According to ECMA-335 (section I.12.6.5):

5.
  Explicit atomic operations.
    The class library provides a variety of atomic operations
  in the
  System.Threading.Interlocked
   class. These operations (e.g., Increment,
  Decrement, Exchange, and CompareExchange) perform implicit acquire/release
  operations.

So, these operations follow principle of least astonishment.

A: ref doesn't respect the usual volatile rules, especially in things like:
volatile bool myField;
...
RunMethod(ref myField);
...
void RunMethod(ref bool isDone) {
    while(!isDone) {} // silly example
}

Here, RunMethod is not guaranteed to spot external changes to isDone even though the underlying field (myField) is volatile; RunMethod doesn't know about it, so doesn't have the right code.
However! This should be a non-issue:

*

*if you are using Interlocked, then use Interlocked for all access to the field

*if you are using lock, then use lock for all access to the field

Follow those rules and it should work OK.

Re the edit; yes, that behaviour is a critical part of Interlocked. To be honest, I don't know how it is implemented (memory barrier, etc - note they are "InternalCall" methods, so I can't check ;-p) - but yes: updates from one thread will be immediately visible to all others as long as they use the Interlocked methods (hence my point above).


text:
Q: Change text overflow in jasper reports chart It seems that the text is to long to be displayed at the bottom... that's ok but it would be nice if the text wasn't cut at the beginning and not at the end.
I can't find the spot where to do it. Is it even possible?


text:
Q: Setting an environment variable in javascript How can I set an environment variable in WSH jscript file that calls another program? Here's the reduced test case:
envtest.js
----------
var oShell = WScript.CreateObject("WScript.Shell");
var oSysEnv = oShell.Environment("SYSTEM");
oSysEnv("TEST_ENV_VAR") = "TEST_VALUE";
oExec = oShell.Run("envtest.bat", 1, true);

envtest.bat
-----------
set
pause

I expect to see TEST_ ENV _VAR in the list of variables, but it's not there. What's wrong?
edit:
If someone can produce a working code sample, I'll mark that as the correct answer. :)

A: The problem is not in your code, but it is in execution of the process. The complete system variables are assigned to the process which is executed. so, your child process also had the same set of variables.
Your code-sample works good. It adds the variable to the SYSTEM environment.
So, you need to set the variable not only for your system but also for your process.
Here's the code.
var oShell = WScript.CreateObject("WScript.Shell");
var oSysEnv = oShell.Environment("SYSTEM");
oSysEnv("TEST1") = "TEST_VALUE";
var oSysEnv = oShell.Environment("PROCESS");
oSysEnv("TEST1") = "TEST_VALUE";
oExec = oShell.Run("envtest.bat", 1, true);

Once you created the system variable.
It will assign the newly created variable for the current process. So, your child process can get that variable while the "SET" command executed.
Sorry for my bad-english.

A: There are 4 "collections" (System, User, Volatile, and Process) you probably want Process if you just need a child process to see the variable

A: You are getting the system environment variables. I suspect you simply don't have permission to modify them; you could try changing this to the user environment variables.
Also I don't know whether the argument to Environment() is case-sensitive or not. MS's documentation uses "System" instead of "SYSTEM". Might make a difference but I don't know for sure.


text:
Q: What is the best practice to show the data fetched by Laravel 4.2 from Database using 'ng-repeat' of AJS I'm fetching data from the database using Laravel 4.2, it returns an array of JSON objects, then I pass that data to a view. But I'm unable to show it using Angular JS' ng-repeat directive. How can I do taht?
Note for Blade I'm using [[ ]], and for Angular JS I'm using {{ }}.
Controller of Laravel is given as Following:
class CountryController extends BaseController {
        public function index()
            {
                return View::make('admin.country.show')
                    ->with('countries', Country::all());// returns array of JASON objects
            }

}

View of Laravel is given as follows:

                    Sr.No	Country

                        {{country.id}}	{{country.country}}

{{query}}

            {{countries}}
            [[ $countries]]

{{countries}} of ajs not works but [[$countries]] works! How can I access $countries in AJS?

A: I don'n know that whether it's a good practice or not but I've found the solution which is given as follows:

        Sr.No	Country

        {{country.id}}	{{country.country}}

Instead of using

I've used the
<?php echo("
"); ?>

It, after rendering becomes

You can clearly see that an array of JSON object is returned by php, which now can easly be printed.
Note again: I don't know that it's best practice or not! I still would like to know the best practice.


text:
Q: Can't centre elements horizontally (image and text) Does anyone have any idea of how to have the image and the text to be horizontal with each other but are centred within the green section within the example?  I need the image to be on the left and for the text to be on the right. I'm happy with the way it displays in mobile and tablet view, however, I just need to allow the content of the image and text to be displayed 50% (centred) within the green section even when the height of the green section is adjusting.
I think the main issue I'm having is that I have a min-height set for the green section, therefore it adjusts according to the size of the screen the user has.
The text appears very small when I adjust the height of the window to this size. It appears higher up in the green section, rather than in the middle:

#expertise-section {
  background-color: #bce4b8;
  border-bottom: 1px solid #000;
  text-align: center;
  padding: 100px 0 0;
  min-height: 650px;
  width: 100%;
} /* Adjusts section sizing, padding and text alignment */

/*------------------------------------------------
    START OF EXPERTISE SECTION STYLING
------------------------------------------------*/

#expertise-section h1 {
  color: #000;
  font-family: "Lobster Two", cursive;
  font-size: 40px;
  margin-top: -2%;
} /* Sets colour, font, font size and position of the h1 title within the expertise section */

.expertise-section-title {
  margin-top: 0;
} /* Sets margin of the expertise title */

.expertise-section-title:before {
  content: "";
  display: block;
  border-top: solid 1px #000;
  width: 100%;
  height: 1px;
  position: absolute;
  top: 50%;
  z-index: 1;
} /* Creates horizontal line for the expertise section titles and sets positioning */

.expertise-section-title span {
  background: #bce4b8;
  padding: 0 20px;
  position: relative;
  z-index: 1;
} /* Sets background of the expertise section background and sets padding for spacing between title and hr line */

.expertise-section-content {
  margin-left: 14%;
  margin-right: 14%;
  margin-top: 4%;
}

.expertise-section-content img {
  float: left;
  display: block;
  border: 1px solid black;
  margin-top: -2.25%;
  max-width: 45vh;
  max-height: 30vh;
  border-radius: 12.5%;
  margin-right: 5%;
} /* Sets size and positioning of image within the expertise section */

.expertise-section-content p {
  text-align: center;
  width: 100%;
  font-size: 2.2vh;
}

.expertise-section-content button {
  font-size: 2vh;
  padding: 0.6em 2em;
  border-radius: 35px;
  color: #fff;
  background-color: #339a9a;
  border: 1px solid black;
  cursor: pointer;
  text-align: center;
  /* clear: both; May not need this included */
  margin-left: 0%;
  margin-top: 2%;
}

.expertise-section-content button a {
  color: white;
}

.expertise-section-content button:hover {
  background-color: #004e4f;
  border: 2px solid white;
}

/*------------------------------------------------
    END OF EXPERTISE SECTION STYLING
  ------------------------------------------------*/

@media only screen and (max-width: 1606px) {
  #expertise-section h1 {
    margin-top: -4%;
    margin-bottom: 5%;
  } /* Sets colour, font, font size and position of the h1 title within the expertise section */

  .expertise-section-content {
    margin-left: 2.5%;
    margin-right: 2.5%;
    margin-top: 3%;
  }

  .expertise-section-content img {
    display: block;
    margin-left: 30%;
    margin-right: 30%;
    width: 40%;
    margin-bottom: 3%;
  } /* Sets size and positioning of image within the expertise section */

  .expertise-section-content p {
    text-align: center;
    font-size: 26px;
  }

  .expertise-section-content button {
    text-align: center;
    margin-bottom: 6.5%;
  }
}

@media only screen and (max-width: 815px) {

  /*------------------------------
    START OF EXPERTISE SECTION
  --------------------------------*/

  #expertise-section h1 {
    margin-top: -10%;
    font-size: 35px;
    color: #000;
  } /* Makes changes to sizing and positioning of the h1 tag */

  .expertise-section-title {
    margin-top: 0;
  } /* Sets margin of the expertise title */

  .expertise-section-title:before {
    content: "";
    display: block;
    border-top: solid 1px #000;
    width: 100%;
    height: 1px;
    position: absolute;
    top: 50%;
    z-index: 1;
  } /* Creates horizontal line for the expertise section titles and sets positioning */

  .expertise-section-title span {
    background: #bce4b8;
    padding: 0 20px;
    position: relative;
    z-index: 1;
  } /* Sets background of the expertise section background and sets padding for spacing between title and hr line */

  .expertise-section-content {
    margin-left: 2.5%;
    margin-right: 2.5%;
    margin-top: 6%;
  }

  .expertise-section-content img {
    margin-left: 12.5%;
    margin-right: 12.5%;
    width: 75%;
    margin-top: 4%;
    margin-bottom: 8%;
  } /* Sets size and positioning of image within the expertise section */

  .expertise-section-content p {
    text-align: center;
    width: 100%;
    font-size: 20px;
  }

  .expertise-section-content button {
    font-size: 26px;
    /* clear: both; May not need this included */
    margin-top: 5%;
    margin-bottom: 15%;
    padding: 0.4em 1.5em;
  }

  /*------------------------------
    END OF EXPERTISE SECTION
  --------------------------------*/
}

Why Choose Me?

My approach is warm and understanding. I am here to listen to you and help you to make sense of difficult times.
        If you would like to find out more, you can read about my experience and qualifications by clicking the button below.

        <button onclick="location.href='findoutmore.html'" type="button">Find Out More</button>

A: Please try these codes:
See: https://codepen.io/en0ndev/pen/bGBJpZW
.element {
  display:flex;
  justify-content:center;
  align-items:center;
  flex-direction:row;
  width:75%;
  margin-left:auto;
  margin-right:auto;
}

@media (max-width:1024px) {
  .element {
    flex-wrap:wrap; // for mobile
  }
}

Apart from these, I made changes in HTML.

#expertise-section {
  background-color: #bce4b8;
  border-bottom: 1px solid #000;
  text-align: center;
  padding: 100px 0 0;
  min-height: 650px;
  width: 100%;
} /* Adjusts section sizing, padding and text alignment */

.element {
  display:flex;
  justify-content:center;
  align-items:center;
  flex-direction:row;
  width:75%;
  margin-left:auto;
  margin-right:auto;
}

@media (max-width:1024px) {
  .element {
    flex-wrap:wrap;
  }
}

/*------------------------------------------------
    START OF EXPERTISE SECTION STYLING
------------------------------------------------*/

#expertise-section h1 {
  color: #000;
  font-family: "Lobster Two", cursive;
  font-size: 40px;
  margin-top: -2%;
} /* Sets colour, font, font size and position of the h1 title within the expertise section */

.expertise-section-title {
  margin-top: 0;
} /* Sets margin of the expertise title */

.expertise-section-title span {
  background: #bce4b8;
  padding: 0 20px;
  position: relative;
  z-index: 1;
} /* Sets background of the expertise section background and sets padding for spacing between title and hr line */

.expertise-section-content {
  margin-left: 14%;
  margin-right: 14%;
  margin-top: 4%;
}

.expertise-section-content img {
  float: left;
  display: block;
  border: 1px solid black;
  margin-top: -2.25%;
  max-width: 45vh;
  max-height: 30vh;
  border-radius: 12.5%;
  margin-right: 2em;
} /* Sets size and positioning of image within the expertise section */

.expertise-section-content p {
  text-align: center;
  width: 100%;
  font-size: 2.2vh;
}

.expertise-section-content button {
  font-size: 2vh;
  padding: 0.6em 2em;
  border-radius: 35px;
  color: #fff;
  background-color: #339a9a;
  border: 1px solid black;
  cursor: pointer;
  text-align: center;
  /* clear: both; May not need this included */
  margin-left: 0%;
  margin-top: 2%;
}

.expertise-section-content button a {
  color: white;
}

.expertise-section-content button:hover {
  background-color: #004e4f;
  border: 2px solid white;
}

/*------------------------------------------------
    END OF EXPERTISE SECTION STYLING
  ------------------------------------------------*/

@media only screen and (max-width: 1606px) {
  #expertise-section h1 {
    margin-top: -4%;
    margin-bottom: 5%;
  } /* Sets colour, font, font size and position of the h1 title within the expertise section */

  .expertise-section-content {
    margin-left: 2.5%;
    margin-right: 2.5%;
    margin-top: 3%;
  }

  .expertise-section-content img {
    display: block;
    width: 40%;
    margin-bottom: 3%;
  } /* Sets size and positioning of image within the expertise section */

  .expertise-section-content p {
    text-align: center;
    font-size: 26px;
  }

  .expertise-section-content button {
    text-align: center;
    margin-bottom: 6.5%;
  }
}

@media only screen and (max-width: 815px) {

  /*------------------------------
    START OF EXPERTISE SECTION
  --------------------------------*/

  #expertise-section h1 {
    margin-top: -10%;
    font-size: 35px;
    color: #000;
  } /* Makes changes to sizing and positioning of the h1 tag */

  .expertise-section-title {
    margin-top: 0;
  } /* Sets margin of the expertise title */

  .expertise-section-title span {
    background: #bce4b8;
    padding: 0 20px;
    position: relative;
    z-index: 1;
  } /* Sets background of the expertise section background and sets padding for spacing between title and hr line */

  .expertise-section-content {
    margin-left: 2.5%;
    margin-right: 2.5%;
    margin-top: 6%;
  }

  .expertise-section-content img {
    width: 75%;
    margin-top: 4%;
    margin-bottom: 8%;
  } /* Sets size and positioning of image within the expertise section */

  .expertise-section-content p {
    text-align: center;
    width: 100%;
    font-size: 20px;
  }

  .expertise-section-content button {
    font-size: 26px;
    /* clear: both; May not need this included */
    margin-top: 5%;
    margin-bottom: 15%;
    padding: 0.4em 1.5em;
  }

  /*------------------------------
    END OF EXPERTISE SECTION
  --------------------------------*/
}

Why Choose Me?

My approach is warm and understanding. I am here to listen to you and help you to make sense of difficult times.
        If you would like to find out more, you can read about my experience and qualifications by clicking the button below.

              <button onclick="location.href='findoutmore.html'" type="button">Find Out More</button>


text:
Q: Кастомизация title в Битрикс Нужно к title добавлять номер страницы при пагинации.
Title выводится в header.php шаблона сайта:
<title><?$APPLICATION->ShowTitle()?></title>

Самый простой способ это сделать - проверить GET-параметры на наличие PAGEN, взять его оттуда и приклеить к title.
Невооруженным глазом видно, что это костыль.
Битрикс только изучаю, а задача нужна уже на вчера. Кто что подскажет по этому случаю? Может есть какие-то события? Как правильно это реализовать в рамках Битрикс?
<title><?$APPLICATION->ShowTitle()?><?php echo isset($_GET['PAGEN_1']) ? ('- ' . GetMessage("PAGINATION_TITLE") . ' ' . $_GET['PAGEN_1']) : ''?></title>

A: Привязывать к $_GET['PAGEN_1'] не совсем правильно. В имени переменной зашит номер пагинации. Может получиться так, что вы добавите еще компонент перед этим и название будет уже $_GET['PAGEN_2']
Правильный вариант такой:

*

*Рядом с шаблоном компонента template.php создать файл result_modifier.php и добавить туда код

$cp = $this->__component;
if (is_object($cp))
{
    $cp->arResult["PAGE_NUMBER"]    = $arResult["NAV_RESULT"]->NavPageNomer;
    $cp->SetResultCacheKeys(["PAGE_NUMBER"]);
}

*Создать там же component_epilog.php и добавить туда код:

if ($arResult["PAGE_NUMBER"] > 1) {
    $APPLICATION->SetTitle($APPLICATION->GetTitle() . " - " . GetMessage("PAGINATION_TITLE") . " " . $arResult["PAGE_NUMBER"]);
}


text:
Q: How To Set Sources For Jupyter Notebooks I've just bought a new computer, and can't remember/don't know how I had Jupyter notebooks set up on my old machine. Specifically, how do you tell Jupyter about sources.
If I have a conda environment called django, and I do source activate django followed by jupyter notebook, I end up with a notebook, but then when I do from django.http import HttpResponse I get the error message
ModuleNotFoundError: No module named 'django'

Which is bizarre (I think), because Django is definitely installed in the Django environment.
How do I set up my Jupyter notebooks so that they know about the various sources that I want them to know about?

A: It is very likely your conda environment django doesn't have iPython Kernel installed which jupyter notebook needs. You can run jupyter notebook without activating a conda environment as notebook allows you to select any conda environment with ipykernel installed.
Try:

*

*run in terminal : source activate django

*run in terminal : conda install ipykernel

*run in terminal : source deactivate

*run in terminal : jupyter notebook

*select django for your kernel

A: I create a kernel for each of my virtual environments. On MacOS Jupyter kernels are located here $HOME/Library/Jupyter/kernels. Make sure ipykernel is installed in your virtual env.
So $HOME/Library/Jupyter/kernels/myenv/kernel.json looks like:
{
 "env": { "VIRTUAL_ENV": "/Users/<User>/<myenv>" },
 "argv": [ "/Users/<User>/<myenv>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
 "display_name": "My Virtual Env",
 "language": "python"
}

A: Found the answer here.
source activate django
conda install ipykernal
python -m ipykernel install --user --name django --display-name "Python (Django)"


text:
Q: Convert Blob from oracle to byte[] I try to read blob and sent it like byte[]. This is method that i use.
    public byte[] getBlob(long blobId)
    {
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = _connection;
        cmd.CommandText = "select TBlob_file FROM Tblob where blobId= " + blobId;
        object obj = cmd.ExecuteScalar();
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, obj);

        return ms.ToArray();
    }

I get answer but format of it is not good. My answer is look like:
<base64Binary>AAEAAAD/////AQAAAAAAAAAPAQAAAIFqBgAC/9j/4AAQSkZJRgABAQEASABIAAD/ .......

Always start with AAEAAAD/////AQAAAAAAAAAPAQ i think that is problem. Maybe i not convert blob in byte[] on right way?
Thanx

A: This is my method for string to byte array conversion (you have to convert obj to string first):
public static byte[] StringToByteArray(string hex)
{
    int numberChars = hex.Length;
    var bytes = new byte[numberChars / 2];
    for (int i = 0; i < numberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}

Also - please read up about sql injection attacks, you can start here: http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/. You have to use parameters instead of just string concatenation.


text:
Q: Visual Studio GIT with Symlinks / Linked Files in Solution I have a file structure as below:
D:\SharedCodeDir\codefile1.txt
D:\SharedCodeDir\codefile2.txt
D:\SharedCodeDir\...
D:\Solution\Project\projectfile1.txt
D:\Solution\Project\projectfile2.txt
D:\Solution\Project\...

I need to include D:\SharedCodeDir\codefile1.txt and other "shared" files in my VS project. I have several options to accomplish this:

*

*I can create a symlink to D:\SharedCodeDir\codefile1.txt in D:\Solution\Project\ so that D:\Solution\Project\codefile1.txt will really be a symbolic link to real file at D:\SharedCodeDir\codefile1.txt

*I can simply add D:\SharedCodeDir\codefile1.txt to my VS project as a link in the Add File dialog.

*I can create a hard link, so that both D:\SharedCodeDir\codefile1.txt and D:\Solution\Project\codefile1.txt will point to the same data on disk. This is least desired.

*I could create a folder symlink / junction in D:\Solution\Project to D:\SharedCodeDir, so that D:\Solution\Project\SharedCodeDir is really a symlink / junction to the real folder in  D:\SharedCodeDir
Question:
In Visual Studio 2013 / 2015, using Microsoft Git provider, how do I properly add my solution / project to Git source control, and which git attributes in the config gile if any I have to set, so that my "shared" files in D:\SharedCodeDir are properly accounted for (i.e. being tracked)?
Behavior I want:
Sample Case:
1) Suppose codefile1.txt is first being edited from VS as part of Solution 1. Then it is committed.
2) Then that same codefile1.txt is edited in some other program or from VS but from Solution 2 (in which case, it too is committed to Solution 2's repo at the end).
3) Now, when I get back to Solution 1, VS / git should alert me that there were changes to codefile1.txt since the last commit and ask me what I want to do.
Now, if codefile1.txt is not committed in step 1), that is it is checked out but not checked back in, I should be able to edit it outside VS or from another solution and it should behave as a normal linked file (VS alerting me of the fact that the file has changed since it was opened, if the file is opened in VS and has been changed outside). Then, I should just commit it as part of a solution that uses the file, so that it will be committed with all the latest changes to the solution's repo.
Finally, under no circumstances, should any Git-bound solution / repo attempt to replace the physical file at D:\SharedCodeDir\codefile1.txt with the latest version that they have committed (in cases they are different). It should only alert me of the fact that the files are different and what I want to do (replace the D:\SharedCodeDir\codefile1.txtwith the one from repo, or the other way around).
Also, I do not want D:\SharedCodeDir\codefile1.txt to be copied locally by Git to D:\SharedCodeDir\Solution\Project\codefile1.txt as another physical file. That is D:\SharedCodeDir\Solution\Project\codefile1.txt should always be a link of some sort (as described in alternatives 1 - 4 above) to the real file in D:\SharedCodeDir\codefile1.txt .
So how can I achieve this setup?
If it is really not possible with Git, how about SVN or alternatives?

A: In my case, very similar to yours, I did the following:

*

*Added files outside my solution folder using Add As Link in Visual Studio. These file links will be placed in a certain folder inside my solution.

In my case, these files will be shared with other projects and so each project will do the next step:

*To physically copy these files from lets say D:\SharedCode\*.cs to D:\MyProject\Shared*.cs I edited .csproj file and added the following just before the
</Project> tag

<Target Name="CopyLinkedFiles" BeforeTargets="Build">
<Copy SourceFiles="%(Compile.Identity)" DestinationFiles="%(Compile.Link)"
SkipUnchangedFiles="true" OverwriteReadOnlyFiles="true" Condition="'%(Compile.Link)'
!= ''" />
</Target>

So in this case all folders will work on newest copy of the shared files but still git will treat them as they were part of the specific project.
Note: If you need to link Content files(Resources,.txt..) instead of Compile files(.cs), replace Compile. with Content. in the code above


text:
Q: Lines printed by a child process to stdout How can I know the number of lines printed by a child process in C.
Better explanation of the scenario,
I have a c program in which I am going to fork a process. So I want to know the number of lines printed by the child process to the stdout.

A: You can override stdin, if ss is a file containing 12:
#include <stdio.h>

int main(int argc, char const *argv[])
{
    printf("%p\n", stdin);
    FILE * fd = fopen("ss", "r+");
    printf("%p\n", fd);
    stdin = fd;
    printf("%p\n", stdin);
    int a = 0;
    scanf("%d", &a);
    printf("%d\n", a);
    return 0;
}

Outputs:
➜ ./a
0x7fff70ab9350
0x7fff70abf280
0x7fff70abf280
12

A:
capture child's Stdout? How can I do that . could you be more speific?

#include <stdio.h>
main()
{
    FILE *fp = popen("ls -1", "r");
    int c, l = 0;
    do if (c = fgetc(fp), c == '\n') ++l; while (c != EOF);
    fclose(fp);
    printf("The child process printed %d lines.\n", l);
}


text:
Q: How can I create an abstract base class in C++? How would I go about doing the following in C++ (the following code is C#):
class Base
{
    public virtual void Foo()
    {
        // do stuff...
    }
}

class C : Base
{
    public override void Foo()
    {
        base.Foo(); // <=== how do you do this line?
    }
}

A: Use operator :::
class Base
{
public:
    virtual ~Base() {}
    virtual void Foo()
    {
        // do stuff
    }
};

class C : public Base
{
public:
    void Foo()
    {
        Base::Foo();
    }
};

To have an abstract class in C++ at least one method needs to be pure virtual:
class Base
{
public:
    virtual ~Base() {}
    virtual void Foo() {}
    virtual void another_function() = 0; // Pure virtual function.
};

A: Like this:
class base {
public:
    virtual void Foo() = 0;
}

class sub : public base {
public:
    void Foo() {
        std::cout << "In Sub!" << std::endl;
    }
}

Notice the use of the virtual keyword. In C++, unless explicitly declared, function implementations are not looked up at runtime, like C#, Objective-C or Java. Thus, we must tell the runtime that
'Hey, we have a function over here that needs to have it's implementation determined at runtime, so don't assume that it's of a class base, but of a subclass.'
Also note the = 0 part of the function declaration. In C++, this describes a pure  virtual function. Without it, base cannot be abstract, unless there is another function that is said to be pure virtual in the class.

A: I would just like to point out that you can  do this in C++. You just implement the pure virtual function in C++ that is you can do this in your .h:
class Base
{
    public:
       Base();
       virtual ~Base();
       virtual void Foo()=0;
};

and this in your .cpp
void Base::Foo()
{
   std::cout<< "In Base::Foo which is pure virtual\n";
}

Then in your derived class do what the others have indicated and in your Derived::Foo() you can call Base::Foo() which will produce output.  Making a function pure virtual does not obviate its a ability to have executable code.

A: To make a class abstract in C++, you need to provide it with a pure virtual function.  The C++ version of your code would be:
class Base
{
public:
    virtual void Foo() = 0; //setting a virtual function to 0 makes it pure virtual.     This is abstract.
}

class C : Base
{
public:
    void Foo()
    {
        Base::Foo(); //I don't think this line will work...You're calling an abstract method.
    }
}