text:
Q: Out of memory when reading a gif file in wpf (C#) I wrote a control read gif file using c# as follows:
public class AnimatedGIFControl : System.Windows.Controls.Image
    {

    public static readonly DependencyProperty IsPlayProperty = DependencyProperty.Register("IsPlay", typeof(bool), typeof(AnimatedGIFControl), new UIPropertyMetadata(false, new PropertyChangedCallback(OnIsPlayChanged)));

    public bool IsPlay
    {
        get
        {
            return (bool)this.GetValue(IsPlayProperty);
        }
        set
        {
            this.SetValue(IsPlayProperty, value);
        }
    }

    private static void OnIsPlayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if((bool)e.NewValue)
        {
            (d as AnimatedGIFControl).StartAnimate();
        }
        else
        {
            (d as AnimatedGIFControl).StopAnimate();
        }
    }

    public static readonly DependencyProperty GifSourceProperty = DependencyProperty.Register("GifSource", typeof(string), typeof(AnimatedGIFControl), new UIPropertyMetadata(null, new PropertyChangedCallback(OnGifSourceChanged)));

    public string GifSource
    {
        get
        {
            return (string)this.GetValue(GifSourceProperty);
        }
        set
        {
            this.SetValue(GifSourceProperty, value);
        }
    }

    private static void OnGifSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        (d as AnimatedGIFControl).AnimatedGIFControl_Loaded();
    }

    private Bitmap _bitmap; // Local bitmap member to cache image resource
    public delegate void FrameUpdatedEventHandler();

    /// <summary>
    /// Delete local bitmap resource
    /// Reference: http://msdn.microsoft.com/en-us/library/dd183539(VS.85).aspx
    /// </summary>
    [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool DeleteObject(IntPtr hObject);

    /// <summary>
    /// Override the OnInitialized method
    /// </summary>
    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);
        this.Unloaded += new RoutedEventHandler(AnimatedGIFControl_Unloaded);
    }

    /// <summary>
    /// Load the embedded image for the Image.Source
    /// </summary>
    public void AnimatedGIFControl_Loaded()
    {
        _bitmap = new Bitmap(Application.GetResourceStream(new Uri(@"pack://application:,,,/" + this.GifSource)).Stream);
        Source = GetBitmapSource(_bitmap);
        if (this.IsPlay && _bitmap.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
        {
            StartAnimate();
        }
    }

    /// <summary>
    /// Close the FileStream to unlock the GIF file
    /// </summary>
    private void AnimatedGIFControl_Unloaded(object sender, RoutedEventArgs e)
    {
        StopAnimate();
    }

    /// <summary>
    /// Start animation
    /// </summary>
    public void StartAnimate()
    {
        ImageAnimator.Animate(_bitmap, OnFrameChanged);
    }

    /// <summary>
    /// Stop animation
    /// </summary>
    public void StopAnimate()
    {
        ImageAnimator.StopAnimate(_bitmap, OnFrameChanged);
    }

    /// <summary>
    /// Event handler for the frame changed
    /// </summary>
    private void OnFrameChanged(object sender, EventArgs e)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle,
                               new FrameUpdatedEventHandler(FrameUpdatedCallback));
    }

    private void FrameUpdatedCallback()
    {
        ImageAnimator.UpdateFrames();

        if (Source != null && Source.CanFreeze)
        {
            Source.Freeze();
        }

        // Convert the bitmap to BitmapSource that can be display in WPF Visual Tree
        Source = GetBitmapSource(_bitmap);
        InvalidateVisual();
    }

    private BitmapSource GetBitmapSource(Bitmap bitmap)
    {
        IntPtr handle = IntPtr.Zero;
        BitmapSource bitmapSource = null;

        try
        {
            handle = bitmap.GetHbitmap();
            bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        }
        finally
        {
            if (handle != IntPtr.Zero)
            {
                DeleteObject(handle);
            }
        }
        return bitmapSource;
    }

}

I use it in wpf as follows:
<customControl:AnimatedGIFControl x:Name="faultImage" HorizontalAlignment="Center" VerticalAlignment="Center"
                              IsPlay="True"
                              GifSource="Images/RouteWindow/BigFaultReportImage.gif"/>

I let applications run 24 hours, rising on a 1GB memory.
If it was because I forgot to clean up the memory or not?
I don't know why. Please, help me!

A: I think the problem is that you create a bitmap every frame update and you never call garbage collector. Did you tried to call GC.Collect(); after InvalidateVisual();    ?


text:
Q: Write each of these functions as a sum of an even and an odd function.. Write each of these functions as a sum of an even and an odd function:

*

*$f(x) = x^3 + x^6$
I am aware the formula is $\frac12(f(x) + f(-x)) + \frac12(f(x) - f(-x))$
but when subbing in $f(x) = x^3 + x^6$ and $f(-x) = - x^3 + x^6$ I just get my original question $x^6 + x^3$ as the answer. am i going wrong? please can someone explain

A: The even function is $$f_{even}=\frac{f(x)+f(-x)}{2}=x^6$$
The odd function is $$f_{odd}=\frac{f(x)-f(-x)}{2}=x^3$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting a FieldLookupValue from Sharepoint in Powershell Looking on the net I came up with this 2 functions to request Sharepoint using this 3 DLL with powershell :
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Taxonomy.dll
Microsoft.SharePoint.Client.Runtime.dll

This function is used to get all items from a list
Function Get-ListItems([Microsoft.SharePoint.Client.ClientContext]$Context, [String]$ListTitle) {
    $list = $Context.Web.Lists.GetByTitle($listTitle)
    $qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
    $items = $list.GetItems($qry)
    $Context.Load($items)
    $Context.ExecuteQuery()
    return $items
}

And this one to work the list :
Function getChangeListsFromSharepoint(){
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
    $items = Get-ListItems -Context $context -ListTitle $listName
    foreach($item in $items)
    {
        /** Working HERE **/
    }
    $context.Dispose()
}

Now when I'm displaying all item content using Write-Host $item.Fields I've got something like this :
[Title,"blabla"]
...
[SpecialField,Microsoft.SharePoint.Client.FieldLookupValue[]]
[OtherField,Microsoft.SharePoint.Client.FieldLookupValue]

I'm trying to get the value of SpecialField and OtherField. To do so I'm using $item["SpecialField"].LookupValue. And I've got no problem. But when I'm doing it on OtherField the value is empty. If I try to use $item["OtherField"].LookupID the value is not empty and I've got an ID. How can I get the value behind this ID ? What's the difference between FieldLookupValue[] and FieldLookupValue ?

A: FieldLookupValue[] is a multi-value lookup column.
It has property Allow multiple values set to true and contains an array of items.

So, $item["OtherField"].LookupValue will not work here, you need to iterate it over as below:
#multi-value lookup
$mvLookup = [Microsoft.SharePoint.Client.FieldLookupValue[]] $item["OtherField"]

$mvLookup |% { "Lookup Value: $($_.LookupId):$($_.LookupValue)" }

which results in values as below:

FieldLookupValue is a single value lookup column. It has the Allow multiple values set to false and contains a single item. So, $item["SpecialField"].LookupValue will work here

A: So the solution was easy : my user didn't had the rights to explore the (field)list because it was from a (sharepoint)list on wich he didn't had any rights. What is strange is that on the website the value was visible but it's not when using powershell.


text:
Q: Printing meters squared in R I wish to print meters squared in R but I'm not having success.
This is an example of the code I am working on:
bmi <- c(24,28,31)
print(paste0("Your body mass index is ", bmi, "kg/m^2"))
# [1] "Your body mass index is 24kg/m^2"
# [2] "Your body mass index is 28kg/m^2"
# [3] "Your body mass index is 31kg/m^2"

Suggestions?

A: You can just use the UTF-8 Character "SUPERSCRIPT TWO", ² (see here).
If you properly encoded your R script (or directly enter into the terminal), it'll work just fine.
If you don't have this option (or you can't type this letter), use the \u escape sequence: \u00B2
bmi <- c(24,28,31)
cat(paste0("Your body mass index is ", bmi, "kg/m²"), sep = "\n")
cat(paste0("Your body mass index is ", bmi, "kg/m\u00B2"), sep = "\n")
# Your body mass index is 24kg/m²
# Your body mass index is 28kg/m²
# Your body mass index is 31kg/m²

Newer R versions allow you to specify the file encoding with source, so that would be
source("myFancyScript.R", encoding = "UTF-8")


text:
Q: Creating a curve envelope (non-signal appliaction) I'm working on developing a transportating engineering tool called a swept path analyzer.  Briefly, as a vehicle turns at a roadway intersection, it may steer in a simple arc, but the body moves in a more complex fashion, as described in  Ackermann Steering theory.
The tool I'm using implements Ackermann Steering and generates the 'tracks' a given vehicle creates as it moves through a curve.  These tracks correlate to specific points on the vehicle: the path the center of the vehicle follows, the paths the wheels themselves follow, and the paths the outermost points on the vehicle follow (usually the outside corners).
As I work on my own implementation, I'm faced with the issue of generating a total vehicle 'envelope' which describes the path taken by the outermost point of the vehicle as it makes it's turn at every point along it's turning path.  This generates a complex shape comprised of several arcs and lines.
I'm familiar with signal envelope theory and the mathematical approach.  However, I feel that would be unnecessarily complex and a better approach would be generating the envelope from the points of the vehicle sampled as the vehicle is driven along it's turning path.
This seems like a boundary problem that I've seen solutions for in game development, and I could pursue that avenue, but as I look at this, it makes me think there has to be a simpler approach - perhaps I'm not looking at the problem correctly.
The images below provide a little visual context:


text:
Q: Check key, value of nested dictionary in python? I'm generating a nested dictionary in  my program. After generating, I want to iterate through that dictionary, and check for the dictionary key and value.
Program-Code
This is the dictionary I want to iterate whose value contains another dictionary.
 main_dict = {101: {1234: [11111,11111],5678: [44444,44444]},
              102: {9100: [55555,55555],1112: [77777,88888]}}

I'm reading a csv file and storing contents in this dictionary. Like this :
Input.csv -
 lineno,item,total
 101,1234,11111
 101,1234,11111
 101,5678,44444
 101,5678,44444
 102,9100,55555
 102,9100,55555
 102,1112,77777
 102,1112,88888

This is input csv file. I'm reading this csv file and I want to know for one unique item total is how many times repeating?
For that stuff I'm doing like this :
for line in reader:
                if line[0] in main_dict:
                    if line[1] in main_dict[line[0]]:
                        main_dict[line[0]][line[1]].append(line[2])
                    else:
                        main_dict[line[0]].update({line[1]:[line[2]]})
                else:
                    main_dict[line[0]] = {line[1]:[line[2]]}

print main_dict

Output of above program :
 {101: {1234: [11111,11111],5678: [44444,44444]},
  102: {9100: [55555,55555],1112: [77777,88888]}}

but I'm facing following error in this line-
 if line[1] in main_dict[line[0]]:
 IndexError: list index out of range

Iteration of main_dict-
 for key,value in main_dict.iteritems():
            f1 = open(outputfile + op_directory +'/'+ key+'.csv', 'w')
            writer1 = csv.DictWriter(f1, delimiter=',', fieldnames = fieldname)
            writer1.writeheader()
            if type(value) == type({}):
                for k,v in value.iteritems():
                    if type(v) == type([]):
                        set1 = set(v)
                        for se in set1:
                           writer1.writerow({'item':k,'total':se,'total_count':v.count(se)})

I want to know best way to iterate this type of dictionary?
Sometimes I'm getting correct result just like above dictionary but many a times I face this error, what is that I'm missing?
Thanks in advance!

A: As the comments pointed out, you are not checking if line is of length 3:
for line in reader:
    if not len(line) == 3:
        continue

