text:
Q: Visualizing modified SIR model I tried to modify the SIR model from the eon package and did some changes to it. It has a new vaccination parameter attached to it with new parameters beta and omega and Vl and my code is-
def test_transmission(u, v, p):

return random.random()<p

def discrete_SIR(G,
            initial_infecteds,beta,
            w,Vl,return_full_data=True):

if G.has_node(initial_infecteds):
    initial_infecteds=[initial_infecteds]

if return_full_data:
    node_history = defaultdict(lambda : ([tmin], ['S']))
    transmissions = []
    for node in initial_infecteds:
        node_history[node] = ([tmin], ['I'])
        transmissions.append((tmin-1, None, node))

node_history = defaultdict(lambda : ([tmin], ['S']))
#    transmissions = []
for node in initial_infecteds:
    node_history[node] = ([tmin], ['I'])
    #transmissions.append((tmin-1, None, node))

N=G.order()
t = [tmin]
S = [N-len(initial_infecteds)]
I = [len(initial_infecteds)]
R = [0]
V = [0]

susceptible = defaultdict(lambda: True)
#above line is equivalent to u.susceptible=True for all nodes.

for u in initial_infecteds:
    susceptible[u] = False

infecteds = set(initial_infecteds)

while infecteds and t[-1]<tmax :
    new_infecteds = set()
    vaccinated= set()
    infector = {}  #used for returning full data.  a waste of time otherwise
    for u in infecteds:
     #   print('u-->' +str(u))
        for v in G.neighbors(u):
     #       print('v --> '+ str(v))
        ##vaccination
            if len(vaccinated)+V[-1]< (Vl*N)  : #check if vaccination over or not
                #print(len(vaccinated),Vl*N)
                #print("HI")

                if susceptible[v] and test_transmission(u, v, w):
                    vaccinated.add(v)
                    susceptible[v] = False
     #               print('transmitting vaccination')

                elif susceptible[v] and test_transmission(u,v,beta):
                    new_infecteds.add(v)
                    susceptible[v]=False
                    infector[v] = [u]
     #               print('transmitting infection')
            else:

    #            print("BYE")
                if susceptible[v] and test_transmission(u, v,beta):
                    new_infecteds.add(v)
                    susceptible[v] = False
                    infector[v] = [u]

           #infector[v] = [u]

    if return_full_data:
        for v in infector.keys():
            transmissions.append((t[-1], random.choice(infector[v]), v))
        next_time = t[-1]+1
        if next_time <= tmax:
            for u in infecteds:
                node_history[u][0].append(next_time)
                node_history[u][1].append('R')
            for v in new_infecteds:
                node_history[v][0].append(next_time)
                node_history[v][1].append('I')

    infecteds = new_infecteds

    R.append(R[-1]+I[-1])
    V.append(len(vaccinated)+V[-1])
    I.append(len(infecteds))
    S.append(N-V[-1]-I[-1]-R[-1])
    #S.append(S[-1]-V[-1]-I[-1])
    t.append(t[-1]+1)

print(str(R[-1])+','+str(V[-1])+','+str(I[-1])+','+str(S[-1]))

if not return_full_data:
    return scipy.array(t), scipy.array(S), scipy.array(I), \
           scipy.array(R)
else:
    return EoN.Simulation_Investigation(G, node_history, transmissions)

Now I want to run the visualizations on it like in the packagae EON-
m=5

G=nx.grid_2d_graph(m,m,periodic=True)
initial_infections = [(u,v) for (u,v) in G if u==int(m/2) and v==int(m/2)]
sim = EoN.basic_discrete_SIR(G,0.5,initial_infecteds = initial_infections,
               return_full_data=True, tmax = 25)

pos = {node:node for node in G}
sim.set_pos(pos)
sim.display(0, node_size = 40) #display time 6
plt.show()
plt.savefig('SIR_2dgrid.png')

What changes do I need to do in my code so that the display function works or do I need to make changes in the display function also?

A: Here's the output I now get:
You'll have to install EoN version 1.0.8rc3 or later, which is available on the github page (see installation instructions).  At present pip will not work to install it.  I want to make sure I haven't broken anything before I make it the default installed by pip.
Here's the code based on yours.  You should look through the changes I've made.  It's also worth looking at the examples I've put in the documentation (including an SIRV model where the vaccination rule is different than what you've got).
from collections import defaultdict
import EoN
import networkx as nx
import random
import matplotlib.pyplot as plt

def test_transmission(u, v, p):
    return random.random()<p

def discrete_SIRV(G, initial_infecteds,beta,
            w,Vl,tmin=0,tmax=float('Inf'), return_full_data=True):

    if G.has_node(initial_infecteds):
        initial_infecteds=[initial_infecteds]

    if return_full_data:
        node_history = defaultdict(lambda : ([tmin], ['S']))
        transmissions = []
        for node in initial_infecteds:
            node_history[node] = ([tmin], ['I'])
            transmissions.append((tmin-1, None, node))

    '''
    node_history = defaultdict(lambda : ([tmin], ['S']))
    #    transmissions = []
    for node in initial_infecteds:
        node_history[node] = ([tmin], ['I'])
    #transmissions.append((tmin-1, None, node))
    '''

    N=G.order()
    t = [tmin]
    S = [N-len(initial_infecteds)]
    I = [len(initial_infecteds)]
    R = [0]
    V = [0]

    susceptible = defaultdict(lambda: True)
    #above line is equivalent to u.susceptible=True for all nodes.

    for u in initial_infecteds:
        susceptible[u] = False

    infecteds = set(initial_infecteds)

    while infecteds and t[-1]<tmax :
        new_infecteds = set()
        vaccinated= set()
        infector = {}  #used for returning full data.  a waste of time otherwise
        for u in infecteds:
            #   print('u-->' +str(u))
            for v in G.neighbors(u):
                #       print('v --> '+ str(v))
                ##vaccination
                if len(vaccinated)+V[-1]< (Vl*N)  : #check if vaccination over or not
                    #print(len(vaccinated),Vl*N)
                    #print("HI")

                    if susceptible[v] and test_transmission(u, v, w):
                        vaccinated.add(v)
                        susceptible[v] = False

                        '''It's probably better to define a `new_vaccinated`
                        set and then do the `return_full_data` stuff later
                        where all the others are done.'''
                        if return_full_data:
                            node_history[v][0].append(t[-1]+1)
                            node_history[v][1].append('V')
     #               print('transmitting vaccination')

                    elif susceptible[v] and test_transmission(u,v,beta):
                        new_infecteds.add(v)
                        susceptible[v]=False
                        infector[v] = [u]
                        #               print('transmitting infection')
                else:

                    #            print("BYE")
                    if susceptible[v] and test_transmission(u, v,beta):
                        new_infecteds.add(v)
                        susceptible[v] = False
                        infector[v] = [u]

                        #infector[v] = [u]

        if return_full_data:
            for v in infector.keys():
                '''This random choice is no longer needed as you've taken out
                the possibility of multiple nodes transmitting to `v` in a given
                time step.  Now only the first one encountered does it.'''

                transmissions.append((t[-1], random.choice(infector[v]), v))
            next_time = t[-1]+1
            if next_time <= tmax:
                for u in infecteds:
                    node_history[u][0].append(next_time)
                    node_history[u][1].append('R')
                for v in new_infecteds:
                    node_history[v][0].append(next_time)
                    node_history[v][1].append('I')

        infecteds = new_infecteds

        R.append(R[-1]+I[-1])
        V.append(len(vaccinated)+V[-1])
        I.append(len(infecteds))
        S.append(N-V[-1]-I[-1]-R[-1])
        #S.append(S[-1]-V[-1]-I[-1])
        t.append(t[-1]+1)

        print(str(R[-1])+','+str(V[-1])+','+str(I[-1])+','+str(S[-1]))

    if not return_full_data:
        return scipy.array(t), scipy.array(S), scipy.array(I), \
           scipy.array(R)
    else:
        return EoN.Simulation_Investigation(G, node_history, transmissions, possible_statuses=['S', 'I', 'R', 'V'])

print(EoN.__version__)
print("line above needs to be 1.0.8rc3 or greater or it will not work\n\n")

m=20

G=nx.grid_2d_graph(m,m,periodic=True)
initial_infections = [(u,v) for (u,v) in G if u==int(m/2) and v==int(m/2)]
beta=0.8
Vl=0.3
w=0.1

sim = discrete_SIRV(G, initial_infections, beta, w, Vl, return_full_data=True)

pos = {node:node for node in G}
sim.set_pos(pos)
sim.sim_update_colordict({'S': '#009a80','I':'#ff2000', 'R':'gray','V': '#5AB3E6'})
sim.display(6, node_size = 40) #display time 6
plt.savefig('SIRV_2dgrid.png')


text:
Q: Nginx SSI - respecing links (with scripts and styles) included by html pointed by proxy-pass I am total Nginx newbie and I am doing my best to compose a UI. Let me give You my short nginx config file:
upstream wizard {
    server wizard:80;
}

server {
    listen 80;
    server_name localhost;
    ssi on;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri /index.html;
    }

    location /wizard {
        proxy_pass http://wizard;
    }
}

and the "master" html with SSI command:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Portal</title>

Portal

and the index.html from the location pointed by the proxy;
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My web</title>

IPA

    <link rel="modulepreload" href="/assets/vendor.d39310c0.js">
    <link rel="stylesheet" href="/assets/index.f1b61ee0.css">

Now this lines from the last html are problematic:
src="/assets/index.41982ecd.js"
href="/assets/vendor.d39310c0.js"
href="/assets/index.f1b61ee0.css"

Because I get 404 not found. The problem is obvious, nginx fetches the html, does SSI and then the browser tries to load the script, css which are not there (they are in the site pointed by the proxy). I can solve this by adding next location in the nginx config:
    location /assets {
        proxy_pass http://wizard;
    }

But is there another way? I can imagine I will have more web pages with asset folders. I can do the renames but yeah... I am looking for other options to solve this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a PHP namespace shortcut for this? I'm trying to find a way to mass apply these namespaces, as this would be inconvenient to write out. I know I can simply do, use jream\ as j  but I would like to see if it's possible to avoid the backslash.
require '../jream/Autoload.php';

use jream\Autoload as Autoload,
    jream\Database as Database,
    jream\Exception as Exception,
    jream\Form as Form,
    jream\Hash as Hash,
    jream\Output as Output,
    jream\Registry as Registry,
    jream\Session as Session;

