text:
Q: MVC prevent updating certain fields I have an ASP.NET MVC 4 application using repository pattern and Entity Framework 6.
When I visit User/Details/5 page and update a users details, I get the following error -

The property 'Password' cannot be set to a null value.

In my view, I have all these fields apart from Password, as I have no need for it in this view. How can I (essentially) tell MVC to not update the password in this view?
This is my UserModel
public class UserModel : IUserModel
{
    public int Id{ get; set; }

    [DisplayName("Employee Number")]
    public int EmployeeNumber { get; set; }

    [DisplayName("First Name")]
    public string Firstname { get; set; }

    [DisplayName("Last Name")]
    public string Surname { get; set; }

    public string Email { get; set; }

    [DisplayName("User Type")]
    public UserType UserType { get; set; }

    [DisplayName("Login")]
    public UserStatus UserStatus { get; set; }

    [DisplayName("Login Status")]
    public bool LoginStatus { get; set; }

    public string Password { get; set; }

    [ReadOnly(true)]
    public DateTime DateCreated { get; set; }

    [ReadOnly(true)]
    public int CreatedBy { get; set; }

    [ReadOnly(true)]
    public DateTime LastUpdated { get; set; }

    [ReadOnly(true)]
    public int LastUpdateBy { get; set; }

    [DisplayName("Full Name")]
    public string SurnameFirstName
    {
        get { return Surname + ", " + Firstname; }
    }

    [NotMapped]
    public State State { get; set; }
}

and this is my controller -
[HttpPost]
    public ActionResult Details(UserModel model)
    {
        if (ModelState.IsValid)
        {

            _userService.Update(model);

            return RedirectToAction("Index");
        }

        return View(model);
    }

And my _userService.Update method
public void Update(UserModel entity)
    {
        User u = _userRepository.FindById(entity.Id);

        AutoMapper.Mapper.CreateMap<UserModel, User>();

        _userRepository.Update(AutoMapper.Mapper.Map(entity, u));
    }

A: Your key sentence is this:
In my view, I have all these fields apart from Password, as I have no need for it in this view.
You should define ViewModels instead of playing with the model (I know there is a lot of examples which do it like you, but the best practice is using viewmodels).
A ViewModel is basically a class which models your views so it only contains the properties you need. After you get this you can update your model as @krillgar said in a comment: pull the user from the database and update only the fields you want to update.


text:
Q: Need help converting CASE statement in LINQ I am trying to convert a few CASE statements in a SQL query to LINQ.
Here is part of the SQL statement with the CASE statements:
         SELECT
         dt.DisplayText,
      CASE WHEN fsh.FieldName = 'SiteId' THEN 'SiteName' ELSE fsh.FieldName END as FieldName,
         fsh.FieldName,
         fsh.[Action],
      CASE WHEN fsh.FieldName = 'SiteId' THEN so.SiteName ELSE fsh.OldValue END as OldValue,
      CASE WHEN fsh.FieldName = 'SiteId' THEN sn.SiteName ELSE fsh.NewValue END as NewValue,
         fsh.OldValue,
         fsh.NewValue,
         u.UserName,
         fsh.ModifiedDate,
         fs.ProgramGroupYear,
         fs.CustomerId