Concerning your algorithm, I would use nested defaultdict to avoid the if/else lines.
EDIT: I added a new defaultdict and the csv writing part after the question edit:
from collections import defaultdict
import csv

counter = defaultdict(lambda: defaultdict(list))
main_dict= defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))
fieldnames=['item', 'total', 'total_count']

# we suppose reader is a cvs.reader object
with open('input.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for line in reader:
        if not len(line) == 3:
            continue
        # Remove unwanted spaces
        lineno, item, total = [el.strip() for el in line]
        # Do not deal with non digit entries (title for example)
        if not lineno.isdigit():
            continue
        counter[lineno][item].append(total)
        csvdict = {'item': item,
                   'total': total,
                   'total_count': counter[lineno][item].count(total)}
        main_dict[lineno][item][total].update(csvdict)

# The writing part
for lineno in sorted(main_dict):
    itemdict = main_dict[lineno]
    output = 'output_%s.csv' % lineno
    with open(output, 'wb') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',')
        writer.writeheader()
        for totaldict in itemdict.values():
            for csvdict in totaldict.values():
                writer.writerow(csvdict)

You can then use the following function to print a readable representation of the result:
def myprint(obj, ntab=0):
    if isinstance(obj, (dict, defaultdict)):
        for k in sorted(obj):
            myprint('%s%s'%(ntab*' ', k), ntab+1)
            myprint(obj[k], ntab+1)
    else:
        print('%s%s'%(ntab*' ', obj))
myprint(main_dict)

But if you want to count the item totals, I would use another defaultdict with the total as the key and a tuple (lineno, item) as the value:
from collections import defaultdict
import csv

total_dict = defaultdict(list)