new Autoload('../jream');

Isn't there a way to say something along these lines: jream\\* as *; ?
Any tips would be appreciated :)

A: At the very least you can skip all the redundant as aliasing:
use jream\Autoload,
    jream\Database,
    jream\Exception,
    jream\Form,
    jream\Hash,
    jream\Output,
    jream\Registry,
    jream\Session;

If you want to use everything in the namespace without typing it out one by one, then indeed the only real choice is to alias the namespace as a whole and use a backslash:
use jream as j;

new j\Autoload;

A:
Isn't there a way to say something along these lines: jream\* as *; ?

No, but you can do this:
// use-jream.php
class Autoload extends jream\Autoload {}
class Database extends jream\Database {}
...

// index.php
require_once 'use-jream.php'

new Autoload('../jream');

But I wouldn't really recommend doing it.
And of course, if you want to just change the default namespace:
namespace jream;

new Autoload('../jream');

That is all an import jream.* could ever mean in PHP, since PHP has absolutely no way to determine if a class could possibly exist in a certain namespace unless you inform it.


text:
Q: SQL: Find rows where Column contains all of the given words I have some column EntityName, and I want to have users to be able to search names by entering words separated by space. The space is implicitly considered as an 'AND' operator, meaning that the returned rows must have all of the words specified, and not necessarily in the given order.
For example, if we have rows like these:

*

*abba nina pretty balerina

*acdc you shook me all night long

*sth you are me

*dream theater it's all about you

when the user enters: me you, or you me (the results must be equivalent), the result has rows 2 and 3.
I know I can go like:
WHERE Col1 LIKE '%' + word1 + '%'
  AND Col1 LIKE '%' + word2 + '%'

but I wanted to know if there's some more optimal solution.
The CONTAINS would require a full text index, which (for various reasons) is not an option.
Maybe Sql2008 has some built-in, semi-hidden solution for these cases?

A: The only thing I can think of is to write a CLR function that does the LIKE comparisons. This should be many times faster.
Update: Now that I think about it, it makes sense CLR would not help. Two other ideas:
1 - Try indexing Col1 and do this:
WHERE (Col1 LIKE word1 + '%' or Col1 LIKE '%' + word1 + '%')
  AND (Col1 LIKE word2 + '%' or Col1 LIKE '%' + word2 + '%')

Depending on the most common searches (starts with vs. substring), this may offer an improvement.
2 - Add your own full text indexing table where each word is a row in the table. Then you can index properly.

A: Function
 CREATE FUNCTION [dbo].[fnSplit] ( @sep CHAR(1), @str VARCHAR(512) )
 RETURNS TABLE AS
 RETURN (
           WITH Pieces(pn, start, stop) AS (
           SELECT 1, 1, CHARINDEX(@sep, @str)
           UNION ALL
           SELECT pn + 1, stop + 1, CHARINDEX(@sep, @str, stop + 1)
           FROM Pieces
           WHERE stop > 0
      )

      SELECT
           pn AS Id,
           SUBSTRING(@str, start, CASE WHEN stop > 0 THEN stop - start ELSE 512 END) AS Data
      FROM
           Pieces
 )

Query
 DECLARE @FilterTable TABLE (Data VARCHAR(512))

 INSERT INTO @FilterTable (Data)
 SELECT DISTINCT S.Data
 FROM fnSplit(' ', 'word1 word2 word3') S -- Contains words

 SELECT DISTINCT
      T.*
 FROM
      MyTable T
      INNER JOIN @FilterTable F1 ON T.Col1 LIKE '%' + F1.Data + '%'
      LEFT JOIN @FilterTable F2 ON T.Col1 NOT LIKE '%' + F2.Data + '%'
 WHERE
      F2.Data IS NULL

Source: SQL SELECT WHERE field contains words

A: http://msdn.microsoft.com/en-us/magazine/cc163473.aspx

A: You're going to end up with a full table scan anyway.
The collation can make a big difference apparently. Kalen Delaney in the book "Microsoft SQL Server 2008 Internals" says:

Collation can make a huge difference
  when SQL Server has to look at almost
  all characters in the strings. For
  instance, look at the following:
SELECT COUNT(*) FROM tbl WHERE longcol LIKE '%abc%'

This may execute 10 times faster or more with a binary collation than a nonbinary Windows collation. And with varchar data, this executes up to seven or eight times faster with a SQL collation than with a Windows collation.

A: WITH Tokens AS(SELECT 'you' AS Token UNION ALL SELECT 'me')
SELECT ...
FROM YourTable AS t
WHERE (SELECT COUNT(*) FROM Tokens WHERE y.Col1 LIKE '%'+Tokens.Token+'%')
 =
(SELECT COUNT(*) FROM Tokens) ;

A: This should ideally be done with the help of Full text search as mentioned above.
BUT,
If you don't have full text configured for your DB, here is a performance intensive solution for doing a prioritized string search.
-- table to search in
drop table if exists dbo.myTable;
go
CREATE TABLE dbo.myTable
    (
    myTableId int NOT NULL IDENTITY (1, 1),
    code varchar(200) NOT NULL,
    description varchar(200) NOT NULL -- this column contains the values we are going to search in
    )  ON [PRIMARY]
GO

-- function to split space separated search string into individual words
drop function if exists [dbo].[fnSplit];
go
CREATE FUNCTION [dbo].[fnSplit] (@StringInput nvarchar(max),
@Delimiter nvarchar(1))
RETURNS @OutputTable TABLE (
  id nvarchar(1000)
)
AS
BEGIN
  DECLARE @String nvarchar(100);

  WHILE LEN(@StringInput) > 0
  BEGIN
    SET @String = LEFT(@StringInput, ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
    LEN(@StringInput)));
    SET @StringInput = SUBSTRING(@StringInput, ISNULL(NULLIF(CHARINDEX
    (
    @Delimiter, @StringInput
    ),
    0
    ), LEN
    (
    @StringInput)
    )
    + 1, LEN(@StringInput));

    INSERT INTO @OutputTable (id)
      VALUES (@String);
  END;

  RETURN;
END;
GO

-- this is the search script which can be optionally converted to a stored procedure /function

declare @search varchar(max) = 'infection upper acute genito'; -- enter your search string here
-- the searched string above should give rows containing the following
-- infection in upper side with acute genitointestinal tract
-- acute infection in upper teeth
-- acute genitointestinal pain

if (len(trim(@search)) = 0) -- if search string is empty, just return records ordered alphabetically
begin
 select 1 as Priority ,myTableid, code, Description from myTable order by Description
 return;
end

declare @splitTable Table(
wordRank int Identity(1,1), -- individual words are assinged priority order (in order of occurence/position)
word varchar(200)
)
declare @nonWordTable Table( -- table to trim out auxiliary verbs, prepositions etc. from the search
id varchar(200)
)

insert into @nonWordTable values
('of'),
('with'),
('at'),
('in'),
('for'),
('on'),
('by'),
('like'),
('up'),
('off'),
('near'),
('is'),
('are'),
(','),
(':'),
(';')

insert into @splitTable
select id from dbo.fnSplit(@search,' '); -- this function gives you a table with rows containing all the space separated words of the search like in this e.g., the output will be -
--  id
-------------
-- infection
-- upper
-- acute
-- genito

delete s from @splitTable s join @nonWordTable n  on s.word = n.id; -- trimming out non-words here
declare @countOfSearchStrings int = (select count(word) from @splitTable);  -- count of space separated words for search
declare @highestPriority int = POWER(@countOfSearchStrings,3);

with plainMatches as
(
select myTableid, @highestPriority as Priority from myTable where Description like @search  -- exact matches have highest priority
union
select myTableid, @highestPriority-1 as Priority from myTable where Description like  @search + '%'  -- then with something at the end
union
select myTableid, @highestPriority-2 as Priority from myTable where Description like '%' + @search -- then with something at the beginning
union
select myTableid, @highestPriority-3 as Priority from myTable where Description like '%' + @search + '%' -- then if the word falls somewhere in between
),
splitWordMatches as( -- give each searched word a rank based on its position in the searched string
                     -- and calculate its char index in the field to search
select myTable.myTableid, (@countOfSearchStrings - s.wordRank) as Priority, s.word,
wordIndex = CHARINDEX(s.word, myTable.Description)  from myTable join @splitTable s on myTable.Description like '%'+ s.word + '%'
-- and not exists(select myTableid from plainMatches p where p.myTableId = myTable.myTableId) -- need not look into myTables that have already been found in plainmatches as they are highest ranked
                                                                              -- this one takes a long time though, so commenting it, will have no impact on the result
),
matchingRowsWithAllWords as (
 select myTableid, count(myTableid) as myTableCount from splitWordMatches group by(myTableid) having count(myTableid) = @countOfSearchStrings
)
, -- trim off the CTE here if you don't care about the ordering of words to be considered for priority
wordIndexRatings as( -- reverse the char indexes retrived above so that words occuring earlier have higher weightage
                     -- and then normalize them to sequential values
select s.myTableid, Priority, word, ROW_NUMBER() over (partition by s.myTableid order by wordindex desc) as comparativeWordIndex
from splitWordMatches s join matchingRowsWithAllWords m on s.myTableId = m.myTableId
)
,
wordIndexSequenceRatings as ( -- need to do this to ensure that if the same set of words from search string is found in two rows,
                              -- their sequence in the field value is taken into account for higher priority
    select w.myTableid, w.word, (w.Priority + w.comparativeWordIndex + coalesce(sequncedPriority ,0)) as Priority
    from wordIndexRatings w left join
    (
     select w1.myTableid, w1.priority, w1.word, w1.comparativeWordIndex, count(w1.myTableid) as sequncedPriority
     from wordIndexRatings w1 join wordIndexRatings w2 on w1.myTableId = w2.myTableId and w1.Priority > w2.Priority and w1.comparativeWordIndex>w2.comparativeWordIndex
     group by w1.myTableid, w1.priority,w1.word, w1.comparativeWordIndex
    )
    sequencedPriority on w.myTableId = sequencedPriority.myTableId and w.Priority = sequencedPriority.Priority
),
prioritizedSplitWordMatches as ( -- this calculates the cumulative priority for a field value
select  w1.myTableId, sum(w1.Priority) as OverallPriority from wordIndexSequenceRatings w1 join wordIndexSequenceRatings w2 on w1.myTableId =  w2.myTableId
where w1.word <> w2.word group by w1.myTableid
),
completeSet as (
select myTableid, priority from plainMatches -- get plain matches which should be highest ranked
union
select myTableid, OverallPriority as priority from prioritizedSplitWordMatches -- get ranked split word matches (which are ordered based on word rank in search string and sequence)
),
maximizedCompleteSet as( -- set the priority of a field value = maximum priority for that field value
select myTableid, max(priority) as Priority  from completeSet group by myTableId
)
select priority, myTable.myTableid , code, Description from maximizedCompleteSet m join myTable  on m.myTableId = myTable.myTableId
order by Priority desc, Description -- order by priority desc to get highest rated items on top
--offset 0 rows fetch next 50 rows only -- optional paging