Part of LINQ with the CASE statements. I put the CASE statements in here as placeholders. Obviously those statements in LINQ won't work.
  public async Task<IEnumerable<HistoryRecord>> GetHistoryRecords(int documentTypeId, int
  programGroupYear, int customerId, DateTime? from, DateTime? to, CancellationToken
  cancellationToken)
{
    Guard.Zero(documentTypeId, nameof(documentTypeId));

    var query = _context.FileStoreHistories
    .Join(_context.FileStores, fsh => fsh.FileStoreId, fs => fs.FileStoreId,
                        (fsh, fs) => new
                        {
                            fs.CustomerId,
                            fs.ProgramGroupYear,
                            fs.DisplayText,
                            **CASE WHEN fsh.FieldName = 'SiteId'
                  THEN 'SiteName' ELSE
                    fsh.FieldName END as FieldName,**
                            fsh.FieldName,
                            fsh.Action,
                            *****CASE WHEN fsh.FieldName = 'SiteId'
                  THEN so.SiteName ELSE
                    fsh.OldValue END as OldValue,
                            CASE WHEN fsh.FieldName = 'SiteId' THEN
                    sn.SiteName ELSE
                    fsh.NewValue END as NewValue,*****
                            fsh.OldValue,
                            fsh.NewValue,
                            fsh.ModifiedBy,
                            fsh.ModifiedDate,
                            fs.DocumentTypeId
                        }
                   ....

If this is not enough code I can provide more. I appreciate any assistance I can get. Thank you

redpajama_set_name: RedPajamaStackExchange


text:
Q: Avoid chapter pagebreak in twocolumn document It took me a while to locate the error, but here's a MWE.
I am using my own class, provided below:
 \documentclass[fleqn,10pt,twocolumn]{MWEclass}
 \usepackage{lipsum} % Required to insert dummy text
 \definecolor{pt_Blau_04}{RGB}{20,20,20}

   \begin{document}
    \makeatletter
         \renewcommand\chapter{\global\@topnum\z@
                 \@afterindentfalse
                 \secdef\@chapter\@schapter}
    \def\@topnewpage[#1]{#1}
 \makeatother

 \input{MWEchapter}
 \chapter{Something}
 \lipsum[7-10]
 %\input{MWEchapter2}
 %\input{MWEchapter3}
  \end{document}

and the class:
 \NeedsTeXFormat{LaTeX2e}
 \ProvidesClass{MWEclass}[17/06/2013, v1.0]

 \AtEndOfClass{\RequirePackage{microtype}}
 \DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}
 \ProcessOptions*
 \LoadClass{report}
 \RequirePackage[usenames,dvipsnames,svgnames,table]{xcolor}

 \RequirePackage[explicit]{titlesec}
 \newlength\mylena
 \newlength\mylenb
 \setlength\mylena{1.3cm}
 \setlength\mylenb{\dimexpr\columnwidth-\mylena\relax}

 \newcommand\PlaceNumber[1]{%
   \makebox[\mylena][l]{#1}}

 \titleformat{\chapter}
  {\color{pt_Blau_04}\Large\sffamily\bfseries}
  {}
  {0em}
  {\PlaceNumber{\thechapter}\parbox[t]{\mylenb}{\raggedright#1}}

 \titlespacing*{\chapter}{0pc}{3ex \@plus4pt \@minus3pt}{5pt}

If i want to avoid the pagebreak for every new chapter (The chapters MWEchapter are just lipsum text) it works up to including TWO chapters, if I want to include more, theres an error message about horizontal mode and the titlesec package..

A: The error stems from the fact that your redefinition of \chapter does not make sure that a paragraph is ended when the chapter title is about to be typeset. So something like
Text\chapter{Foo}

triggers the error.
Since you are using titlesec anyway, I would recommend to remove the hacky redefinition of \chapter, and use the interface of titlesec to make chapters not start a new page. This can be achieved by setting the class of \chapters from top to straight. MWEclass.cls then looks like this (see the last line):
\NeedsTeXFormat{LaTeX2e}
 \ProvidesClass{MWEclass}[17/06/2013, v1.0]

 \AtEndOfClass{\RequirePackage{microtype}}
 \DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}
 \ProcessOptions*
 \LoadClass{report}
 \RequirePackage[usenames,dvipsnames,svgnames,table]{xcolor}

 \RequirePackage[explicit]{titlesec}
 \newlength\mylena
 \newlength\mylenb
 \setlength\mylena{1.3cm}
 \setlength\mylenb{\dimexpr\columnwidth-\mylena\relax}

 \newcommand\PlaceNumber[1]{%
   \makebox[\mylena][l]{#1}}

 \titleformat{\chapter}
  {\color{pt_Blau_04}\Large\sffamily\bfseries}
  {}
  {0em}
  {\PlaceNumber{\thechapter}\parbox[t]{\mylenb}{\raggedright#1}}

 \titlespacing*{\chapter}{0pc}{3ex \@plus4pt \@minus3pt}{5pt}

\titleclass{\chapter}{straight}%% added

and the redefinition of \chapter in your main file can be deleted.

A: This works for me, only the cleardoublepage needs to be reset, if you hold it in memory, it can be restored.
\documentclass{book}

\begin{document}
\chapter{One}
Bla
\chapter{Two}
Bla Bla

%Reset
\makeatletter
    \let\cleardoublepage@old\cleardoublepage
    \let\cleardoublepage\relax
\makeatother

\chapter{Three}
Bla Bla Bla

%Restore
\makeatletter
    \let\cleardoublepage\cleardoublepage@old
\makeatother

\chapter{Four}
Bla Bla Bla

\end{document}


text:
Q: export excel to sql using visual basic Was hoping if someone could help script this for me
I am trying to create a excel file with a macro attached to a button that will export the data to sql.
My sql table is as follows
    RecordedPeriod (datetime, not null)

    EventDate (varchar(8), not null)

    ID (int, not null)

    DeptCode (varchar(2), not null)

    OpCode (varchar(2), not null)

    StartTime (time(0), not null)

    FinishTime (time(0), not null)

    Units (int, not null)

While creating the macro in Visual Basic for Applications my code is as follows
Sub Button1_Click()

Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sRecordedPeriod, sEventDate, sID, sDeptCode, sOpCode, sStartTime, sFinishTime, sUnits  As String

With Sheets("Sheet1")

    'Open a connection to SQL Server
    conn.Open "Provider=SQLOLEDB;Data Source=db1\db1;Initial Catalog=ProdTrack;Integrated Security=SSPI;"

    'Skip the header row
    iRowNo = 2

    'Loop until empty cell in FirstName
    Do Until .Cells(iRowNo, 1) = ""
        sRecordedPeriod = .Cells(iRowNo, 1)
        sEventDate = .Cells(iRowNo, 2)
        sID = .Cells(iRowNo, 3)
        sDeptCode = .Cells(iRowNo, 4)
        sOpCode = .Cells(iRowNo, 5)
        sStartTime = .Cells(iRowNo, 6)
        sFinishTime = .Cells(iRowNo, 7)
        sUnits = .Cells(iRowNo, 8)

        'Generate and execute sql statement to import the excel rows to SQL Server table
        conn.Execute "insert into dbo.TimeLog (RecordedPeriod, EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sRecordedPeriod & "', '" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', '" & sStartTime & "', '" & sFinishTime & "', '" & sUnits & "')"

        iRowNo = iRowNo + 1
    Loop

    MsgBox "Data Successfully Exported."

    conn.Close
    Set conn = Nothing

I receive this error message when exporting.
    Run-time error '2147217913 (80040e07)':

    Conversion failed when converting date and/or time from character string.

Does anyone have any suggestions?
This is how my excel table looks. Im trying to change the time format still getting an error. My EventDate is a Varchar in SQL so there should be no issues there.
    RecordedPeriod  EventDate   ID  DeptCode    OpCode  StartTime   FinishTime  Units
    NULL           6/15/2017 45318   DS         DS      8:00:00     9:00:00     500
    NULL           6/15/2017 45318   DS         DS      9:00:00     9:15:00     500
    NULL           6/15/2017 45318   DS         DS      9:15:00     9:20:00     500

The data in my excel file is deleted after we export to sql, and we will drop new data in daily.

A: The date that you provide in your query is not in the correct format.  Here is a list of accepted formats, you're going to need to make sure the format you use complies with this:
https://learn.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql
I would recommend using Debug.Print "insert int..." and checking the format in the immediates window (in the VBExplorer), then running the query

A: Consider in your design to export to XML and create rules with XSLT (or DTD, etc.) for SQL to import. XML can be a powerful way to communicate data between formats.
add: https://learn.microsoft.com/en-us/sql/relational-databases/import-export/examples-of-bulk-import-and-export-of-xml-documents-sql-server
This solution is more scaleable as your database and spread sheet changes. You'll instead of creating more macros, will only have to change the XML rules.


text:
Q: What's the difference between '>' and '>>'? What's the difference between
cat int.txt > out.txt

and
cat int.txt >> out.txt

Does the >> do anything differently from >?

A: The > will overwrite out.txt if it already exists. The >> will simply append to out.txt.

A: > overwrites to the file. >> appends to the file.

A: >>  will append to out.txt if it exists
>  will overwrite out.txt if it exists

A: > is to re-direct standard output to the file and overwrite it if the file exists.
>> is to append standard output to the file if it exists
Some more options:
http://www.mathinfo.u-picardie.fr/asch/f/MeCS/courseware/users/help/general/unix/redirection.html

A: cat int.txt > out.txt

This has written the contents of int.txt to out.txt and overwritten anything that was in that file (out.txt) if it already existed.
cat int.txt >> out.txt

This has appended int.txt to the end of out.txt if it existed or simply created it if it didn't, and copied int.txt into it.


text:
Q: Problems in implementing Horner's method in Python So I have written down the codes for evaluating polynomial using three different methods. Horner's method should be the fastest, while the naive method should be the slowest, right? But how come the time for computing it is not what I expect? And the time for calculation sometimes turns out to be exactly the same for itera and naive method. What's wrong with it?
import numpy.random as npr
import time

def Horner(c,x):
    p=0
    for i in c[-1::-1]:
        p = p*x+i
    return p

def naive(c,x):
    n = len(c)
    p = 0
    for i in range(len(c)):
        p += c[i]*x**i
    return p

def itera(c,x):
    p = 0
    xi = 1
    for i in range(len(c)):
        p += c[i]*xi
        xi *= x
    return p

c=npr.uniform(size=(500,1))
x=-1.34

start_time=time.time()
print Horner(c,x)
print time.time()-start_time

start_time=time.time()
print itera(c,x)
print time.time()-start_time

start_time=time.time()
print naive(c,x)
print time.time()-start_time

here are some of the results:
[  2.58646959e+69]
0.00699996948242
[  2.58646959e+69]
0.00600004196167
[  2.58646959e+69]
0.00600004196167

[ -3.30717922e+69]
0.00899982452393
[ -3.30717922e+69]
0.00600004196167
[ -3.30717922e+69]
0.00600004196167

[ -2.83469309e+69]
0.00999999046326
[ -2.83469309e+69]
0.00999999046326
[ -2.83469309e+69]
0.0120000839233

A: You cannot obtain accurate result by measuring things like that:
start_time=time.time()
print Horner(c,x)
print time.time()-start_time

Presumably most of the time is spend in the IO function involved by the print function. In addition, to have something significant, you should perform the measure on a large number of iteration in order to smooth errors. In the general case, you might want to perform your test on various input data as well -- as depending your algorithm, some case might coincidentally be solved more efficiently than others.
You should definitively take a look at the timeit module. Something like that, maybe:
import timeit
print 'Horner',timeit.timeit(stmt='Horner(c,x)',
                  setup='from __main__ import Horner, c, x',
                  number = 10000)
#                          ^^^^^
#                probably not enough. Increase that once you will
#                be confident

print 'naive',timeit.timeit(stmt='naive(c,x)',
                  setup='from __main__ import naive, c, x',
                  number = 10000)
print 'itera',timeit.timeit(stmt='itera(c,x)',
                  setup='from __main__ import itera, c, x',
                  number = 10000)

Producing this on my system:
Horner 23.3317809105
naive 28.305519104
itera 24.385917902

But still with variable results from on run to the other:
Horner 21.1151690483
naive 23.4374330044
itera 21.305426836

As I said before, to obtain more meaningful results, you should definitively increase the number of tests, and run that on several test case in order to smooth results.

A: If you are doing a lot of benchmarking, scientific computing, numpy  related work and many more things using ipython will be an extremely useful tool.
To benchmark you can time the code with timeit using ipython magic where you will get more consistent results each run, it is simply a matter of using timeit then the function or code to time :
In [28]: timeit Horner(c,x)
1000 loops, best of 3: 670 µs per loop

In [29]: timeit naive(c,x)
1000 loops, best of 3: 983 µs per loop

In [30]: timeit itera(c,x)
1000 loops, best of 3: 804 µs per loop

To time code spanning more than one line you simply use %%timeit:
In [35]: %%timeit
   ....: for i in range(100):
   ....:     i ** i
   ....:
10000 loops, best of 3: 110 µs per loop

ipython can compile cython code, f2py code and do numerous other very helpful tasks using different plugins and ipython magic commands.
builtin magic commands
Using cython and some very basic improvements we can improve the efficiency of Horner by about 25 percent:
In [166]: %%cython
import numpy as np
cimport numpy as np
cimport cython
ctypedef np.float_t DTYPE_t
def C_Horner(c, DTYPE_t x):
    cdef DTYPE_t p
    for i in reversed(c):
        p = p * x + i
    return p

In [28]: c=npr.uniform(size=(2000,1))

In [29]: timeit Horner(c,-1.34)
100 loops, best of 3: 3.93 ms per loop
In [30]: timeit C_Horner(c,-1.34)
100 loops, best of 3: 2.21 ms per loop

In [31]: timeit itera(c,x)
100 loops, best of 3: 4.10 ms per loop
In [32]: timeit naive(c,x)
100 loops, best of 3: 4.95 ms per loop

Using the list in @Paul drapers answer our cythonised version runs  twice as fast as the original function and much faster then ietra and naive:
In [214]: import random

In [215]: c = [random.random() for _ in range(500)]

In [44]: timeit C_Horner(c, -1.34)
10000 loops, best of 3: 18.9 µs per loop
In [45]: timeit Horner(c, -1.34)
10000 loops, best of 3: 44.6 µs per loop
In [46]: timeit naive(c, -1.34)
10000 loops, best of 3: 167 µs per loop
In [47]: timeit itera(c,-1.34)
10000 loops, best of 3: 75.8 µs per loop

A: Your profiling can be much improved. Plus, we can make your code run 200-500x faster.

(1) Rinse and repeat
You can't run just one iteration of a performance test, for two reasons.

*

*Your time resolution might not be good enough. This is why you sometimes got the same time for two implementations: the time for one run was near the resolution of your timing mechanism, so you recorded only one "tick".

*There are all sorts of factors that affect performance. Your best bet for a meaningful comparison will be a lot of iterations.

You don't need gazillions of runs (though, of course, that doesn't hurt), but you estimate and adjust the number of iterations until the variance is within a level acceptable to your purpose.
timeit is a nice little module for profiling Python code.
I added this to bottom of your script.
import timeit

n = 1000

print 'Horner', timeit.timeit(
    number = n,
    setup='from __main__ import Horner, c, x',
    stmt='Horner(c,x)'
)
print 'naive', timeit.timeit(
    number = n,
    setup='from __main__ import naive, c, x',
    stmt='naive(c,x)',
)
print 'itera', timeit.timeit(
    number = n,
    setup='from __main__ import itera, c, x',
    stmt='itera(c,x)',
)

Which produces
Horner 1.8656351566314697
naive 2.2408010959625244
itera 1.9751169681549072

Horner is the fastest, but it's not exactly blowing the doors off the other two.

(2) Look at what is happening...very carefully
Python has operator overloading, so it's easy to miss seeing this.
npr.uniform(size=(500,1)) is giving you a 500 x 1 numpy structure of random numbers.
So what?
Well, c[i] isn't a number. It's a numpy array with one element. Numpy overloads the operators so you can do things like multiply an array by a scalar.
That's fine, but using an array for every element is a lot of overhead, so it's harder to see the difference between the algorithms.
Instead, let's try a simple Python list:
import random
c = [random.random() for _ in range(500)]

And now,
Horner 0.034661054611206055
naive 0.12771987915039062
itera 0.07331395149230957

Whoa! All the time times just got faster (by 10-60x). Proportionally, the Horner implementation got even faster than the other two. We removed the overhead on all three, and can now see the "bare bones" difference.
Horner is 4x faster than naive and 2x faster than itera.

(3) Alternate runtimes
You're using Python 2. I assume 2.7.
Let's see how Python 3.4 fares. (Syntax adjustment: you'll need to put parenthesis around the argument list to print.)
Horner 0.03298933599944576
naive 0.13706714100044337
itera 0.06771054599812487

About the same.
Let's try PyPy, a JIT implementation of Python. (The "normal" Python implementation is called CPython.)
Horner 0.006507158279418945
naive 0.07541298866271973
itera 0.005059003829956055

Nice! Each implementation is now running 2-5x faster. Horner is now 10x the speed of naive, but slightly slower than itera.
JIT runtimes are more difficult to profile than interpreters. Let's increase the number of iterations to 50000, and try it  just to make sure.
Horner 0.12749004364013672
naive 3.2823100090026855
itera 0.06546688079833984

(Note that we have 50x the iterations, but only 20x the time...the JIT hadn't taken full effect for many of the first 1000 runs.) Same conclusions, but the differences are even more pronounced.
Granted, the idea of JIT is to profile, analyze, and rewrite the program at runtime, so if your goal is to compare algorithms, this is going to add a lot of non-obvious implementation detail.
Nonetheless, comparing runtimes can be useful in giving a broader perspective.

There are a few more things. For example, your naive implementation computes a variable it never uses. You use range instead of xrange. You could try iterating backwards with an index rather than a reverse slice. Etc.
None of these changed the results much for me, but they were worth considering.


text:
Q: Python regex AttributeError: 'NoneType' object has no attribute 'group' I use Regex to retrieve certain content from a search box on a webpage with selenium.webDriver.
searchbox = driver.find_element_by_class_name("searchbox")
searchbox_result = re.match(r"^.*(?=(\())", searchbox).group()

The code works as long as the search box returns results that match the Regex.  But if the search box replies with the string "No results" I get error:

AttributeError: 'NoneType' object has no attribute 'group'

How can I make the script handle the "No results" situation?

A: I managed to figure out this solution: omit group() for the situation where the searchbox reply is "No results" and thus doesn't match the Regex.
try:
    searchbox_result = re.match("^.*(?=(\())", searchbox).group()
except AttributeError:
    searchbox_result = re.match("^.*(?=(\())", searchbox)

A: When you do
re.match("^.*(?=(\())", search_result.text)

then if no match was found, None will be returned:

Return None if the string does not match the pattern; note that this is different from a zero-length match.

You should check that you got a result before you apply group on it:
res = re.match("^.*(?=(\())", search_result.text)
if res:
    # ...

A: This error occurs due to your regular expression doesn't match your targeted value. Make sure whether you use the right form of a regular expression or use a try-catch block to prevent that error.
try:
    pattern = r"^.*(?=(\())"
    searchbox_result = re.match(pattern, searchbox).group()
except AttributeError:
    print("can't make a group")

Thank you


text:
Q: c3chart export issues - styles are not downloaded Is there a way to export svg generated by c3 chart with the styles. I am able to export the svg to png image but the styles are missing. I am using c3 angular to generate charts.

A: When you export chart , only svg part is exported with its inline styles . To export svg with its css you need to add the styles in the svg tag itself .
for ex :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" preserveAspectRatio="xMidYMid meet">
    <defs>
        <style type="text/css"><![CDATA[
            circle {
                stroke: #909;
                stroke-width: 10;
                fill: #f6f;
            }
        ]]></style>
    </defs>
    <circle cx="100" cy="100" r="80" />
</svg>

Add your styles to svg like this then export it as svg or png .

A: After searching for a while, I found a solution to export svg with styles by gonsakon. It can be found in the below link
https://github.com/gonsakon/SVGtoPNG


text:
Q: How to calculated the absolute value via of bit operations In the Hacker's delight, there is an example of calculating the absolute value of x as (х XOR (x >> 31)) - (x >> 31).
I know that x >> 31 returns the sign of x. I understand Boolean algebra, but how does (х XOR (x >> 31)) - (x >> 31) work?

A: It follows from the definition of two's complement, -x = ~x + 1
If x is negative: y = x>>31 = -1.  Rewrite the ~x inversion as x ^ -1, and the +1 to subtracting -1, to get:
-x = (x ^ -1) - -1 = abs(x)

If x is non-negative: y = 0, and (x ^ 0) - 0) is obviously just x.

A: (x XOR y) - y is just doing 2's complement on a negative number. For positive number, y will be 0 so x remains unchanged.
Example. x = -2.
-2 is represented as 0xFFFFFFFE
x>>31 will make y = 0xFFFFFFFF (ie. -1)
x XOR y will flip all the bits in x giving result as 0x00000001
(x XOR y) - y = 0x00000001 - (-1) = 0x00000002.


text:
Q: Will SQL Server Express work with a database made in regular SQL Server? I was wondering if we could backup the database that we currently host on regular SQL Server, and put it onto our clients computer when we setup SQL Server Express for them.
Is this possible?
Thanks,
Matt

A: Yes, it's possible to restore a database backup from the Standard edition to the Express edition. It's not possible to restore a SQL Server 2008 to a SQL Server 2005 version, though.
However, there a some minor differences between versions. I've noticed an issue in SQL Server Express 2005 when calling .NET SQL CLR functions across databases, so your mileage may vary. I haven't been able to find a good overview of the exact differences between the various SQL Server editions.
It's always best to keep the development platform as close as possible to the release platform. I can only recommend that you use the Express edition of SQL Server for development as well; and re-test your application.


text:
Q: PyQt: How to get the row values from a select query I am creating an application in PyQt where I want to create a list, and the list items are the result of an SQL query. I am trying to do this from the following code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *

def main():
    app  = QApplication(sys.argv)
    win=QWidget()
    layout=QHBoxLayout()
    db = QSqlDatabase.addDatabase("QODBC")
    win.setWindowTitle("Connect to MSSQL Database Example")
    db.setHostName('LAPTOP-B79DRPA3')
    db.setDatabaseName('local')
    db.open()
    if (db.open()==False):
      QMessageBox.critical(None, "Database Error",
                db.lastError().text())

    query = QSqlQuery ()
    query.exec_  ("select lydelse, bransch from [Sarah].[dbo].fraga")

    listWidget = QListWidget()
    index=0
    while (query.next()):
        listWidget.addItem(str(query.value(index)))
        index = index+1
    listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
    layout.addWidget(listWidget)
    win.setLayout(layout)
    win.show()
    return app.exec_()

if __name__ == '__main__':
    main()

But what is happening is here is that the output is a list with items from different columns. What I want is that I should be able to select a column and add all the row items to the list as list-items :
index=0
while (query.next()):
    listWidget.addItem(str(query.value(index)))
    index = index+1

A: When you use a select statement with explicit column names, the columns/fields in the query result will be in the same order, and numbered from left to right, starting at zero. Thus, in the statement:
select lydelse, bransch from [Sarah].[dbo].fraga

the lydelse column is 0 and the bransch column is 1. So to get all the values from the lydelse column, you would simply do:
query = QSqlQuery()
query.exec_("select lydelse, bransch from [Sarah].[dbo].fraga")
while query.next():
    print(query.value(0))

However, if you used a select * statement, this may not work, because the columns would be in no particular order. In that case, your code should look like this:
query = QSqlQuery()
query.exec_("select * from [Sarah].[dbo].fraga"):
index = query.record().indexOf('lydelse')
while query.next():
    print(query.value(index))


text:
Q: Using Wordpress Gutenberg components in plugin admin development I would like to use Wordpress Gutenberg components to develop a plugin admin side but I have some style issues, so please let me know is it possible to use these components to develop admin side of a plugin? And how can I fix these style issues?
Component code:
import { __ } from '@wordpress/i18n';
import { Component } from '@wordpress/element';
import {
    Panel,
    PanelBody,
    PanelRow,
    TextControl,
    TextareaControl,
    ColorPalette
} from '@wordpress/components';

export default class Account extends Component {
    constructor() {
        super( ...arguments );

        this.state = {
            name: '',
            number: '',
            default_text: '',
            button_label: '',
            button_color: '',
            button_text_color: ''
        };
    }

    render() {
        const colors = [
            { name: 'red', color: '#f00' },
            { name: 'white', color: '#fff' },
            { name: 'blue', color: '#00f' },
        ];

        return (
            <div>
                {/* <Panel header={ __( 'Account', 'easy-wordpress-whatsapp' ) }> */}
                    <PanelBody initialOpen={ true } title={ __( 'Account', 'easy-wordpress-whatsapp' ) }>
                        <PanelRow>
                            <TextControl
                                label={ __( 'Name', 'easy-wordpress-whatsapp' ) }
                                onChange={ value => this.setState( { name: value } ) }
                                required
                                value={ this.state.name }
                            />
                        </PanelRow>

                        <PanelRow>
                            <TextControl
                                label={ __( 'Number or Group Chat URL', 'easy-wordpress-whatsapp' ) }
                                onChange={ value => this.setState( { number: value } ) }
                                required
                                value={ this.state.number }
                            />
                        </PanelRow>

                        <PanelRow>
                            <TextareaControl
                                label={ __( 'Default Text', 'easy-wordpress-whatsapp' ) }
                                onChange={ value => this.setState( { default_text: value } ) }
                                value={ this.state.default_text }
                            />
                        </PanelRow>
                    </PanelBody>
                {/* </Panel> */}

                {/* <Panel header={ __( 'Button', 'easy-wordpress-whatsapp' ) }> */}
                    <PanelBody initialOpen={ true } title={ __( 'Button', 'easy-wordpress-whatsapp' ) }>
                        <PanelRow>
                            <TextControl
                                label={ __( 'Label', 'easy-wordpress-whatsapp' ) }
                                onChange={ value => this.setState( { button_label: value } ) }
                                required
                                value={ this.state.button_label }
                            />
                        </PanelRow>

                        <PanelRow>
                            <ColorPalette
                                colors={ colors }
                                value={ this.state.button_color }
                                onChange={ ( color ) => this.setState( { color } ) }
                            />
                        </PanelRow>

                        <PanelRow>
                            <ColorPalette
                                colors={ colors }
                                value={ this.state.button_text_color }
                                onChange={ ( color ) => this.setState( { color } ) }
                            />
                        </PanelRow>
                    </PanelBody>
                {/* </Panel> */}

            </div>
        )
    }
}

Also, I should say that I enqueued "wp-components" styles and javascript.
$this->enqueue_style( 'wp-components' );
$this->enqueue_script(
'whatsapp',
 $this->get_asset_url( 'dist/admin/index.js' ),
 array(
  'wp-components',
  'wp-data',
  'wp-element',
  'wp-hooks',
  'wp-i18n',
 )
);


text:
Q: How do you bootstrap an Angular2 submodule out of an angular 2 cli bundle? Background: We are using angular cli to create a UI component library. I am thinking this is not a good fit for CLI as it seems more designed for producing an application. So we are trying to make this library so we can load it into other Angular2 apps and use it as a default toolbox, also so we can use it in legacy non-angular apps. This is a media players library that presently contains an audio player component and will contain a video player and other players.
Specific Problem: I am trying to use the library (main.bundle.js) inside a non-angular.js app. The main.bundle.js bootstraps the entire application. "AppModule." There is a sub-module or AppModule that is being exported that is called "PlayersModule" this contains all the players. I want to be able to load just the PlayerModule into this app and use the  component within that module (also exported).  I am not sure how to take a blank html page and bootstrap just the PlayersModule out of the webpack bundle and have the html page only us the audio-player directive. When I try I get errors about not including the  for the AppComponent Module. However I am not wanting to load that.
Does anyone have some insights on how to do this? Am I over reaching with the angularcli tool to make this happen?


text:
Q: Getting all letters between two specified letters For objective-c, how do I find out the letters between two given letters. For example, for two letters A and D, I should get A, B, C, D.

A: you may try this code:
NSString *start = @"A";
NSString *end = @"D";
unichar startChar = [start characterAtIndex:0];
unichar endChar = [end characterAtIndex:0];
for (unichar c = startChar; c <= endChar; c++)
{
    NSLog(@"%c",c);
}

result:
2012-12-17 19:01:36.259 Test[7492:907] A
2012-12-17 19:01:36.263 Test[7492:907] B
2012-12-17 19:01:36.264 Test[7492:907] C
2012-12-17 19:01:36.265 Test[7492:907] D

hope this helps.

A: The shortest code would be:
for (char c = 'a'; c <= 'd'; c++)
    NSLog(@"char = %c", c);

A: First
unichar StartChar = [@"R" characterAtIndex:0];
unichar EndChar = [@"X" characterAtIndex:0];
for (unichar Result = StartChar; c <= EndChar; c++)
{
    NSLog(@"%c",Result);
}

Second
NSString *string = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int startIndex = [string rangeOfString:@"A"].location;
NSString *subString = [string substringFromIndex:startIndex];

int EndIndex = [subString rangeOfString:@"H"].location;

NSString*result = [subString substringToIndex:EndIndex+1];
NSLog(@"%@",result);

Third
NSArray *string = [[UILocalizedIndexedCollation currentCollation] sectionTitles];
int startIndex = [string indexOfObject:@"D"];
int EndIndexIndex = [string indexOfObject:@"I"];

for (int i=startIndex; i<=EndIndexIndex; i++)
{
    NSLog(@"%@",[string objectAtIndex:i]);
}


text:
Q: Requests.get not saving images on the webpage when I right click a page and click save as and save it as html, it saves everything on the page, including images. However, when I use python's requests.get, it saves the html page without saving the images. They appear as broken links, like so:
Broken images
Instead of like so:
Working images
How can I get requests.get to get all the data on the webpage? Appreciate any advice.
Edit: This is the code I'm using to scrape the website:
for link in aosa1:
    res=requests.get("http://aosabook.org/en/"+link)
    print(res.status_code)
    print(len(res.text))
    res.raise_for_status()

    playfile=open(link,'wb')
    for chunk in res.iter_content(100000):
        playfile.write(chunk)
    playfile.close

A: You don't understand how HTML works.  Those images are not part of the page.  When a browser downloads an HTML file, it then scans the HTML looking for <img> tags.  For each <img> tag, it make a new HTML request to fetch that so it can display it.  Now, if the <img> tags had absolute URLs, it would still show for you.  But if they have relative URLs (<img src="/images/abc.png">), then the browser is going to try to fetch them from your localhost web server, which does not exist.  You can try to scan the HTML and fetch those images.


text:
Q: ng-repeat in AngularJS not working Here is a simple Select done in Angular
<select ng-model="myCar">
    <option ng-repeat="car in cars" value="{{car}}">{{car}}</option>
</select>

I have the following in my scope in angular.js
$scope.cars = ["Toyota", "Ford", "Rolls"];

why isn't the options showing up, instead I get {{car}}

A: You can try this.
<select ng-model="myCar" ng-options = "car for car in cars" ng-init="myCar = 'Rolls'">

</select>

or this
<select ng-model="myCar" ng-init="myCar = 'Rolls'">
        <option ng-repeat="car in cars" value={{car}}>{{car}}</option>
</select>

A: Your's code is working fine. Only the default value isn't selected, so at the beginning it shows blank.
Refer here.
HTML:
<div ng-app="app" ng-controller="test">
    <select ng-model="myCar">
        <option value="">Select</option>
        <option ng-repeat="car in cars" value="{{car}}">{{car}}</option>
    </select>
</div>

JS:
var app = angular.module('app', []);

app.controller('test', function ($scope) {
    $scope.cars = ["Toyota", "Ford", "Rolls"];
});


text:
Q: Why doesn't shared module import fall through? I have a small angular application that makes use of the CoreModule and SharedModule pattern. Because
my application is quite small at the moment, I have imported the SharedModule in the root module, AppModule. I also have a lazy loaded admin module called AdminModule but it seems like it does not have access to shared module even though it has been imported in the root module. I have to explicitly import the SharedModule again in order to use it inside the components of the admin module. Why is this? If I have to re-import them again inside each lazy loaded module, what's the point of importing them in the root module?
AppModule
...
imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MatExpansionModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule, // imports firebase/firestore, only needed for database features
    AngularFireAuthModule, // imports firebase/auth, only needed for auth features,
    AngularFireStorageModule, // imports firebase/storage only needed for storage features
    SharedModule, // To be imported on each feature module, instead of AppModule. For now, this is fine though
    CoreModule,
    HttpClientModule
  ],
...

App routing module (Lazy loaded)
const routes: Routes = [
  {
    path: 'admin',
    loadChildren: './admin/admin.module#AdminModule',
    canActivate: [AdminAuthGuard]
  }]

AdminModule
...
imports: [CommonModule, AdminRoutingModule, SharedModule, CoreModule],

An example is if I have a footer component inside the SharedModule and try to use it in my AdminHomeComponent which is a part of the AdminModule, I get an error (without importing the SharedModule). All works fine when I import it.

A: Importing a Module lets the components of the module that imports the external module, to be able to see the components from that imported module. But only the ones in that module, not in the nested ones.
Importing a module in the root module is useful for PROVIDERS, that's quite different from Components.
If you import a Module that provides a service in a module, all the components from that module and the nested modules will be able to see the providers. (this is the reason why it's a good practice to put the providers of a module only in a static forRoot() method if the module has providers and components that will be reused).

A: I also found this great answer on another post https://stackoverflow.com/a/43153529/8948458

The minute you create a new module, lazy or not, any new module and you declare anything into it, that new module has a clean state. It has no knowledge of anything,


text:
Q: How should this instanceof condition look like? I have a list of nodes. This nodes are a data class I defined by myself. Each node has a data field of the type Object. Now I want to find the node in a list of nodes that has the parameter object in the data field. I wrote this method, because I wanted to first compare if the two objects (the parameter and the object in the data field) are of the same type:
public Node getnNodeByData(Object obj) {
    for (Node node : nodes) {
        if (node.getData() instanceof obj.getClass()) {

        }
    }
}

Unfortunately this condition does not work:
Incompatible operand types boolean and Class<capture#1-of ? extends Graph>

I don't really know why this is a problem. How can I make this working?

A: No, you need to use Class.isInstance(Object).  The instanceof keyword does not expect an object of type Class, but only the name of the class directly -- but Class.isInstance is basically analogous.

A: No, that is not possible like that. You should use isAssignableFrom() or isInstance(). The difference between the two methods is that isInstance(null) will return false and isAssignableFrom(null) will give true.

[object] instanceof [class]

should be translated to this:
[class].class.isAssignableFrom(object.getClass());

Example:
Integer i = 4;
boolean b = i instanceof Number;
boolean k = Number.class.isAssignableFrom(i.getClass());

b and k are equivalent.


text:
Q: Why does DebugActiveProcessStop crash my debugging app? I have a debugging program which I've written to attach to a process and create a crash dump file. That part works fine.
The problem I have is that when the debugger program terminates, so does the program that it was debugging.
I did some Googling and found the DebugActiveProcessStop() API call. This didn't show up in my older MSDN documentation as it was only introduced in Windows XP so I've tried loading it dynamicall from Kernel32.dll at runtime.
Now my problem is that my debugger program crashes as soon as the _DebugActiveProcessStop() call is made. Can somebody please tell me what I'm doing wrong?
typedef BOOL (*DEBUGACTIVEPROCESSSTOP)(DWORD);

DEBUGACTIVEPROCESSSTOP _DebugActiveProcessStop;

HMODULE hK32 = LoadLibrary( "kernel32.dll" );

if( hK32 )
  _DebugActiveProcessStop = (DEBUGACTIVEPROCESSSTOP) GetProcAddress( hK32,"DebugActiveProcessStop" );
else
{
  printf( "Can't load Kernel32.dll\n" );
  return;
}

if( ! _DebugActiveProcessStop )
{
  printf( "Can't find DebugActiveProcessStop\n" );
  return;
}

...

void DebugLoop( void )
{
  DEBUG_EVENT de;

  while( 1 )
  {
    WaitForDebugEvent( &de, INFINITE );

    switch( de.dwDebugEventCode )
    {
      case CREATE_PROCESS_DEBUG_EVENT:
        hProcess = de.u.CreateProcessInfo.hProcess;
        break;

      case EXCEPTION_DEBUG_EVENT:

        // PDS: I want a crash dump immediately!
        dwProcessId = de.dwProcessId;
        dwThreadId  = de.dwThreadId;

        WriteCrashDump( &de.u.Exception );
        return;

      case CREATE_THREAD_DEBUG_EVENT:
      case OUTPUT_DEBUG_STRING_EVENT:
      case EXIT_THREAD_DEBUG_EVENT:
      case EXIT_PROCESS_DEBUG_EVENT :
      case LOAD_DLL_DEBUG_EVENT:
      case UNLOAD_DLL_DEBUG_EVENT:
      case RIP_EVENT:
      default:
        break;
    }

    ContinueDebugEvent( de.dwProcessId, de.dwThreadId, DBG_CONTINUE );
  }
}

...
void main( void )
{
...
  BOOL bo = DebugActiveProcess( dwProcessId );

  if( bo == 0 )
    printf( "DebugActiveProcess failed, GetLastError: %u \n",GetLastError() );

  hProcess = OpenProcess( PROCESS_ALL_ACCESS, TRUE, dwProcessId );

  if( hProcess == NULL )
    printf( "OpenProcess failed, GetLastError: %u \n",GetLastError() );

  DebugLoop();

  _DebugActiveProcessStop( dwProcessId );

  CloseHandle( hProcess );
}

A: The reason its crashing is because I missed out the WINAPI keyword on my function pointer definitions.
This works:
typedef BOOL (WINAPI *DEBUGSETPROCESSKILLONEXIT)(BOOL);


text:
Q: Help - Saving a DigitaPersona Template file. See sample code DELPHI 5 SAMPLE FOR SAVING A DigitaPersona TEMPLATE SERIAL DATA
TO A DBASE4 DBF FILE.
procedure TFormEnroll.DPFPEnrollmentControl1Enroll(Sender: TObject;
  lFingerMask: Integer; const pTemplate, pStatus: IDispatch);
var
  MMask : Integer;
  Template : IDispatch;
  MTempStr : OleVariant;

  lByteArray: Variant;
  lArrayPointer: Pointer;
  lStr: AnsiString;
  DPFPTemplate: TDPFPTemplate;
  aRawData : Variant;
begin
  aRawData := pTemplate;
  lStr := aRawData.Serialize;
  MMask := lFingerMask;
  if lStr = null then
    StatusBar.Panels.Items[0].Text := 'The fingerprint TEMPLATE is empty! + Mask=' + IntToStr(MMask)
  else
    StatusBar.Panels.Items[0].Text := 'The fingerprint TEMPLATE has something! + Mask=' + IntToStr(MMask);
  MMsg := lStr;
  MLen := Length(MMsg);
  EditSerialData.Text := MMsg;
  MemoSerialData.Lines.Text := MMsg;
  MemoSerialData2.Lines.Text := MMsg;
  EditLenSerialData.Text := IntToStr(MLen);
  EditFingerMask.Text := IntToStr(DPFPEnrollmentControl1.EnrolledFingersMask);
  //Update database - Take to separate save button
  DMForm.Finger.First;
  if DMForm.Finger.State in [dsEdit, dsInsert] then
    // do nothing
  else
    DMForm.Finger.Edit;
  DMForm.FingerUSERNAME.Value := 'Testing ';
  DMForm.Finger.Post;
  DMForm.Finger.Edit;
  DMForm.FingerUSERNAME.Value := 'Testing ' + IntToStr(DMForm.FingerFINGERID.Value);
  DMForm.FingerFINGERTEMP.Value := MMsg;
  DMForm.FingerEnrolledFingerMask.Value := IntToStr(DPFPEnrollmentControl1.EnrolledFingersMask);
  DMForm.FingerFingerSerialData.Value := MMsg;
  DMForm.Finger.Post;
end;

EXAMPLE STRING OF THE SAVED TEMPLATE = "?b?????????????????????????????????????????????????????õ???????????????????????????????????+???????[??????????????????V????????????????????????????????????????????????????????????????9??????????o??????????????????????????????????????????????????????????????????¦???????????????????????????????????????????????????????????????????????????????????????????????????????j??????????????????????o????????????????????????????????????????????????????????U·?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????#??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"

Is this the kind of result we expect?
Is this a workable template?
Can you explain ( aRawData := pTemplate;) the interaction of 'aRawData' which is a variant with 'pTemplate;) ' which is a Dispatch variable.
Am I on the write path?

A: Yeah, that's the binary data of the fingerprint template which is used to verify the fingerprint.
You can save it in a blob in a database or a binary file and load it or to bintohex and save it in a text file.
The difference between a template and the rawdata is that the template is the one that is used to verify the finger the next time it is pressed in the reader.  You'll see that if you print out the rawdata that it's a lot bigger.
Looks like you're on the right track, just don't worry about the binary data.


text:
Q: OOP - Do I over complicate things? I was looking at some of my projects and comparing them to things I've seen on github and I feel like I over-think things. I like OOP but I feel like I make too many files, too many classes.
For example, on a small project I had of a game of checkers, I had so many files that could maybe all go into one file/class. How do I know when I have over-thought my solutions? Here is what some of my files look like;
|src
| |- player.cpp
| |- piece.cpp
| |- color.cpp
| |- ...

And of course, there are many more files that will deal with things like rules, setting the game, GUI, etc,. But in this short example you can see how my projects can and will get very large. Is this common, to write things in this way? Or should I simply write a player.cpp file that either contains multiple classes that, in this case, are related and would set pieces/colors/king information, etc,.

A: Yes, distributing your code to multiple files is a good practice, since it makes your project maintainable.
I can see your concerns on a small project (is the overhead worth it?), but in real big projects, if you don't do it that way, you will end up with people scrolling forever in a large file, and using searching trough the file to find out what they are looking for.
Try to keep your files compact, and one class per file, where every class is robust and its goal is clear.
Sometimes, we write functions to files. It would not be wise to have a file for every small, inline function, it will increase the number of files without a reason. It would be better to have a family of functions inside a file (functions related to printing for example).
At the end, it's probably opinion based which is the ideal balance between size and number of files, but I hope I made myself clear.

A: You are actually asking two distinct questions: "what is the good granularity for separating functionality into classes" and "what is the good practice to organize project file structure". Both are rather broad.
The answer to first one would probably be to follow a single responsibility idiom. The answer to second one would be to make folder structure resemble the namespace structure (like in boost for example). Your current approach with storing everything in src folder is not good for C++ because it will lead to longer file names to prevent names collision when classes with the same name appearing in different namespaces. Larger projects indeed tend to have too many files as one class would require 4-5 files. And that leads to yet another question of selecting appropriate granularity for projects...

A: People tend to worry a lot about "too many classes" or "too many files", but that's largely a historical carryover.  40 years ago when we wrote programs on punch cards, and had to carry large trays and boxes of them (and not drop them!), this certainly would have been a concern.  35 years ago when the biggest hard drive you could get for a PC was 33MB, this was a concern.  Today, when you wouldn't consider buying a PC with less than 512GB of SSD, and have access to terabytes and petabytes of online storage, the number of files and number of bytes taken up by the programs are essentially immaterial to the development process.
What that means to us humans is that we should use this abundance of capacity to improve other aspects of our code.  If more files helps you understand the code better, use more files.  If longer file names help you understand the code better, use longer file names.  If following a rule like "one .cpp and one .h file per class" helps people maintain the codebase, then follow the rule.  The key is to focus on truly important issues, such as "what makes this code more maintainable, more readable, more understandable to me and my team?"
Another way to approach this is to ask if the "number of files" is a useful metric for determining if code is maintainable?   While a number that is obviously too low for the app would be concerning, I wouldn't be able to tell you if 10 or 100 or 1000 was an appropriate number (at least without knowing the number of classes they contain.)  Therefore, it doesn't appear to be a useful metric.
Does that mean a program should have 1000 files all piled into a single folder, all compiling and linking into a single library or executable file?  It depends, but it seems that 1000 classes in the same namespace would be a bit crowded and the resultant program might be too monolithic.  At some point you'll probably want to refactor the architecture into smaller, more cohesive packages, each with an appropriate area of responsibility.  Of course, nobody can tell you what that magic number is, as it's completely application dependent.  But it's not the number of files that drives a decision like this, it's that the files should be related to each other logically or architecturally.

A: Each class should be designed and programmed to accomplish one, and only one, thing
Because each class is designed to have only a single responsibility, many classes are used to build an entire application


text:
Q: StreamReader problems of some kind I am having a problem in c# with the StreamReader object. I pass in a StreamReader object to a function, then I read through it to gather some information about its contents. Once I pass it through the code to gather information I think its empty when I pass it to subsequent functions.
public DataScraper GetDataValues(StreamReader sr)
{

    DataScraper dsGd = new DataScraper();

    string line = string.Empty;
    int intCurrentLine = 0;
    int intLineAskingPrice = 0;
    int intLineHOADues = 0;
    int intLineTaxes = 0;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("For Sale: $"))
            intLineAskingPrice = intCurrentLine;
        if (line.Contains(@"HOA Fee"))
            intLineHOADues = intCurrentLine - 1;
        if (line.Contains("Annually:"))
            intLineTaxes = intCurrentLine + 1;
        intCurrentLine++;
    }

    //HOA Fee
    dsGd.intAskingPrice = GetAskingPrice(sr, intLineAskingPrice);
    dsGd.intHOADues = GetHOADues(sr, intLineHOADues);
    dsGd.intTaxes = GetTaxes(sr, intLineTaxes);

    return dsGd;
}

Any thoughts how I can pass in a StreamReader object through subsequent functions and be at the beginning of the StreamReader instead of the end (if that is what is actually happening to my code)?

A: You can set the Position of the BaseStream to 0, this works only if your underlying stream supports Position. I hope that's not your case.
public DataScraper GetDataValues(StreamReader sr)
{
  if(sr.BaseStream != null&&sr.BaseStream.CanSeek) sr.BaseStream.Position = 0;
  //remaining code
  //....
  //....
}


text:
Q: How do I start the 'contains' decision operator in ColdFusion at a specific character in a string? My question is super simple, but I can't seem to figure it out.  I'm trying to find the character 'C' in a seemingly random 10 character string.  However, I only care about the character 'C' if it is the 6th character in the string.  If the character 'C' is found at the 6th position in the string the string should be enclosed in dashes (-).   For example:
14CSI14550 should not be enclosed in dashes, because the C is the 3rd character in the string.
14EFEC4933 should be enclosed in dashes, because C is the 6th character in the string.
14CSIC5005 should also be enclosed in dashes even though there is another C in the string.
Here is what I have so far, I think I'm on the right track with contains, but I think I need it to start looking for C at the 5th character in the string, so as to skip the first 5 characters. I could be wrong though.
Code:
<cfif #queryName.TenDigitNumber# contains 'C'>
-#Plan.Code#-
<cfelse>
#Plan.Code#
</cfif>

This obviously encloses all 10 character strings that have C in them with dashes including something like 14CSI14550, which would be incorrect.  Any help would be appreciated!  Thanks!

A: <cfif mid(queryname.tendigitnumber, 6, 1) eq 'C'> .. do stuff .. </cfif>


text:
Q: How to Change Save Location in Office 2013 using VBScript I am wondering how to change the save location in Office 2013 by using VBScript.
Can any one help with that?
Thanks

A: I recorded a macro changing the document paths (Alt + T, O, File Locations tab). The relevant code recorded is
Options.DefaultFilePath(Path:=wdDocumentsPath) = _
    "C:\Users\User\Desktop\"

In VBS, which doesn't support named arguments (and options isn't in the global namespace as app objects are when hosted by that app), becomes
wrd.Options.DefaultFilePath = "C:\Users\Users\Desktop\"

To open word with  wrd set as the app object use  set wrd = createobject("Word.Application").


text:
Q: How do you loop and test multiple "numpy.isclose" values on a column of a dataframe? I'm using this line of code to determine values in a column of a large dataframe, df, that are close to the value of A (within a tolerance):
df[df[['column']].apply(numpy.isclose, b=A, atol=0.004).any(1)]

However, in some instances, A can have multiple values (i.e. 2-4 different values). Is there a method that would allow me to loop through each of the values of A to test each one? I know that the line of code shown above will only let me use A if it has one value assigned to it.
An example of this would be (using a much shorter dataframe):
   column1   column2
0  0.902062    5.8
1  0.557808    3.3
2  0.655985    3.9
3  0.832471    4.1
4  0.199884    1.2
5  0.127254    1.8
6  0.771439    4.9
7  0.432289    2.8
8  0.385282    2.2
9  0.783643    3.7

Where A has values:
A=[0.432, 0.783, 0.902]

But in another example, it may have the values:
A=[0.558, 0.002]

(where it is obvious here that nothing from the dataframe will actually match 0.002).
I'd like some code which would be able to return the rows from the dataframe where the column1 values match the values of A for ALL examples, regardless of the number of different A values (and if there is no match, return "NaN" instead).

A: I believe you need repeat columns values by  numpy.broadcast_to before using numpy.isclose:
np.random.seed(142)

df = pd.DataFrame({'column':np.random.rand(10)})
print (df)
     column
0  0.902062
1  0.557808
2  0.655985
3  0.832471
4  0.199884
5  0.127254
6  0.771439
7  0.432289
8  0.385282
9  0.783643

A = [0.432, 0.783, 0.902]

#repeat by length of number of list A
len_A = len(A)
a = np.broadcast_to(df['column'].values[:, None], (len(df),len_A))
print (a)
[[0.90206152 0.90206152 0.90206152]
 [0.55780754 0.55780754 0.55780754]
 [0.65598471 0.65598471 0.65598471]
 [0.83247141 0.83247141 0.83247141]
 [0.19988419 0.19988419 0.19988419]
 [0.12725426 0.12725426 0.12725426]
 [0.77143911 0.77143911 0.77143911]
 [0.43228855 0.43228855 0.43228855]
 [0.38528223 0.38528223 0.38528223]
 [0.78364337 0.78364337 0.78364337]]

#pandas solution
m = pd.concat([df['column']] * len_A, axis=1)
print (m)
     column    column    column
0  0.902062  0.902062  0.902062
1  0.557808  0.557808  0.557808
2  0.655985  0.655985  0.655985
3  0.832471  0.832471  0.832471
4  0.199884  0.199884  0.199884
5  0.127254  0.127254  0.127254
6  0.771439  0.771439  0.771439
7  0.432289  0.432289  0.432289
8  0.385282  0.385282  0.385282
9  0.783643  0.783643  0.783643

m = np.isclose(a, b=A, atol=0.004)
print (m)
[[False False  True]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [ True False False]
 [False False False]
 [False  True False]]

Last get all values with True per rows by any:
print (m.any(axis=1))
[ True False False False False False False  True False  True]

And last filter by boolean indexing:
print (df[m.any(axis=1)])
     column
0  0.902062
7  0.432289
9  0.783643


text:
Q: Permalink for Custom Taxonomy Wordpress Currently, I have WordPress website which has pages, blog and custom post type named "Case Studies".
My permalink setting is a custom structure which is: /blog/%postname%/ so that I can show "Blog" in URLs for all blog posts.
URL structure for my custom post type is http://www.my-domain/case-studies/case-study-url-here/ which is working fine with below setup.
    "rewrite" => array('slug' => 'case-studies', 'with_front' => FALSE),

I have a custom taxonomy to categorize my case studies division wise, hence I have created a taxonomy called division and I want its URL to be "http://www.my-domain/case-studies/division-here/ but current it shows like "http://www.my-domain/blog/case-studies/division-here" which is not right.
To remove word blog from division URL, I changed rewrite code for the same to look like below.
    "rewrite" => array( 'slug' => 'case-studies', 'with_front' => false),

but the issue is, by doing this, I can not go to division taxonomy page properly it rather shows some random page or post from my website, but the old URL with "blog" base works fine and shows list of case studies on it if I make "with_front" true; but that is not how I want it.
Any help? how can I remove blog from URL and make it work?
Regards
Manoj Soni

A: In your custom post type you need to add rewrite slug like 'rewrite'   => array('slug' => '%division%', 'with_front' => false ),
and then you need to add following code in your function file.
function d_reset_permlinks( $post_link, $post ){
    if ( is_object( $post ) && $post->post_type == 'case-studies' ){
    $terms = wp_get_object_terms( $post->ID, 'division' );
    if( $terms ){
        return str_replace( '%division%' , $terms[0]->slug , $post_link );
    }
   }
   return $post_link;
}
 add_filter( 'post_type_link', 'd_reset_permlinks', 1, 2 );

And reset the permlinks with Post name  then check.


text:
Q: How often should you use git-gc? How often should you use git-gc?
The manual page simply says:

Users are encouraged to run this task on a regular basis within each repository to maintain good disk space utilization and good operating performance.

Are there some commands to get some object counts to find out whether it's time to gc?

A: Drop it in a cron job that runs every night (afternoon?) when you're sleeping.

A: You can do it without any interruption, with the new (Git 2.0 Q2 2014) setting gc.autodetach.
See commit 4c4ac4d and commit 9f673f9 (Nguyễn Thái Ngọc Duy, aka pclouds):

gc --auto takes time and can block the user temporarily (but not any less annoyingly).
  Make it run in background on systems that support it.
  The only thing lost with running in background is printouts. But gc output is not really interesting.
  You can keep it in foreground by changing gc.autodetach.

Since that 2.0 release, there was a bug though: git 2.7 (Q4 2015) will make sure to not lose the error message.
See commit 329e6e8 (19 Sep 2015) by Nguyễn Thái Ngọc Duy (pclouds).
(Merged by Junio C Hamano -- gitster -- in commit 076c827, 15 Oct 2015)

gc: save log from daemonized gc --auto and print it next time
While commit 9f673f9 (gc: config option for running --auto in background - 2014-02-08) helps reduce some complaints about 'gc --auto' hogging the terminal, it creates another set of problems.
The latest in this set is, as the result of daemonizing, stderr is closed and all warnings are lost. This warning at the end of cmd_gc() is particularly important because it tells the user how to avoid "gc --auto" running repeatedly.
  Because stderr is closed, the user does not know, naturally they complain about 'gc --auto' wasting CPU.
Daemonized gc now saves stderr to $GIT_DIR/gc.log.
  Following gc --auto will not run and gc.log printed out until the user removes gc.log.

A: I use git gc after I do a big checkout, and have a lot of new object. it can save space. E.g. if you checkout a big SVN project using git-svn, and do a git gc, you typically save a lot of space

A: This quote is taken from;
Version Control with Git

Git runs garbage collection automatically:
• If there are too many loose objects in the repository
• When a push to a remote repository happens
• After some commands that might introduce many loose objects
• When some commands such as  git reflog expire explicitly request it
And finally, garbage collection occurs when you explicitly request it
using the  git gc command. But when should that be? There's no solid
answer to this question, but there is some good advice and best
practice.
You should consider running  git gc manually in a few
situations:
• If you have just completed a  git filter-branch . Recall that
filter-branch rewrites many commits, introduces new ones, and leaves
the old ones on a  ref that should be removed when you are satisfied
with the results. All those dead objects (that are no longer
referenced since you just removed the one  ref pointing to them)
should be removed via garbage collection.
• After some commands that might introduce many loose objects. This
might be a large rebase effort, for example.
And on the flip side,
when should you be wary of garbage collection?
• If there are orphaned refs that you might want to recover
• In the context of  git rerere and you do not need to save the
resolutions forever
• In the context of only tags and branches being sufficient to cause
Git to retain a commit permanently
• In the context of  FETCH_HEAD retrievals (URL-direct retrievals via
git fetch ) because they are immediately subject to garbage collection

A: I use when I do a big commit, above all when I remove more files from the repository.. after, the commits are faster

A: Recent versions of git run gc automatically when required, so you shouldn't have to do anything. See the Options section of man git-gc(1): "Some git commands run git gc --auto after performing operations that could create many loose objects."

A: You don't have to use git gc very often, because git gc (Garbage collection) is run automatically on several frequently used commands:
git pull
git merge
git rebase
git commit

Source: git gc best practices and FAQS

A: It depends mostly on how much the repository is used.  With one user checking in once a day and a branch/merge/etc operation once a week you probably don't need to run it more than once a year.
With several dozen developers working on several dozen projects each checking in 2-3 times a day, you might want to run it nightly.
It won't hurt to run it more frequently than needed, though.
What I'd do is run it now, then a week from now take a measurement of disk utilization, run it again, and measure disk utilization again.  If it drops 5% in size, then run it once a week.  If it drops more, then run it more frequently.  If it drops less, then run it less frequently.

A: If you're using Git-Gui, it tells you when you should worry:

This repository currently has approximately 1500 loose objects.

The following command will bring a similar number:
$ git count-objects

Except, from its source, git-gui will do the math by itself, actually counting something at .git/objects folder and probably brings an approximation (I don't know tcl to properly read that!).
In any case, it seems to give the warning based on an arbitrary number around 300 loose objects.

A: Note that the downside of garbage-collecting your repository is that, well, the garbage gets collected. As we all know as computer users, files we consider garbage right now might turn out to be very valuable three days in the future. The fact that git keeps most of its debris around has saved my bacon several times – by browsing all the dangling commits, I have recovered much work that I had accidentally canned.
So don't be too much of a neat freak in your private clones. There's little need for it.
OTOH, the value of data recoverability is questionable for repos used mainly as remotes, eg. the place all the devs push to and/or pulled from. There, it might be sensible to kick off a GC run and a repacking frequently.


text:
Q: Constructing a Decision Tree using arguments in caret package in R I am trying to construct a decision tree using the caret package in R. Can someone please explain to me what is the difference between the "metric" and "parms" arguments as shown in the R code below? I'm trying to understand how this tree is being constructed.
train(Credit ~ CreditAmount + Age + CreditHistory + Employment,
            data = credit,
            method = 'rpart',
            trControl = trainControl(method = 'cv', number = 6),
            metric = "Accuracy",
            tuneGrid = expand.grid(cp = seq(0, 0.1, 0.001)),
            na.action = na.omit,
            parms = list(split='information'))

A: The parms is fed into the rpart model, and it is a metric, used by rpart to choose a variable at each step that best splits the set of items:
parms: a list of method specific optional parameters. For classification, the list can
contain any of: the vector of prior probabilities (component prior), the loss matrix
(component loss) or the splitting index (component split). The priors must be
positive and sum to 1. The loss matrix must have zeros on the diagonal and positive
off-diagonal elements. The splitting index can be "gini" or "information".

You can read this for more details and I would say this parms option decides how you want to construct the tree model, just like the complexity parameter cp you are training on with caret.
What you need to do after fitting the model is to evaluate how good it is at predicting labels on the tested fold and select the best cp based on this. In your example, you set it to be "Accuracy", but you can also set it to be "Kappa" (cohen's kappa) or other defined metrics. For example:
library(caret)
mdl = train(Species ~ .,data=iris,method="rpart")
print(mdl)

CART

150 samples
  4 predictor
  3 classes: 'setosa', 'versicolor', 'virginica'

No pre-processing
Resampling: Bootstrapped (25 reps)
Summary of sample sizes: 150, 150, 150, 150, 150, 150, ...
Resampling results across tuning parameters:

  cp    Accuracy   Kappa
  0.00  0.9334562  0.8993173
  0.44  0.8144866  0.7246185
  0.50  0.5181330  0.3012537

Accuracy was used to select the optimal model using the largest value.
The final value used for the model was cp = 0.

From the above training, cp = 0 was chosen because it has the highest accuracy. Unfortunately you cannot use caret to find whether gini or information is better. Hope this clears the confusion


text:
Q: ControlID across office versions I'm trying to write a VSTO plugin for Outlook, but I want it to work across multiple versions. The ControlID for the Home tab is 'TabHome' in some versions, and 'TabMail' in others - does anyone have an idea how to properly deal with this?

A: You could create a function using something like this.
 If Application.ProductVersion.Substring(0, 2) > "14" Then ' Outlook 2010
     Return "TabHome"
 Else
     Return "TabMail"
 End If


text:
Q: Is this "limit" of a sequence of $L^2$ functions in $L^2$? Suppose we have a sequence $\{f_n\}$ in $L^2([0,1])$ and a Lebesgue measurable $f$ such that $$\int_E f_ndx\rightarrow\int_E fdx$$ as $n\rightarrow\infty$ for every Lebesgue measurable subset $E\subseteq[0,1]$. If $\sup_n\|f_n\|_2<\infty$, then do we necessarily have $f\in L^2([0,1])$?
I'm not seeing how to show this, one way or the other. I tried constructing a counterexample along the lines of $f_n(x)=x^{\frac{1}{n}-\frac{1}{2}}$, since then $f(x)=x^{-1/2}$ isn't square-integrable, but this doesn't satisfy either condition. I'm inclined to think that we do have $f\in L^2([0,1])$, since it doesn't seem like you can make $\int_{[0,1]}|f|^2dx$ blow up without either of $\int_{[0,1]}|f_n|^2dx$ or $\int f dx$ blowing up, but I don't see a way to formalize or justify this instinct.

A: Disclaimer: I prefer the "functional analysis" approach, as it is more natural to me; but here is a pure measure-theory argument. All it uses is the definition of Lebesgue integral and the Cauchy-Schwarz inequality.
The key observation is that, by linearity, the property can be written as
$$
\int_F f\,s=\lim_n\int_F f_n\,s
$$
for any measurable set $F$ and any simple function $s$.
I will assume $f$ real; if it is complex, one can work with real and imaginary parts, so no loss of generality.
Suppose that $f\not\in L^2[0,1]$. That is, $$\int_{[0,1]}f^2=\infty.$$
By working on the set $F=\{f\geq0\}$, we may assume $\int_F f^2=\infty$ (otherwise, we work with $-f$). By definition of Lebesgue integral, this means that there exists a sequence of simple functions $\{s_m\}$ with $0\leq s_m\leq f^2$ and $\lim_m\int_F s_m=\infty$. By choosing a subsequence if necessary, we may assume that the numbers $\int_Fs_m$ increase monotonically.
Choose positive integers $k(m)$ with $k(m)\leq \int_Fs_m< k(m)+1$. Then $k(m)\nearrow\infty$. We have, with $C=\sup_n\|f_n\|^2$,
\begin{align}
 k(m)&\leq \int_F s_m^{1/2}\,s_m^{1/2}\leq\int_F f\,s_m^{1/2}=\lim_n\int_Ff_n\,s_m^{1/2}\\[0.3cm]
&\leq \sup_n\|f_n\|_2\,\bigg(\int_Fs_m\bigg)^{1/2}\\[0.3cm]
&\leq C\,(k(m)+1)^{1/2}\leq 2C\,k(m)^{1/2}.
\end{align}
This implies that $k(m)$ is bounded, a contradiction.


text:
Q: Hide a word within a class with just CSS A WordPresss site, where I'm attempting to hide the word 'SKU' as seen below in the html code.
Here is the html

Phase 1 Phonics Planning Week 1 Example TEST FREE

SKU:

I want to use a just CSS to hide the SKU word, my effort thus far, but I'm unable to see how to target just SKU, I presume I need to use the  element some how?:
CSS
.card .card-body {
    display: none;
}

A: Unless im misunderstanding your question, you can just use:
.card-body p small strong {display:none}

If this isn't what you require please elaborate.

A: There are a couple of ways. One is to use
.card-body small {
    display: none;
}

But, it would probably be better to create a new class just for hidden things, like this
.hide-sku {
    display: none;
}

and in the html
SKU:
(also, you have the class card-body duplicated -- not sure if that's your intention)

A: If you can control classes in your html code - the easiest way is to add some helper class:

.hidden {
  display: none;
}

    Phase 1 Phonics Planning Week 1 Example TEST FREE

      SKU:

Some other content

If you can't control classes and change html code - you can use :nth-of-type or :nth-child pseudoclasses:

.card-body p:nth-of-type(1) {
  display: none;
}

    Phase 1 Phonics Planning Week 1 Example TEST FREE

      SKU:

Some other content


text:
Q: Many to one NAT on Fortigate I am able to configure the one to one NAT (VIP) in Fortigate. but it seems many to one NAT is not possible.
We dont want to use the interface IP as NAT address. we want to assign another IP as the NAT address
External: 192.168.2.1
Internal: 192.168.1.1
we want use 192.168.2.2 as the NAT ip for 192.168.1.1, 192.168.1.2 and 192.168.1.3

A: You should look at the Load Balancing feature of FortiOS.
VIP are more for one-to-one NAT or for port translation.

A: Found that Overload is the answer.
Policy & Objects >> IP Pools >> create your IP Pools select the overload option .
go to the policy you want to NAT, inside the policy and under Firewall / Network Options, select Dynamic IP and select the IP Pools you just created.


text:
Q: SSL on Jelastic and Jetty 9 I created Jelastic environment with Jetty 9. Then I added SSL support - Jelastic created NGinx instance and my solution now available using https and provides certificate. Question is - how to deny access on old non secure way? I mean using ordinary http?

A: You just need to edit the nginx config. to redirect http requests to https.
Example configs:

*

*NGINX Redirect http to https and non-www to ww

*https://serverfault.com/questions/250476/how-to-force-or-redirect-to-ssl-in-nginx


text:
Q: JavaFX select text from second column does not matter where in row is clicked I have a little problem I need to select exactly one column(cell) of row independently where I click in row.
For example I have 3 column table, I click on first column but I need text of second column every time.
Is there any way I can do this. In swing there were indexes for rows and columns but i can't find anything like that in JavaFX.
My code for double click selection is:
@Override
public void handle(MouseEvent click) {
    if (click.getClickCount() == 2) {
        @SuppressWarnings("rawtypes")
        TablePosition pos = searchResult.getSelectionModel().getSelectedCells().get(0);
        int row = pos.getRow();
        int col = pos.getColumn();
        @SuppressWarnings("rawtypes")
        TableColumn column = pos.getTableColumn();
        String val = column.getCellData(row).toString();
        System.out.println("Selected Value, " + val + ", Column: " + col + ", Row: " + row);
        try {
            if (button1.isSelected()) {
                Runtime.getRuntime().exec("explorer.exe /select," + val);
            } else {
                if (button2.isSelected()) {
                    File file = new File(val);
                    Desktop.getDesktop().open(file);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Thanks you for any answers.

A: If you actually want to select the cell
You can set the cellSelectionEnabledProperty of the selection model of your table view to true.
You can listen to the change of the focused cell property of the focus model of your table view.
Then in the change listener you can select any TableColumn what you want in the same row.
Example:
// Enable cell selection
tableView.getSelectionModel().setCellSelectionEnabled(true);

// On focused property change
tableView.getFocusModel().focusedCellProperty().addListener(new ChangeListener<TablePosition>() {

    @Override
    public void changed(ObservableValue<? extends TablePosition> arg0, TablePosition arg1, TablePosition arg2) {
        // Select TableColumn "col2" in the same row
        tableView.getSelectionModel().select(arg2.getRow(), col2);

    }
});

This will produce a tableview which selects the cell in the desired column independently which cell is selected in the row.
If you just want to get the value of a cell on row selection
// Just row selection
tableView.getSelectionModel().setCellSelectionEnabled(false);

tableView.getFocusModel().focusedCellProperty().addListener(new ChangeListener<TablePosition>() {

    @Override
    public void changed(ObservableValue<? extends TablePosition> arg0, TablePosition arg1, TablePosition arg2) {
        // Get the data from the desired cell (tableview displays Data objects)
        Data item = tableView.getItems().get(arg2.getRow());
        String data = (String) col2.getCellObservableValue(item).getValue();
        System.out.println(data);
    }
});

This example gets and prints the value from the desired column independently which column is selected.

A: Register the mouse listener with the table row, using a row factory:
TableView<MyDataType> tableView = ... ;

tableView.setRowFactory(tv -> {
    TableRow<MyDataType> row = new TableRow<>();
    row.setOnMouseClicked(e -> {
        if (e.getClickCount() == 2) {
            MyDataType rowData = row.getItem();
            if (rowData != null) {
                // get value displayed in second column from rowData...
                // and process it however you need
            }
        }
    });
    return row ;
});


text:
Q: Take multiple separate inputs from lines read in from file in C Basically I have a few problems.
The problem I am trying to solve involves a "banking program" that gets its info from a text file. It reads the first five lines of code (which are all floats) and uses each as the starting balance.
Next, the following 1-5 lines of code each begin with a single character indicating the account that it affects. Next is a single letter indicating either withdraw or deposit, etc. Following that is the amount that will be used in the action. I have to use multiple functions.
Here's what I have so far, I know some spaces have been left in pseudocode while I'm working on it.
  float balance();
float withdraw();
float deposit();
float update();

#define INTEREST 3.5;
int main(){

//initializing variables
int count =0,count2=0,acctNum=1,acct1,acct2,acct3,acct4,acct5,i=0;
float orgBalance, balance;
char activity,B,W,U,D;

//opening files
FILE *input;
input = fopen("bankfile.txt","r");

//error checking that file opened correctly
if (input == NULL){
    fprintf(stderr, "Can't open input file!\n");
    exit(1);
}
printf("Account          Balance\n");
printf("------------------------\n");
while(count<5){
    fscanf(input,"%f",&orgBalance);

    //printf("%d               %.2f\n",acctNum,orgBalance);
    //acctNum++;
    i++;
    count++;
    printf("%d balance is %.2f\n",i,orgBalance);
}
printf("------------------------\n");

while(fscanf(input, "%d ",&i)!=EOF){
//while(count2<5)
    fgetc(i);

    switch (activity){
        case 'B':
            balance;
            ;
            break;
        case 'W':
            withdraw;
            ;
            break;
        case 'D':
            deposit;
            ;
            break;
        case'U':
            update;
            ;
            break;

    }
    count2++;
}

system("pause");
return 0;
}

 float balance(){
    float bal;
    return bal;
  }
  float withdraw(){
    float bal1, bal2;
    if(bal1>bal2){
        return bal1 - bal2;
    }
    else{
        printf("Sorry, you can't withdraw that much");
        return bal1;

}
}
float deposit(){
    float bal1,bal2;
    return bal1 += bal2;
}
float update(){
    float bal;
    return bal*= INTEREST;

}

A: these are wrong
switch (activity){
    case 'B':
        balance;
        ;

....
you mean
switch (activity){
    case 'B':
        balance(); <<<======
        ;

A: You can extract the accounts like this using an array:
float ogAcnts[5] = {0,0,0,0,0}; // original account balances initialized to zero
fscanf(input, "%f%f%f%f%f", &ogAcnts[0], &ogAcnts[1], &ogAcnts[2], &ogAcnts[3], &ogAcnts[4]);

You can have a second array with the new balances if you need to keep the original balances for future reference:
float newAcnts[5] = {0,0,0,0,0}; // initialized to zero, could also be replaced with the original balances

To display the original account balances:
// you can fill in the rest
for(int i=0; i<=4; i++)
{
    printf("%d balance is %.2f\n",i,ogAcnts[i]);
}

You can skip the account balances in the file when scanning, like this:
fscanf(input+5, %d%c%f, &acountNum, &transactionType, &amount); // note these variables don't exist in your code but it's an example of how you could use them

You can then follow this same method to get the remaining transactions. Get the transaction parameters and act on them. Use the arrays to access the balances instead of the file. The first account will be element 0 and ends with account number 5 being in index 4 (zero based). So you will have to follow this pattern. I say that because of how the transactions are labeled with the account number (either starts with 0 or 1). if you are using zero based then it makes it easier to access that account balance in the array. Like this example "2 W 200" if account #2 has 400 in it and you are starting with the first account being account 0, you can pass the account number and amount to your transaction functions like this:
...
newAcnts[accountNum] = ogAcnts[accountNum]-amount; // withdraw example using the variables from above

Note: It would probably be better to just have one running balance for each account unless (like mentioned) you need to know what it was before you started. Because for any additional transactions on the same account you'd want to use newAcnts[accountNum] to have the correct balance of the account. Or before starting any transactions copy the original balances into the new accounts array and only do your transactions on the newAcnts array. Hopefully that makes sense :)
newAcnts[accountNum] = newAcnts[accountNum]-amount; // withdraw example


text:
Q: How to resolve Zend_Acl permission conflict for user with multiple roles? I'm trying to create an RBAC with Zend_Acl.  The question I have is that I want users to be able to have multiple roles, but I'm not sure how to solve permission conflicts between the various roles?  In cases where there is a both an allow and deny, should the allow always override the deny?  As always, thanks a lot for taking out the time to check out my question.  Cheers!

A: Think of it like your home.

*

*deny | person

*deny | anyone from Russia

*allow | family member

*allow | friend

Let's say you have bad feeling about Russians. Would you think, that you should deny your good friend access to your home just because he is a Russian? No. He has proven some quality that granted him the "friend" status. The allow should override the deny IMO.
No offense to the Russians :P

A: you should add role priority to your implementation. If exact resource/privilege pair exists in several roles you will take one on them with highest priority. If none of the roles have exact match - take whatever higher priority role will return.
Another approach is to define user role, like user123
$acl->addRole('user123', array('admin', 'banned'));
I don't know behavior of role with multiple parent roles, so check it out for yourself

A: Security Best practices indicate when there is a conflict issue a denial.
That being said, from practical experience I build security in the following manner (when it comes to RBAC):
Each user has a set of rights; user rights superseded group rights
Each user can have one or more group rights
Each group has a priority level of application; typically admin is applied where the last applied right
I very rarely apply multiple groups to multiple people; and most people that have rights to apply rights can not do this except for the primary admin (instead I make a new group).
I use Negative (groups with Deny rights) VERY sparingly.
Upon applying group rights to a person I have the system check for conflicts and notify the person applying it.
In addition to the standard RBAC roles I also have a flag grant view others, grant edit others, etc.
In addition use many other mechanisms, such as a sha256 session token, use database tables to temporary check for idle sessions + replay attacks, require the person's ip address stays constant, etc.

A: Both variants are fine, the question is what you prefer more? Having "deny" priority higher over "allow" would result in system where single "deny" permission would take the rights away, does not matter what others say or vice versa - having "allow" as higher priority would result that single "allow" would grant permission despite many "denys". So questions is - how strict your system should be?


text:
Q: Keras: fit_generator get much lower accuracy then the evaluate_generator just one line above? I am following the blog for transfer learning:
##First I compute the saved the bottleneck features and build a new model and train it with the bottleneck features:
input_layer = Input(shape=base_model.output_shape[1:])
x = GlobalAveragePooling2D()(input_layer)
x = Dense(512, activation='relu',name='fc_new_1')(x)
x = Dropout(0.2)(x)
x = Dense(512, activation='relu',name='fc_new_2')(x)
x = Dense(num_classes, activation='softmax',name='logit_new')(x)
Add_layers = Model(inputs=input_layer, outputs=x,name='Add_layers')

##Then I put this new model at the end of pretrained models:
base_model = ResNet50(include_top=False, weights='imagenet', input_shape=
(img_shape[0],img_shape[1],3))
x = base_model.output
predictions = Add_layers(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=
['accuracy'])

##Then, I evaluate the model :
score = model.evaluate_generator(train_generator, nb_train_samples //
batch_size_finetuning)
print('The evaluation of the entire model before fine tuning : ')
print(score)
score = model.evaluate_generator(validation_generator, nb_validation_samples
// batch_size_evaluation)
print('The evaluation of the entire model before fine tuning : ')
print(score)

And get training loss and accuracy : [0.015362062912073827, 1.0]
validation loss and accuracy : [0.89740632474422455, 0.75]
##Just one line below it, I trained the new model:
model.fit_generator(train_generator,
                steps_per_epoch= nb_train_samples // batch_size_finetuning,
                epochs=finetuning_epoch,
                validation_data=validation_generator,
                validation_steps=nb_validation_samples //batch_size_evaluation,
                callbacks=[checkpointer_finetuning,
 history_finetuning,TB_finetuning,
lrate_finetuning,Eartly_Stopping_finetuning]);

Then the output is :
31/31 [==============================] - 35s - loss: 3.4004 - acc: 0.3297 - val_loss: 0.9591 - val_acc: 0.7083

Weird thing is: This problem only happens if I use Resnet50 and InceptionV3 but not with vgg16. I am pretty sure that changing the pretrained model is the only difference. I understand that the dropout might make it different but it should not be this large and vgg16 has no obvious problem at all.
Another weird thing is: If I change every layer to be .trainable = False and compile, the validation accuracy will still decrease dramatically. I even checked the weights of every layer and if .trainable = False weights will not change and .trainable = True weights will change.
Any help is appreciated!!! THANKS!!!


text:
Q: Prevent a rollback of an inserted record due to an exception I have a LWC component which calls an apex class that does callout:
public static List<Case> doCallout(List<Case> cases) {
    .......
    CalloutLogger.insertLog(req, res, time);
    ........
    try {
         ....
         if(isFromComponent) throwAuraException(System.Label.CustomException);
         ....
     } catch(Exception e) {
         ....
     }
}

The throwAuraException method:
private static void throwAuraException(String message) {
     AuraHandledException e = new AuraHandledException(message);
     e.setMessage(message);
     throw e;
}

On LWC:
handleSend() {
     sendRequest({caseToSend : this.recordId})
     .catch(error => {
      ......
     }).then(result => {
      ......
     });
}

Inside the CalloutLogger.insertLog(req, res, time); method I am inserting a record of Logger__c. The problem is that when throwAuraException method is called the logger record inserted gets rolledback, due to throwing an exception that is not handled in the Apex code. But the exception is caught in the catch of LWC.
I would like to insert the logger record even if the exception is thrown.

A: Your code is oversimplified (the Apex appears to never throw an exception, thus would always insert the log record), but in general, there are two ways to go about this.
First, you can create a Platform Event with "Publish Immediately" enabled, then call EventBus.publish, with a trigger or Flow on a Platform Event to log the record asynchronously.
try {
  doStuff();
} catch(Exception e) {
  EventBus.publish(createLogEvent(e.getMessage()));
  throw new AuraHandledException(e.getMessage());
}

Second, the method I typically use, is to call another apex function in your catch for which the sole purpose is to log an error.
@AuraEnabled(cacheable=false) public static void logError(String error) {
  insert new Log__c(Message__c=error);
}

...
try {
  let result = await apexMethod1(params);
} catch(e) {
  await logError(e.message);
}

(or...)
 apexMethod1(params)
.then(
   result => { ... }
 )
 .catch(
   error => { logError(error.message); }
 );


text:
Q: SQL Server 2005 Table Alter History Does SQL Server maintains any history to track table alterations like column add, delete, rename, type/ length change etc? I found many suggest to use stored procedures to do this manually. But I'm curious if SQL Server keeps such history in any system tables? Thanks.

A: in SQL Server 2005 and up you can create a database level trigger to track table changes.  Use something like:
CREATE TRIGGER [YourDatabaseTrigger]
ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS

DECLARE @EventData      xml
DECLARE @Message        varchar(1000)
SET @EventData=EVENTDATA()

INSERT INTO YourLogTable
    (EventDateTime,EventDescription)
    VALUES (GETDATE(),SUSER_NAME()
                     +'; '+@EventData.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(250)')
                     +'; '+@EventData.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(250)')
                     +'; '+@EventData.value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
           )
RETURN
GO

ENABLE TRIGGER [YourDatabaseTrigger] ON DATABASE

here is some simple output from the log:
select * from YourLogTable
EventID     EventDateTime           EventDescription
----------- ----------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------
1           2010-04-06 08:25:47.333 sa; TABLE; YourLogTable2; create table YourLogTable2 (EventID int primary key identity(1,1),EventDateTime datetime, EventDescription varchar(max))
2           2010-04-06 08:25:55.113 sa; TABLE; YourLogTable2; drop table YourLogTable2

(2 row(s) affected)

you could expand the log to contain more columns, or just dump everything within a one like in this simple example.

A: The transaction logs store all this information and the DBCC LOG command should let you view that, but it's an undocumented command.
DBCC LOG(<database name>[,{0|1|2|3|4}])
0 – Basic Log Information (default)
1 – Lengthy Info
2 – Very Length Info
3 – Detailed
4 – Full Example

Syntax:
DBCC log (MY_DB, 4)

A: This kind of information is not retained in any RDBMS by default because it could increase the required storage requirements by orders of magnitude, and could severely decrease performance.
Triggers can do this for you. Triggers are not considered manual method - they are a core part of database design.


text:
Q: jquery Ajax doesn't show any message(neither success nor failure) I want to submit a form with jquery Ajax. But it does not show any kind of message. I have followed this question and this question. But I didn't get my solution. My jquery code is:
$(document).ready(function () {

  $("#btnSave").submit(function (e) {

    e.preventDefault();

    var myTableArray = [];

    $("table#vouchTable tr").not(':first').each(function () {
        var arrayOfThisRow = [];
        var tableData = $(this).find('td');
        if (tableData.length > 0) {
            tableData.each(function () { arrayOfThisRow.push($(this).text()); });
            myTableArray.push(arrayOfThisRow);
        }

   }); ///This Part works fine

    ///But this part does not work

    $.ajax({
        url: '/Accounts/VoucherEntry',
        type: 'POST',
        data: JSON.stringify(myTableArray),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',

        success: function (msg) {
            alert(msg);
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }

    });

    return false;

    ////////////////////

  });
});

A: Try this:
Missing end brackets for : $(document).ready(function () {
Missing end brackets for : $("#btnSave").submit(function (e) {
   $(document).ready(function () {

      $("#btnSave").submit(function (e) {

        e.preventDefault();

        var myTableArray = [];

        $("table#vouchTable tr").not(':first').each(function () {
            var arrayOfThisRow = [];
            var tableData = $(this).find('td');
            if (tableData.length > 0) {
                tableData.each(function () { arrayOfThisRow.push($(this).text()); });
                myTableArray.push(arrayOfThisRow);
            }

       });

       var data = JSON.stringify(myTableArray);
        $.ajax({
            url: '/Accounts/VoucherEntry',
            type: 'POST',
            data: data,
            dataType: 'json',

            success: function (msg) {
                alert(msg);
            },
            error: function (xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                alert(err.Message);
            }

        });
     });  // <-----  Missing brackets!!!
  });    //  <-----  Missing brackets!!!

A: Format you data like:
data: {data:myTableArray},

in c# get the data by the key data