# we suppose reader is a cvs.reader object
with open('input.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for line in reader:
        if not len(line) == 3:
            continue
        # Remove unwanted spaces
        lineno, item, total = [el.strip() for el in line]
        # Do not deal with non digit entries (title for example)
        if not lineno.isdigit():
            continue
        total_dict[total].append((lineno, item))

You can have the number of each total very easily:
>>> print len(total_dict['55555'])
2


text:
Q: Call np.sqrt in cython %%cython
import numpy as np
cimport numpy as np

def cy_sum(int n):
    cdef double s=0
    cdef int i
    for i in range(n):
        s += np.sqrt(i)
    return s

I have the code for calculating the sum of square root as above.
By using cython -a, I got the result as in the picture.
The cython code interacts with python at function call np.sqrt(i), and there is no improvement compared to pure python code.
I don't know if I have done something wrong in specifying the type of variables.
There are other solutions, such as using i**(1/2) or import the function sqrt from clib, but I would like to understand why cython cannot compile np.sqrt in this case.
Thank you.

A: In general, when Cython sees a python function call, it is treated as an opaque operation.  Cython might elide a bit of calling overhead, but otherwise it will generate the exact same semantics as if that function was called from python.
Certain numpy constructs, such as the ndarray[dtype] type are special cased by the Cython compiler to generate more efficient code.  numpy ufuncs are not, so to cython np.sqrt is just another python function, so it can do nothing better than calling back into python to run it.
Other python accelerators, such as numba will intercept the call to np.sqrt and rewrite it to the equivalent low level code.


text:
Q: Columns with a Right Parenthesis I want to arrange my frame as shown in the attached figure. However, despite the idea, I don't know how to do that. Please help me out.
The left and right columns need not be framed. I used frames here for a better understanding of what I want to achieve.

A: Which solution to choose heavily depends on the context in which you wish to use such an arrangement. Since this was not clear to me, I opted for a very customizable variant using the tcolorbox package:
\documentclass{article}

\usepackage{tcolorbox}
\tcbuselibrary{skins}
\usetikzlibrary{decorations.pathreplacing}

\usepackage{lipsum}

\newtcolorbox{twocolbox}[1]{
    empty,
    left*=0pt,
    right*=25pt,
    sidebyside,
    sidebyside align=top,
    sidebyside gap=15pt,
    overlay={
        \draw[decorate, decoration={brace}]
            ([xshift=-15pt, yshift=-10pt]frame.north east) --
            ([xshift=-15pt, yshift=10pt]frame.south east)
            node[midway, xshift=10pt, rotate=-90, font=\large] {#1};
    }
}

\begin{document}

\lipsum[3]

\begin{twocolbox}{Methods}

Random Text in Left Column

\lipsum[1]

\tcblower

Random Text in Right Column

\lipsum[2]

\end{twocolbox}

\lipsum[3]

\end{document}

Since you can use the full scope of TikZ magic here, it is easy to color the brace or draw it thicker or make it look more like the braces in math mode (for this you also need to load the calligraphy library):
\usetikzlibrary{decorations.pathreplacing, calligraphy}

% [...]

\newtcolorbox{twocolbox}[1]{
    empty,
    left*=0pt,
    right*=25pt,
    sidebyside,
    sidebyside align=top,
    sidebyside gap=15pt,
    overlay={
        \draw[decorate, decoration={calligraphic brace}, pen colour={blue}, very thick]
            ([xshift=-15pt, yshift=-10pt]frame.north east) --
            ([xshift=-15pt, yshift=10pt]frame.south east)
            node[midway, xshift=10pt, rotate=-90, font=\large] {#1};
    }
}

A: Here's a solution that uses side by side minipage environments. The first (outer) minipage contains a second pair of side by side "inner" minipages, which contain the itemized lists. The second outer minipage serves to house the rotated string "Methods".

\documentclass{article} % or some other suitable class
\usepackage{ragged2e} % for \RaggedRight macro
\usepackage{enumitem} % for \newlist and \setlist macros
\newlist{myitemize}{itemize}{1} % create a bespoke itemize-like list env.
\setlist[myitemize,1]{label=\textbullet,left=0pt,nosep,
            before={\begin{minipage}[t]{\linewidth}\RaggedRight},
            after={\strut\end{minipage}}}
\usepackage{graphicx} % for \rotatebox macro
\usepackage{lipsum}   % filler text

\begin{document}
\hrule % just to illustrate width of text block
\begin{center}
$\left.
\begin{minipage}{0.7\textwidth}     % outer minipage (choose a suitable width)
%% sum of widths of two "inner" minipages and of \hspace instr. should equal `1\linewidth`.
\begin{minipage}[t]{0.5\linewidth}  % first inner minipage
\begin{myitemize}
\item \lipsum[2][1-3] % filler text
\item \lipsum[3][1-3] % more filler text
\end{myitemize}
\end{minipage}%                     % end of first inner minipage
\hspace{0.05\linewidth}%
\begin{minipage}[t]{0.45\linewidth} % second inner minipage
\begin{myitemize}
\item \lipsum[3][1-3]
\item \lipsum[2][1-3]
\end{myitemize}
\end{minipage}%                     % end of second inner minipage
\end{minipage}                      % end of outer minipage
\hspace{1em}
\right\}$
\hspace{1em}
\begin{minipage}{0.04\textwidth}    % encase \rotatebox instruction in another minipage
\rotatebox{-90}{\huge Methods}
\end{minipage}
\end{center}
\end{document}

A: You should define your own environment, in order not to pollute the document with raw code. Choose a better name than foo.
\documentclass{article}
\usepackage{graphicx}

\usepackage{lipsum}

\newsavebox{\foobox}
\newlength{\foowidth}
\newlength{\foowidthaux}
\newenvironment{foo}[1]
 {%
  \begin{flushleft}
  \sbox{\foobox}{\rotatebox[origin=Bc]{-90}{\LARGE#1}}%
  \settowidth{\foowidthaux}{%
    $\Biggr\rbrace\,\usebox{\foobox}$%
    \hspace{2\arraycolsep}%
  }%
  \setlength{\foowidth}{\dimexpr(\textwidth-\foowidthaux)/2\relax}%
  $\left.\kern-\nulldelimiterspace
  \begin{array}{@{}ll@{}}
  \begin{minipage}[t]{\foowidth}
 }
 {%
  \end{minipage}
  \end{array}
  \right\rbrace\!\usebox{\foobox}$
  \end{flushleft}
 }
\newcommand{\changecolumn}{\end{minipage}&\begin{minipage}[t]{\foowidth}}

\begin{document}

\lipsum[2]

\begin{foo}{Methods}
\lipsum[3][1-6]
\changecolumn
\lipsum[4]
\end{foo}

\lipsum[5]

\end{document}

I save the part to be rotated, so I can measure it, together with a couple of adjustments, so I can compute the width for the two minipages. They are top aligned inside an array, so \right\rbrace can do the right thing and cover the whole thing, independent of the text in the two minipages.
The \changecolumn command provides the end for the left minipage, the alignment character and the begin for the right minipage.


text:
Q: Makefile target name compared to string In a makefile I'm trying to compare the target name with a string, and depending on this set a variable with a string or another.
This example illustrates what I'm trying to do:
ifeq ($@,"Target_A")
 THE_PATH="Path_a"
 THE_TARGET=$@
else
 THE_PATH="Path_b"
 THE_TARGET=$@
endif

Target_A:
    @echo $(THE_PATH)
    @echo $(THE_TARGET)

Target_B:
    @echo $(THE_PATH)
    @echo $(THE_TARGET)

This is the output when I call make passing Target_A and when I call it passing Target_B:
$ make Target_A
Path_b
Target_A

$ make Target_B
Path_b
Target_B

The fact that I always get "Path_b" indicates the ifeq always evaluates to false, but you can see that $@ contained the right string.
Why doesn't this work?

A: You probably want target-specific variables:
Target_A: THE_PATH="Path_a"
Target_A:
    @echo $(THE_PATH)

Since contents of a (regular) variable are expanded each time it's used, THE_TARGET=$@ can be made global.

Target-specific variables are only accesible in a target they belong to, and its dependencies.
Normally this is enough, but if you need to have global variables, you can use the same code you have in the question, with the condition changed to this:
ifneq ($(filter Target_A,$(MAKECMDGOALS)),)

$@ (which you tried to use) only works inside of a recipe, and expands to a target name that the recipe builds.
$(MAKECMDGOALS) is a global variable that contains all targets specified (as command-line parameters) when invoking make.
This option will only work if the target you're looking for was specified as a command-line parameter.


text:
Q: RSpec & Database Cleaner - Keep certain objects permanently in the test database I have (belatedly) started testing my Rails app (a shopping website) with RSpec/capybara, using database cleaner to clear the database and Factory Girl to generate new objects for every test (like most people do). This works fine, and I do think it is a good idea to clear the data between tests.
However, it can get slow and (as far as I can figure out) a bit tedious to generate multiple instances of the same object. There are some objects that are always the same in my database, or that I will always generate an identical copy of for testing. For example, my Package model, which defines the pricing and feature limits for a subscription package. It will probably never change.
Is there a way, with this configuration (please comment and specify if you require more info), to put certain instances of objects in the test database and exclude them from Database Cleaner, or any other way to keep permanent copies of specific objects in your test database?
This is mainly to increase testing speed.

A: If you have database objects that your application never changes, and that are the same in your production and development databases as well as in your test databases, the right thing to do is to make them seeds. Create them in db/seeds.rb. More on seeds here: http://guides.rubyonrails.org/active_record_migrations.html#migrations-and-seed-data
If the objects that you're talking about only belong in your test database, you could make them Rails fixtures. More on fixtures here: http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures (Beware, though, that fixtures are usually a bad idea, because they make your tests harder to read and encourage you to write tests around existing fixtures, which leads to an entangled mess. Test clarity and robustness is more important than speed.)
If you're using Database Cleaner's truncation or deletion strategy (probably because you're using a Javascript-capable driver with Capybara), and you've used either of the foregoing methods to leave data in your test database between tests, you can tell Database Cleaner to not empty specific tables:
DatabaseCleaner.strategy = :truncation, {:only => %w[widgets dogs some_other_table]}

or
DatabaseCleaner.strategy = :truncation, {:except => %w[widgets]}

(Source: https://github.com/bmabey/database_cleaner#how-to-use) I don't know of a way to tell Database Cleaner to delete some instances of a given class and not others, however.


text:
Q: How can I refactor this code in javascript? I have this code and I need to refactor that

I tried creating a new function and passing it through reduce but It doesn't work

function fx(n) {
  let d= (new Array(n+1)).join('x').split('').reduce((d,v,i)=>{
  let J=2*i+1+(i&1)
  return d += J+(J+1-2*i+1)
  },-1-Math.floor(n/2) * 2);
  return d-(n-2);
};

A: This is what it should be doing.
const squareIncrement = number => Math.pow(Math.abs(number) + 1, 2);


text:
Q: How to get the current row index in a dynamic table? C# / ASP.NET MVC I have a table displaying object elements from a dynamic list, hence the table should be able to grow and shrink in size, as the user sees fit. How would i be able to get the specific row index?
I basically have a shopping cart, with price, quantity, name and so forth. And lastly, a delete button, that when clicked should delete the current row. So i need to be able to associate the current list element with its respective delete button.
Below is my table:

                Product
                Quantity
                Price
                Total
                Remove

            @foreach (var itemList in Model)
            {

                    @itemList.Name
                    @itemList.Quantity
                    @itemList.Price
                    @itemList.Total
                    <button class="btn-dark">Delete</button>

            }

Would there be a way to give the delete button, 'btn-dark' , a dynamic id that increments/decrements as the table grows/shrinks?

A: Assuming Model is a List you can do:
@for (int i = 0; i < Model.Count; i++){
    var itemList = Model[i];
    ....
    <button id="Delete@(i)" class="btn-dark">Delete</button>
    ....
}

Generates:
<button id="Delete1" class="btn-dark">Delete</button>
<button id="Delete2" class="btn-dark">Delete</button>
<button id="Delete3" class="btn-dark">Delete</button>
...

Another option less efficient in terms of performance but requiring less code it's using IndexOf() to get the index of an element. If Model is IEnumerable<T> you need to cast it as a List first.

A: Looks like your dynamic list is been passed into the view so why not have the Unique ID created before you pass it in?
You can then bind it something like below and call a action in the controller passing the ID(or modify to use AJAX or call JS function)
Delete

You can then bind that unique ID to the delete button and do what you want with it.

A: Without changing your foreach loop I would have done something like this:

                Product
                Quantity
                Price
                Total
                Remove

            var model = Model.ToList();
            @foreach (var itemList in model)
            {
                @{
                  var index = model.IndexOf(itemList);
                 }

                    @itemList.Name
                    @itemList.Quantity
                    @itemList.Price
                    @itemList.Total
                    <button data-delete-id="@index" class="btn-dark">Delete</button>

            }

Then you'd use JQuery to retrieve the data-delete-id parameter value on click of the button and remove the item from the table.

A: You can simply remove the row from the table using closest function of jquery.
$(".customTable").on('click', '.delete', function (event) {
   $(this).closest(' tr').remove();
});

For the above code your delete button should contain the delete class.
<button class="btn-dark delete">Delete</button>


text:
Q: Xamarin Froms Android phone camera not opening I create xamarin forms where it takes a photo from camera but when i click camera open button it not open the camera. My code is here "https://github.com/Malith1994124/Kiosk/blob/master/Kiosk_V2/Kiosk_V2/Helpers/Utilities.cs" and i gave all required permissions in android section.
Can someone please help me. I am new to xamarin and um stuck here more than 1 week now.

A: Try this: set CrossCurrentActivity.Current.Init(this, bundle); on your MainActivity.cs OnCreate Method.
The CurrentActivity Plugin is a dependency for CrossMedia Plugin and if it didn't create a MainApplication.cs file, you must configure it yourself, and at the minimum, you need that method call.


text:
Q: Scifi book where all human knowledge is stored in some kind of encrypted device - passwords are lost I'm looking for a book I've never read that was mentioned in passing in an IT article about encryption.  It is a sci-fi post human (?) piece of fiction where all human knowledge of everything has been stored in some kind of electronic device.  However, no one can retrieve the valuable knowledge inside as the password(s) have been lost.
I have no idea how it ends or starts.  I've tried googling the plot line and ended up at this site.

A: While it isn't a password that is lost, the classic SF story "Twilight" by John Campbell has some of those elements.
A time travel visits the far future, and finds that men live in a world run by perfect machines, but they can't understand them because the language they use has changed over vast time.

"What is its end? I have seen it -- almost. I saw them -- the little
  men -- bewildered -- lost. And the machines. Must it be -- can't
  anything sway it?
"Listen -- I heard this song."
He sang the song. Then he didn't have to tell me about the people. I
  knew them. I could hear their voices, in the queer, crackling,
  un-English words. I could read their bewildered longings. It was in a
  minor key, I think. It called, it called and asked, and hunted
  hopelessly. And over it all the steady rumble and whine of the
  unknown, forgotten machines.
The machines that couldn't stop, because they had been started, and
  the little men had forgotten how to stop them, or even what they were
  for, looking at them and listening -- and wondering. They couldn't
  read or write any more, and the language had changed, you see, so that
  the phonic records of their ancestors meant nothing to them.


text:
Q: MIPS - create a delay that "regulates" an 80MHz processor down to 1Hz we got a task to implement a delay into a "running light" program. What i mean with that is, that we have a processor running at 80MHz but it should only output the light at a frequency of 1Hz. So I thought to implement a delay of 80.000 operations so that every 80.001 would be the light. And here is my try for that:
delay80M:
    li a0, 5000
    loopdelay:
    addi    a0, a0, -1
    nop
    addiu   sp, sp, -8 // Beispiel zur Stackverwendung (hier eigentlich nicht erforderlich)
    nop
    sw      s0, (sp)
    nop
    sw      s1,4(sp)
    nop
    lw      s1,4(sp)
    nop
    lw      s0, (sp)
    nop
    addiu   sp, sp, 8
    bgtz    a0, loopdelay
    jr      ra
    nop

Yet I'm not too sure if this is the most optimal way. Thanks in advance and have a nice day :)

A: Your approach looks like it will work, but it wastes a lot of power.
If you can setup a timer that interrupts the CPU once a second, you can use the MIPS WAIT instruction to stop the processor until the timer interrupt is received.


text:
Q: Get Controller from ControllerContext Asp Core Im upgrading my .NET Framework project to .NET Core. I have a line of code in a BaseModel class ControllerContext.Controller as Controllers.BaseController;
ControllerContext in .NET Core doesnt seem to have .Controller anymore. Is there anyway to access this in Core?


text:
Q: Prove that all numbers have a unique reciprocal I'm learning logic for computer science and came across the question:

If $\ n$ is a real number, $\frac{1}{n}$ is the reciprocal of $\ n$. Prove that all
  numbers have a unique reciprocal.

I came up with the following method, but it seems so simple that I doubt it'll work:
$\frac{1}{n}=p$
Since we know that $\ n=ℝ$, and we assume that $\ p=$ the unique reciprocal, but will this work when proving all real numbers have unique reciprocals?

A: Your conclusion is false. Not all $x\in\mathbb{R}$ has reciprocal. $0$ as no reciprocal.
To show unicity.
If $a\ne 0$ then $a^{-1}a=aa^{-1}=1$. If $a$ had another reciprocal $b$ such that $ab=1$ then left multiply by $a^{-1}$ you get $a^{-1}ab=a^{-1}$ hence $b=a^{-1}$. Same procedure for $ba=1$ right multiply etc
I assumed for granted associativity

A: The way to prove that a certain property is uniquely satisfied, is to assume that two things satisfy and then prove that they are equal.
In this case, suppose that $p,q$ are both reciprocals of $n$.  Then, $qn=1=pn$.  We divide both sides by $n$ (which needs to be nonzero) to conclude that $p=q$.
Now, this doesn't prove existence; i.e. there might be no reciprocal for $n$ at all.  Indeed this is true for $n=0$; without considering this exception the problem is false as written.


text:
Q: twisted server cannot connect over internet I have written server (I've used python 3, twisted, tkinter) and everything is Okay when I try to connect to it on my local machine, for example via telnet I do so - "telnet localhost port", but when I try this "telnet ip_address port" it's not going to be connected. Question is why? And to simplify this, here's simple code:
from twisted.internet import reactor, protocol

class Echo(protocol.Protocol):

    def dataReceived(self, data):
        self.transport.write(data)

def main():
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(8123, factory)
    reactor.run()

if __name__ == '__main__':
    main()

A: Here is an overview of what needs to be done. To start things off, you have to bind to an interface other than localhost. Alternatively, you can listen on all interfaces (ie. interface = '0.0.0.'). In your code, you need to append the interface to your reactor.listenTCP() function:
reactor.listenTCP(8123, factory, interface='0.0.0.0')

Next you will have to ensure incoming TCP traffic is permitted on your router and server. You will also have to forward traffic from your incoming WAN interface from your router to the interface on your server. On the server side, you'll have to ensure incoming traffic is permitted by your firewall(s). So let's say your WAN IP address provided by your ISP is 72.10.20.30 and your Twisted server is running on server's interface 192.168.1.100:8123. Go onto your router and look for Port Forward or NAT functions then set them so that requests for your WAN IP are forwarded to your server's IP.
Take extra precautions with these steps as this can leave your network very vulnerable! It's probably better to use services like OpenShift or Heroku to host your Python projects.


text:
Q: htaccess redirection with exclusion Here is my .htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/index.php$
RewriteCond %{QUERY_STRING} ^$
RewriteCond %{HTTP_REFERER} !^http://shop.com/index.php?controller=authentication&back=my-account [NC]
RewriteRule (.*) http://shop.com/index.php?id_category=12&controller=category [R=301,L]

I want :

*

*my index.php to be redirected to index.php?id_category=12&controller=category.

*override this redirection if the Referer is equal to http://shop.com/index.php?controller=authentication&back=my-account
It seems the third RewriteCond, which is supposed to create the exception, doesn't match the request to index.php when the Referer is equal to http://shop.com/index.php?controller=authentication&back=my-account. As a result, the RewriteRule is taken into account, whereas it shouldn't.
This behavior makes me think %{HTTP_REFERER} doesn't include params in URL (in this case: id_category=12&controller=category).

A: It does. You just have to escape the question mark. Try this:
RewriteCond %{HTTP_REFERER} !^http://shop.com/index.php\?controller=authentication&back=my-account [NC]


text:
Q: add product to cart programmatically not working WooCommerce I am trying the add the product to cart programmatically through rest api. I followed this code to add product to the cart through rest api.
but the products are not adding to the cart. cart gives empty array as the response.
How to solve this.
include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
include_once WC_ABSPATH . 'includes/wc-notice-functions.php';
include_once WC_ABSPATH . 'includes/wc-template-hooks.php';
global $wpdb;
 $response = array();
 $result=array();
 $parameters = $request->get_json_params(); // to get json type data
 $user_id = $parameters['user_id'];
WC()->session = new WC_Session_Handler();
WC()->session->init();

$wc_session_data = WC()->session->get_session($user_id);

// Get the persistent cart may be _woocommerce_persistent_cart can be in your case check in user_meta table
$full_user_meta = get_user_meta($user_id,'_woocommerce_persistent_cart_1',true);
WC()->customer = new WC_Customer($user_id, true );
// create new Cart Object
WC()->cart = new WC_Cart();
// return $full_user_meta;
// Add old cart data to newly created cart object
if($full_user_meta['cart']) {
    foreach($full_user_meta['cart'] as $sinle_user_meta) {
        WC()->cart->add_to_cart( $sinle_user_meta['product_id'], $sinle_user_meta['quantity']);
    }
}

  WC()->cart->add_to_cart($parameters['product_id'],$parameters['quantity']);

$updatedCart = [];

foreach($cartobj->cart_contents as $key => $val) {
    //unset($val['data']);
    $updatedCart[$key] = $val;
    $updatedCart[$key]['file'] = "hello file here";
}

// If there is a current session cart, overwrite it with the new cart
if($wc_session_data) {
    $wc_session_data['cart'] = serialize($updatedCart);
    $serializedObj = maybe_serialize($wc_session_data);
    $table_name = 'wp_woocommerce_sessions';

    // Update the wp_session table with updated cart data
    $sql ="UPDATE $table_name SET 'session_value'= '".$serializedObj."', WHERE  'session_key' = '".$user_id."'";

    // Execute the query
    $rez = $wpdb->query($sql);
}

// Overwrite the persistent cart with the new cart data
$full_user_meta['cart'] = $updatedCart;
update_user_meta($user_id, '_woocommerce_persistent_cart_1', $full_user_meta);

 return array(
    'success' => true,
    'responsecode' => 200,
    "message" => "Products successfully added to cart",
    "data" => $full_user_meta['cart'],
);


text:
Q: How to access index value of the axis in question with numpy apply_along_axis() I have a problem that can be fully vectorised, but I don't have enough space, so I am trying for a half and half solution, using numpy's apply_along_axis().
(NOTE: This is a toy example that illustrates the nub of the problem. In other words, I am not looking for a numpy or scipy function that does what the function here is doing - it is not the real function, just one that is simple to illustrate with.)
What I would like to do is figure out a way to access the index of the axis being passed at each iteration.
Say we took a 4 x 4 matrix:
    M = np.array(([0,0,1,1], [1,1,0,1], [1,0,1,0], [0,0,1,1]))
    M

   array([[0, 0, 1, 1],
          [1, 1, 0, 1],
          [1, 0, 1, 0],
          [0, 0, 1, 1]])

And wanted to compute the pairwise bitwise logical and of each column against every other column, but to save (a lot of) time, we only compute for columns i,j where index of j > i (so that we end up with a triangular matrix).
In pandas I can do this quite easily with apply(), but it is too slow for my purposes.
I know there are pairwise functions in scikit-learn, but please assume these do not suit my purposes (my function is more complicated than this toy one)
If I were to use numpy's apply_long_axis(), I can only work out how to compare all i,j and j,i, not the smaller problem as described before.
This is my solution:
def intersections_np(col, M):
    col = col[:,np.newaxis]
    intersection = (M & col).sum(0)
    return(intersection)

result_np = np.apply_along_axis(intersections_np, arr = M, axis = 0,  M = M)
result_np

array([[2, 1, 1, 1],
       [1, 1, 0, 1],
       [1, 0, 3, 2],
       [1, 1, 2, 3]], dtype=int32)

But what I would really like to do is something like:
def intersections_np(col, M):
    col = col[:,np.newaxis]
    start_index = <index_of_current_column> + 1
    other_cols = M[:,start_index:]
    intersection = (other_cols & col).sum(0)
    <possible padding of the array with nans here>
    return(intersection)

result_np = np.apply_along_axis(intersections_np, arr = M, axis = 0,  M = M)

and return:
result_np

array([[nan, nan, nan, nan],
       [1, nan, nan, nan],
       [1, 0, nan, nan],
       [1, 1, 2, nan]], dtype=int32)

Does any one know if something like this can be done?
Thanks

A: Let's do a bit of timing.
Your basic apply:
In [142]: timeit np.apply_along_axis(intersections_np, arr = M, axis = 0,  M = M)
158 µs ± 3.97 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

And equivalent iteration (technically it may require a transpose, the the result is symmetric, so that doesn't matter):
In [143]: timeit np.array([intersections_np(M[:,i],M) for i in range(M.shape[1])])
65.4 µs ± 1.93 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

and @jfahne suggestion:
In [144]: %%timeit
     ...: np.reshape(np.array([(M.T[i] & M.T[j]).sum(0) if j>i else 0 \
     ...: for i in range(len(M.T)) for j in range(len(M.T))]),(M.T).shape).T
     ...:
     ...:
95.2 µs ± 2.99 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Notice that apply is slower than plain iteration.  That's consistent with my past testing.  apply is only a help if the array is 3d or more, and iteration is an 'ugly' double nested one.  There it's prettier, though still not faster.  It's a convenience tool, not a speed one.
A fully 'vectorized' solution (with numpy broadcasting etc):
In [148]: (M[:,:,None] & M[:,None,:]).sum(0)
Out[148]:
array([[2, 1, 1, 1],
       [1, 1, 0, 1],
       [1, 0, 3, 2],
       [1, 1, 2, 3]])
In [149]: timeit (M[:,:,None] & M[:,None,:]).sum(0)
14.9 µs ± 182 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

It does make an intermediate (4,4,4) array, and doesn't avoid the duplicates, but because there's no iteration at a Python level, it is quite fast.  Trying to restrict the calculations to the lower (or upper) triangle isn't usually worth it.
But if you really want the lower triangle, and speed, consider using numba.  It can be quite fast for iterative problems (but at some cost in flexibility).

Here's a version of your intersections restricted to the lower triangle
In [159]: def foo(M):
     ...:     m = M.shape[0]
     ...:     res = np.full((m,m), np.nan)
     ...:     for i in range(m-1):
     ...:         temp = (M[:,i,None] & M[:,(i+1):]).sum(0)
     ...:         res[-temp.shape[0]:,i] = temp
     ...:     return res
     ...:
     ...:
In [160]: foo(M)
Out[160]:
array([[nan, nan, nan, nan],
       [ 1., nan, nan, nan],
       [ 1.,  0., nan, nan],
       [ 1.,  1.,  2., nan]])
In [161]: timeit foo(M)
59.3 µs ± 2.42 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Basically the same timing as my [143] - it has fewer calculations in the & step, but more indexing, so there's little speed change.

A: This has a rather nice pythonic solution:
np.reshape(np.array([(M.T[i] & M.T[j]).sum(0) if j>i else 0 \
for i in range(len(M.T)) for j in range(len(M.T))]),(M.T).shape).T

The use of M.T is to access the columns. The resultant vector is reshaped into the same shape as the transposed array. The array is then transposed back to the original array shape and yields the desired output.


text:
Q: Show that $k= \{\mathfrak A|\mathfrak A\text{ is S-model and} \space R^\mathfrak{A} \space \text{is well founded}\}$ is not $\Delta$-elementary class I need to show that the set:
$k= \{\mathfrak A|\mathfrak A\text{ is S-model and} \space R^\mathfrak{a} \space \text{is well founded}\}$
is not a $\Delta$-elementary class, that is:
$k \neq \{\mathfrak A|\mathfrak A\text{ is S-model and} \space \mathfrak A \models \Phi \}$
Where $\Phi$ is an arbitrary set of well formed formulas.
In S we only have the relation $R$. $R$ is a relation that takes two arguments. Well founded is defined by: $(a_{i+1}, a_i)$, won't be in R for any $i \in \mathbb N $, when $a_i \in A$ ($A$ is the universe of the model).
I start by assuming that for ever model  $\mathfrak A \in k$, $\mathfrak A \models \Phi$, and then try to show that there exists $\mathfrak A \notin k$, such that $\mathfrak A \models \Phi$, but can't see how to show that.

A: First of all, your definition of well-foundedness is a bit mangled: $R$ is a well-founded relation if whenever we have elements $a_1, a_2, ...,$ there is at least one $i$ such that $R(a_{i+1}, a_i)$ doesn't hold. (The way you've written it makes it sound like we can't have any $R(a_{i+1}, a_i)$ hold, that is, $R$ is the empty relation.)
Now on to the question. In general, when you want to show that a class of models isn't elementary, a good tool to use is compactness, which states that any set of sentences which is finitely satisfiable (= every finite subset has a model) is actually satisfiable. So your goal is to, for each $\Phi$, come up with a $\Gamma$ such that $\Gamma\cup\Phi$ is finitely consistent but any model of $\Gamma\cup\Phi$ can't be in $k$. This will show that $\Phi$ doesn't define $k$ (do you see why?).
Now, applying compactness here takes a trick which you've probably seen before: expanding the language. Think about how one proves that if a theory $T$ has arbitrarily large finite models, then it has infinite models:

*

*Expand the language of $T$ by infinitely many new constant symbols $c_1, c_2, ...$.

*Consider the theory $T'=T\cup\{c_i\not=c_j: i\not=j\}$, consisting of $T$ plus "the constants name distinct elements."

*$T'$ is finitely consistent, since $T$ has arbitrarily large finite models; so $T'$ has a model $\mathcal{M}$.

*The reduct of $\mathcal{M}$ to the language of $T$ is a model of $T$; but $\mathcal{M}$ is infinite, so its reduct is also infinite. (Do you see why each of these things is true?)
We're going to do a similar trick here: pass to a larger language, produce a model of the relevant theory, and then show that the reduct of that model to the original language is "bad." HINT: in the definition of well-foundedness, you refer to infinitely many elements $a_i$ - do you see a natural way of expanding the language that this suggests?


text:
Q: How to find chromatic number of graph in R? I have the adjacency matrix of the graph (graph theory). First of all, I want to get the chromatic number of this graph (the smallest number of colors needed to color the vertices of a graph so that no two adjacent vertices share the same color). Then I want to get colors (like groups: from 1 to 4 maximum) of the vertices. Is it possible to get it in R using the igraph package? Thanks a lot.

A: You can use the greedy_vertex_coloring() function to estimate the chromatic number.
library(igraph)
set.seed(44)
n = 8
m <- t(matrix(c(
0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,
1,0,0,1,1,0,0,0,
0,0,1,0,0,1,1,0,
0,1,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,
1,1,0,0,1,0,0,1,
0,1,0,0,0,1,0,0),ncol=n))
g1 <- graph_from_adjacency_matrix(m, weighted=TRUE, mode="directed")
ch_number <- max(greedy_vertex_coloring(g1))


text:
Q: Problem with join two lists by linq I wanna join two list and fill drop down list by specific column but i have error in join query
 note:c.user_id is lookup field
my code
lst.DataSource = (from c in dc.Complainant
                     join u in dc.User_collec
                     on c.User_id equals u.User_id
                     select new { m=u.Title }).ToList();

the Error is The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'Join'.

A: If your lookup is not of multi type, something like this is worth a shot:
lst.DataSource = (from SPListItem c in dc.Complainant
    where c["User_id"] != null
    join SPListItem u in dc.User_collec
    on new SPFieldLookupValue(c["User_id"] as string).LookupValue
    equals u.User_id
    select new { m=u.Title }).ToList();

The differens is mainly the extraction of the value from the Lookup column, and that it takes in account cases where the c.User_id is null


text:
Q: PHP-FPM is not able to use OCI however PHP is So I've installed the REMI PHP on RHEL 7.
It is PHP 7.2
Also included is the Oracle Instant Client.
I've set the correct LD_LIBRARY_PATH.
When I run php -m it shows the module. oci8.
When see if the module is installed via php Code is says YES via command line and NO via the NGINX/PHP_FPM.
The PDO even says that OCI is a driver on the PHP command line side and not via PHP-FPM on the web.
Not sure what I could be missing.
-R


text:
Q: How to add lots of rows to Postgres fast with Golang I get 8000 rows back daily from an API and I have to save these results in my database.
Doing this 1 by 1 is crazy, it takes way to long. Therefor I decided to give go routines a try, to find out that out of the 8000 rows only 1000 (plus minus) rows actually got inserted.
wg := sync.WaitGroup{}
wg.Add(len(xyz.Hours))

for _, e := range xyz.Hours {
    go createDatabaseEntry(e, &wg)
}

Using the Go routine, it is super fast but only around 1000 rows will be inserted and the rest will be left blank for whatever reason.
Can someone tell me what would be the appropriate way to store it to my Postgress database?
I am using GORM as database library.
When I use the code below (createDatabaseEntry fn) it takes well over 5 minutes to complete.
for _, e := range xyz.Hours {
    msInt, _ := strconv.ParseInt(strconv.Itoa(e.Timestamp), 10, 64)
    t := time.Unix(0, msInt*int64(time.Millisecond))

    ef := models.Xyz{
        Timestamp: t,
        Unit:      e.Unit,
        Value:     e.Value,
    }

    db.Create(&ef)
}

It are not the two first lines (strconv) who make it slow, I removed them and it still remains extremely slow adding the rows to Postgres.
I also tried to do a batch insert but then I get a long list of errors from Gorm and I dont understand why.
var test []models.XyzFlow

for _, e := range xyz.Hours {
    msInt, _ := strconv.ParseInt(strconv.Itoa(e.Timestamp), 10, 64)
    t := time.Unix(0, msInt*int64(time.Millisecond))

    test = append(test, models.XyzFlow{
        Timestamp: t,
        Unit:      e.Unit,
        Value:     e.Value,
    })
}

db.Create(&test)

2020/10/29 23:47:39 http: panic serving [::1]:52886: reflect: call of reflect.Value.Interface on zero Value
goroutine 35 [running]:

A: It would be helpful for you to refer to Transactions in GORM.
https://gorm.io/docs/transactions.html#A-Specific-Example
If you process and commit multiple queries within the transaction, I don't think there will be any significant performance load.


text:
Q: ¿Como desactivar menu contextual dentro de cmd? Miren lo que pasa es que cree un .bat que crea un menu contextual activado por el click derecho, pero al hacerlo sale el típico menú...

complicando las cosas necesito que QUICK EDIT este DESACTIVADO ya que si no lo esta el .bat no detectará los click..... AYUDA
(es mi primera pregunta, hagan sugerencias de edición cualquier cosa).


text:
Q: magento2 upgrade - readiness check fails and uses system php instead of webserver I've installed magento2 without issues and at installation it detected my php version correctly (7.0.0, using mamp). Now at upgrade it detects the system one (5.5.31) and some packages missing, like mcrypt.
using phpinfo() on my webserver gives version 7.0.0 and mcrypt enabled.
Why is that and how can it be fixed?

A: It turns out that magento is using the cron information to check for your php info. In my crontab I had (sudo crontab -u user -e):
*/1 * * * * /usr/bin/php -c /Library/Application\ Support/appsolute/MAMP\ PRO/conf/php.ini /User/magento-2/bin/magento cron:run >> /User/magento-2/var/log/setup.cron.log&
*/1 * * * * /usr/bin/php -c /Library/Application\ Support/appsolute/MAMP\ PRO/conf/php.ini /User/magento-2/update/cron.php >> /User/magento-2/var/log/setup.cron.log&
*/1 * * * * /usr/bin/php -c /Library/Application\ Support/appsolute/MAMP\ PRO/conf/php.ini /User/magento-2/bin/magento setup:cron:run >> /User/magento-2/var/log/setup.cron.log&

So it was using the binary /usr/bin/php. Instead it should have been using my environment php, which was from mamp:
*/1 * * * * /Applications/MAMP/bin/php/php7.0.0/bin/php -c /Library/Application\ Support/appsolute/MAMP\ PRO/conf/php.ini /User/magento-2/bin/magento cron:run >> /User/magento-2/var/log/setup.cron.log&
*/1 * * * * /Applications/MAMP/bin/php/php7.0.0/bin/php -c /Library/Application\ Support/appsolute/MAMP\ PRO/conf/php.ini /User/magento-2/update/cron.php >> /User/magento-2/var/log/setup.cron.log&
*/1 * * * * /Applications/MAMP/bin/php/php7.0.0/bin/php -c /Library/Application\ Support/appsolute/MAMP\ PRO/conf/php.ini /User/magento-2/bin/magento setup:cron:run >> /User/magento-2/var/log/setup.cron.log&

Now the check is detecting php7.


text:
Q: Type mismatch when applying defined range to WorksheetFunction Need to add in an if statement to control what I am looping through in my code so have started with this line:
If Application.WorksheetFunction.Or(checkrange.value = 0, checkrange.value = "") = "False" Then

I have defined checkrange as the following
Set checkrange = finwb.Sheets("Strt_Dash_Final").Range(Cells((cfcll.Row + 1), q), Cells((cfcll.Row + (cfcll.value - 2)), q))

my code stops on the worksheet function line with run-time error 13, Type Mismatch. The purpose of the statment was to check if the range only contains 0s or blanks. The formula OR(A1:A5 = 0,A1:A5 = "") works fine in excel so I am assuming that it is not accepting my range in its current form (Note: i tried removing the .value from checkrange.value but this did not work either)
Any help on this, as always, is greatly appreciated!
EDIT : I have Dim checkrange As range to define it as a range

A: There is no need to be using a WorksheetFunction in the If statement.
If checkrange.value = 0 Or checkrange.value = "" Then

Because your checking a Range not a Cell you have to use CountA or CountIf
here is an example of CountA:
If Application.WorksheetFunction.CountA(checkrange) = 0 Then

A: You need two separate COUNTIF statements:
If Application.WorksheetFunction.Countif(checkrange, "0") + Application.WorksheetFunction.Countif(checkrange, "") = 0 Then

A: I guess it should be
If Application.WorksheetFunction.Or(checkrange.value = 0, checkrange.value = "") = False Then

though it's not really necessary to use worksheet function OR here. Have a try and let's see what happen.

A: The array formula OR(A1:A5 = 0,A1:A5 = "") checks if any (1 or more) of the cells in the range are 0 or "". To check if any of the cells in the range are not 0 or "" then you can use this
If WorksheetFunction.CountIfs(checkrange, "<>0", checkrange, "<>") > 0 Then


text:
Q: Why can't I setState the data I've successfully in React? So I'm new to React, and having trouble fetching API. I've successfully fetched data object(I've checked it with console.log(), but somehow cannot setState it. Please see the code below. It's my full code.
import React, { Component } from 'react';
import EachCake from './EachCake';

class Cake extends Component {
    constructor(props){
        super(props);
        this.state = {

        }
    }

    componentDidMount() {
        this._fetchApiEachCake();
    }

    _renderEachCake = () => {
        return <EachCake
        image={this.cake_object.image}
        source={this.cake_object.source}
        body={this.cake_object.body}
        />
    }

    _fetchApiEachCake = () => {
        return fetch("http://127.0.0.1:8000/api/cake/3")
        .then((response) => response.json())
        .then(data => console.log(data))
        .then(data => this.setState({cake_object : data}))
        // .catch((err) => console.log(err))
    }

    render() {
        return (

                {this.state.cake_object ? this._renderEachCake() : "Loading this cake"}

        )
    }
}

export default Cake

For some reason, all I get on the screen is "Loading this cake". What do you think is the problem?

A: if you are trying to check if the data is loaded or not you should use the callback this.setstate({key: value}, () => {//do something})
you can use this to set a flag whether data has been loaded into state or not. and i also think that you should initialize that cake_object to null.
so after that your code would be like:
this.state = {
       loaded: false,
       cake_object: null
    }

  _fetchApiEachCake = () => {
    return fetch("http://127.0.0.1:8000/api/cake/3")
    .then((response) => response.json())
    .then(data => console.log(data))
    .then(data => this.setState({cake_object : data}, () => {
            console.log(this.state.cake_object);
            this.setState({loaded: true});
     }))
    // .catch((err) => console.log(err))
}

render() {
    return (

            {this.state.loaded ? this._renderEachCake() : "Loading this cake"}

    )
}

A: 2 changes :
1.
this.state = {
   cake_object:null,
}

*

 _fetchApiEachCake = () => {
        return fetch("http://127.0.0.1:8000/api/cake/3")
        .then((response) => response.json())
        .then((data) => {
              console.log(data)
              this.setState({cake_object : data})
         })
        // .catch((err) => console.log(err))
    }

Hopefully it works!

A: import React, { Component } from 'react';
import EachCake from './EachCake';

class Cake extends Component {
    constructor(props){
        super(props);
        this.state = {
        //  state initialization is optional also, useful for default values
        }
    }

    componentDidMount() {
        this._fetchApiEachCake();
    }

    _renderEachCake = () => {
        return (
          <EachCake
            image={this.state.cake_object.image} //
            source={this.state.cake_object.source}
            body={this.state.cake_object.body}
          />
      )
   }

    _fetchApiEachCake = () => {
        //  you can also remove return here
        return fetch("http://127.0.0.1:8000/api/cake/3")
        .then((response) => response.json())
        .then(data => console.log(data) || data) //
        .then(data => this.setState({cake_object : data}))
        // .catch((err) => console.log(err))
    }

    render() {
        return (

                {this.state.cake_object ? this._renderEachCake() : "Loading this cake"}

        )
    }
}

export default Cake

 must be grabbed from the state not directly from this reference.
 console.log doesn't return anything, so you must return data yourself oق combine setState and logging step both in one step e.g.
.then(cake_object => console.log(cake_object) || this.setState({ cake_object }))

The then() method returns a Promise.


text:
Q: MySQL Error #1064 on this INSERT? Not sure what's wrong, just running this in PHP MyAdmin right now. Does anything pop out to you? Thanks.
INSERT INTO order (CustomerID, BillAddr, ShipAddr, Date, Total)
VALUES ('test', 'test', 'test', '2012-07-02', 22)

Error:

MySQL said: #1064

Structure of order table:
FIELD                TYPE
OrderID         int(11) auto increment
CustomerID      varchar(50)
BillAddr        varchar(200)
ShipAddr        varchar(200)
Date            date
Total           double

(I leave the OrderID out of the INSERT as it is an auto increment)
EDIT
Same error with this syntax:
SQL query:

INSERT INTO 'order'( CustomerID, BillAddr, ShipAddr, 'Date', Total )
VALUES (
'test', 'test', 'test', '2012-07-02', 22
)
MySQL said: Documentation
#1064 -

A: The word Date is a keyword.  Try it like this:
INSERT INTO `order` (CustomerID, BillAddr, ShipAddr, `Date`, Total)
VALUES ('test', 'test', 'test', '2012-07-02', 22)

ETA: And order is also a keyword :)


text:
Q: Custom XML Serialization, how to write custom root element? I'm probably just doing this wrong, i know.
I'm using custom serialization and when the xml is generated it's putting the class name as the root element
Example:
<MyClassName>
 <MyIntendedRootNode>
   <ObjectType>
     <Property1/>
     <Property2/>
...

I'm invoking the serialization by calling xmlserializer.Serialize(writer,Me) so I'm sure that has something to do with it.
I've tried putting XMLRoot onto the class, but I think as vb is compiling this partial class with its aspx page, it's either overwriting this property or ignoring it entirely.
Ideally I'd like to just tell it to either throw away everything it has and use a different root element.
Anybody else do this except me?
Thanks

A: You can use either IXmlSerializable or use the XML attributes. I use XmlSerializer passing the root in the constructor.
var MemoryStream ms;
var customRoot = dataObject as XmlRootAttribute;
var xml = new XmlSerializer(dataObject.GetType(), customRoot);
xml.Serialize(ms, dataObject);

A: In ASP.NET, the actual class that is loaded is a generated class that inherits from your class. (It turns out--surprisingly--that this generated code is actually separate from the additional generated code that is combined with your code using the partial class technique. The generated class has the same name as the class you are working on, but it is in a different namespace.) Since XmlRoot is not an inherited attribute, the XmlSerializer does not see it.
I don't think there is any solution (other than modify the document after you have generated it).

A: Are you trying to serialize a codebehind file?
I would suggest writing a model to contain the data that needs to be saved, and then serializing that instead. Then use the appropriate XMLWriter attributes to make sure your root element is correctly named.

A: Or you could implement IXmlSerializable and have full control over your Xml but its a bit of extra effort just to change a root element name.

A: You can create a wrapper class and give that wrapper class with the name that you wish to be shown in the xml root.


text:
Q: RoboGuice: method needs a new instance each call, injection possible? If I want to make a new instance of an injected class each time, how do I do it?  Here is the example that I am trying to do:
class Jet
{
  List<Missile> mAllMissiles;

  //
  // make a new missile, and add it to the table.
  //
  void fireMissile()
  {
     Missile missile = new Missile();
     missile.doSomething();
     mAllMissiles.add(missile);
  }
}

Now, I can Inject the Missile, but wont it be the same missile each time?  Is this a case where I need to inject the Provider?
http://code.google.com/p/google-guice/wiki/InjectingProviders
Or is there a different means of doing this?
Thanks.

A: Yes, inject a Provider<Missile>. If you can inject X, you can inject Provider<X>, and vice-versa. Injecting a Provider is the best way of requesting multiple instances of a class from the injector.


text:
Q: Extracting Wordpress.zip file on Linux server I'm new to Linux and I'm currently trying to do the following:

*

*unzip the contents of wordpress-4.1.1.zip to the directory in which it is contained which is /my-test-site/wordpress-4.1.1.zip

I understand to unzip I can run this command from within the directory:
unzip wordpress-4.1.1.zip
but that then leaves me with a sub directory called wordpress. I can then go in and run this command from the sub directory in order to move the files up a level:
mv * ../

If I do that I then have all of the wordpress core files in the my-test-site directory which I want. But I'm wondering If I can run the unzip command in such a way that it extracts the contents directly into my-test-site directory and doesnt  create a sub directory containing the files?
Thanks

A: You can use two command line options to unzip to get your desired result, provided the zip contains no sub directories.
unzip -j -d /my-test-site wordpress-4.1.1.zip

Note that if your zip was of the order:
foo
├── 1
├── 2
├── 3
├── 4
├── 5
├── 6
├── 7
├── 8
├── 9
└── bar
    ├── 1
    ├── 2
    ├── 3
    ├── 4
    ├── 5
    ├── 6
    ├── 7
    ├── 8
    └── 9

Using this option would mean the files contained in foo/bar would clobber (replace the contents of) all files located in foo. I.e, the -j option removes all paths relatives to the file locations in the zip and puts in them in either the current directory (default) or the directory specified by the -d option.
If your zip has sub-directories, your method would be the way to go about extracting that zip file.
You could always alias the command:
alias wp_unzip='mv wordpress-4.1.1.zip /my-test-site && \
    cd /my-test-site && unzip wordpress-4.1.1.zip && \
    mv wordpress/* . && rmdir wordpress'


text:
Q: how do we use kmalloc in linux driver code How will I come to know that where exactly or at what point I should  use the kmalloc() to allocate a memory to the device in the device driver?
Is it during initialization or during open? As in malloc,wil kmalloc allocates memory dynamically?

A: It depends on when you need it. There is no hard and fast rule.
For eg, in the i2c driver in linux kernel, there are two kmalloc calls and none in initialization or any specific function.
And yes, it acts similar to user space malloc call and allocates memory dynamically.

A: In general, you can use kmalloc() when you need physically contigous memory in kernel space.
You can use this during init/open depending on your use case.
If you kmalloc in init() but never use the device, then memory allocated is waste.
If kmalloc is used in open(), memory allocated is actually used because memory is allocated only if device is used.
Also, note that you can use vmalloc() in kernel in case you are not in need of physically contigous memory allocation.


text:
Q: VPN between domain and office with no server IS this even possible? The main office is running server 2008 r2 and is on a domain. The sub office we want to create a vpn connection to does not have a server and just has a regular modem like they would put in your house. IS this setup able to support a vpn connection?

A: Why not? You can create Remote Access VPN (use this article, or any such)
And everybody clients from sub office will be able connect to you LAN.

A: If you have an old "beige box" desktop computer lying around you could install pfSense or something similar and use it for your remote office gateway -- it has multiple options for site-to-site VPNs and is very easy to get up and running.
This would keep each user in the remote office from having to configure and run individual VPN clients, and reduce the bandwidth consumed to the overhead of the single tunnel.


text:
Q: Align geom_point data with geom_col data when combining with patchwork I am working to create two graphics and merging them into a single graphic using patchwork.
The x-axis are dates and the top graph is a geom_line/geom_point graph and the bottom graph is created using geom_col.   When combined, I'd like to have the points in the top graphic align with the center of columns in the bottom graphic.
I was hoping that b/c the x-axis spans the same dates, the points would align with the center of columns.  In several attempts, I was unable to center the dots above the column.  The resulting graphic (and the code) is below.

library(patchwork)

nn<-15
p1data = tibble(date=ymd('2021-01-01') + days(0:(nn-1)), values=floor(runif(nn, 5.0, 75)))

p2data <- tibble(initdate = ymd('2021-01-01')+days(0:(nn-1)), data=runif(nn,4,10))

# set up a tibble to shade in every other day
shade <- tibble(min=ymd('2021-01-01 00:00')+days(0:20),max=lead(min))
# Remove every other row
toDelete <- seq(1,dim(shade)[1],by=2)
shade <- shade[-toDelete,]

plot_limits = c(ymd('2021-01-01'),ymd('2021-01-16'))

# Orginal Attempt
p1 <- p1data %>%
  ggplot() +
  geom_rect(data=shade, aes(xmin=min,xmax=max,ymin=-Inf,ymax=Inf),fill='grey80' ) +
  geom_line(aes(x=date,y=values)) +
  geom_point(aes(x=date,y=values),color='red',size=3) +
  scale_x_date(expand=c(0,0),
                   date_breaks = '1 days',
                   date_labels = '%b-%d',
                   limits=plot_limits) +
  labs(title='two plots combined') +
  theme_bw() +
  theme(plot.title=element_text(hjust=0.5),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.x=element_blank())

p2 <- p2data %>%
  ggplot() +
  geom_col(aes(x=initdate,y=data, fill=data)) +
  scale_x_date(expand=c(0,0),date_breaks = '1 days',date_labels = '%b-%d') +
  theme_bw() +
  theme(plot.title=element_blank(),
        axis.title.x=element_blank(),
        axis.text.x=element_text(angle=0),
        legend.direction = "horizontal",
        legend.position = "bottom",
        legend.key.width=unit(1.25,"cm"),
        legend.key.height=unit(.25,"cm"),
        legend.box = "vertical",
        legend.box.background = element_blank(),
        legend.title = element_text(face = "bold"),
        legend.spacing = unit(1,"cm"),
        legend.justification = "center",
        legend.margin = margin(0.,0.,0.,0., unit="cm"),
        legend.background = element_blank(),
        plot.margin = margin(0, 0, 0, 0, "cm")
  )

p1/p2

Are there other ways to achieve center the dots for each day in the top graph with the column in the bottom graph?

A: While working to prepare this question, I was able to develop a solution.
The solution is to use datetime formats for the top graphic instead of just date. The datetimes associated with the data can then be set to YYYY-MM-DD 12:00.   The data is then plotted in the middle of the day rather than at the start of each day.
The resulting graphic is:

And the code that achieves it is:
# The solution that works
# Specify the dates in datetime format and use the hours to center the data in the day.

# The shade data for daily shades must be in datetime asd well.
# set up a tibble to shade in every other day
shade_dtm <- tibble(min=ymd_hm('2021-01-01 00:00')+days(0:20),max=as_datetime(lead(min)))
# Remove every other row
toDelete <- seq(1,dim(shade_dtm)[1],by=2)
shade_dtm <- shade_dtm[-toDelete,]

# create data
p1data_dtm = tibble(date=ymd_hm('2021-01-01 12:00') + days(0:(nn-1)), values=floor(runif(nn, 5.0, 75)))

plot_limits_dtm = c(ymd_hm('2021-01-01 00:00'),ymd_hm('2021-01-16 00:00'))

p1 <- p1data_dtm %>%
      ggplot() +
      geom_rect(data=shade_dtm, aes(xmin=min,xmax=max,ymin=-Inf,ymax=Inf),fill='grey80' ) +
      geom_line(aes(x=date,y=values)) +
      geom_point(aes(x=date,y=values),color='red',size=3) +
      scale_x_datetime(expand=c(0,0),
                       date_breaks = '1 days',
                       date_labels = '%b-%d',
                       limits=plot_limits_dtm) +
      labs(title='two plots combined: data aligned') +
      theme_bw() +
      theme(plot.title=element_text(hjust=0.5),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.x=element_blank())

p2 <- p2data %>%
      ggplot() +
      geom_col(aes(x=initdate,y=data, fill=data)) +
      scale_x_date(expand=c(0,0),date_breaks = '1 days',date_labels = '%b-%d') +
      theme_bw() +
      theme(plot.title=element_blank(),
        axis.title.x=element_blank(),
        axis.text.x=element_text(angle=0),
        legend.direction = "horizontal",
        legend.position = "bottom",
        legend.key.width=unit(1.25,"cm"),
        legend.key.height=unit(.25,"cm"),
        legend.box = "vertical",
        legend.box.background = element_blank(),
        legend.title = element_text(face = "bold"),
        legend.spacing = unit(1,"cm"),
        legend.justification = "center",
        legend.margin = margin(0.,0.,0.,0., unit="cm"),
        legend.background = element_blank(),
        plot.margin = margin(0, 0, 0, 0, "cm")
  )

p1/p2


text:
Q: Changing Font Icon in WPF using Font Awesome I am making use of Font Awesome's icons to render basic font images within my C# WPF application. During run-time when I attempt to alter the TextBlock to display a different font icon but the unicode representation is displayed instead of the font icon.
I have created a sample application to display this. When either of the buttons are clicked, it replaces the TextBlock's Text property with the unicode for the respective icon. There is a Resources folder in the project which has the FontAwesome.ttf font file as a Build Resource which the The TextBlock's FontFamily property references.
Here's my sample application's source code:
Code-Behind:
namespace FontAwesomeTest
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnGlass_Click(object sender, RoutedEventArgs e)
    {
        tblkFontIcon.Text = "";
    }

    private void btnMusic_Click(object sender, RoutedEventArgs e)
    {
        tblkFontIcon.Text = "";
    }

    private void btnSearch_Click(object sender, RoutedEventArgs e)
    {
        tblkFontIcon.Text = "";
    }
}
}

XAML:
<Window x:Class="FontAwesomeTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Font Awesome Test Window" Height="300" Width="330" Name="FontAwesomeTestWindow">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition Height="25"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Button Name="btnGlass" Height="35" Width="85" Click="btnGlass_Click" >Glass</Button>
    <Button Name="btnMusic" Grid.Column="1" Height="35" Width="85" Click="btnMusic_Click">Music</Button>
    <Button Name="btnSearch" Grid.Column="2" Width="85" Height="35"  Click="btnSearch_Click">Search</Button>
    <TextBlock Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" FontFamily="../Resources/#FontAwesome"></TextBlock>
    <TextBlock Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" FontFamily="../Resources/#FontAwesome"></TextBlock>
    <TextBlock Grid.Row="1" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" FontFamily="../Resources/#FontAwesome"></TextBlock>
    <TextBlock Name="tblkFontIcon" Grid.Row="2" Grid.ColumnSpan="3" FontSize="64" FontFamily="../Resources/#FontAwesome" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
</Grid>

I used the following tutorial to incorporate Font Awesome into my application http://www.codeproject.com/Tips/634540/Using-Font-Icons
So in essence, how can I change the Icon but have an Icon display - not Unicode?
Thanks in advance.

A: Font Awesome has NuGet packages named FontAwesome.UWP and FontAwesome.WPF. Just download  one of this.

If you will use a icon import follow namespace into your XAML code:
xmlns:fa="http://schemas.fontawesome.io/icons/"

Use it into your button like this:
<Button x:Name="btnButton">
    <Button.Content>
        <fa:ImageAwesome Icon="LongArrowLeft"/>
    </Button.Content>
</Button>

And finally in your C# code behind:
using FontAwesome.WPF; // on the top of the code
btnButton.Content = FontAwesomeIcon.LongArrowRight;

A: UPDATE
I found a different post for this topic --
Add Icon font in wpf
I think this should be more likely to what you want.

Make sure your font is added as a resource. Then, use the following
  string:
<Setter Property="TextElement.FontFamily" Value="pack://application:,,,/fonts/#FontAwesome" />

In the string above, I'm assuming that the font's name (not the
  font's filename) is FontAwesome.

You just need to:

*

*Add the Font to your project, let's say you put them in to a folder "fonts"

*Change the Build Action to Resource not Embedded Resource

*Add your style to set the font family like the code snip above, and set the TextBlock.Text to the icon you like and apply the style to the TextBlock.

If you want change the icon by updating the TextBlock.Text property, you should set the Text property with the supported unicode string.
Try something like
 tblkFontIcon.Text = "\uf000";

rather than
tblkFontIcon.Text = "";

If your're using the code from Using Font Icons
then you probably missed the "How It Works" section in that post.
You should use that markup extension, rather than using the TextBlock.Text property.
In his sample code:
<RibbonButton Label="Import data"
  LargeImageSource="{WpfTools:ImageFromFont Text=,
  FontFamily=/RibbonFontIconSample;component/Resources/#FontAwesome, Brush=Brown}" />

pay attention to the WpfTools:ImageFromFont, it is the Markup Extention, it allows xaml parser to convert the
{WpfTools:ImageFromFont Text=,
      FontFamily=/RibbonFontIconSample;component/Resources/#FontAwesome, Brush=Brown}

to an  ImageSource and assigned to the LargeImageSource property.
So in your xaml, you could replace the TextBlock with an Image, then it should be something like:
<Image Source="{WpfTools:ImageFromFont Text=,
      FontFamily=/RibbonFontIconSample;component/Resources/#FontAwesome, Brush=Brown}" />

If you want to change the Icon, you will have to change the ImageSource yourself, just follow the Using Font Icons to create your own method, or simply copy the following code from that tutorial.
private static ImageSource CreateGlyph(string text,
        FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight,
        FontStretch fontStretch, Brush foreBrush)
{
    if (fontFamily != null && !String.IsNullOrEmpty(text))
    {
        Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
        GlyphTypeface glyphTypeface;
        if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
                throw new InvalidOperationException("No glyphtypeface found");

        ushort[] glyphIndexes = new ushort[text.Length];
        double[] advanceWidths = new double[text.Length];
        for (int n = 0; n < text.Length; n++)
        {
            ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]];
            glyphIndexes[n] = glyphIndex;
            double width = glyphTypeface.AdvanceWidths[glyphIndex] * 1.0;
            advanceWidths[n] = width;
        }

        GlyphRun gr = new GlyphRun(glyphTypeface, 0, false, 1.0, glyphIndexes,
                                    new Point(0, 0), advanceWidths,
                                    null, null, null, null, null, null);
        GlyphRunDrawing glyphRunDrawing = new GlyphRunDrawing(foreBrush, gr);
        return new DrawingImage(glyphRunDrawing);

    }
    return null;
}

A: Simple and very easy:
You should install fontawesome font on your system use it as follows
<Button Content="" FontFamily="FontAwesome" FontSize="32" />

How to compose icon, {&#x}{FontAwesome icon code} e.g &#xf2b9 for address book
To find the list of codes goto FontAwesome or astronaut web


text:
Q: ¿Cómo firmar correctamente archivo XML "CAF" con caracteres especiales? Tengo armado todo un proceso de emisión de DTE (documentos tributarios electrónicos) en Chile. Hasta la fecha no he tenido inconvenientes con la firma de los timbres y tampoco con la firma del documento en sí.
Resulta que hay un contribuyente que tiene doble comillas en su razón social, por lo que al enviar el DTE firmado, el SII me responde: (CAF-3-514) Firma del CAF incorrecta
Aplico correctamente el Encoding ISO-8859-1 y nunca he tenido problemas con las tildes o eñes, pero no puedo resolverlo cuando hay una doble comilla.
El archivo XML es el siguiente:
<?xml version="1.0"?>
<AUTORIZACION>
<CAF version="1.0">
<DA>
<RE>11111111-1</RE>
<RS>SOCIEDAD BERNARDO O"HIGGINS SPA</RS>
33
<RNG><D>101</D><H>200</H></RNG>
<FA>2020-05-28</FA>
<RSAPK><M>t6ldOQd1Mz+1tiYhaMvVCKeAyT2vQK4rqYCHtbMDWIAHBGwI3mr1mmgLUpXKfvisRl1pTY2RXWdZVd6vE12PSw==</M><E>Aw==</E></RSAPK>
<IDK>100</IDK>
</DA>
<FRMA algoritmo="SHA1withRSA">UQ85YCoqC+pBw7kjzU0g+0uufqKKg759DapDJP4Bt4LMk1mK4330cgBPpVh/iUo5oC9TxINqo0icwFYiAabskw==</FRMA>
</CAF>
<RSASK>-----BEGIN RSA PRIVATE KEY-----
MIIBOQIBAAJBALepXTkHdTM/tbYmIWjL1QingMk9r0CuK6mAh7WzA1iABwRsCN5q
9ZpoC1KVyn74rEZdaU2NkV1nWVXerxNdj0sCAQMCQHpw6NCvo3d/znluwPCH41sa
Vdt+dNXJcnEAWnkiAjr+4v/O/o8lhCUGHFaf/0B+1jp2kTnb7b/A4qrd9fxFs7sC
IQDm1L63s29TnXKNkSrlDPGRuqBa0IsmFoXM82Xp0aVhfwIhAMuv9tNUQ1vFbFM/
euaRSNk0CzSmOIanQDhiK9RHT6A1AiEAmeMpz8z04mj3CQtx7gihC9HAPIsHbrmu
iKJD8TZuQP8CIQCHyqSM4teSg52M1PyZtjCQzVzNxCWvGirQQXKNhN/AIwIgXDO7
2/zf8L8fGm6nrDl56Oiybnq0PIg67W4FJ3NBXxI=
-----END RSA PRIVATE KEY-----
</RSASK>

<RSAPUBK>-----BEGIN PUBLIC KEY-----
MFowDQYJKoZIhvcNAQEBBQADSQAwRgJBALepXTkHdTM/tbYmIWjL1QingMk9r0Cu
K6mAh7WzA1iABwRsCN5q9ZpoC1KVyn74rEZdaU2NkV1nWVXerxNdj0sCAQM=
-----END PUBLIC KEY-----
</RSAPUBK>
</AUTORIZACION>

En la etiqueta RS encontramos lo siguiente:
<RS>SOCIEDAD BERNARDO O"HIGGINS SPA</RS>

Para la serialización utilizo C#:
public static T DeserializeRawWithoutEncoding<T>(string filePath)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    T obj;
    using (StreamReader reader = new StreamReader(filePath))
    {
        obj = (T)serializer.Deserialize(reader);
        reader.Close();
    }
    return obj;
}

Pero al deserializar " se transforma automáticamente a \".

Entiendo que ambos casos son válidos pues es sólo una interpretación del Encoding, y la firma del timbre  la realiza bien según los validadores que tengo implementados. Además cuando tengo problemas en la firma del timbre, el SII indica el siguiente error: (TED-2-510) REPARO- Firma Timbre Electrónico Incorrecta
Y este no ha sido el caso.
El XML final generado es el siguiente:
<TED version="1.0">

<RE>76521854-3</RE>
33
<F>101</F>
<FE>2020-05-30</FE>
<RR>66666666-6</RR>
<RSR>Razon Social de Cliente</RSR>
<MNT>0</MNT>
<IT1>Cajón AFECTO</IT1>
<CAF version="1.0">
<DA>
<RE>76521854-3</RE>
<RS>SOCIEDAD FARMACEUTICA O"HIGGINS SPA</RS>
33
<RNG>
<D>101</D>
<H>200</H>
</RNG>
<FA>2020-05-28</FA>
<RSAPK>
<M>t6ldOQd1Mz+1tiYhaMvVCKeAyT2vQK4rqYCHtbMDWIAHBGwI3mr1mmgLUpXKfvisRl1pTY2RXWdZVd6vE12PSw==</M>
<E>Aw==</E>
</RSAPK>
<IDK>100</IDK>
</DA>
<FRMA algoritmo="SHA1withRSA">UQ85YCoqC+pBw7kjzU0g+0uufqKKg759DapDJP4Bt4LMk1mK4330cgBPpVh/iUo5oC9TxINqo0icwFYiAabskw==</FRMA>
</CAF>
<TSTED>2020-05-30T20:37:53</TSTED>

<FRMT algoritmo="SHA1withRSA">tVLkmiiS4+f2df6VSAuUbtBFzfBREEPu/xY2425y6+GOoBY7RJ44GN0sJOWZV4gqMrVm1bYUFR5PsMFuxyGPQA==</FRMT>
</TED>

Como podrán fijarse en la etiqueta <RS>, " es reemplazado por \". Es por eso que asumo que el SII me está reclamando que la firma del CAF no es válida. (CAF-3-514) Firma del CAF incorrecta
Este XML es generado después de serializar un objeto TED de esta forma:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.GetEncoding("ISO-8859-1");
settings.Indent = true;
settings.IndentChars = "";
settings.OmitXmlDeclaration = false;
using (XmlWriter xmlWriter = XmlWriter.Create(tempFilePath, settings))
{
      XmlSerializer s = new XmlSerializer(obj.GetType());
      s.Serialize(xmlWriter, obj, ns);
}

Acciones que he realizado sin frutos:

*

*Reemplazar \" por " de distintas maneras. Directo con string.Replace() y con SecurityElement.Escape(), sin embargo el SII sigue respondiendo con error y generalmente también con error de firma en el timbre. Esto también ha provocado que la etiqueta termine como <RS>SOCIEDAD BERNARDO O&quot;HIGGINS SPA</RS> malinterpretando la intención.

*En todos los procedimientos utilizo Encoding ISO-8859-1, y los he ido variando por UTF-8 sin tener ninguna mejora al respecto.

El SII dispone de un manual público (página 20) donde se indica que estos caracteres deben ser reemplazados, pero al hacerlo sigo con el problema.
¿Cómo resolverlo en C#?

A: Yo tuve el mismo problema, estuvimos todo el dia probando y nada el CAF se daña cuando se baja del SII, finalmente conversamos con el cliente  y le pedimos que cambie la razon social, eliminando las comillas del nombre como es empresa en un dia no debe hacer escritura, se puede hacer por intenet

A: No debe ser considerado como una solución correcta cambiar la Razón Social en SII.
La respuesta a este problema es leer con el encoding adecuado el archivo, el cual es el "ISO-8859-1", el XML del CAF generado de SII no lo indica correctamente en el tag "xml".
DeserializeRawWithEncoding(filePath, "iso-8859-1");

public static T DeserializeRawWithEncoding<T>(string filePath, string encoding)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    T obj;
    using (StreamReader reader = new StreamReader(filePath, encoding))
    {
        obj = (T)serializer.Deserialize(reader);
        reader.Close();
    }
    return obj;
}

Dependiendo de que libreria utilizes, no siempre es posible forzar otro encoding al leer el archivo, porque puede ser que siempre lo lea desde el tag "xml".
En este caso bastaría con editar el tag antes de importarlo.
Ejemplo con Chilkat en C#:
// Arreglar tag xml para indicar encoding
Chilkat.StringBuilder sbCAF = new Chilkat.StringBuilder();
sbCAF.LoadFile("CAF.xml", "ISO-8859-1");
sbCAF.Replace("<?xml version=\"1.0\"?>", "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
sbCAF.WriteFile("CAF_CORRECTO.xml", "ISO-8859-1", false);

// Ahora la carga se realiza con el encoding correcto
Chilkat.Xml xmlCAF = new Chilkat.Xml();
bool success = xmlCAF.LoadXmlFile("CAF_CORRECTO.xml");
if (success == true)
{
    Console.WriteLine("CAF cargado correctamente.");
    return;
}


text:
Q: AD sync with Liferay We have a portal hosted at our side on Liferay and a Active Directory is in sync through LDAP with Liferay. The problem which we are facing is that when the user gets deleted from the AD it neither gets deactivated nor deleted from Liferay. I want the user to be deactivated not deleted from Liferay when deleted from the AD.
Although Liferay strongly discourages to deactivate/delete the user when the user is deleted from the AD  as there may be dependencies on other user, sites or organisations or unexpected behavior which may be caused.
I checked all the required fields which are necessary for AD synchronization with Liferay. I am unable to upload the screenshot due to less reputation.
How can I achieve the aforementioned requirement?
Please suggest the possible ways.
Thank you

A: When you interface with LDAP you shouldn't rely on Liferay to tell you if a user is deactivated or not - e.g. just look up the existance of a user in LDAP to determine if an account is valid.
My advice is to require LDAP for those users and not save their password in Liferay's database - thus, no matter if the user is activated or deactivated, they can't log in to Liferay because Liferay would authenticate them with LDAP (which would fail)
If this is - for some reason - really mandatory you can either deactivate them on a subsequent try for login or bulk import/validate all users against LDAP from time to time.
And yet another possibility is depending on the way you maintain your LDAP database - you could also use Liferay's API from your LDAP maintenance software to deactivate users when deleted from AD.
But the key is: Deleted LDAP users should not be able to log in to Liferay - when they log in Liferay would import all of their data, which doesn't work. And when Liferay can't validate their passwords, they couldn't log in without LDAP, thus you shouldn't be facing any actual problem

A: In order to customize such default behavior of Liferay, you need to create a plugin ext by extending PortalLDAPImporterImpl.java.
The following link will help you -
http://www.liferay.com/community/forums/-/message_boards/message/10755176


text:
Q: What is the meaning of T D P S S S C I when I get output of usb-devices on terminal? I want to get USB bus port details (which have USB serial ID number, USB type, USB name, port type, port name, and many other data points) in Ubuntu.
I typed usb-devices where I got a certain no of rows starting with T, D, P, S, etc.

Someone help me in identifying these terminologies.

A: According to source code: https://github.com/gregkh/usbutils/blob/master/usb-devices

*

*T: Transport

*D: Device class

*P: Product vendor id

*S: String

*C: Configuration

*E: Endpoint

*I: Interface


text:
Q: ngx-useful-swiper setup in Angular 8 gives error I followed this guide to set up swiper slider in my Angular 8 application.
I get the below error when importing NgxUsefulSwiperModule into app.module.ts
ERROR in ./node_modules/ngx-useful-swiper/fesm2015/ngx-useful-swiper.js
Module not found: Error: Can't resolve 'swiper/bundle' in 'C:\Users\Dan\NewAngular\node_modules\ngx-useful-swiper\fesm2015'
I tried deleting the node_modules folder and reinstalling everything but it fails every time.
Can someone please tell me what I'm doing wrong?
This is my package.json file
{
  "name": "angular",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --ssl",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "run:prod": "ng build --prod",
    "test-single-run": "ng test --watch=false"
  },
  "private": true,
  "dependencies": {
    "@aleesaan/ng-scrollspy": "^1.0.2",
    "@angular/animations": "^8.2.14",
    "@angular/cdk": "^8.2.3",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "^8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/material": "^8.2.3",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/pwa": "^0.1000.0",
    "@angular/router": "~8.2.14",
    "@angular/service-worker": "~8.2.14",
    "@auth0/angular-jwt": "^4.0.0",
    "@iplab/ngx-file-upload": "^1.5.4",
    "@kolkov/angular-editor": "^1.1.5",
    "@microsoft/applicationinsights-web": "^2.0.0",
    "@nebular/eva-icons": "^4.6.0",
    "@nebular/theme": "^4.6.0",
    "@ng-bootstrap/ng-bootstrap": "^5.2.2",
    "@ng-select/ng-select": "^3.7.2",
    "@nicky-lenaers/ngx-scroll-to": "^9.0.0",
    "@thisissoon/angular-inviewport": "^4.2.2",
    "@thisissoon/angular-scrollspy": "^2.2.0",
    "angular-animations": "0.0.10",
    "angular-crumbs": "^3.0.1",
    "angular-scroll": "^1.0.2",
    "angular2-csv": "0.2.5",
    "angular2-jwt": "^0.2.3",
    "bootstrap": "^4.4.1",
    "bs4-toast": "^0.7.1",
    "classlist.js": "^1.1.20150312",
    "cors": "^2.8.5",
    "eva-icons": "^1.1.3",
    "font-awesome": "^4.7.0",
    "guid-typescript": "^1.0.9",
    "jquery": "^3.5.1",
    "jwt-decode": "^2.2.0",
    "microsoft-adal-angular6": "^1.3.0",
    "moment": "^2.27.0",
    "nebular-icons": "^1.1.0",
    "ng-click-outside": "^7.0.0",
    "ng-material-multilevel-menu": "^5.5.3",
    "ng-otp-input": "^1.7.7",
    "ng-pick-datetime": "^7.0.0",
    "ng-recaptcha": "^5.0.0",
    "ng-scroll-spy": "^1.0.1",
    "ng-sidebar": "^9.2.1",
    "ng-whiteboard": "^1.4.5",
    "ng2-completer": "^2.0.8",
    "ng2-google-charts": "^6.1.0",
    "ng2-smart-table": "1.5.0",
    "ng2-truncate": "^1.3.17",
    "ng5-slider": "^1.2.4",
    "ngx-chips": "^1.9.8",
    "ngx-drag-drop": "^2.0.0",
    "ngx-infinite-scroll": "^10.0.1",
    "ngx-logger": "4.2.0",
    "ngx-perfect-scrollbar": "^8.0.0",
    "ngx-quill": "^5.2.0",
    "ngx-scrollspy": "^1.2.1",
    "ngx-skeleton-loader": "2.6.1",
    "ngx-ui-loader": "^7.2.2",
    "ngx-useful-swiper": "^10.0.1",
    "pdfmake": "^0.2.0",
    "popper.js": "^1.16.1",
    "primeicons": "^2.0.0",
    "primeng": "^9.1.0",
    "quill": "^1.3.7",
    "quill-delta": "^4.1.0",
    "quill-emoji": "^0.1.4",
    "quill-mention": "^2.0.4",
    "roboto-fontface": "^0.10.0",
    "rxjs": "~6.4.0",
    "swiper": "^7.0.8",
    "tslib": "^1.13.0",
    "web-animations-js": "^2.3.2",
    "windows-10-icons": "^1.0.1",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.803.29",
    "@angular/cli": "^8.3.29",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^8.10.64",
    "@types/swiper": "^5.4.3",
    "codelyzer": "^5.2.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^5.2.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-edge-launcher": "^0.4.2",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "ng2-mock-component": "^0.2.0",
    "protractor": "^7.0.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "3.5.3",
    "webpack": "^4.44.2"
  }
}

A: Looks like ngx-useful-swiper is not compatible with the latest version of swiper.
The error clearly states that ngx-useful-swiper is trying to access a file that's not available in the swiper package you just installed.
Try installing a different version of swiper slider.
Follow these steps:
1) Uninstall the current swiper
npm uninstall swiper

2) Install older version
npm install swiper@6.8.1

That should do the trick.

A: Try installing ngx-swiper-wrapper. It has been created upon swiper and working perfectly with angular.
Here is the npm page of ngx-swiper-wrapper (this page has an initial doc for installing):
https://www.npmjs.com/package/ngx-swiper-wrapper


text:
Q: Looping through object to retrieve data from another nested object I'm trying to loop through an object's values which in turn are objects of there own with data that I want to retrieve. I'm trying to get the data that matches a variable that is created dynamically, not a hard-coded path. The only solutions I can find are for objects that have data attached at the top level not nested in another object. Below is a simple version of my problem. Thank you in advance.

const VMs = {
  'VM01': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM02': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM03': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  }
};

const thisVM = 'VM03'; // Hardcoded here but actually this.$route.params.data (data not defined in this example)

for (let obj in VMs) {
  console.log(obj) // this is only a string of the key eg "VM01". I
  // want obj to be an object where I can reference its data.

  if (obj = thisVM) {

    // get data from this VM

  }
}

A: I am not really sure what's your intents, but if you want to acces the nested props, you can use Object.entries method, like that:

const VMs = {
  'VM01': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM02': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM03': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  }
};

const thisVM = 'VM03';

Object.entries(VMs).forEach(([prop, val]) => {
  console.log(val)
  if (prop === thisVM) {
    // Your action
  }
})

If the depth of the nesting is bigger or unknown, it is better to use recursive traversing.

A: Use VMs[obj] to get the object.
Your if statement has a typo, = should be == to perform a comparison.
But there's little need for the loop in the first place. You can just use VMs[thisVM] to get the specific object you want. See Dynamically access object property using variable

const VMs = {
  'VM01': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM02': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  },
  'VM03': {
    "1": "value1",
    "2": "value2",
    "3": "value3"
  }
};

const thisVM = 'VM03'; // Hardcoded here but actually this.$route.params.data (data not defined in this example)

for (let obj in VMs) {
  console.log(VMs[obj]) // this is only a string of the key eg "VM01". I
  // want obj to be an object where I can reference its data.

  if (obj == thisVM) {

    // get data from this VM

  }
}


text:
Q: OpenCV cvtColor image truncated I am using cvtColor to convert an image from YUYV format to RGB24. The output is fine as far as color is concerned but half of the image is cut. The image is 640x480 YUYV image buffer without any headers. I am using the following code:
 FILE* fd = fopen("imgdump", "r+b");

 char buffer[640*480*2]; // Each pixel takes two bytes in YUYV

 if (fd != NULL)
 {
     fread(buffer, sizeof(char), 640*480*2, fd);
     fclose(fd);
 }

 Mat s_sImageMat = Mat(640, 480, CV_8UC2);
 Mat s_sConvertedImageMat;

 cout << "before conversion\n";
 s_sImageMat.data = (uchar*) buffer;
 cvtColor(s_sImageMat, s_sConvertedImageMat, CV_YUV2RGB_YUYV);
 cout << "after conversion\n";

 FILE* fw = fopen("converted", "w+b");

 if (fw != NULL)
 {
     fwrite((char*)s_sConvertedImageMat.data, sizeof(char), 640*480*2, fw);
     fclose(fw);
 }

Original file: https://drive.google.com/file/d/0B0YG1rjiNkBUQ0ZuaWN6Y1E2LUU/view?usp=sharing
Additional info: I am using opencv 3.2

A: The issue seems to be in the following line :
fwrite((char*)s_sConvertedImageMat.data, sizeof(char), 640*480*2, fw);

For RGB24, it should be be :
fwrite((char*)s_sConvertedImageMat.data, sizeof(char), 640*480*3, fw);

Each pixel is 3 bytes in RGB24