text:
Q: Word Addin Debug I have created a Word Addin for MS Word 2010. I want to debug the code. When I press Debug, a new instance of word is opened but no Addin seem to be loaded.
I can see my addin after installing via setup(.msi).
My addin is loaded as a COM object in word in mscoree.dll not as vsto.

A: It is possible your setup program is putting in necessary registry keys for the add-in down: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\Word\Addins (or alternately down this path but in HKCU). Or, if this key is already there, ensure the HKCU entry, if exists, has LoadBehavior set to 3


text:
Q: Only getting one element returned, OO PHP class Score
{
    var $score;
    var $name;
    var $dept;
    var $date;

    function Score($score, $name, $dept, $date)
    {
        $this->scores = ($score);
        $this->name = ($name);
        $this->dept = ($dept);
        $this->date = ($date);
    }

    function return_score(){
        return $this->scores;
        return $this->name;
        return $this->dept;
        return $this->date;
    }
}

$newscore = new Score("131313","James", "Marketing", "19/05/2008");
echo $newscore->return_score();

The above code is only echoing 131313. I am just beginning to learn OO PHP so please go easy! Totally lost, so any help would be much appreciated.

A: You can only return one value in each function or method.
In your situation, you should have a method for each of the class members:
public function getScore() {
   return $this->score;
}

public function getName() {
   return $this->name;
}

public function getDept() {
   return $this->dept;
}

public function getDate() {
   return $this->date;
}

Edit after the comments:
You could also need a method that returns all the members as a single string:
public function getAll() {
   return $this->getScore(). " " .$this->getName() . " " .$this->getDept(). " " .$this->getDate();
}

A: You can't return more than once in a function. You could return a concatenated string:
return $this->scores.' '.this->name.' '.$this->dept.' '.$this->date;
//added spaces for readability, but this is a silly thing to do anyway...

I wouldn't recommend it though as you'd be mixing you presentation of the object with its functionality - don't.
I'd suggest making a template of some sort (I'm imagining you might want to tabulate this data?). Each row would look something like:

  <?php echo $score->name; ?>
  <?php echo $score->scores; ?>

and giving it your object or objects in array (you know about foreach{} ?). I know it looks more long-winded, but separating these concerns is going to be better for you in the long run.
Assigning with = : you don't need the parentheses around the thing being assigned (usually).
Also:
Are you running PHP4? Your constructor function indicates you are. I'd recommend moving to 5.21 or higher if at all possible as classes and objects are much better. You can also use the rather useful __construct method (as opposed to using the class named method - in your case: Score()). This makes inheritance and extending easier because your classes are no longer having to remember in two places what class they are extending from.

A: First of all you should use public, protected or private instead of var
var $score;
var $name;
var $dept;
var $date;

such as
protected $score;

or with a coding standard prefix protected/private variables and methods with underscore like such
protected $_score;

This method can also be called __construct
function Score($score, $name, $dept, $date)
{

The var is declared as score but you assign a variable to scores. I also don't understand why you have parentheses around the variable.
        $this->scores = ($score);
        $this->name = ($name);
        $this->dept = ($dept);
        $this->date = ($date);

Replace with
    $this->score = $score;
    $this->name = $name;
    $this->dept = $dept;
    $this->date = $date;

}

The first return encountered will return that value from the function/method. I suggest you recode to add get/set for each variable, ie getScore() or to use PHP5 method overloading __set, __get and __call.
public function getScore() {
        return $this->score;
}

}
You can also look at the automatic methods to set and get variables Overloading


text:
Q: Limit a number into a range in Python? I want to limit a number onto a specific range in Python, I will be updating this number through the code constantly so I would prefer it to be a class or something that i can just reuse or call.
When I say limit in a range I mean that number can't be higher than 100 or lower than 0 for example.
I am pretty new to programming and python and i would appreciate if you could explain to me your solutions please.
Thanks.


text:
Q: How to append a text containing pipe symbol with text file using command prompt? I am trying to create a powershell script to a directory using batch file.
echo $ie=new-object -com "InternetExplorer.Application" >> C:\scripts\IEAutomate.ps1
echo $ie.navigate("http://google.com") >> C:\scripts\IEAutomate.ps1
echo $ie.visible=$true >> C:\scripts\IEAutomate.ps1
echo sleep 10 >> C:\scripts\IEAutomate.ps1
echo $doc=$ie.document >> C:\scripts\IEAutomate.ps1
echo if (Test-Path (c:\scripts\username.txt)) >> C:\scripts\IEAutomate.ps1
echo { >> C:\scripts\IEAutomate.ps1
echo } >> C:\scripts\IEAutomate.ps1
else >> C:\scripts\IEAutomate.ps1
echo { >> C:\scripts\IEAutomate.ps1
echo $credential=Get-Credential >> C:\scripts\IEAutomate.ps1
echo $credential.Username | ConvertFrom-SecureString | Set-Content   c:\scripts\username.txt >> C:\scripts\IEAutomate.ps1
echo $credential.Password | ConvertFrom-SecureString | Set-Content c:\scripts\password.txt >> C:\scripts\IEAutomate.ps1
echo } >> C:\scripts\IEAutomate.ps1

It is creating fine but when I am trying to write a line which has pipe symbol (|), It is not happening and treating that as a cmdlet.
Please help me to get this done.

A: Pipe symbol | is interpreted as a special character. For printing it you can exploit the escape character: ^
e.g.,:
echo ^|

or in your case
echo $credential.Username ^| [...]

A: Insert a caret (^) before the pipe.
This is a standard solution to any of batch's special characters - except % which requires to be escaped with % (ie. double-up)

A: Try escaping the pipe with a caret!
echo hi ^| joe > fred

A: Take a look at this URL to escape certain characters in powershell 3.0+.
To do what you need to do you need a caret, but in the link below it explains escaping.
http://ss64.com/ps/syntax-esc.html


text:
Q: Problems with Open/Close sql connection I hope you forgive my beginner's head. I am having some problems with a code designed to open a connect to a SQL Server database.
As you can see frmManageAppointment form is loaded from a different Winform. So far so good. Upon loading, the Connect() part of the code kicks in and connects to my SQL Server database. So far so good.
I have a second script that load upon pressing the Save button on the form (basically saving a variety of textboxes and such). My guess is that the second instance of conn in the MakeAppointment code somehow closed the connection, based on the error I am getting.
I know I am not handling the script correctly so I would appreciate some help.
namespace Scheduler1
{
    public partial class frmManageAppointment : Form
    {
        public frmManageAppointment()
        {
            InitializeComponent();
        }

        private void frmManageAppointment_Load(object sender, EventArgs e)
        {
            Connect();

            txtDBConnection.Text = "Connected";
        }

        private void ExitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtSurname.Text))
            {
                MessageBox.Show("Απαιτείται το Επίθετο του Εξεταζόμενου!");
                return;
            }

            if (MakeAppointment())
            {
                MessageBox.Show("Επιτυχής Προσθήκη!");
            }
            else
            {
                MessageBox.Show("Ανεπιτυχής Προσθήκη");
            }
        }

        public void Connect()
        {
            string conString = "Data Source=DIMITRIS-PC\\DIMITRISSQL;Initial Catalog=AppointmentDB;Integrated Security=True";
            SqlConnection conn = new SqlConnection(conString);

            conn.Open();

            if (conn.State == System.Data.ConnectionState.Closed)
            {
                MessageBox.Show("Closed");
            }
            else if (conn.State == System.Data.ConnectionState.Open)
            {
                MessageBox.Show("Open");
            }
        }

        public Boolean MakeAppointment()
        {
            string conString = "Data Source=DIMITRIS-PC\\DIMITRISSQL;Initial Catalog=AppointmentDB;Integrated Security=True";
            SqlConnection conn = new SqlConnection(conString);
            string sql = "INSERT INTO Appointmentdbo(Date, Time, Name, Surname, DOB, PatientID, Comments) VALUES ('" + dtpDate.Value.Date.ToString("MM/dd/yyyy") + "','" + comboTime.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + dtpDOB.Value.Date.ToString("MM/dd/yyyy") + "','" + txtID.Text + "','" + txtComments.Text + "')";

            SqlCommand cmd = new SqlCommand(sql, conn);

            return cmd.ExecuteNonQuery() > 0;
        }
    }
}

A: As the comments pointed out, you're creating a connection (the conn object in Connect(), opening it, and then conn goes out of scope.  It's the conn object here that IS the open connection.
Here's the shortest way to get this to work, but as the comments also state, this isn't really that great, either.  I laid this out to explain exactly what you were doing wrong/why what you had wasn't working.  Below this I have an example with using statements.
public class frmManageAppointment : Form {

    SqlConnection conn; //private variable available to all methods in this class

    private void frmManageAppointment_Load(object sender, EventArgs e)
    {
        Connect();
    }

    private void ExitButton_Click(object sender, EventArgs e)
    {
        this.CloseConn(); //new method here
        this.Close();
    }

    void CloseConn() {
        //we want to close/dispose the connection obect
        conn.Close();
        conn.Dispose();
    }

    public void Connect()
    {
        string conString = "<constring>";
        conn = new SqlConnection(conString); //removed type here so conn now the class level variable
        conn.Open();
        //rest of code snipped
    }

    public Boolean MakeAppointment()
    {
        string sql = "<sql string>"; //btw, the way you're generating this string is ... not ideal.  Google sql injection
        SqlCommand cmd = new SqlCommand(sql, conn); //conn is our global variable, which we're assuming here is still open/valid (not ideal)
        return cmd.ExecuteNonQuery() > 0;
    }

}
The problem with this is that your form will be open for an indefinite length of time.  This probably won't be an issue with a small app connecting to a local database where the app is the only thing connecting, but leaving the connection open wastes server resources and you have no guarantee that the conn object is still valid when you later try to use it in MakeAppointment().  You could add checks that it is actually open and call Connect() again if it's not, but that's a bunch of work for no gain.  A better pattern/habit to adopt when working with databases (or any network resource) is to only open them when you need to do work and close/release them as soon as you're done.  So that said, here's what your code would look like.
public class frmManageAppointment : Form {

    //no need for a Connect() method, conn global variable, or a CloseConn() method
    //your other methods pertaining to the UI would need to be copied over

    public Boolean MakeAppointment()
    {
        string sql = "<sql string>"; //again, what you're doing here is bad
        using(SqlConnection conn = new SqlConnection("<connectionstring>") {
            conn.Open();
            using(SqlCommand cmd = new SqlCommand(sql, conn)) {
                return cmd.ExecuteNonQuery() > 0;
            }
        }
    }
}

You only open the connection immediately before using it (the only place you're doing work in this example is in MakeAppointment()), and by wrapping the connection and command in using statements, they're automatically disposed of (by calling those objects Dispose() method) as soon as they go out of scope.


text:
Q: Building hybrid RAID10 + RAID5 environment I have the following configuration: simple video surveillance system (server 1: recording past 24h; server 2: recording past 30 days). I am primarily using the content on the 24h storage, while I recompress and archive the following 30 days on the other server.
My idea is to use RAID 1+0 for server 1 (for better performance & reliability) and RAID5 for server 2 (for lower cost). Is this a good plan or there are better alternatives to this architecture? Thanks.

A: According to your comments, you're using 5400 or 7200 RPM drives. In this scenario, on local storage, I'd recommend either RAID 6 or RAID 10. RAID 10 is not much of a gain in redundancy, so I'd go RAID 6 for both groups. There is a write overhead on RAID 6 that doesn't exist on RAID 10, however since you're doing mostly sequential writes, it will not interfere.


text:
Q: Moving files between Libraries along with Lookup Columns? Is it possible to move a file from one library to another along with the lookup columns associated with it?

A: Well, Finally I figured out :-)
See while making a workflow, there is option of "Association Columns" there we can add new column and select the type as "Look-up",search for the specific column name and save it.
Now just save and publish the workflow !! And it finally works. Revert, for any clarifications.


text:
Q: Angular 2 Disable Specific Dates in Date Picker I was having some problem when trying to disable certain dates in date picker. My customized date picker in typescript as per following:
import { DateFormatter } from './ng2-bootstrap/date-formatter';
import { DatePickerComponent } from './ng2-bootstrap/datepicker.component';
import * as moment from 'moment-timezone';

@Component({
    selector: '[acn-datepicker-popup]',
    templateUrl: './datepicker-popup.component.html',
    inputs: [],
    host: {}
})
export class DatepickerPopupComponent implements OnInit {
    @Input() datepickerDirective: any;
    @Input() minDate: moment.Moment;
    @Input() maxYears: number;
    @Input() alignRight: boolean = false;
    @Input() disabledDates: string;

    private dateFormat: string = 'DD/MM/YYYY';
    private earliestDate: string = '01/01/1970';

    datePickerCmp: DatePickerComponent;
    datepickerFormControl: FormControl;
    selectedDate: moment.Moment;
    dateFormatter: DateFormatter = new DateFormatter();

    constructor(private _datePickerCmp: DatePickerComponent, @Inject('datepickerFormControl') private _datepickerFormControl: FormControl) {
        this.datePickerCmp = _datePickerCmp;
        this.datepickerFormControl = _datepickerFormControl;
        if (this.datepickerFormControl.value && this.dateFormatter.isValid(this.datepickerFormControl.value, this.dateFormat)) {
            this.selectedDate = moment(this.datepickerFormControl.value, this.dateFormat);
        }
    }

    ngOnInit() {
        var splits = this.disabledDates.toString().split(";");
        for(let i = 0; i < splits.length; i++){
            console.log("Dates" + splits[i]);
        }
    }

My date picker component in HTML:

        TEST DATE*

            <input type="text" [formControl]="bookingModel.controls.testDte" class="form-control"  maxlength="10" style="border-right:transparent">

                <button class="btn btn-square btn-white-primary form-control" type="button"></button>

I managed to passed in the dates to be disabled in ngOnInit(). The splits variable contains the list of dates to be greyed out in date picker. However, I have no idea how to set the dates to be disabled in the date picker. Any ideas?
Thanks!

A: I will give you simple example of how to disable specific dates.
First we need to just install material design theme in our angular application. so let's add as like bellow:
ng add @angular/material

Ts File:
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'my-app';

    myHolidayDates = [
                    new Date("12/1/2020"),
                    new Date("12/20/2020"),
                    new Date("12/17/2020"),
                    new Date("12/25/2020"),
                    new Date("12/4/2020"),
                    new Date("12/7/2020"),
                    new Date("12/12/2020"),
                    new Date("12/11/2020"),
                    new Date("12/26/2020"),
                    new Date("12/25/2020")
                ];

    myHolidayFilter = (d: Date): boolean => {
        const time=d.getTime();
        return !this.myHolidayDates.find(x=>x.getTime()==time);
    }
}

Now in view file, we will write code of input element with datepicker as like bellow:

Angular Material Disable specific dates

<mat-form-field>
  <input matInput [matDatepicker]="picker" [matDatepickerFilter]="myHolidayFilter" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker ></mat-datepicker>
</mat-form-field>

Try this method.


text:
Q: Best approach for time series What approach would be best for time series that tracked user generate some events (activitie is file creation - from 0 files per day - 18 files per day ). I determined that number of events per day follow negative binomial distribution and I used pseudo random generator to generate / simulate user behavior, but I don t know how to determine time of events(creation). Final goal is simulation of this user so if there is 4 events (user created 4 files that day) when in simulation that will be scheduled durring 24 h. Do I need to filter data in a way to have one data set 1 event/day, second dataset with 2 events/day and so on .. or some other approach.

A: SARIMA model https://autobox.com/pdfs/SARMAX.pdf identification is the answer following the ITERATIVE process here https://autobox.com/pdfs/ARIMA%20FLOW%20CHART.pdf . I strongly suggest that you consider approaches that allow for latent determinstic structure to be identified and incorporated as compared to freely available dated solutions that assume that there is no deterministic structure AND no outliers/pulses AND that the model parameters are constant over time AND that model error variance is constant over time.
The true Gold Standard of time series model identification includes an iterative process not just a single list-based presumptive approach that sometime is suggested here. Carefully ask and know the assumptions underlying all statistical tests . Read about A. Wald here https://medium.com/@penguinpress/an-excerpt-from-how-not-to-be-wrong-by-jordan-ellenberg-664e708cfc3d .  A mathematician is always asking, "What assumptions are you making? And are they justified?"
Read closely the advice of @AdamO "The correlogram should be calculated from residuals using a model that controls for intervention administration, otherwise the intervention effects are taken to be Gaussian noise, underestimating the actual autoregressive effect." from Interrupted Time Series Analysis - ARIMAX for High Frequency Biological Data? . In layman's words don't over-trust or over-believe the acf/pacf if there are possible untreated deterministic structure in your data.


text:
Q: Parallel Deployment Exception when I deploy a new version (3.0.1) of my webapp on Tomcat 8 [on tomcat is deployed an older version (3.0.0)] i get this exception:
Failed to register LiveBeansView MBean; nested exception is javax.management.InstanceAlreadyExistsException

org.springframework.context.ApplicationContextException: Failed to register LiveBeansView MBean; nested exception is javax.management.InstanceAlreadyExistsException: security-base,security-api:application=/MyWebApplication
      at org.springframework.context.support.LiveBeansView.registerApplicationContext(LiveBeansView.java:72)
      at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:776)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:483)
      at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
      at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
      at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
      at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
      at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
      at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
      at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
      at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
      at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
      at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:473)
      at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1617)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
      at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
      at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1483)
      at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:731)
      at org.apache.catalina.manager.ManagerServlet.doPut(ManagerServlet.java:424)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:651)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:589)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
      at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: javax.management.InstanceAlreadyExistsException: security-base,security-api:application=/MyWebApplication
      at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
      at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
      at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
      at org.springframework.context.support.LiveBeansView.registerApplicationContext(LiveBeansView.java:68)
      ... 51 more

In web.xml of my application i have this configuration:
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>
<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>
<context-param>
    <param-name>spring.liveBeansView.mbeanDomain</param-name>
    <param-value>security-base,security-api</param-value>
</context-param>

Anyone can help me ?

A: Since you have two deployments on your Tomcat server for the same application (albeit different versions), you'll need to name your MBeans differently. Since MBeans are accessed per server (via a single JMX endpoint), each MBean identifier has to be separate.
You have a few options to make these unique in your apps:

*

*The simplest solution is to set endpoints.jmx.unique-names to true and let Spring Boot make the MBean paths unique for you, rather than using default names.
.

*Alternatively, you can change the MBean domain by setting thespring.jmx.default-domain=applicationname for the application

*And you might likely not need this, but adding here for completeness; if you're manually loading your beans in Spring Configuration, you can add the EnableMBeanExport specifying a domain as such:
@Configuration
@EnableMBeanExport(defaultDomain="first")
public class MBeanConfig {...}

A: In my application 'spring.profiles' were added to get rid of debug log. spring jndi NamingException: Name [spring.liveBeansView.mbeanDomain] is not bound in this Context
I fixed this issue by modifying web.xml for each deployed application making param-value  unique per web.xml.
<param-value>prod</param-value>
vs
<param-value>test</param-value>
For example:
Production:
  <context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>prod</param-value>
  </context-param>
  <context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>prod</param-value>
  </context-param>
  <context-param>
    <param-name>spring.liveBeansView.mbeanDomain</param-name>
    <param-value>prod</param-value>
  </context-param>

Testing
  <context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>test</param-value>
  </context-param>
  <context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>test</param-value>
  </context-param>
  <context-param>
    <param-name>spring.liveBeansView.mbeanDomain</param-name>
    <param-value>test</param-value>
  </context-param>


text:
Q: Django Forms: Connecting two functions together for Email Verification I have created a basic Create User form (username, email, password1, password2) called CreateUserForm and i would like to create an email verification process. It is simple enough to do using one function. But i want to add an additional function that asks the user to accept Terms and Conditions before a verification email is sent. In addition the terms and conditions has to be on a separate html template page. I have also created a Terms and Conditions form which is just a simple BoolianField. I am getting an error saying: ''User' object has no attribute 'get'. Do i have to use a request.get somewhere in my code? A steer in the right direction would be helpful. My code is below:
view.py:
def registerPage(request):
    form = CreateUserForm()
    if request.method =='POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)# Save user data but do not commit to database
            return redirect('accept_terms') and instance #accept_terms is the name of the registration/terms_and_conditions.html
    else:
        form = CreateUserForm()
    return render(request,'registration/register.html', {'form': form})

def AcceptTerms(request):
    form = Terms_Conditions()
    if request.method =='POST':
        form = Terms_Conditions(request.POST)
        if form.is_valid():
            userform = registerPage # I want to get the saved User data from the registerPage function
            send_verification_email(request, userform) #Sends verification email
            return HttpResponse('Thank you, an email will be sent for you to verify.')
    else:
        form = Terms_Conditions()
    return render(request,'registration/terms_and_conditions.html', {'form': form})

Edit:
So i have decided to use Form Wizard instead and i have the following code:
class ContactWizard(SessionWizardView):
    template_name = "test.html"

    def done(self, form_list, **kwargs):
        form_data = process_form_data(form_list)
        context = [form_data[0]['username'],form_data[0]['email'],form_data[0]['password1'],form_data[0]['password2']]

        send_verification_email(self.request, context) # Problem is here
        return HttpResponse('Sent')

def process_form_data(form_list):
    form_data = [form.cleaned_data for form in form_list]
    return form_data

However i am getting the error  'list' object has no attribute 'save'. I think it does not like the send_verification_email function but i am unclear how to resolve it.

A: I have solved it. The issue was i was cleaning the data twice once outside the 'send_verification_email' function and once inside it which was throwing the error.
def done(self, form_list, **kwargs):

    form_data = [form for form in form_list]
    first_form = form_data[0]
    send_verification_email(self.request, first_form)

    return HttpResponse('Sent')


text:
Q: connect one Output to two diffrent Inputs of two components in Modelica? I want to connect one single OUTPUT of an evaporator to two different INPUTS of two valves (as shown in the code main_1), and also trying to see if its possible to connect two OUTPUTS of two valves to a single INPUT of an evaporator (as shown in code main_2) in MODELICA, is that possible?
-model evaporator have one input and one output.
-model evaporator_2 have one input and one output.
    model main_1
evaporator EVAP;
valve_a valve_1;
valve_b valve_2;
equation
connect(EVAP.port_out,valve_1.port_in);
connect(EVAP.port_out,valve_2.port_in);
end main_1

    model main_2
evaporator_2 EVAP;
valve_c valve_3;
valve_d valve_4;
equation
connect(valve_3.port_out,EVAP.port_in,);
connect(valve_4.port_out,EVAP.port_in);
end main_2


text:
Q: Simplifying jquery / javascript for checkbox links I have written a couple simple lines of code that allows checkboxes in a sidebar navigation when clicked to send the user to a specified link. The checkboxes work as filters.
here is the HTML for the checkbox:

<input id="path1" type="checkbox" value="Accessories">
Accessories

And the jquery / javascript that creates the interaction:
    $('#path1').click(function(){
                 window.location='href'; //href would be a unique link
   });

The issue isn't getting this interaction to work, I'm having a logic problem. The way it's written is it's targeting the id of the checkbox. It isn't scalable. 8 links aren't so bad, but 500 links, each one unique, you get the idea.
Is there a solution that targets every checkbox but allows for unique links for each one? I.e. targeting the class makes all of the checkboxes have the same href, so that isn't an option, etc.

A: Assuming your href value comes from the link that follows the input you can use:
$('li.inactive input[type="checkbox"]').click(function(){
    window.location = $(this).next('a').attr('href')
});

A: You can do the following:
<input type="checkbox" data-custom-click="href">

The above code can be repeated many times as you need and enables you to have as many number of checkboxes as you want.
Note href in the above HTML represents your link for that specific checkbox.
And the one liner JavaScript:
$("input[data-custom-click]").click(function (){
    window.location=$(this).attr("data-custom-click");
});

The selector input[data-custom-click] will select all your custom behaviour checkboxes and the $(this) selects the clicked checkbox.


text:
Q: DFSR Backlog Stuck on Non-Existent Folders I have two 2008r2 servers setup in a full-mesh multipurpose replication group. (01 and 02). 01 was the source server. The initial sync just finished last night and there are 2 folders that do not appear on either server but they are stuck in the backlog of changes being pushed from 02 to 01. The backlog from 01 to 02 is clear and is replicating perfectly.

*

*I've attempted rebooting 02, this did nothing.

*The Event viewer for both servers contains nothing helpful.

*I've attempted creating and deleting the "batman" folder hoping that would clear it out. It didn't. When I created it on 01 it pushed it to 02. When I created it on 02 it created a redundant entry on the backlog.

*There were some other random files stuck in the backlog. They were unnecessary so I just deleted them from 01 and it cleared them from the backlog. I was hoping to just do the same with the folders...

Is there somewhere else I can look to help find why those folders are stuck?
Edit:
I also found this from the DFSR debug log (This occurred while the initial sync was finishing up last night):
20140513 23:27:39.254 2372 CSMG  6769 ContentSetManager::Initialize csId:{2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB} csName:Art rootPath:E:\Art state:InitialSync(Sync) ptr:0000000000F83D50
20140513 23:27:39.254 2372 CSMG  5547 ContentSetManager::CheckContentSetState Updating content set record csId:{2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB} csName:Art ghosted:0 readOnly:0 readOnlySince:16010101 00:00:00.000
20140513 23:27:39.254 2372 CSMG  5590 ContentSetManager::CheckContentSetState Content set csId:{2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB} state:InitialSync(Cleanup)
20140513 23:27:39.395 2372 STAG  2594 Staging::ScanStagingDirectory Staging space usage is: 285794033664
20140513 23:27:39.395 2372 CSMG  2960 ContentSetManager::StartInitialSyncCleanup csId:{2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB}
20140513 23:27:39.395  448 ISYN   153 InitialSyncCleanupTask::Run csId:{2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB}
20140513 23:27:45.760  448 ISYN   453 InitialSyncCleanupTask::MoveOut Moving \\.\E:\Art\Artist Files\Christine\batman to pre-existing:0x9000000156B80 csId:{2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB}
20140513 23:27:45.776  448 CSMG   547 ContentSetManager::DeleteChildren LDB Updating ID Record:
+   fid                             0x1000000001DF2
+   usn                             0x0
+   uidVisible                      0
+   filtered                        0
+   journalWrapped                  0
+   slowRecoverCheck                0
+   pendingTombstone                1
+   internalUpdate                  0
+   dirtyShutdownMismatch           0
+   meetInstallUpdate               0
+   meetReanimated                  0
+   recUpdateTime                   20140505 11:56:12.179 GMT
+   present                         1
+   nameConflict                    0
+   attributes                      0x10
+   ghostedHeader                   0
+   data                            0
+   gvsn                            {BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133
+   uid                             {BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133
+   parent                          {29CFABC2-0180-41C7-A9CE-21DD92783892}-v6880183
+   fence                           Initial Sync (1)
+   clockDecrementedInDirtyShutdown 0
+   clock                           20140501 00:01:02.367 GMT (0x1cf64d070b1522c)
+   createTime                      20140124 09:37:42.441 GMT
+   csId                            {2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB}
+   hash                            00000000-00000000-00000000-00000000
+   similarity                      00000000-00000000-00000000-00000000
+   name                            batman
+
20140513 23:27:45.776  448 LDBX  4435 Ldb::InsertWalkerJob Inserting dirWalkerJob:uid:{BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133 moveType:MoveOut (2) at time:20140514 03:27:45.776
20140513 23:27:45.807  448 DIRW   647 DirWalkerTask::QueueMoveoutJob Queueing move-out uid:{BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133 fid:0x1000000001DF2
20140513 23:27:45.807 2372 DIRW   317 DirWalkerTask::Run Start walking directory.
20140513 23:27:45.807 2372 DIRW  1373 DirWalkerTask::MoveoutStep Starting to process move-out job. uid:{BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133
20140513 23:27:45.807 2372 DIRW  1398 DirWalkerTask::MoveoutStep Iterating children of uid: {BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133
20140513 23:27:45.807 2372 DIRW  2764 DirWalkerTask::TombstoneOrDelete LDB Updating ID Record:
+   fid                             0x1000000001DF2
+   usn                             0x0
+   uidVisible                      0
+   filtered                        0
+   journalWrapped                  0
+   slowRecoverCheck                0
+   pendingTombstone                0
+   internalUpdate                  0
+   dirtyShutdownMismatch           0
+   meetInstallUpdate               0
+   meetReanimated                  0
+   recUpdateTime                   20140505 11:56:12.179 GMT
+   present                         0
+   nameConflict                    1
+   attributes                      0x10
+   ghostedHeader                   0
+   data                            0
+   gvsn                            {BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1376267
+   uid                             {BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133
+   parent                          {29CFABC2-0180-41C7-A9CE-21DD92783892}-v6880183
+   fence                           Default (3)
+   clockDecrementedInDirtyShutdown 0
+   clock                           20140514 03:27:45.776 GMT (0x1cf6f247911f746)
+   createTime                      20140124 09:37:42.441 GMT
+   csId                            {2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB}
+   hash                            00000000-00000000-00000000-00000000
+   similarity                      00000000-00000000-00000000-00000000
+   name                            batman
+
20140513 23:27:45.807 2372 DIRW   101 DirWalkerTask::Job::Finish MoveOut csId:{2D9CF1D7-50E2-4B3E-AC6B-3D60C6B026EB} uid:{BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133
20140513 23:27:45.807 2372 DIRW   893 DirWalkerTask::RemoveJob Removing job type:2 uid:{BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133
20140513 23:27:45.807 2372 LDBX  4472 Ldb::DeleteWalkerJob Deleting dirWalkerJob. uid:{BE36C74B-B5FC-4E8A-8735-039CF9FB3982}-v1264133
20140513 23:27:45.807 2372 DIRW   364 DirWalkerTask::Run Exit.

A: This is a slightly stale question but have you explored the 'Staging' and 'Conflict and Deleted' folders?
DFS Staging and Conflict and Deleted Folders
One way that you could end up with this situation is the presence of leftover files or fragments floating around in these folders that are not getting properly resolved.  You could clean out those locations to manually 'reset' synchronization on both sides.  However, I'd also investigate the source of the folder and ensure that:

*

*Conflicting permissions are not being set on the files/folders in question.

*Another server or endpoint is not repeatedly creating this folder because of an old or misconfigured script or synchronization task.


text:
Q: Drupal php page that accepts clean URL arguments I am using Drupal 6 and have my own node that is pulling in my custom php page.  The URL is domain.com/blogs. I want to use clean URLs for arguments.  For example, domain.com/blogs/1 will pull in the information from the database regarding the first blog post.
I've tried:
domain.com/blogs/1 and in the php code use arg(0) BUT I never even get to run the code because Drupal comes up with Page Not Found error.
Is there any way to let Drupal know that any arguments after domain.com/blogs is allowed and to load the node for /blogs also sending the args?

A: Aliasing node/1234 to blogs doesn't mean you can control the rest of the menu router item.
For an example, if your unaliased node path is "node/1234" , you "own" the rest of the arguments.
i.e You can access 567 from node/1234/567 from PHP like this:
<?php print arg(2); ?>

If you want to "own" /blogs URL part, you have to define it using hook_menu. As you have already touched php, I think the best way would be making the module.
You can however use Views or Panels modules for that.
<?php
function MYMODULE_menu() {
  $items = array();

  $items['blogs'] = array(
    'title' => 'Main Blogs page',
    'page callback' => 'MYMODULE_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  $items['blogs/%'] = array(
    'page callback' => 'MYMODULE_blog_view',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}
function MYMODULE_blog_view($blog_id){
// $node = node_load($blog_id);
// return print_r($node, TRUE);
}
?>

Now, in MYMODULE_blog_view function, you can get the arguments from arg(1) as well. You can also make it in a single page callback by combining both menu router items but I'd recommend separate router items.
Update( Aug 8 ) :
The reason why I used node_load($blog_id) and other commented junk there is assuming you needed parts from the node (e.g: You want make show a View with the node ID argument, or something similar that needs specific data from the node).
But never allow users to view a node loaded from node_load() because it's like god giving whatever the user asks for.
For nodes, let me explain a little gimmic. Put this in the callback function.
  $node = node_load($blog_id);
  if ($node && $node->type == 'blog'){
    $_GET['q'] = 'node/' . $node->nid;
    return menu_execute_active_handler('node/' . $node->nid, FALSE);
   }
   drupal_not_found(); // important!

This will load the node ID from the blog ID (which is from the URL), check if it's in 'blog' type and sets the menu handler to the relevant node ID path.
Now, when you access blog/123 , you will see content of node/123 if it's a blog node. But it's not a redirection. It will not work as fully aliased URL but is helpful sometimes.
Alternately you can check if theuser has access to the node from node_access().

A: here some links you can read about Defining and sending Views Arguments
drupal.org/1
drupal.org/2


text:
Q: How can I digitally sign System.IdentityModel.Tokens.Jwt.dll using strong name signature in local system? I am using System.IdentityModel.Tokens.Jwt.dll for my project. It needs to be updated to version 6.15.0 and it needs to be compiled from source code. I downloaded the source code from :
https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/releases/tag/v6.15.0
I compiled Wilson.sln using Visual Studio 2019 but the generated libraries are not digitally signed. In the project properties, 'Sign the assembly' option is checked and 35MSSharedLib1024.snk file is added under 'Choose a strong name key file'.
Still, the libraries fail the VerifySigning test.
Am I missing anything?


text:
Q: Is it possible to use app_offline.htm when publishing via ftp? Is it possible to configure Visual Studio 2012 to automatically create (and delete) the app_offline.htm file when using ftp as the publishing method?
I tried to create the file by hand and add it to the solution (so it would be uploaded automatically and I could delete it by hand once the publishing process is done).
But because it exists in my solution, every request is redirected to it and I can't debug anything.
Changing the name to app_offline.htm.deactivated during development and changing it back to app_offline.htm before publishing doesn't seem like a perfect solution.
If VS12 doesn't support this natively, I would be happy to use any available extension.
Edit: I noticed, that the app_offline.htm file is created when activating delete all content before publishing but not when this option isn't selected.
Inserting <EnableMSDeployAppOffline>true</EnableMSDeployAppOffline> to the .pubxml file didn't change anything.

A: From: http://www.asp.net/mvc/tutorials/deployment/visual-studio-web-deployment/deploying-a-code-update
It says:

You can configure Web Deploy to automatically put a default app_offline.htm file on the server when it
  starts deploying and remove it when it finishes.  To do that all you have to do is add the following XML element to your publish profile (.pubxml) file:

<EnableMSDeployAppOffline>true</EnableMSDeployAppOffline>


text:
Q: Retaining the changes made to the backcolor property I am developing a windows application.
I have 3 forms:
I want to change the backcolor of all the 3 forms to the color selected by the user.
I have used the following code I am able to change the backcolor but When I exit the application and restart it I am not able to get the color that user has set. I am getting the default colour only.
Is it possible to retain the colour selected by the user and use it as backcolor when the user restarts the application.
CODE
In Form1
ColorDialog c1 = new ColorDialog();

   public static System.Drawing.Color bkc;
    private void button1_Click(object sender, EventArgs e)
    {

        DialogResult res = c1.ShowDialog();
        if (res == DialogResult.OK)
        {
            bkc = c1.Color;
            this.BackColor = bkc;

            MessageBox.Show(Convert.ToString(bkc));
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form2 obj1 = new Form2();
        obj1.BackColor = bkc;
        obj1.Show();
    }

In Form 2
CODE
    private void button2_Click(object sender, EventArgs e)
    {
        Form3 obj1 = new Form3();
        obj1.Show();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        this.BackColor = Form1.bkc;

    }

In Form3
CODE
    private void button2_Click(object sender, EventArgs e)
    {
        Form1 obj1 = new Form1();
        obj1.Show();
    }

    private void Form3_Load(object sender, EventArgs e)
    {
        //Form1 obj2 = new Form1();
        this.BackColor = Form1.bkc;
    }

In the color dialog box I am selecting a color and pressing Ok button the color is also changed but when I restart the application I dont get the colour which I set using the Color Dialog.I want to retain this setting so that the user can get the desired color without resetting it each time the application is executed.
The above code does not generate any error.
can anybody help me out in performing this task?
Thanks in advance!

A: You will need to save the value somewhere such as the Application.exe.config:
    // Open App.Config of executable
    System.Configuration.Configuration config =
     ConfigurationManager.OpenExeConfiguration
                (ConfigurationUserLevel.None);

    // Add an Application Setting.
    config.AppSettings.Settings.Add("BackgroundColour",
                   bkc + " ");

    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);

    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");

Here is a C# full code example: Using System.Configuration.ConfigurationManager Example

A: The suggestion of using the application configuration file is close, but there are two things wrong with it.
First, all users of the application share the same application configuration file.  If you have multiple users (on a network, say, or different users on the same machine), storing a user's preference in the application configuration file will change that setting for all users.  A second thing wrong with it is that under a default installation on Vista it won't work anyway:  by default, Vista doesn't give the user write access to anything under the Program Files directory, so saving changes to the application configuration file will throw an exception.
The right answer is to use user settings.  These get stored in the application's user settings file, which lives in a (deeply nested, and OS-version-dependent) subdirectory of the user's home directory.  The ConfigurationManager loads these settings at runtime, and lets you update and save them in your code.  There's an entire infrastructure built into Visual Studio to make this (relatively) easy, which is good, because doing it properly involves writing a spooky amount of code against the ConfigurationManager class.  Here's how it works:
If you look under the Properties of your VS project, you'll see an item called Settings.settings.  When you double-click on this, it will show you a grid that lets you add settings to your project.  You give the setting name, choose its the data type and default value, and, crucially, the scope.  The setting can be application scope, in which case its value will be common to all users of the application and be stored in the application configuration file.  Or it can be user scope, in which case each user can have his own value for the setting, and the setting will live in the user settings file.
When you add a setting to this grid, VS generates code to make the setting available to your code.  Basically, it creates a class that exposes these settings to your code as properties of a singleton object.  (You can see this code if you want to get an idea of what this is saving you from having to do yourself; it gets stored in the 'Settings.Designer.cs' file created under 'Settings.settings' in the project view.)  It also, conveniently, regenerates this class every time you change the information in the Settings grid.  Once you create a setting in the settings grid, you can reference it in your code thusly:
ctl.BackColor = Properties.Settings.Default.BackColor;

User settings can be modified by your code:
Properties.Settings.Default.BackColor = newBackColor;

And you can save them to the user settings file like this:
Properties.Settings.Default.Save();

Having these settings being exposed as properties of a class is useful for a lot of reasons.  One of the most important is that since they're properties (and not, say, dictionary entries accessed by a key, which is how most code that people write against the ConfigurationManager class works), there's compile-time checking of the names you're using in code.  You're not ever going to get a NullReferenceException at runtime if you misspell  the name of a setting; you'll get an error when you compile it instead.
There are a few subtleties to using user settings.  One of the less obvious ones is:  what happens when you produce a new release of the software?  The user settings are stored in a directory that's keyed to the version number of the program; if you release a new version, the user settings file for it won't exist.  How do you keep the user from losing all of his settings when he upgrades your program?
This is also built in to that Settings class; all you need to do is this:
if (Properties.Settings.Default.UpgradeSettings)
{
   Properties.Settings.Default.Upgrade();
   Properties.Settings.Default.UpgradeSettings = false;
}

This will copy the user's settings from the previous release into the settings file for the new release.

A: Why dont you create an event that all three forms listen to and get them to change the background colour when listening to the "change colour" event? And you could store the colour in a static variable so that when the form gets loaded, the background colour could be set to that stored in the variable.
In order for the screen to remember the colour settings, why not store the colour selected in a user preferences file? Try the "IsolatedStorage" functionality to save a preferences file.

A: You are doing it wrong way.
How will the application remember the user choice of backcolor?
The app runs in memory & shows chosen backcolor till its terminated.
Read on this & take it forward.
EDIT: Also, it is not right thing to use Form1.BackColor in Form2.
Open Form1, change backcolor, close Form1 & open Form2 to see what happens (you might see that Form1 opens again).


text:
Q: On which step can a goroutine be interrupted I am writing some asynchromous code in go which basically implements in-memory caching. I have a not very fast source which I query every minute (using ticker), and save the result into a cache struct field. This field can be queried from different goroutines asynchronously.
In order to avoid using mutexes when updating values from source I do not write to the same struct field which is being queried by other goroutines but create another variable, fill it and then assign it to the queried field. This works fine since assigning operation is atomic and no race occurs.
The code looks like the following:
// this fires up when cache is created
func (f *FeaturesCache) goStartUpdaterDaemon(ctx context.Context) {
    go func() {
        defer kiterrors.RecoverFunc(ctx, f.logger(ctx))

        ticker := time.NewTicker(updateFeaturesPeriod) // every minute
        defer ticker.Stop()

        for {
            select {
            case <-ticker.C:
                f.refill(ctx)
            case <-ctx.Done():
                return
            }
        }
    }()
}

func (f *FeaturesCache) refill(ctx context.Context) {
    var newSources map[string]FeatureData
    // some querying and processing logic

    // save new data for future queries
    f.features = newSources

}

Now I need to add another view of my data so I can also get it from cache. Basically that means adding one more struct field which will be queriad and filled in the same way the previous one (features) was.
I need these 2 views of my data to be in sync, so it is undesired to have, for example, new data in view 2 and old data in view 1 or the other way round.
So the only thing I need to change about refill is to add a new field, at first I did it this way:
func (f *FeaturesCache) refill(ctx context.Context) {
    var newSources map[string]FeatureData
    var anotherView map[string]DataView2
    // some querying and processing logic

    // save new data for future queries
    f.features = newSources      // line A
    f.anotherView = anotherView  // line B
}

However, for this code I'm wondering whether it satisfies my consistency requirements. I am worried that if the scheduler decides to interrupt the goroutine which runs refill between lines A nd B (check the code above) than I might get inconsistency between data views.
So I researched the problem. Many sources on the Internet say that the scheduler switches goroutines on syscalls and function calls. However, according to this answer https://stackoverflow.com/a/64113553/12702274 since go 1.14 there is an asynchronous preemtion mechanism in go scheduler which switches goroutines based on their running time in addition to previously checked signals. That makes me think that it is actually possible that refill goroutine can be interrupted between lines A and B.
Then I thought about surrounding those 2 assignments with mutex - lock before line A, unlock after line B. However, it seems to me that this doesn't change things much. The goroutine may still be interrupted between lines A and B and the data gets inconsistent. The only thing mutex achieves here is that 2 simultaneous refills do not conflict with each other which is actually impossible, because I run them in the same thread as timer. Thus it is useless here.
So, is there any way I can ensure atomicity for two consecutive assignments?

A: If I understand your concern correctly, you don't want to lock existing cached data while updating it(bec. it takes time to update, you want to be able to allow usage of existing cached data while updating it in another routine right ?).
Also you want to make f.features and f.anotherView updates atomic.
What about to take your data in a map[int]map[string]FeatureData and map[int]map[string]DataView2. Put the data to a new key each time and let the queries from this key(newSearchIndex).
Just tried to explain in code roughly(think below like pseudo code)
type FeaturesCache struct {
    mu             sync.RWMutex
    features       map[int8]map[string]FeatureData
    anotherView    map[int8]map[string]DataView2
    oldSearchIndex int8
    newSearchIndex int8
}

func (f *FeaturesCache) CreateNewIndex() int8 {
    f.mu.Lock()
    defer f.mu.Unlock()
    return (f.newSearchIndex + 1) % 16 // mod 16 could be change per your refill rate
}

func (f *FeaturesCache) SetNewIndex(newIndex int8) {
    f.mu.Lock()
    defer f.mu.Unlock()
    f.oldSearchIndex = f.newSearchIndex
    f.newSearchIndex = newIndex
}

func (f *FeaturesCache) refill(ctx context.Context) {
    var newSources map[string]FeatureData
    var anotherView map[string]DataView2
    // some querying and processing logic

    // save new data for future queries
    newSearchIndex := f.CreateNewIndex()
    f.features[newSearchIndex] = newSources
    f.anotherView[newSearchIndex] = anotherView
    f.SetNewIndex(newSearchIndex) //Let the queries to new cached datas after updating search Index
    f.features[f.oldSearchIndex] = nil
    f.anotherView[f.oldSearchIndex] = nil
}


text:
Q: C++ delete [] - how to check if "all is deleted"? I was wondering, throughout a program I am using a lot of char* pointers to cstrings, and other pointers.
I want to make sure that I have delete all pointers after the program is done, even though Visual Studio and Code Blocks both do it for me (I think..).
Is there a way to check is all memory is cleared? That nothing is still 'using memory'?

A: The obvious answer on Linux would be valgrind, but the VS mention makes me think you're on Windows. Here is a SO thread discussing valgrind alternatives for windows.

A:
I was wondering, throughout a program I am using a lot of char* pointers to cstrings

Why?  I write C++ code every day and I very rarely use a pointer at all.  Really it's only when using third party API's, and even then I can usually work around it to some degree.  Not that pointers are inherently bad, but if you can avoid them, do so as it simplifies your program.

I want to make sure that I have delete all pointers after the program is done

This is a bit of a pointless exercise.  The OS will do it for you when it cleans up your process.

A: Visual Studio is an IDE.  It isn't even there by the time your code is deployed.  It doesn't release memory for you.
For what you want you can look into tools like this:
http://sourceforge.net/apps/mediawiki/cppcheck/index.php?title=Main_Page

A: You might want to use some sort of a smart pointer (see the Boost library, for example).  The idea is that instead of having to manage memory manually (that is call delete explicitly when you don't need the object any more), you enlist the power of RAII to do the work for you.
The problem with manual memory management (and in general resource management) is that it is hard to write a program that properly deallocates all memory -- because you forget, or later when you change your code do not realize there was some other memory that needed to be deallocated.
RAII in C++ takes advantage of the fact that the destructor of a stack-allocated object is called automatically when that object goes out of scope.  If the destructor logic is written properly, the last object that references (manages) the dynamically allocated data will be the one (and only one) that deallocates that memory.  This could be achieved via reference counting, maintaining a list of references, etc.
The RAII paradigm for memory is in a sense similar to the garbage collection of mamged languages, except it is running when needed and dictated by your code, not at certain intervals, largely independent from your code.

A: Unless you're writing driver code, there's absolutely nothing you can do with heap/freestore-allocated memory that would cause it to remain leaked once the program terminates.  Leaked memory is only an issue during the lifetime of a given process; once a particular process has leaked its entire address space, it can't get any more for _that_particular_ process.
And it's not your compiler that does the uiltimate cleanup, it's the OS.  In all modern operating systems that support segregated process address spaces (i.e. in which one process cannot read/write another process's address space, at least not without OS assistance), when a program terminates, the process's entire address space is reclaimed by the OS, whether or not the program has cleanly free()ed or deleted all of its heap/freestore-allocated memory.  You can easily test this:  Write a program that allocates 256 MBytes of space and then either exits or returns normally without freeing/deleting the allocated memory.  Then run your program 16 times (or more).  Shoot, run it 1000 times.  If exiting without releasing that memory made it leak into oblivion until reboot, then you'd very soon run out of available memory.  You'll find this to not be the case.
This same carelessness is not acceptable for certain other types of memory, however:  If your program is holding onto any "handles" (a number that identifies some sort of resource granted to the process by the operating system), in some cases if you exit the program abnormally or uncleanly without releasing the handles, they remain lost until the next reboot.  But unless your program is calling OS functions that give you such handles, that isn't a concern anyway.

A: If this is windows specific you can call this at the start of your program :-
_CrtSetDbgFlag(_crtDbgFlag | _CRTDBG_LEAK_CHECK_DF);

After including
#include <crtdbg.h>

And when your program exits the C++ runtime will output to the debugger a list of all memory blocks that are still allocated so you can see if you forgot to free anything.
Note that this only happens in DEBUG builds, in RELEASE builds the code does nothing (which is probabyl what you want anyway)


text:
Q: FutureBuilder>: snapshot.hasdata always false I'm trying to fill a ListView with account information, which gets fetched from a Sqflite database. Here is how I read the account data from db:
dbhelper.dart
  Future<List<AccountModel>> getAllAccounts() async {
    final dbClient = await db;
    print('getAllAccounts');
    List<Map> res = await dbClient.rawQuery('SELECT * FROM Accounts');
    if (res.isNotEmpty) {
      print('Accounts $res');
      var accounts = [];
      for (var i = 0; i < res.length; i++) {
        var account =AccountModel.fromDb(res[i]);
        print('Account $account');
        accounts.add(account);
      }
      print('Return $accounts');
      return accounts;
    }
    return [];

This is, how I try to contruct the list view, using the FutureBuilder-Widget:
account_list_widget.dart
class AccountList extends StatefulWidget {
  State<StatefulWidget> createState() {
    return AccountListState();
  }
}

class AccountListState extends State<AccountList> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        FutureBuilder<List<AccountModel>>(
          future: DbProvider().getAllAccounts(),
          builder: (BuildContext context, AsyncSnapshot<List<AccountModel>> snapshot) {
            if (snapshot.hasData) {
              return  Stack(
                children: <Widget>[
                  ListView.builder(
                    itemCount: snapshot.data.length + 1,
                    itemBuilder: (BuildContext context, int index) {
                      if (index == 0) {
                        return ListSectionHeader('Konten');
                      } else {
                        // Korrigieren des Index, da ja die 0 schon "verbraucht" wurde,
                        // auf die Daten aber weiterhhin mit Start-Index 0 zugegriffen wird.
                        index--;
                        AccountModel account = snapshot.data[index];
                        return Dismissible(
                          key: UniqueKey(),
                          background: Container(color: Colors.red),
                          onDismissed: (direction) {
                            DbProvider().removeAccount(account.uuid);
                          },
                          child: ListTile(
                            title: Text(account.accountName),
                            leading: Icon(Icons.crop_square),
                            trailing: Icon(Icons.keyboard_arrow_right),
                          ),
                        );
                      }
                    },
                  ),
                  addAccountTile()
                ],
              );
            } else {
              return ListView.builder(
                itemCount: 2,
                itemBuilder: (BuildContext context, int index) {
                  if (index == 0) {
                    return ListSectionHeader('Konten2');
                  } else {
                    return addAccountTile();
                  }
                },
              );
            }
          },
        ),
      ],
    );
  }

  Widget addAccountTile() {
    return ListTile(
      title: Text('Neues Konto hinzufügen'),
      leading: Icon(
        Icons.add_circle,
        color: Colors.blue,
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        Navigator.pushNamed(context, '/newaccount');
      }
    );
  }
}

The custom data model is defined like this:
account_model.dart
class AccountModel {
  final String uuid;
  final String accountName;
  final String host;
  final String userName;
  final String password;
  final String lastConnected;
  final bool active;
  final bool useHeadset;

  AccountModel(this.uuid, this.accountName, this.host, this.userName,
    this.password, this.lastConnected, this.active, this.useHeadset);

  AccountModel.fromJson(Map<String, dynamic> parsedJson)
    : uuid = parsedJson['uuid'],
      accountName = parsedJson['accountName'],
      host = parsedJson['host'],
      userName = parsedJson['userName'],
      password = parsedJson['password'],
      lastConnected = parsedJson['lastConnected'],
      active = parsedJson['active'],
      useHeadset = parsedJson['useHeadset'];

  AccountModel.fromDb(Map<String, dynamic> parsedJson)
    : uuid = parsedJson['uuid'],
    accountName = parsedJson['accountName'],
    host = parsedJson['host'],
    userName = parsedJson['userName'],
    password = parsedJson['password'],
    lastConnected = parsedJson['lastConnected'],
    active = parsedJson['active'] == 1,
    useHeadset = parsedJson['useHeadset'] == 1;

  Map<String, dynamic> toMap() {
    return <String, dynamic> {
      'uuid': uuid,
      'accountName': accountName,
      'host': host,
      'userName': userName,
      'password': password,
      'lastConnected': lastConnected,
      'active': active ? 1 : 0,
      'useHeadset': useHeadset ? 1 : 0
    };
  }
}

My problem is, that although the database stores valid data and also the method getAllAccounts()seems to return valid data, the statement snapshot.hasdatainside the FutureBuilder widget alsways is false.
What goes wrong here?
From the console:
D/Sqflite ( 9179): [Thread[main,5,main]] opened 6 /data/user/0/com.example.dashboard/app_flutter/test.db total open count (6)
D/Sqflite ( 9179): [Thread[Sqflite,5,main]] BEGIN EXCLUSIVE
D/Sqflite ( 9179): [Thread[Sqflite,5,main]] PRAGMA user_version;
D/Sqflite ( 9179): [Thread[Sqflite,5,main]] PRAGMA user_version = 1;
D/Sqflite ( 9179): [Thread[Sqflite,5,main]] COMMIT
I/flutter ( 9179): getAllAccounts
D/Sqflite ( 9179): [Thread[Sqflite,5,main]] SELECT * FROM Accounts
I/flutter ( 9179): Accounts [{uuid: 436f2c10-3260-11e9-fe03-65fdfe3a7bbd, accountName: 12345, host: 12345, userName: 12345, password: 12345, lastConnected: 0, active: 0, useHeadset: 0}]
I/flutter ( 9179): Account Instance of 'AccountModel'
I/flutter ( 9179): Return [Instance of 'AccountModel']

(The last line of this snippet from the console corresponds with the print statement at the end of the "getAllAccounts" method.)

A: I solved the problem:
In the database provider in the method "getAllAccounts() I had to explicitly declare the type of the accounts object like so:
List<AccountModel> accounts = [];


text:
Q: SSE optimized emulation of 64-bit integers For a hobby project I'm working on, I need to emulate certain 64-bit integer operations on a x86 CPU, and it needs to be fast.
Currently, I'm doing this via MMX instructions, but that's really a pain to work with, because I have to flush the fp register state all the time (and because most MMX instructions deal with signed integers, and I need unsigned behavior).
So I'm wondering if the SSE/optimization gurus here on SO can come up with a better implementation using SSE.
The operations I need are the following (quite specific) ones:
uint64_t X, Y;

X = 0;
X = 1;
X << 1;
X != Y;
X + 1;
X & 0x1 // get lsb
X | 0x1 // set lsb
X > Y;

Specifically, I don't need general-purpose addition or shifting, for example, just add one and left-shift one. Really, just the exact operations shown here.
Except, of course, on x86, uint64_t is emulated by using two 32-bit scalars, which is slow (and, in my case, simply doesn't work, because I need loads/stores to be atomic, which they won't be when loading/storing two separate registers).
Hence, I need a SIMD solution.
Some of these operations are trivial, supported by SSE2 already. Others (!= and <) require a bit more work.
Suggestions?
SSE and SSE2 are fine. It'd take some persuasion to permit SSE3, and SSE4 is probably out of the question (A CPU which supports SSE4 is likely to run 64-bit anyway, and so I don't need these workarounds)

A: SSE2 has direct support for some 64-bit integer operations:
Set both elements to 0:
__m128i z = _mm_setzero_si128();

Set both elements to 1:
__m128i z = _mm_set1_epi64x(1);      // also works for variables.
__m128i z = _mm_set_epi64x(hi, lo);  // elements can be different

__m128i z = _mm_set_epi32(0,1,0,1);  // if any compilers refuse int64_t in 32-bit mode.  (None of the major ones do.)

Set/load the low 64 bits, zero-extending to __m128i
// supported even in 32-bit mode, and listed as an intrinsic for MOVQ
// so it should be atomic on aligned integers.
_mm_loadl_epi64((const __m128i*)p);     // movq or movsd 64-bit load

_mm_cvtsi64x_si128(a);      // only ICC, others refuse in 32-bit mode
_mm_loadl_epi64((const __m128i*)&a);  // portable for a value instead of pointer

Things based on _mm_set_epi32 can get compiled into a mess by some compilers, so _mm_loadl_epi64 appears to be the best bet across MSVC and ICC as well as gcc/clang, and should actually be safe for your requirement of atomic 64-bit loads in 32-bit mode.  See it on the Godbolt compiler explorer
Vertically add/subtract each 64-bit integer:
__m128i z = _mm_add_epi64(x,y)
__m128i z = _mm_sub_epi64(x,y)

http://software.intel.com/sites/products/documentation/studio/composer/en-us/2011/compiler_c/intref_cls/common/intref_sse2_integer_arithmetic.htm#intref_sse2_integer_arithmetic
Left Shift:
__m128i z = _mm_slli_epi64(x,i)   // i must be an immediate

http://software.intel.com/sites/products/documentation/studio/composer/en-us/2011/compiler_c/intref_cls/common/intref_sse2_int_shift.htm
Bitwise operators:
__m128i z = _mm_and_si128(x,y)
__m128i z = _mm_or_si128(x,y)

http://software.intel.com/sites/products/documentation/studio/composer/en-us/2011/compiler_c/intref_cls/common/intref_sse2_integer_logical.htm
SSE doesn't have increments, so you'll have to use a constant with 1.

Comparisons are harder since there's no 64-bit support until SSE4.1 pcmpeqq and SSE4.2 pcmpgtq
Here's the one for equality:
__m128i t = _mm_cmpeq_epi32(a,b);
__m128i z = _mm_and_si128(t,_mm_shuffle_epi32(t,177));

This will set the each 64-bit element to 0xffffffffffff (aka -1) if they are equal. If you want it as a 0 or 1 in an int, you can pull it out using _mm_cvtsi32_si128() and add 1.  (But sometimes you can do total -= cmp_result; instead of converting and adding.)
And Less-Than: (not fully tested)
a = _mm_xor_si128(a,_mm_set1_epi32(0x80000000));
b = _mm_xor_si128(b,_mm_set1_epi32(0x80000000));
__m128i t = _mm_cmplt_epi32(a,b);
__m128i u = _mm_cmpgt_epi32(a,b);
__m128i z = _mm_or_si128(t,_mm_shuffle_epi32(t,177));
z = _mm_andnot_si128(_mm_shuffle_epi32(u,245),z);

This will set the each 64-bit element to 0xffffffffffff if the corresponding element in a is less than b.

Here's are versions of "equals" and "less-than" that return a bool. They return the result of the comparison for the bottom 64-bit integer.
inline bool equals(__m128i a,__m128i b){
    __m128i t = _mm_cmpeq_epi32(a,b);
    __m128i z = _mm_and_si128(t,_mm_shuffle_epi32(t,177));
    return _mm_cvtsi128_si32(z) & 1;
}
inline bool lessthan(__m128i a,__m128i b){
    a = _mm_xor_si128(a,_mm_set1_epi32(0x80000000));
    b = _mm_xor_si128(b,_mm_set1_epi32(0x80000000));
    __m128i t = _mm_cmplt_epi32(a,b);
    __m128i u = _mm_cmpgt_epi32(a,b);
    __m128i z = _mm_or_si128(t,_mm_shuffle_epi32(t,177));
    z = _mm_andnot_si128(_mm_shuffle_epi32(u,245),z);
    return _mm_cvtsi128_si32(z) & 1;
}


text:
Q: DataSet Add Column gives ArgumentException using the following code and the following xml, I get an ArgumentException when adding a new Column to a Table in a DataSet.
Though, I have no Idea why, because the specified column does not exist anywhere in the xml before.
class Program
{
    static void Main(string[] args)
    {

        DataSet set = new DataSet();
        set.ReadXml("../../test.xml");

        DataColumn column = new DataColumn("mobile", typeof(string));
        set.Tables["Contact"].Columns.Add(column); //exception is thrown here

        Console.ReadKey();

    }

}

using the following test.xml:
<ROOT>
    <CONTACT TYPE="PHONE" SIGN="HOME">123</CONTACT>
    <CONTACT TYPE="PHONE" SIGN="BUSINESS">456</CONTACT>
</ROOT>

Exception I get is:
An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll

Additional Information: Cannot add a nested relation or
an element column to a table containing a SimpleContent column

I don't really understand why I get the exception, and what it means. Can someone enlighten me please, thank you.


text:
Q: CheckColumn in StringGrid Как программно заполнить(выставить чеки) поле CheckColumn из Базы данных? Использую SQLite и поле Status INTEGER. В примере от Embarcadero делается с Visual Bind. Никаких SetCheck или isCheck не нашел в доступных свойствах.

A: Все оказалось намного проще.
Grid.Cells[c,i] := 'True';