Powershell: Child Property Deflation

Question: Not sure if "deflating" is the right term, but I was wondering if there's a nicer way to specify that you only want to return a selection of an object's children's properties whilst using Select-Object? I'm using Powershell v5.
Here's a fully working example - the $test variable is hard coded here for demonstration purposes; in my use-case, the $test array is being returned from an API. I want to remove the name property from the testChild object during the projection.
The only way I could figure out how to do this is by using a foreach loop whilst piping into $result, then re-creating each child object and setting only the required properties, but it feels like powershell should have nicer way to do this.
$test = @(
    [PSCustomObject]@{
        testProp = "test1"
        testChild = [PSCustomObject]@{
            id = 1
            name = "test name 1"
        }
    },
    [PSCustomObject]@{
        testProp = "test2"
        testChild = [PSCustomObject]@{
            id = 2
            name = "test name 2"
        }
    }
)

$result = $test | select testProp, testChild | % {
    $_.testChild = [PSCustomObject]@{
        id = $_.testChild.id
    }
    $_
}

$result

This outputs:
testProp testChild
-------- ---------
test1    @{id=1}
test2    @{id=2}

Which is exactly what I want. I'd be nice if I could do something like this:
$result = $test | select testProp, testChild.id

Bearing in mind that I do not want flat properties returned - I want the original object with some properties removed / only the properties I specify included.
Answer: You can do this with Select-Object:
$result = $test | select testProp, @{
    Name = 'id'
    Expression = { $_.testChild.id }
}

Basically, Select-Object allows you to define your own properties, where the value is determined by an expression (a [ScriptBlock]), so you can run any code you want to determine the value. Within the block, $_ refers to the "current object" the same way it would in a ForEach-Object call.
Comment: Thanks. That still feels fairly long-winded (and actually produces /more/ code than my example in my use-case - mostly because I'm manipulating arrays for some properties). I'll accept this if no one else comes up with anything neater!
Comment: Actually, your answer does not do what I specified - you've returned a flat `id` property. It needs to be an object as per my example.
Comment: @Spikeh you can make the expression its own `Select-Object` statement, which will keep it an object, or you can make the expression create a `[PSObject]` directly as you were doing before. There are several ways, but there's nothing that directly gives you the exact result you want

Powershell: Child Property Deflation


Is it possible to create a cross-browser AJAX photo uploader with a progressbar?

Question: I've been searching around and round the web on how to do this.
It seems almost impossible??
Is it possible to create a cross-browser AJAX photo uploader with a progressbar? Dynamic thumbnail generation I can do, but I can't seem to find a cross browser solution for pure-javascript dynamic upload with progressbar that will work on IE and other browsers.
Any tips guys? :/
Comment: *Anything* is posible with enough work -- but I think you'll want a framework.
Comment: https://github.com/valums/file-uploader
Comment: You are probably better off going for something that uses flash like uploadify if you want to be cross browser.
Answer: I recommend using this http://www.uploadify.com/ with html 5 fallback.
Comment: They can't be used in commercial applications? What does that mean?
Comment: On their site.. :S

The main points subject to the terms of the License are:

Source Code cannot be used in commercial applications;
Source Code cannot be redistributed; and
Source Code can be modified to create derivative works.
No claim of suitability, guarantee, or any warranty whatsoever is provided. The software is provided "as-is".
The Article(s) accompanying the Work may not be distributed or republished without the Author's consent
Comment: They are saying you can't take the **source code** and resell it.  You are free you use it as intended in commercial or non- apps.
Comment: Hi...are you using any services call for the data fetch? if yes then i have solution...


Closedness of $L^\infty_+$ in $\sigma(L^\infty,L^1)$

Question: Let $L^\infty_+$ be the set of all $f\in L^\infty$ which are non negative. Our measure can be assumed to be finite. My goal is to prove that $L^\infty_+$ is closed in the weak-star topology $\sigma(L^\infty,L^1)$. Hence I view $L^\infty$ as the dual of $L^1$. We know that every linear continuous function of $L^1$ can be written:
$$F(x)=\int xy d\mu$$
for $x\in L^1$ and a unique $y\in L^\infty$. So $L^\infty_+$ is the space of all $F$ with $y\ge 0\iff \int xy d\mu \ge 0 $ for all $0\le x\in L^1$. I've learned that the weak-star topology (on $L^\infty$) is generated by the sets
$$\Omega_{x,U}=\{y\in L^\infty: \int xy d\mu\subset U \}$$
for $U\subset \mathbb{R}$ closed. Somehow I have to choose $x,U$ such that $\Omega_{x,U}=L^\infty_+$. But maybe there is a simpler characterization of closed sets in $\sigma(L^\infty,L^1)$? Or how else could I show that $L^\infty_+$ is weak-star closed?
Answer: One can write
$$L^\infty_+=\bigcap_{A\in\mathcal F}\left\{g\in L^{\infty},\int_Ag\geqslant 0\right\},$$
where $\mathcal F$ is the collection of sets of finite measure. Inclusion $\subset$ is obvious, and $\supset$ follows by the following argument. Assume the measure space $\sigma$-finite (hence $X=\bigcup F_n$, where each $F_n$ is measurable and has finite measure, and the $F_n$ are nested); if $g<0$ on a set of positive measure, take the intersection of the characteristic function of this set with a $F_n$ for a $n$ large enough.
And for each $A\in\mathcal F$, $\left\{g\in L^{\infty},\int_Ag\geqslant 0\right\}$ is weak-* closed, and so is an intersection of such sets.
Comment: sorry, we can assume that the we have a finite measure!
Comment: So the same argument works in a simpler way.


Dificuldade em transcrever um programa de console application para windows form(C#)

Question: Estava aprendendo a usar split e no fim tinha esse codigo:
namespace String_Split
{
    class Program
    {
        static void Main(string[] args)
        {
            string mensagem_completa;
            string palavra;
            string[] Apenas_palavras;
            Console.WriteLine("Apresente o texto a ser lido . . .");
            mensagem_completa = Console.ReadLine();

            Apenas_palavras = mensagem_completa.Split(' ', '.', ',');
            int tamanho = Apenas_palavras.Length;

            Console.ReadKey();

            for (int i = 0; i < tamanho; i++)
            {
                palavra = Apenas_palavras[i];
                Console.Clear();
                Console.WriteLine(palavra);
                Thread.Sleep(1000);

            }
            Console.WriteLine("Total de caracteres: " + mensagem_completa.Length);
            Console.WriteLine("Total de palavras: {0}", tamanho);
            Console.ReadKey();

        }

    }
}

O programa executou sem problemas, tudo certinho.
Dai então pensei, por que não transforma-lo em um programa com windows form?
O resultado foi esse aqui:
namespace Split_em_Form
{

    public partial class Form1 : Form
    {

        public string[] texto_em_array;
        public string texto;
        public int tamanho_do_texto;
        public string palavra;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            texto = textBox1.Text;
            texto_em_array = texto.Split(' ', ',', '\n', '.');
            tamanho_do_texto = texto_em_array.Length;

            for (int i = 0; i < tamanho_do_texto; i++)
            {
                palavra = texto_em_array[i];
                label1.Text = "";
                label1.Text = palavra;
                Thread.Sleep(1000);
            }
        }
    }
}

Ao clicar no button1 algo inesperado aconteceu, apenas o ultimo item da array apareceu no label1.
Ai minha duvida fica,por que isso aconteceu? Qual a diferença do código que escrevi na primeira vez para o segundo código e como posso resolver isso?
Answer: Você está jogando os valores no label e não concatenando-os, isso faz com que a cada loop label.Text tenha um valor diferente.
Sempre que você faz Console.WriteLine() uma nova linha é escrita. Já quando você faz label.Text = "texto", você está fazendo com o que texto atual do label seja substituído por esse novo texto.
Para concatenar todos os valores do array no label ficaria assim:
for (int i = 0; i < tamanho_do_texto; i++)
{
    palavra = texto_em_array[i];
    label1.Text += " - " + palavra;
    Thread.Sleep(1000);
}

Só como alternativa, ao invés de usar um loop para concatenar seus valores, você pode usar string.Join().
label.Text = string.Join(", ", texto_em_array);

O primeiro parâmetro do método recebe o separador para os valores do array, o segundo é o array de string e o retorno será todos os valores do array separados por , (vírgula).
Answer: Um Label só pode usar um texto de cada vez. Sempre que lhe é atribuído um valor, através de label1.Text = palavra;, o texto anterior é reposto pelo novo.
Apesar de utilizar o Thread.Sleep(1000); o Label só é actualizado visualmente(na tela) após o ciclo for ter terminado.
Para obter o efeito que pretende terá de chamar o método Refresh após cada label1.Text = palavra;
for (int i = 0; i < tamanho_do_texto; i++)
{
    palavra = texto_em_array[i];
    label1.Text = palavra;
    Refresh();
    Thread.Sleep(1000);
}

Talvez uma melhor forma de apresentar as palavras seria usar uma ListBox em vez de um Label.
Coloque uma ListBox na sua Window e altere o código do for para:
listBox1.Items.Clear();
for (int i = 0; i < tamanho_do_texto; i++)
{
    palavra = texto_em_array[i];
    listBox1.Items.Add(palavra);
}


ExpressJs configuring html and css pages

Question: I am a newbie in ExpressJs. I have tried using html and css while building the app. But there is always asset-pipelining problem. Sometime css could not be loaded and sometime it does not get refreshed even if I restart the server. I have used static serve method. Still could not figure out the problem. Please help me out of this.
Answer: here is the solution
<code> install npm serve-static
</code>
this should solve the problem


Get screenshot on Windows with Python?

Question: I am creating a Beta Testers reporting module so they can send in thier comments on my software, but I would like to have the option to include a screenshot with the report. How do I take a screenshot of the screen with Python on Windows? I have found several examples on Linux, but haven't had much luck on Windows.
Comment: This one worked for me: http://stackoverflow.com/questions/4589206/python-windows-7-screenshot-without-pil
Answer: Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes standard module, so it does not require big dependencies. It is OS independant and its use is made easy:
from mss import mss

with mss() as sct:
    sct.shot()

And just find the screenshot.png file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot objects and OpenCV/Numpy/PIL/etc..
Comment: see more examples in https://python-mss.readthedocs.io/en/dev/examples.html
Comment: @AdrianKeister: The good link is https://python-mss.readthedocs.io/en/latest/examples.html ; you will find answers :)
Comment: Never mind. I found out that the png filesize is a lot more dependent on what's on the screen than anything else. Thanks again!
Comment: @tal: Your link is outdated. Could you please update?
Comment: @Tiger-222: How would you get multiple monitors?
Comment: @Tiger-222: Excellent! One thing more: when I did one monitor with your code, I got a very nicely small 63kB file. In the examples link, when I did a single screenshot for all three monitors, I get a whopping 1.2 MB file. Any way to get the full screenshot down to compare in size with the single monitor?
Comment: MSS is a lot faster than the others because it does not save the screen into a temp file but relies on a system CoreGraphics module (on OS X at least).  So, you can probably either avoid saving pngs altogether or you may want to save the screenshots as jpeg.
Answer: Worth noting that ImageGrab only works on MSWindows.
For cross platform compatibility, a person may be best off with using the wxPython library.
http://wiki.wxpython.org/WorkingWithImages#A_Flexible_Screen_Capture_App
import wx
app = wx.App()  # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.Bitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem  # Release bitmap
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)

Comment: app = wx.App() otherwise you might get: wx._core.PyNoAppError: The wx.App object must be created first!
Also, download wxPython from here: http://wxpython.org/download.php For some reason it's not the same "wx" if you just do "pip install wx"
Comment: @Sepero: How would you get multiple monitors?
Comment: @ChristianAdam: your must  pip install -U wxPython
Comment: AttributeError: 'module' object has no attribute 'App'
Comment: CLI windows coming out empty
Comment: wx.EmptyBitmap is deprecated: `wxPyDeprecationWarning: Call to deprecated item EmptyBitmap. Use :class :wx.Bitmap instead` use wx.Bitmap
Comment: Note that you actually need to assign the result of `wx.App()` as cSN writes, otherwise it will get GC'd with unpredictable results.
Answer: This can be done with PIL. First, install it, then you can take a full screenshot like this:
import PIL.ImageGrab

im = PIL.ImageGrab.grab()
im.show()

Comment: PIL.ImageGrab is only for Windows and OS X. Linux alternative to ImageGrab is  pyscreenshot
Comment: As of PIL 7.1.0, [support has been added for `ImageGrab.grab()` on Linux](https://pillow.readthedocs.io/en/stable/releasenotes/7.1.0.html#x11-imagegrab-grab).
Answer: You can use the ImageGrab module. ImageGrab works on Windows and macOS, and you need PIL (Pillow) to use it. Here is a little example:
from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)

Answer: For pyautogui users:
import pyautogui
screenshot = pyautogui.screenshot()

Comment: pyautogui.screenshot('filename.png')
Comment: And how do I write the image into pgn file?
Comment: the result size of image with PIL is better than above module:  from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = r"E:\havaee\mypic.jpg"
snapshot.save(save_path)
Answer: A simple way to take a screenshot is through Pygame.
 pygame.image.save(Surface, filename)

Where 'Surface' is the surface you are taking a screenshot of, and 'filename' is the file path, name, and type where you save thew image.
You can export as BMP, TGA, PNG, or JPEG. As of Pygame 1.8, PNG, and JPEG also work.
If no file extension is specified it will default to a .TGA file.
You can even use the 'os' library for saving to specific file directories.
An example:
import os
import pygame
surface = pygame.display.set_mode((100, 100), 0, 32)
surface.fill((255, 255, 255))
pygame.draw.circle(surface, (0, 0, 0), (10, 10), 15, 0)
pygame.display.update()
pygame.image.save(surface, os.path.expanduser("~/Desktop/pic.png"))

This saves anything on the 'surface' Surface to the user's desktop as pic.png
Comment: As far as I know, Pygame is platform is independent. This code will only screenshot the pygame screen, and only the pygame screen. If your screen spans across 2 monitors, i would think that it would be able to (though I am unable to test this). Hope this helps!
Comment: Two questions: 1. Is pygame platform-independent? 2. Can you get a multiple-monitor screenshot?
Answer: If you want to snap particular running Windows app you'll have to acquire a handle by looping over all open windows in your system.
It's easier if you can open this app from Python script.
Then you can convert process pid into window handle.
Another challenge is to snap the app that runs in particular monitor. I have 3 monitor system and I had to figure out how to snap display 2 and 3.
This example will take multiple application snapshots and save them into JPEG files.
import wx

print(wx.version())
app=wx.App()  # Need to create an App instance before doing anything
dc=wx.Display.GetCount()
print(dc)
#e(0)
displays = (wx.Display(i) for i in range(wx.Display.GetCount()))
sizes = [display.GetGeometry().GetSize() for display in displays]

for (i,s) in enumerate(sizes):
    print("Monitor{} size is {}".format(i,s))
screen = wx.ScreenDC()
#pprint(dir(screen))
size = screen.GetSize()

print("Width = {}".format(size[0]))
print("Heigh = {}".format(size[1]))

width=size[0]
height=size[1]
x,y,w,h =putty_rect

bmp = wx.Bitmap(w,h)
mem = wx.MemoryDC(bmp)

for i in range(98):
    if 1:
        #1-st display:

        #pprint(putty_rect)
        #e(0)

        mem.Blit(-x,-y,w+x,h+y, screen, 0,0)

    if 0:
        #2-nd display:
        mem.Blit(0, 0, x,y, screen, width,0)
    #e(0)

    if 0:
        #3-rd display:
        mem.Blit(0, 0, width, height, screen, width*2,0)

    bmp.SaveFile(os.path.join(home,"image_%s.jpg" % i), wx.BITMAP_TYPE_JPEG)
    print (i)
    sleep(0.2)
del mem

Details are here
Answer: First of all, install PrtSc Library using pip3.
 import PrtSc.PrtSc as Screen
 screenshot=PrtSc.PrtSc(True,'filename.png')

Get screenshot on Windows with Python?


angular.js http.get() service not working

Question: I'm not exactly sure where I'm going wrong but when I put my data into a separate .json file and used $http.get() to retrieve that data my scatter chart isn't visualizing anymore. Here's my code:
http://plnkr.co/edit/bJE8qTG8CEI957xKMh6q?p=preview
Specifically these lines I feel I might be making a mistake:
$http.get('data.json').success(function(response){
    $scope.exampleData = response.data;

Comment: do you have a property `data` in your response object? if not it is just `$scope.exampleData = response`
Answer: the $http.get() works fine.
There is an error below:
app.controller('ExampleCtrl', [$scope, $http, function ($scope, $http){
should be
app.controller('ExampleCtrl', ['$scope', '$http', function ($scope, $http){
and your json doesn't contain a data prop so change $scope.exampleData = response.data; to this $scope.exampleData = response;
also
var colorArray = ['#000000', '#660000', '#CC0000', '#FF6666', '#FF3333', '#FF6666', '#FFE6E6'];
$scope.colorFunction = function(){
  return function(d, i){
    return colorArray[i];
  };
}

needs to be in a controller; you get $scope is undefined if it isn't
edit
PSL is right, there is no data prop in the object, but still the original plnkr had errors in it. The get() worked just fine which was answering OPs question.
Comment: if you're going to downvote my answer, please leave a reason as to why. Please explain why this isn't working plnkr: http://plnkr.co/edit/ACS7S7JXx2P18M4Ce53C?p=preview  screenshot: http://i.imgur.com/4MZyKna.jpg
Comment: I edited the file for the few errors...but again the scatter chart is still not visualizing. My real question is..what is preventing the app from working? Of course I wouldn't down vote, you're trying to help. It is, however, discouraging when I come to a reputable tech help forum and get 3 down votes for something I consider pertinent.
Comment: yeah I dont understand the downvotes. Anyway, to get the scatter plot to show, change this `$scope.exampleData = response.data;` to this `$scope.exampleData = response;`
Comment: Awesome thank you. If I were to separate this into a service and controller I am under the impression this would essentially be it...but again now it's not visualizing for some reason. http://i.imgur.com/1vvNlsA.png


How can I pin an Internet Explorer URL shortcut or favorite to the Start screen with Group Policy in Windows 8.1?

Question: I created my Start UI like I want and used this PowerShell cmdlet to create the .xml file for a user's default layout:
export-startlayout –path <path><file name>.xml -as xml
(http://technet.microsoft.com/en-us/library/dn467928.aspx)
It created an AppID for each shortcut to a URL in the xml file.
Those AppIDs are not consistent across machines (I tried it).
How can I add shortcuts to my Start UI in Windows 8.1 Pro with the layout xml file?
I put the xml file here.  It works great but no shortcuts.
*Administrative Templates / Start Menu and Task bar / Start Screen Layout*

Answer: From my tests, the physical shortcut file needs to exist in the following path for it to display on the start screen:
%homeshare%\start menu\Programs\
Like you, I couldn't find a way of archiving this using "Export-startlayout".
Instead what I've done is put the shortcuts I want deployed in the GPT part of a GPO, I've then created a simply ROBOCOPY command to copy them to the start menu directory on login.
Example:
\domain.local\SysVol\tamar.local\Policies{F0C57572-7D16-49BC-8B4B-C8ABD9A363CB}\User\Scripts\Logon\ "%homeshare%\Start Menu\Programs" " webmail.url


I am trying to do multiline ToolTip. Linebreaking characters don`t work

Question: I am trying to create multiline ToolTip.
myToolTip.ToolTipTitle="First line\nSecond line";
myToolTip.ToolTipTitle="First line\r\nSecond line";
myToolTip.ToolTipTitle="First line\nSecond line";
string s="First line\nSecond line";
s = s.Replace("\n", Environment.NewLine);
myToolTip.ToolTipTitle=s;

All the above code shows only oneline tooltip and always adds extra row below:
enter image description here
I tried to insert in ToolTipTitle string line break characters such as "\r\n" "\n" or Environment.Newline, but it still does not work. Any suggestions?
Answer: The ToolTipTitle can't have multiple lines, but the caption can.
Try it this way:
StringBuilder sb = new StringBuilder();
sb.AppendLine("First Line");
sb.AppendLine("Second Line");
myToolTip.SetToolTip(button1, sb.ToString());

or
myToolTip.Show(sb.ToString(), button1);

Comment: Thank you @LarsTech. I found the resolution and added my own answer with working example.
Comment: @Alexander Wasn't that pretty much my answer?
Comment: Yes, it much, but I provided full working example. Besides, I think using symbol "\n" to break string is the shortest way. I also experienced the problem with flickering, when user moves the mouse over the PictureBox. This was also resolved.
Comment: @Alexander Shorter isn't always better.  It's safer to use Environment.NewLine or the AppendLine in my example.  Your question didn't address the flicker issue.
Answer: I found the resolution that is partially based on @Shimmy's answer on the question Displaying tooltip on mouse hover of a text.
I had to use toolTip1.SetToolTip(pictureBox1, TextString) function. ToolTip Title can`t be multiline.
The Timer is needed to avoid flickering. When the user moves mouse over PictureBox the ToolTip shows multiline text.
public partial class Form1 : Form
{
    private System.Windows.Forms.ToolTip toolTip1;
    private System.Windows.Forms.PictureBox pictureBox1;
    System.Windows.Forms.Timer ToolTipsTimer = new System.Windows.Forms.Timer();
    public Form1()
    {
        InitializeComponent();

        ToolTipsTimer.Tick += new EventHandler(ToolTipsTimerEventProcessor);
        ToolTipsTimer.Interval = 300;
        ToolTipsTimer.Start();
        toolTip1.AutomaticDelay = 300;

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    private void ToolTipsTimerEventProcessor(Object myObject, EventArgs myEventArgs)
    {
        ToolTipsTimer.Enabled = false;
    }

    string TextString = "First line\n Second line";
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (!ToolTipsTimer.Enabled)
        {
            toolTip1.SetToolTip(pictureBox1, TextString);
            ToolTipsTimer.Enabled = true;
        }
    }
}

Comment: When you answer your own question with help of [another answer](http://stackoverflow.com/a/39534999/3110834) a good manner is upvoting the answer which you used to solve the problem :)
Answer: There is not enough of your JavaScript code to troubleshoot your problem. If you were using a popup alert() then the "\n\n" would work; I do that all the time.
This is one workaround: Use the HTML5 title attribute and hard-code the line breaks. Like this:


Serve images from a directory but be accessed by a different URL path

Question: How can I specify a URL rewrite in my web.config whereby any request for an image is served from a different directory on disk?
The images are located in directory site-root\foo\bar\images. Normally they're accessible by http://site-root/foo/bar/images/
I'd like the images to be accessible via a different URL like http://site-root/img/
For example:
site-root\foo\bar\images\test.png

to be accessed at
http://site-root/img/test.png

I won't really need a filter for file extensions (png, gif, jpg, etc), but just rather any file/resource being requested from img to be read from the real directory.
How can I use ASP.NET web.config URL rewrites, or any other method, to achieve this?
I'm going for a web.config solution, as this will be deployed to Windows Azure Websites.
Answer: I've achieved this in the past by setting up a virtual directory in IIS to map the URL to a specific folder.
Comment: Thanks David. Unfortunately, I'm using Windows Azure Websites, and thus don't have access to create virtual dirs.
Comment: Sorry, I missed that in your question.
Answer: Use this web.config rewrite rule.
<system.webServer>
<rewrite>
  <rules>
    <rule name="Blog Images to Thier Real Location" stopProcessing="true">
      <match url="^img/(.*)" />
      <action type="Redirect" url="foo/bar/images/{R:1}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>
</system.webServer>

From Carlos AG's blog post IIS 7.0 and URL Rewrite


Will an IIS SelfSSL certificate still be valid when the signing server is replaced?

Question: Will my 10 year valid self-signed certificate, that is using a common name not resembling any hostname, still be valid/trusted by others in the AD, after the signing server is replaced in maybe a few years?
It will be used for 802.1x authentication.
I think yes, as it is being deployed via GPO to all clients, but I'd like some expert opinion on this please.
Answer: If you're deploying the self signed certificate into a Trusted container in the user's or computer's local store via GPO then yes it will be valid.


Material UI, internal link scrolling not working on mobile

Question: I am using internal links such as /lessons/lesson-slug#heading-slug for internal scrolling on a page. All of this works totally fine on desktop, but breaks on mobile view with an overlaid drawer nav component. See screen recording:

I can't pinpoint where the problem is... I have already tried passing these ModalProps on the Drawer component, but no luck sofar:
ModalProps={{
            hideBackdrop: true,
            disableScrollLock: true,
            disablePortal: true,
            disableAutoFocus: true
          }}

Any ideas? thanks in advance.
Answer: Adding disableEnforceFocus: true fixed it.


How to display custom block without default wrapped html around

Question: I have custom module with new block. When this block is displayed, the output is wrapped with html tags from block.tpl.php template:
<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

I would like to display only content without the wrapped html around. I can accomplish this by overriding the block.tpl.php file in the theme, however. This requires me to go into every possible theme and override the template file every time installing the module. How to avoid that? How to display only content of the custom block from custom module without overriding template file?
Is there some attribute that i can set in the block render array like #theme_wrapper?:
$block['content'] = array(
               '#markup' => '
Hello World!
',
              // '#theme_wrappers' => array('attempt_to_override'),
)

I was thinking the 'theme_wrappers' attribute can be used, but i wasn't able. Thank you for any help
Answer: I don't actually think this is possible using a block; however, take a look at hook_block_view() and hook_block_view_alter().
Those MAY do what you want.  They allow you to alter the contents of a block before it is displayed; however, it is likely that you'll still end up with the contents of the block 'inside' the template's block boiler plate.
Keep in mind that it's up to the theme to decide how blocks are styled so the theme markup boilerplate is there by design.
If you need to inject html into specific areas of the site / page you might need to do something differently.
In that case hook_page_build() or hook_page_alter() might be a better choice.
Comment: Thank You SMTF. I agree it is more of responsability of theme and not the module/block per say


Retrieve (negative) double values from Cassandra using Hector gives wrong results

Question: I want to store double values (as column names) using Hector. As far as I understand it, I have to use the LONGTYPE comparator in conjunction with a DoubleSerializer.
I have created a columnFamily with ComparatorType.LONGTYPE as comparator and ComparatorType.UTF8TYPE as validator.
I insert data into my column family like this:
Mutator<String> m = HFactory.createMutator(_keyspace, _ss);
m.addInsertion(rowKey, cf, HFactory.createColumn(colKey, "", _ds, _ss));

where rowKey is a String, colKey is a double, _ds a DoubleSerializer and _ss a StringSerializer.
Everything seems to work for positive double values. However, when I want to do range queries with negative start and/or finish parameters, things get odd.
This is the code I use to query:
SliceQuery<String, Double, String> q =
          HFactory.createSliceQuery(ks, _ss, _ds, _ss);
q.setRange(START, FINISH., false, 500);

When START and FINISH are positive, everything is ok.
When START is negative and FINISH positive, it will return the correct positive values, but only those negative values that are actually smaller then START.
When both are negative and START is smaller (as it should be !?) then FINISH, it will throw an
InvalidRequestException(why:range finish must come after start in the order of traversal).

When both are negative, but START is bigger then FINISH (i.e. less negative), it will return the correct results, but in the wrong order (the least negative, i.e. biggest, first).
Can anyone comment on that? Am I doing something wrong or is there maybe a bug in hector somewhere?
Edit: Unfortunately, the DoubleType has been removed in a previous version of hector. I forgot to mention that the version Im using is 1.1-0.
Answer: You should use the LongSerializer, as a double-precision floating-point number and a 64-bit integer are not the same.  It's not at all surprising that 64-bit negative integers would come out strangely when using a deserializer expecting doubles, as the encoding is different.
Answer: Since there seemed to be no way to "solve" this issue, I have implemented Double and Float format for hector. It has been pulled into the masterbranch and is therefore available in current snapshot .
I assume it will make its way into the next release as well.


Unable to set umask for Ansible tasks

Question: I'm trying to run an arbitrary Ansible module with a specific umask (0002).
Some Ansible modules (like git) support a umask parameter (or a mode parameter to set permissions directly), but many do not.
To my knowledge, Ansible does not invoke a shell (unless you use the shell module), so changing the umask in my shell profile is useless.
My approach was to change the UMASK line in /etc/login.defs, but that didn't make a difference to Ansible. The umask remains at 0022.
PAM seems to be configured to include pam_umask.so.
I know I could use the shell module as a workaround (shell: umask 0002; some_command) but that seems like an ugly hack.
How do I get Ansible to respect my umask?
This is Ansible 2.9.9 targeting a CentOS 8 System.
Comment: There is not reason why this would not work. If it does not work is not because of Ansible.
Comment: In case you are running Ansible locally, did you remember to logout and login again after changing `/etc/login.defs`? You might also have to enable the `pam_umask.so` PAM module. See https://stackoverflow.com/questions/10220531
Comment: Good point, but in this case Ansible was targeting a remote system
Answer: It is possible to change the umask for the remote host(s), the simplest way is to edit the ~/.bash_profile of the remote_user to have for instance:
umask 0002

To use that setting you'll need to change executable in your ansible,cfg, or use ansible_shell_executable in your inventory:
[demo]
example.com ansible_shell_executable='/bin/bash -l'

Why this works? The -l argument forces bash to behave as a login shell, sourcing the profile.
Verification Use the verbosity -vvv when running ansible or ansible-playbook, you'll see that any Ansible module is running form the executable with argument -l (and -c added), you'll see something like:
EXEC /bin/bash -l -c '/usr/libexec/platform-python /home/demo/.ansible/tmp/ansible-tmp-1706875415.3499873-5842-271431387344170/AnsiballZ_command.py && sleep 0'

Comment: Hey, many thanks for paying attention to such an old question!
While this would probably work out, I'm wondering how to do this without invoking umask from a particular shell's (or even ssh) config.
There has to be a way to set a default umask somewhere deeper in the stack?
I thought `pam_umask` would be the way to go, but couldn't get that to do anything.
Comment: My later answer on this question is more elegant.

The pam_umask module tries to get the umask value from the following places in the following order:
      ·   umask= entry in the user's GECOS field
       ·   umask= argument
       ·   UMASK entry from /etc/login.defs
       ·   UMASK= entry from /etc/default/login
Comment: While your later answer would indeed be preferable, I'm still searching for a way to do this without involving shell or ssh config. As you can see in the original question, I already tried to modify `/etc/login.defs`. Maybe I did something wrong there, maybe some of the other possibilities you mentioned might help.
It will take me some time to tinker with that, as I'm busy with other stuff at the moment unfortunately.
Answer: The SSH rc file ~/.ssh/rc is much like a shell startup file (e.g., ~/.bash_profile), but it executes only when your account is accessed by SSH. It is run for both interactive logins and remote commands. Place any commands in this script that you would like executed when your account is accessed by SSH, rather than an ordinary login.
You need PermitUserRC yes in /etc/sshd_config, but that is the default for OpenSSH.

Unable to set umask for Ansible tasks


Problems with jQuery slider and input

Question: I'm trying to make my first jQuery slider, and I have this code:
$("#str").keyup(function(event) {
var data=$("#str").val();
if (data.length>0)
{
 var intdata=SpecialRound(parseFloat(data));
 if (intdata>=0 && intdata<=20)
 {
  $("#str_slider").slider("option", "value", data);
 }
 else
 {
  if (intdata<0)
  {
   $("#str").val("0");
   $("#str_slider").slider("option", "value", "0");
  }
  if (intdata>20)
  {
   $("#str").val("20");
   $("#str_slider").slider("option", "value", "20");
  }
 }
}
});

Although, I have a problem. When I write something in the input with the ID #str, nothing happens. Though, the sliders works perfect.
You can test att http://vpopulus.tk/damage
EDIT: I basicly want to make so when you edit the input, the slider is changed too.
Comment: Oh, that is just a function I use to round to two decimals.
Answer: I think your selector $('#str') is the problem, because your input has no ID #str but just a name attribute with value "str". The correct selector would be $('input[name="str"]')
EDIT:
The actual problem is this SpecialRound function because you're using a not-existing function "round()" there. Use this instead:
//Special round
function SpecialRound(f) {
   return Math.round(f*100) / 100;
}

Comment: Ah, you didn't put your code (that one binding the event listener to the keyup event) into your onReady event listener, so that it would be executed when the DOM is ready for that kind of action. Now jQuery tries to bind the event listener to an input that isn't yet present the time your code is executed. Understand what I mean?
Comment: Ah, sorry. I mixed some old code with the new one. But you can see at about row 232 that I have ID.
Comment: Ok, didn't see the second input, sorry. Your specialRound() function is the problem, you're using `round()` there, but it is actually `Math.round()`.
Answer: if i were you i'd use the change event instead of keyup
for example:
$( "#str" ).change(function() {
    var val = this.val(); // you can do your rounding here then...
    $("#str_slider").slider( "value", val );
});

Answer: By looking at your testpage, you have at line 54 in SpecialRound
var r=round(f*100)/100;

that should be
var r=Math.round(f*100)/100;

Problems with jQuery slider and input


Comparing many means in JMP

Question: I'm trying to compare several sets of experiment data, by comparing means. I read there are several different tests such as Each Pair, Student's t and All Pairs, Tukey HSD, which give different circles of different radius, an example shown below

How are the circles defined? How do I calculate the radius? And is there a rule what test one should use for what kind of data?
Comment: What kind of software is that?
Comment: @mbq, This is JMP. But is this comparison circle a general concept, not specific to the software?
Comment: This is a first time I see such plot, so I think it is native to JMP. BTW I bet SAS would sue for even thinking to implement this in other applications (-;
Comment: @mbq, I'm sure they'll do. But what applications are these plots for? Or what other criteria I can use to compare data? Basically I want to compare several data sets and find out which set is _significantly different_ from others, so I can exclude them in my future development.
Comment: I suspect the red ones are outliers due to various methods and radii somewhat correspond to confidence intervals; but honestly I have no idea what this mean. However the question is now properly tagged so I hope some JMP expert will give you a satisfying answer soon.
Answer: There is a discussion of the circle construction in the JMP help/manuals. See Statistical Details for Comparison Circles.
Answer: those are post-hoc tests which should be performed after a ANOVA in JMP. I don't think you should take into account the circle, which are here I think for visual comparison.
If you have issue for statistical test: Clic on mean/ANOVA to obtain the result of the ANOVA, it will indicate if you have a statistical difference among your conditions/treatments. If the result provided below the graph is significant (in Analysis of Variance: Prob>F is <0.05 or lower), you can perform one of the posthoc test: choose one, not all of them. Choice may depend on your dataset or statistical reasons but I am not expert enough to provide you good explanation of all post hoc tests. Usually, in Biology, each pair student t test or Tukey HSD are used. Tukey HSD may provide less Type I error.
Tukey HSD results are detailed below the figure and give you groups such as A, B, AB, C, D, etc... Different letter will indicate conditions/groups that are significantly different. Results also give the detailed P statistic. This is the result you want.

Comparing many means in JMP


Subdomain redirect to my external IP - SSL Certificate not valid

Question: I am running an local Ubuntu-Server as my cloud. This machine is reachable from the outside via my routers portforwarding. This works fine (via IP). Now i created a subdomain in my existing 1und1 domain and used "domain-redirect", to redirect this subdomain xxx.mydomain.com to my external (static) ip with port, which looks like that: https://ip.ip.ip.ip:2000/nextcloud
This is also working fine (but inputs the IP in the adressbar, instead of xxx.mydomain.com), but the standard ubuntu SSL-Cert is obviously not trustworthy. Thats why i bought a cheap ssl-cert from comodo for my subdomain: xxx.mydomain.com
Then i imported the certificate to my ubuntu server (/etc/ssl/certs...) and corrected the /etc/apache2/sites-availabe/nextcloud.conf
(SSLCertificateFile and SSLCertificateKeyFile). This (after apache2 restart) lead to the browser reading the Comodo ssl certificate when browsing to xxx.mydomain.com.
Problem: The Comodo Cert is still not trusted (There are issues with the site's certificate chain (net::ERR_CERT_COMMON_NAME_INVALID).)
Has this something to do with the redirecting process? And if yes, how can i solve it?
Or have i missed something else?
Thanks in advance!
€dit: This is the nextcloud.conf file:
Alias /nextcloud "/var/www/nextcloud/"
<VirtualHost *:443>
ServerName          cloud.myDomain.com
DocumentRoot        /var/www/nextcloud

SSLEngine               on
SSLCertificateKeyFile /etc/ssl/private/myComodo.key
SSLCertificateFile /etc/ssl/certs/myComodo.crt
SSLCertificateChainFile /etc/ssl/certs/myComodo.ca-bundle
</VirtualHost>
<Directory /var/www/nextcloud/>
  Options +FollowSymlinks
  AllowOverride All

 <IfModule mod_dav.c>
  Dav off
 </IfModule>

 SetEnv HOME /var/www/nextcloud
 SetEnv HTTP_HOME /var/www/nextcloud

</Directory>

Comment: redirect as ...? does it rewrite the URL from https://sub.domain.tld/ to https://220.127.116.11/ ?
Comment: Yes, it does. I can chose between HTTP-Redirect (which i use) and Frame-Redirect (which produces an too many redirects error, so i went with HTTP-Redirect).
Answer: The problem is most probably the redirect.
Let's say you use sub.domain.tld and you get a certificate for this host.
The second you redirect the visitor to 126.96.36.199 the certificate is no longer "valid", because it was setup to work for (COMMON_NAME) https://sub.domain.tld and not https://220.127.116.11.
The only real solution would be to work with A/CName records. If you do not have a static IP you could use a free dynamic dns and then setup a CNAME record.
Comment: Thanks! I have a static IP. How to "work with A/CName records"?
My hoster has the following settings for my subdomain:
A/AAAA- und CNAME-Entries, MX-Entries and TXT- / SRV-Entries.
Comment: Simply create an A record pointing to your IP.


Does this progression through the modes have a name?

Question: I discovered that if I play a major scale, i.e. Ionian mode, then move through the modes with the same root note in the following order:

Ionian
Mixolydian
Dorian
Aolian
Phrygian
Locrian

At this point I'd next play the Lydian scale, but starting a semitone lower than the Ionian I started with earlier.
Then I'd finish on the Ionian scale starting a semitone lower than my original scale. I've sort of drifted downwards by a semitone. I've attached the snap showing what I'd play if I started in C major. But applying the same sequence of modes again means I drift down a semitone each time I reach the next Lydian scale.
I really like that each subsequent scale in the sequence of modes has one more flat than its predecessor.
Question is - what's the name of this progression?
Comment: For completeness, maybe you should start with lydian!
Comment: Notice how you are adding a flat every time ^^ you arranged modes in a circle of 5ths/4ths order, and when you complete the full turn, you end up one semitone higher / lower from the starting note, based on the direction you took.
Comment: Why does C Lydian suddenly have to be Cb Lydian?
Comment: @awelotta Yes for consistency you're absolutely right. When I was framing this question I did consider starting with Lydian but I wanted to start with the most familiar scale possible so people start on a firm footing and only then go somewhere unfamiliar. Rather than _starting_ with Lydian.
Comment: Each subsequent line differs from its predecessor in just one pitch. e.g. C Ionian to C Mixolydian - just the B changes to Bb. Later on, C Lochrian changes to Cb Lydian by changing C to Cb. All the other pitches stay the same.
Answer: You have discovered they way I practice scales.  If you are playing C mixolydian after playing C maj you are in the Key of F maj. C Dorian is Bb Maj, etc.  You are changing key up a 4th each time you change modes like this, and as you discovered the pattern comes back to Ionian but a half step up from where you started.  Keep going until you've covered the neck!  I usually start on G.
I would not call this a progression but a sequence of key changes, following the circle of 4ths.  This is a great way to play through keys on the guitar as it teaches you to stay in place through the change rather than jumping up half the length of the neck.
Comment: Would you recommend playing melodic/natural minor when you get to Aeolian?
Comment: Not in this context.  When I play through the modes like this I am going through the circle of 4th and I an really in the Major Key.  When I play G aeolian I am in Bb Major and want to hear it that way.
Answer: I also find this conceptual arrangement of the diatonic modes useful and came to search SE (and the wider web) for an established name for it.  I have found none.
The name I have decided to use for myself is the Circle of Modes, since it has a similarity to the Circle of Fifths.  As you say, it highlights the relatedness of modes that only differ from each other by the alteration of one scale degree.
Not surprisingly, I prefer to visualize the modes around a circle or 7-pointed star with the "sharper" ones going clockwise.  It doesn't actually change anything about the relationships between modes, but it can make some things more apparent than they would be in other visual or textual depictions.
There are many interesting properties that are highlighted by the arrangement, for example:  Consider the chord quality of tonic triad of each mode:  You have the oddball Locrian with its diminished tonic triad, the "Majors" all lined up going counterclockwise from it (Lydian, Major, and Mixolydian), and the "minors" clockwise from it (Phrygian, Aeolian, and Dorian).
After some thought, I standardized this with Dorian at the top, because if you start with the Dorian for any given tonic, you can reach any of the other modes for that tonic by the shortest distance (without altering the tonic itself).  Dorian is also special in other ways, e.g. as the only symmetrical diatonic mode.
Comment: This is LIMDAPL too, I think.
Answer: I just discovered (Thanks to @JohnDoe in a comment he added to the question below) that the sequence of modes I discovered on my own has the acronym LIMDAPL and is An Actual Musical Thing. You can search for LIMDAPL here in MP&T or google more widely.
https://music.stackexchange.com/a/82646/9426
Answer: In one sense, you have discovered "tonality" in the wide sense. Taking fifths or fourths gives a symmetric circle of fifths. Replacing a single by a diminished fifth yields a system for which note has a unique relation to all other notes.


Gatling Handling of Cache-Control headers

Question: The response I am testing using Gatling has the following headers, which includes a Cache-Control header of 2 minutes.
Accept-Ranges: bytes
Cache-Control: max-age=120, public
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 17975
Content-Type: application/json;charset=UTF-8
Date: Tue, 06 Oct 2015 00:21:43 GMT
ETag: "0be271f09dc4c9a0ddea9e4b5899b59b4"
Expires: Tue, 06 Oct 2015 00:23:42 GMT
P3P: CP="CAO DSP COR CURa ADMa DEVa TAIa PSAa PSDa IVAi IVDi CONi OUR SAMo OTRo BUS PHY ONL UNI PUR COM NAV INT DEM CNT STA PRE"
Vary: Accept-Encoding
X-Application-Context: application:prod

When using a basic simulation like so, I can easily overwhelm the servers despite being behind a Varnish server.  Is Gatling by default including a cache buster?
constantUsersPerSec(500) during(1 minute)

Answer: Each virtual users has its own caches, there's no global shared one (it wouldn't make sense). Here, you're creating 500 new virtual users by second. Assuming your scenario only sends one request, you'll be hitting your server 500 times/s. Isn't it what you observe?
Comment: Thanks for the response.  The RFC mentions that the max-age takes precedence: "If a response includes both an Expires header and a max-age directive, the max-age directive overrides the Expires header, even if the Expires header is more restrictive."  I'd expect each user to have it's own cache, but I'd also expect the Varnish server to always serve a cached copy as it's been instructed to cache the content for 2 minutes.
Comment: Right, sorry. Gatling properly gives max-age higher precedence over expires. Fixing my answer.
Comment: If your resource was indeed cached, I would expect a s-maxage attribute too. Are you sure about your Varnish configuration?


Case Statement with complex AND/OR not working as intended

Question: I am expecting this to return the value of 'C', but it is returning 'A'.  I cannot seem to figure out why this will not work as my logic looks sound.
DECLARE @WeekStartDay varchar(10)
DECLARE @WeekEndDay varchar(10)
SET @WeekStartDay = 'Saturday'
SET @WeekEndDay = 'Saturday'

SELECT

    CASE

        WHEN (
                ((@WeekStartDay = 'Saturday') OR (@WeekStartDay = 'Sunday'))
                         AND
                ((@WeekEndDay <> 'Saturday') OR (@WeekEndDay <> 'Sunday'))
            )
            THEN 'A'

        WHEN (
                ((@WeekEndDay = 'Saturday') OR (@WeekEndDay = 'Sunday'))
                        AND
                ((@WeekStartDay <> 'Saturday') OR (@WeekStartDay <> 'Sunday'))
            )
            THEN 'B'
        WHEN (
                ((@WeekEndDay = 'Saturday') OR (@WeekEndDay = 'Sunday'))
                        AND
                ((@WeekStartDay = 'Saturday') OR (@WeekStartDay = 'Sunday'))
            )
            THEN 'C'

    END AS Result

My intended function is:
I am trying to get it to deteremine
IF the @WeekStartDay = Saturday or Sunday AND @WeekEndDay IS NOT Saturday or Sunday THEN 'A'
IF the @WeekEndDay = Saturday or Sunday AND @WeekStartDay IS NOT Saturday or Sunday THEN 'B'
IF @WeekStartDay AND @WeekEndDay BOTH = Saturday or Sunday THEN 'C'
Hmmm from responses looks like my logic was way more off than I thought.
Answer: AND means when both conditions are true, OR means when either condition is true.
@WeekStartDay is "Saturday".
@WeekEndDay is "Saturday".
Therefore if you start breaking it all down:
A: (TRUE OR FALSE) AND (FALSE OR TRUE) = TRUE AND TRUE = TRUE

A wins because it is the first condition to match your requirements.
You'll have to explain further what you are trying to do, because I cannot see what I'd need to do to help fix the code.
Comment: I am trying to get it to deteremine

IF the @WeekStartDay = Saturday or Sunday AND @WeekEndDay IS NOT Saturday or Sunday THEN 'A'
IF the @WeekEndDay = Saturday or Sunday AND @WeekStartDay IS NOT Saturday or Sunday THEN 'B'
IF @WeekStartDay AND @WeekEndDay BOTH = Saturday or Sunday THEN 'C'

Hmmm, looks like my logic was way more off than I thought.
Answer: Substituting the parameter values in as literals gives (for the first case)
         WHEN ((('Saturday' = 'Saturday')  OR ('Saturday' = 'Sunday'))
                           AND
               (( 'Saturday' <> 'Saturday') OR ( 'Saturday' <> 'Sunday')))

Which is
         WHEN ((True OR False) AND (False OR True))

Which is
         WHEN (True AND True)

Which is
         WHEN (True)

I think you need
SELECT
    CASE WHEN @WeekStartDay IN ('Saturday', 'Sunday') THEN
        CASE WHEN @WeekEndDay IN ('Saturday', 'Sunday') THEN
            'C'
        ELSE
            'A'
        END
    ELSE
        CASE WHEN @WeekEndDay IN ('Saturday', 'Sunday') THEN
            'B'
        ELSE
            NULL /*You haven't said what should happen here?*/
        END
    END
 AS Result

Comment: Thank you so much this is a huge help! Oh wow, Yeah, that makes a lot more sense nesting the case statements like that and using IN. I appreciate it!
Answer: (@WeekEndDay <> 'Saturday') OR (@WeekEndDay <> 'Sunday') is the problem.
That will always return true.
Case B: has the same issue with
(@WeekStartDay <> 'Saturday') OR (@WeekStartDay <> 'Sunday')


Obter o menor valor com o map em um dict

Question: Estou estudando a função map() e queria saber se tem como eu recuperar o menor valor de um dicionário dentro de uma lista. Da forma que estou fazendo só estou conseguindo alterar todos os valores.
arroz = [
{'item': 'arroz', 'preco': 20.15, 'mercado': 'mercado_1'},
{'item': 'arroz', 'preco': 19.99, 'mercado': 'mercado_2'},
{'item': 'arroz', 'preco': 22.00, 'mercado': 'mercado_3'},
{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}]

def menorpreco(arroz, valor):
    def item(p):
        p['preco'] = valor
        return p
    return map(item, arroz)

print(list(menorpreco(arroz, 10)))

Answer: A função item está modificando o valor do preço porque você faz p['preco'] = valor, então não parece ser o que você precisa.
Além disso, map serve para aplicar uma função a todos os elementos de um iterável, retornando os resultados desta função (no caso, ela está usando a função item, que modifica os preços, por isso o retorno tem os preços modificados).
Se você quer buscar o menor preço, use min:
def menorpreco(arroz):
    return min(arroz, key=lambda d : d['preco'])

arroz = [
{'item': 'arroz', 'preco': 20.15, 'mercado': 'mercado_1'},
{'item': 'arroz', 'preco': 19.99, 'mercado': 'mercado_2'},
{'item': 'arroz', 'preco': 22.00, 'mercado': 'mercado_3'},
{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}]

mais_barato = menorpreco(arroz)
print(mais_barato) # {'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}

O parâmetro key indica qual valor será usado na comparação, e no caso eu usei o preço.
O retorno é todo o dicionário que contém o menor preço. Mas se quiser apenas o valor, basta fazer mais_barato['preco'].

Mas em caso de empate (tem mais de um item que é o mais barato), você pode retornar uma lista com os itens mais baratos:
def menorpreco(arroz):
    # primeiro vê qual o menor preço
    menor_preco = min(arroz, key=lambda d : d['preco'])['preco']
    # retorna uma lista com todos os itens cujo preço é igual ao menor_preco
    return [ item for item in arroz if item['preco'] == menor_preco]

arroz = [
{'item': 'arroz', 'preco': 20.15, 'mercado': 'mercado_1'},
{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_5'},
{'item': 'arroz', 'preco': 19.99, 'mercado': 'mercado_2'},
{'item': 'arroz', 'preco': 22.00, 'mercado': 'mercado_3'},
{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}]

print(menorpreco(arroz)) # [{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_5'}, {'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}]

Comment: Obrigado. me ajudou e muito no entendimento. vlw


Domain of Composite Functions by using Maple

Question: I have two functions $f(x)=\frac{(x+1)}{(x-1)}$ and $g(x)=\frac{(x-1)}{(x+1)}$. I need to confirm by using maple that $D_{fog}=R-\{-1\}$ and $D_{gof}=R-\{0,1\}$. When I try f@g and g@f syntax im CompositionPlot command on Maple prompt, I get graphs which does not show the discontinuities. How to handle such situations in Maple?
Comment: Are you to find the domain of the composite function?
Comment: Is your problem the composition of two functions? or, moreover, finding the domains and ranges?
Answer: <code>f:=x->(x+1)/(x-1):
g:=x->(x-1)/(x+1):

discont((f@g)(x),x);
                          {-1}

discont((g@f)(x),x);
                         {0, 1}
</code>
Comment: Apart from discontinuities, you can try to find any other restrictions on the domain. Eg, compare the unretricted result `x=x` from `solve({evalc(Im((x+1)/(x-1)))=0},x);` with the restricted domain (union) `{1 < x}, {0 <= x, x < 1}` returned by `solve({evalc(Im((sqrt(x)+1)/(x-1)))=0},x);`
Comment: May I ask your point of view doing [this](http://math.stackexchange.com/q/575797/8581) by Maple? Thanks acer.
Answer: You need to create a function first. So, in your case, we have in maple language
<code>[> f := x -> (x+1)/(x-1);
   g := x-> (x-1)/(x+1);
   h := (g@f)(x);
</code>
This will give you the composition of the two functions.
Comment: @B.S.: Thanks for the edit. I really appreciate it.
Comment: $\ddot\smile{}{}$
Answer: You might consult Maple to examine the functions $g\circ f(x)$ and $f\circ g(x)$ and finding their asymptotes. I mean vertical an horizontal ones. The data which is achieved can help us to have a good perspective of domains and also ranges. Here are the needed codes:
<code>[> f := x-> (x+1)/(x-1):
   g := x-> (x-1)/(x+1):
   h := x-> simplify((g@f)(x),symbolic);

                                     h(x)=1/x
[> with(Student[Calculus1]):
   Asymptotes(h(x), x);
                                  [y = 0, x = 0]
</code>


Using Amazon S3 for multiple remote data site uploads, securely

Question: I've been playing about with Amazon S3 a little for the first time and like what I see for various reasons relating to my potential use case.
We have multiple (online) remote server boxes harvesting sensor data that is regularly uploaded every hour or so (rsync'ed) to a VPS server. The number of remote server boxes is growing regularly and forecast to keep growing (hundreds). The servers are geographically dispersed. The servers are also automatically built, therefore generic with standard tools and not bespoke per location. The data is many hundreds of files per day.
I want to avoid a situation where I need to provision more VPS storage, or additional servers every time we hit the VPS capacity limit, after every N server deployments, whatever N might be.
The remote servers can never be considered fully secure due to us not knowing what might happen to them when we are not looking. Our current solution is a bit naive and simply restricts inbound rsync only over ssh to known mac address directories and a known public key. There are plenty of holes to pick in this, I know.
Let's say I write or use a script like s3cmd/s3sync to potentially push up the files.

Would I need to manage hundreds of access keys and have each server customized to include this (do-able, but key management becomes nightmarish?)
Could I restrict inbound connections somehow (eg by mac address), or just allow write-only to any client that was running the script? ( i could deal with a flood of data if someone got into a system? )
having a bucket per remote machine does not seem feasible due to bucket limits?
I don't think I want to use a single common key as if one machine is breached then potentially, a malicious hack could get access to the filestore key and start deleting for ll clients, correct?
I hope my inexperience has not blinded me to some other solution that might be suggested!

I've read lots of examples of people using S3 for backup, but can't really find anything about this sort of data collection, unless my google terminology is wrong...
I've written more than I should here, perhaps it can be summarised thus: In a perfect world I just want to have one of our techs install a new remote server into a location and it automagically starts sending files home with little or no intervention, and minimises risk? Pipedream or feasible?
TIA, Aitch
Edit 1:
Perhaps bad form to answer ones own question but...
After much further googling and browsing it appears that the (new?) Identity and Access Management (IAM) might be what I need, it says "...IAM eliminates the need to share passwords or access keys, and makes it easy to enable or disable a User's access as appropriate..." I may start thinking about using the hw mac address as some sort of unique user and a hash os some form as the password so it can be programatically set.
Answer: That's correct you'll want to use IAM http://aws.amazon.com/documentation/iam/ to handle the per server credentials. As far as buckets there's a 100 bucket limit. One way to use multiple buckets can be to have a bucket per region, if the server is compromise you reduce your loss.  Another option is to have servers upload to bucket A every night and have a separate secure process that moves data from bucket A to bucket B (you only have access to this bucket). If a server is compromised you have up to the last run of the process.


Making Javascript Code run on Page Start

Question: I need to run my JavaScript Code on Page Start.

Currently I'musing a Onload property in Body Tag and using the code in that. By using in this way the code is running after the total page is loaded and it takes some time to make the label and the textbox to disappear.
Is there any way to run this code before the page Loads??
Or some other way in which I can accomplish this ?
(I'm using another JavaScript function to make the Label and Textbox Visible and Invisible basing on a DropdownList SelectedIndex so if I use properties like style="display:none" I could not make them visible again using JavaScript)
Comment: You would be better off using the JQuery `$(function () {});` rather than using the on load method of the HTML body.
Answer: You don't need to make your html elements invisible with javascript when the page is being loaded. You can set them invisible with css using visibility:hidden or display:none and then set them visible with javascript like this:
document.getElementById("someobject").style.display="block";
OR
document.getElementById("someobject").style.visibility="visible";

Also if you are using jquery you can use
$(document).ready(function(){

});

Comment: How can we make them visible using style="display:none" and set "display:block" with javascript??
Comment: Thank you @Rafael Sedrakyan. I've set the style="display:none" to the textbox & label and set document.getElementById("lbl_OtherProof").style.display = "block"; in JavaScript. I don't want to use JQuery for very minor things so I didn't try JQuery.
Comment: You're welcome. That is why I wrote "If you are using jquery" :)
Comment: Yep Gotcha. Thanks again. Bye
Answer: Use jquery's $(document).ready(function(){ this is my code; });


When does complexity in machine learning algorithms actually become an issue?

Question: I keep seeing complexities for machine learning algorithms e.g. Gaussian process implementation requires inversion of an nxn matrix so complexity is $O(n^3)$.
When does complexity actually become an issue? Is there a way to work out when it becomes prohibitive?
Comment: Are you looking for guidance on $n$ for Gaussian processes in particular or more general guidelines/information on complexity and scalability?
Comment: @jcken, more general guidelines please but would also appreciate info on n for Gaussian processes !
Answer: I use least-squares support vector machines a fair bit, which are $\mathcal{O}(n^3)$ for the most obvious implementation, and problems with up to a ten thousand or so examples are just about practical on my machine, but memory usage is not insignificant either, and 8192*8192 matrix in double precision format is 0.5Gb of memory.
Gaussian processes are not dissimilar to LS-SVMs (bit more expensive).
However as well as fitting the model, you will need to perform model selection as well (tuning the hyper-parameters) and that is where things get expensive as you have to refit the model many times (not so bad if you can perform the calculations in parallel).
If you have more data than that, you will probably want to look into sparse approximation.


Navigation block title no longer defaulting to user name in d7

Question: The default behavior for the Navigation block in d6 was to replace the word Navigation with the user name.  It appears that this logic was removed from the core user module in d7.  My client stills wants the user name to display.  Is there a way to duplicate this same behavior in d7 ??
What complicates things a bit is that we are using a mini panel that includes that block but I haven't figured out a way to override the title with the user name.  I've tried using the user:name token as the Navigation block title and then overriding the title with %title but it displays the literal value 'user:name' instead of the actual user name.
Answer: Have you set "user" in the contexts? It sounds like you do not have access to the %user:name token, and that's why it sets the actual text instead of the username.
Answer: This is the covered by the use case of the Block Title Link module. It allows you to replace any block title with your arbitrary title/link with token support (e.g. <code>[current-user:name]</code>). If you're just looking to rename the block title (without a link), you can leave the link field empty and just rewrite the title display.


Existence of equilibrium solutions of ODEs

Question: This may be impossible to answer, but I was curious as to general theorems that let one guarantee that an ODE system ($ f(x) \in \mathbb{R}^{n}$)
\begin{align*}
\dot{x} &= f(x)
\end{align*}
has at least one equilibrium solution?  For example, I think for planar systems, if the solution remains bounded, it must contain at least one equilibrium point (a corollary of Poincare Bendixson).
Can this be extended to higher dimensions?  What about solutions in the positive orthant, say that are bounded; can we be sure it contains a positive equilibrium point?  Are there any general theorems or techniques to attack such a question, based on the dynamics of the system.
Comment: You are asking about solutions to the non-linear system of equations $f(x)=0$. In general, a root-free region has index 0, so a non-zero index implies a root. The index is the generalization of the winding number, telling you how many unit spheres the normalized vector field covers.
Comment: If the system has a compact convex forward-invariant set $K$, then $K$ contains an equilibrium, see here https://mathoverflow.net/questions/68174/equilibria-exist-in-compact-convex-forward-invariant-sets
Answer: There is no such extension to higher dimensions: The following simple example in $\mathbb{R}^3$ has some bounded solutions but no equilibrium:
$$
x_1'=-x_2, \quad x_2'=x_1 \quad x_3'=1-(x_1^2+x_2^2).
$$
A bounded solution is $(x(t),y(t),z(t))=(\cos(t),\sin(t),0)$, for example. Of course this system also has unbounded solutions. The question if there is a dynamical system $x'=f(x)$ in $\mathbb{R}^3$ with no equilibrium but ${\bf all}$ solutions bounded is much harder, but answered by "yes" in a paper of Jones & Yorke:  The Existence and Nonexistence of Critical Points in Bounded Flows. A way to show the existence of an equilibrium based on the dynamics of the system is to look for invariant compact convex sets:
Assume that $f:\mathbb{R}^n \to \mathbb{R}^n$ is locally Lipschitz and that there is a nonempty compact convex set $C \subseteq \mathbb{R}^n$ such that for each $c \in C$ the solution of $x'=f(x)$, $x(0)=c$ stays in $C$ (that is $x(t,c) \in C$ $(t\ge 0)$), then $C$ contains an equilibrium.
To outline a proof first note that $f$ is Lipschitz continuous on $C$ (since $C$ is compact), that is for some $L\ge 0$ we have $\|f(x)-f(y)\| \le L\|x-y\|$ $(x,y \in C)$. Choose $P > 0$ such that $LP < 6$ and consider the Poincaré map $g:C \to C$, $g(c)=x(P,c)$. Since $g$ is continuous it has a fixed point $c_0 \in C$ by Brouwers FPT. Hence $t \mapsto x(t,c_0)$ is a periodic solution of $x'=f(x)$ in $C$. By the Busenberg-Fisher-Martelli inequality we have
$$
\int_0^P \int_0^P \|x(t,c_0)-x(s,c_0)\| dsdt \le\frac{P}{6} \int_0^P \int_0^P  \|x'(t,c_0)-x'(s,c_0)\|dsdt
$$
$$
\le \frac{LP}{6} \int_0^P \int_0^P  \|x(t,c_0)-x(s,c_0)\|dsdt,
$$
with $LP/6<1$ hence
$$
\int_0^P \int_0^P \|x(t,c_0)-x(s,c_0)\| dsdt =0.
$$
Thus  $x(t,c_0)=c_0$ $(t \in  \mathbb{R})$, which yields $f(c_0)=0$.


Kernels and Features

Question: I am studying about kernel ridge regression and please bear with me, I have a couple points that left me very startled.
Here is the equation for Kernel ridge regression:
$f^{ridge}(x) = \phi(x)^T\beta^{ridge} = \phi(x)^TX^T(XX^T+\lambda I)^{-1}y $
The explanation below clarifies the kernel matrix definition:
$K_{ij} = k(x_i, x_j) := \phi(x_i)^T\phi(x_j)$
And a definition for a $\kappa$ vector:
$\kappa(x)^T = \phi(x)^TX^T = k(x,x_{i:n})$
The regression equation is then:
$f^{ridge}(x) = \kappa(x)^T(K + \lambda I)^{-1}y$
It seems to be useful because:
→ at no place we actually need to compute the parameters β
→ at no place we actually need to compute the features φ($x_i$)
→ we only need to be able to compute k(x, x') for any x, x'
I don't really understand why we don't have to compute the features for φ($x_i$) - actually as far as I see we have to compute the features for all elements as they are incorporated in the kernel matrix K as well as in vector $\kappa$. Is there a way to compute the dot product without computing the features? Or what is this referring to?
Answer:
Is there a way to compute the dot product without computing the features?

Yes, exactly; this is the point of the "kernel trick." For example, the very popular exponentiated quadratic (also called Gaussian) kernel is
$$
k(x, y) = \exp\left( - \frac12 \lVert x - y \rVert^2 \right)
,$$
which you can see can be computed pretty straightforwardly, but the corresponding features $\varphi$ are rather complicated and even infinite-dimensional, so we don't use them in practice.

Kernels and Features


Session management in GWT client side

Question: I am building a GWT application where I have 3 RootPanels one of which contains the login panel (userId and Password). My application is a one page application. In order to login the user's id and password is varified from the server through RPC and if the combination is correct the next Panel loads which is my main application. Since it is a one page application, I want to know how should I carry out session management in this application.
Answer: Few ways I used in my different GWT applications

Checking user's credentials on each RPC (client/server). Follow generic
programming (obvious time delay in each RPC :-/)
Using Thread Local (preferred way)

getThreadLocalRequest().getSession().setAttribute("user", user); //and get

Use Cookies to allow the user's web browser to 'remember' the login.
Few others which I'm not using. For ex : Local storage (not secured, dependent)
Comment: I would like to understand one thing. Since my entire application is basically one page application consisting of loginPanel and then the application(mainPanel) which is added to the RootPanel once the user credentials are verified from mySQL database through RPC call.
Do I need to add another page to  my application for Login??
Or am I doing it correctly?
Comment: @VaibhavShukla You can still have user in your thread local. No need to add any other new pages.
Comment: Also, since the entire application share the same URL, how would session management work? Am I heading correctly till now ? Thank you:)
Comment: After studying 'Thread Local' I understood the most. I still have a small doubt in the example. What is IndexPage() class in that example?
Thanks :)
Comment: @VaibhavShukla Ask that in another question :) If you feel like your problem solved regarding the login, please upvote and mark as answer :)
Answer: You can configure session in your applications web.xml and you can write session filter which will filter all or specific request to the server where you can verify whether your session is expired or valid. If it is expired you can redirect user to whatever page you want.
Comment: Sorry for confusing you with word page. I am actually mean the view. Since you may have different views in your application. You can redirect user to session expired view.
Comment: I am new to GWT. I want to know whether or not I need to add an extra page to my application since my application only contains panels which appear and disappear once login credentials are verified through RPC call to my database. Thank you :)
Comment: I am still not clear. I have only Panels which get added and removed from rootpanel depending on validation of credentials. Am I doing it right? Can you help me through it? Thanks :) Any sample example would be very useful.
Answer: One of the great advantages of a AJAX-application is the chance to work without a session on the server side. As far as I remember Ray Ryan mentioned also stateless services on the Google I/O presentation "Best practices for Architecting GWT Applicaitons" at the Google I/O 2009.
Having a session on the server side has some impacts:

the session can expire
it needs a lot of resources
it makes load balancing a lot more complicated

Even if you have a session management on the server side, you have to check the user credentials on every server call! You can never be sure, that it is always your application that's calling your service!
So, I personally avoid using a session management on the server side in my GWT application.
Instead you can do something like that:
After a secuessful login, store some informations like userid, login time, ip address, etc. in a database table. Use the key of the record, encrypt it and send this token back to the client. All your services on the server side should require the userId and token as input parameters. Before you start doing your business logic, you should check the user credentials. Decrypt the token and read the record from the database table.

no record found -> user not logged on
not a valid database key -> user not logged on
compare the stored userId with the one, you get from the server call -> not equal ->  user not logged on
compare the stored ip address with the one from the server call -> not equel -> user not logged on

and so on.
Also, you should always use SSL!

Session management in GWT client side


Usando o método de triangularização inferior calcular o determinante de uma matriz transposta

Question: Usando o método de triangularização inferior, eu tenho que calcular o determinante de uma matriz transposta.
Eu estou querendo, a partir da matriz transposta, calcular o determinante usando para isso o método de triangularização inferior, pois o determinante tem que ser igual ao determinante da matriz original.
A matriz transposta já está no código, eu não estou conseguindo é fazer a triangularização para depois calcular o determinante.
Segue o código:
#include <stdio.h>

#define linhas 2
#define colunas 2

void main(){

    double mat[linhas][colunas] = { 1, 4, 7, 3 };
    // double mat[linhas][colunas] = { {2, -4, 8}, {5, 4, 6}, {-3, 0, 2} };
    // double mat[linhas][colunas] = { 1, 4, 7, 3, 2, 6, -3, 0, 2, 1, 3, 6, 8, -2, 5, -1 };
    // double mat[linhas][colunas] = { 1, 4, 7, 3, 2, 6, -3, 0, 2, 1, 3, 6, 8, -2, 5, -1, 0, 1, -7, -5, 4, 6, -10.5, 0, -5 };

    double det=1, mult, aux;

    int i, j, pivo; //indices para efetuar modificações na matriz
    int a, b; //indices apenas para debugar a modificação da matriz
    int r, l, inicio;
    int p, c;

    printf("\nMatriz antes do cálculo\n");
    for(a=0; a<linhas; a++){
        for(b=0; b<colunas; b++)
        printf("%.2f\t", mat[a][b]);
    printf("\n");
}
    printf("\n");

    aux= mat[linhas][colunas];
    mat[linhas][colunas] = mat[colunas][linhas];
    mat[colunas][linhas] = aux;
    printf("\nMatriz transposta é\n");
    for(a=0; a<colunas; a++){
        for(b=0; b<linhas; b++)
    printf("%.2f\t",mat[b][a]);
    printf("\n");
}
    printf("\n");

    //Triangulizando a matriz
    for(pivo=0; pivo>linhas; pivo--){

    for(i=pivo-1; i>linhas; i--){

    mult=(-1)*mat[i][pivo]/mat[pivo][pivo];

    for(j=0; j>colunas; j--){
        mat[i][j] = mat[i][j] + (mult*mat[pivo][j]);
        }//fim for j

    printf("Matriz alterada com pivo=%d, i=%d\n", pivo,i);
    for(a=0; a<linhas; a++){
        for(b=0; b<colunas; b++)
        printf("%.2f\t", mat[a][b]);
        printf("\n");
}//fim for a

}//fim for i
}//fim for pivo
//fim da triangulização da matriz. Pronto para cálculo do determinante

   //calculando determinante
    for(i=0; i<linhas; i++){
        printf("mat[%d][%d] = %.2f\n",i , i, mat[i][i]);
        det=det*mat[i][i];
    }//fim cálculo do determinante
    printf("\nDeterminante = %.2f\n", det);

    printf("\nMatriz após o cálculo\n");
    for(a=0; a<linhas; a++){
        for(b=0; b<colunas; b++)
        printf("%.2f\t", mat[a][b]);
    printf("\n");
    }//fim for a
    printf("\n");

}

Comment: Pelo visto você é novo aqui, então pra começar, sempre que você faz uma pergunta, você precisa detalhar sua dúvida e o que realmente está te perturbando ou atrapalhando, assim poderemos te ajudar :). Seja direto, nada de enrolação, mas conte tudo que possa colaborar para uma resposta que lhe ajude.
Comment: Ola Alan, nao estou conseguindo entender seu problema, sugiro vc editar sua pergunta e adicionar mais informações a ela.
Comment: Dê uma olhada em outras perguntas para se ter ideia de como se deve prosseguir em um questionamento. Algo que também pode lhe ajudar é a área de [ajuda do stackoverflow](http://pt.stackoverflow.com/help).
Comment: Então eu estou querendo é, a partir da matriz transposta calcular o determinante usando para isso o método de triangularização inferior, pois o determinante tem que ser igual ao determinante da matriz original, a matriz transposta já está no código, eu não estou conseguindo é fazer a triangularização para depois calcular o determinante.
Answer: 1. Primeiras pequenas correções e melhorias
Primeiramente, olhe isso:
double mat[linhas][colunas] = { 1, 4, 7, 3 };

Isso não é uma matriz 2x2! Isso é um vetor de 4 posições. O que você queria era isso:
double mat[linhas][colunas] = { {1, 4}, {7, 3} };

Também dá para simplificar isso:
det=det*mat[i][i];

Para isso:
det *= mat[i][i];

E isso:
mat[i][j] = mat[i][j] + (mult*mat[pivo][j]);

Para isso:
mat[i][j] += mult * mat[pivo][j];

Vamos dar uma melhor olhada nisso:
2. O erro na triangularização
Vamos dar uma olhada neste trecho do seu código:
    for(pivo=0; pivo>linhas; pivo--){

    for(i=pivo-1; i>linhas; i--){

    mult=(-1)*mat[i][pivo]/mat[pivo][pivo];

    for(j=0; j>colunas; j--){

Observe a condição dos seus três fors estão totalmente erradas! pivo>linhas, i>linhas e j>colunas são condições que sempre serão falsas. Acho que o que você queria era isso:
    for (pivo = linhas - 1; pivo >= 0; pivo--) {

        for (i = pivo - 1; i >= 0; i--) {

            mult = (-1) * mat[i][pivo] / mat[pivo][pivo];

            for (j = colunas - 1; j >= 0; j--) {
                mat[i][j] += mult * mat[pivo][j];
            } // Fim do for j.

3. A transposição que não faz nada
E também, observe isso:
    aux = mat[linhas][colunas];
    mat[linhas][colunas] = mat[colunas][linhas];
    mat[colunas][linhas] = aux;

Dado que a matriz é quadrada, então sempre teremos que linhas = colunas. Supondo que linhas = colunas = N, para algum valor inteiro N, teremos isso:
    aux = mat[N][N];
    mat[N][N] = mat[N][N];
    mat[N][N] = aux;

A linha do meio é completamente desnecessária, logo isso é reduzido para:
    aux = mat[N][N];
    mat[N][N] = aux;

E isso efetivamente não faz nada! Logo, pode ser eliminado. Ao eliminar isso, a variável aux não é mais necessária.
Há mais um porém neste trecho. Em uma matriz NxN, os índices das linhas e colunas vão de 0 até N-1, e portanto acessar mat[N][N] é acessar uma região de memória fora da matriz. Ainda bem que essa parte do código pode ser simplesmente eliminada.
4. O código revisado
Feitas as correções acima, vamos reidentar o seu código e eliminar as variáveis que não são usadas (aux, r, l, inicio, p e c). Também estou movendo det e mult para serem declaradas apenas quando serão necessárias. Uma vez que apenas matrizes quadradas têm sentido, então podemos unificar linhas e colunas em uma coisa só, chamada tamanho. Também aproveito para fazer main retornar int ao invés de void. E finalmente, o seu código completo revisado fica assim:
#include <stdio.h>

#define tamanho 2

int main() {

    double mat[tamanho][tamanho] = { {1, 4}, {7, 3} };
    // double mat[tamanho][tamanho] = { {2, -4, 8}, {5, 4, 6}, {-3, 0, 2} };
    // double mat[tamanho][tamanho] = { {1, 4, 7, 3}, {2, 6, -3, 0}, {2, 1, 3, 6}, {8, -2, 5, -1} };
    // double mat[tamanho][tamanho] = { {1, 4, 7, 3, 2}, {6, -3, 0, 2, 1}, {3, 6, 8, -2, 5}, {-1, 0, 1, -7, -5}, {4, 6, -10.5, 0, -5} };

    int i, j, pivo; // Índices para efetuar modificações na matriz.
    int a, b; // Índices apenas para debugar a modificaçõo da matriz.

    printf("\nMatriz antes do cálculo\n");
    for (a = 0; a < tamanho; a++) {
        for (b = 0; b < tamanho; b++) {
            printf("%.2f\t", mat[a][b]);
        }
        printf("\n");
    }
    printf("\n");

    printf("\nMatriz transposta é\n");
    for (a = 0; a < tamanho; a++) {
        for (b = 0; b < tamanho; b++) {
            printf("%.2f\t", mat[b][a]);
        }
        printf("\n");
    }
    printf("\n");

    // Triangularizando a matriz.
    for (pivo = tamanho - 1; pivo >= 0; pivo--) {

        for (i = pivo - 1; i >= 0; i--) {

            double mult = (-1) * mat[i][pivo] / mat[pivo][pivo];

            for (j = tamanho - 1; j >= 0; j--) {
                mat[i][j] += mult * mat[pivo][j];
            } // Fim do for j.

            printf("Matriz alterada com pivo=%d, i=%d\n", pivo, i);
            for (a = 0; a < tamanho; a++) {
                for (b = 0; b < tamanho; b++) {
                    printf("%.2f\t", mat[a][b]);
                }
                printf("\n");
            } // Fim do for a.

        } // Fim do for i.
    } // Fim do for pivo.
    // Fim da triangularização da matriz. Pronto para o cálculo do determinante.

    // Calculando determinante.
    double det = 1;
    for (i = 0; i < tamanho; i++) {
        printf("mat[%d][%d] = %.2f\n", i, i, mat[i][i]);
        det *= mat[i][i];
    } // Fim do cálculo do determinante.
    printf("\nDeterminante = %.2f\n", det);

    printf("\nMatriz após o cálculo\n");
    for (a = 0; a < tamanho; a++) {
        for (b = 0; b < tamanho; b++) {
            printf("%.2f\t", mat[a][b]);
        }
        printf("\n");
    } // Fim do for a.
    printf("\n");

    return 0;
}

5. Testando o código
E então, eis o resultado para a matriz 2x2:
Matriz antes do cálculo
1.00    4.00
7.00    3.00

Matriz transposta é
1.00    7.00
4.00    3.00

Matriz alterada com pivo=1, i=0
-8.33   0.00
7.00    3.00
mat[0][0] = -8.33
mat[1][1] = 3.00

Determinante = -25.00

Matriz após o cálculo
-8.33   0.00
7.00    3.00

Para a matriz 3x3:
Matriz antes do cálculo
2.00    -4.00   8.00
5.00    4.00    6.00
-3.00   0.00    2.00

Matriz transposta é
2.00    5.00    -3.00
-4.00   4.00    0.00
8.00    6.00    2.00

Matriz alterada com pivo=2, i=1
2.00    -4.00   8.00
14.00   4.00    0.00
-3.00   0.00    2.00
Matriz alterada com pivo=2, i=0
14.00   -4.00   0.00
14.00   4.00    0.00
-3.00   0.00    2.00
Matriz alterada com pivo=1, i=0
28.00   0.00    0.00
14.00   4.00    0.00
-3.00   0.00    2.00
mat[0][0] = 28.00
mat[1][1] = 4.00
mat[2][2] = 2.00

Determinante = 224.00

Matriz após o cálculo
28.00   0.00    0.00
14.00   4.00    0.00
-3.00   0.00    2.00

Para a matriz 4x4:
Matriz antes do cálculo
1.00    4.00    7.00    3.00
2.00    6.00    -3.00   0.00
2.00    1.00    3.00    6.00
8.00    -2.00   5.00    -1.00

Matriz transposta é
1.00    2.00    2.00    8.00
4.00    6.00    1.00    -2.00
7.00    -3.00   3.00    5.00
3.00    0.00    6.00    -1.00

Matriz alterada com pivo=3, i=2
1.00    4.00    7.00    3.00
2.00    6.00    -3.00   0.00
50.00   -11.00  33.00   0.00
8.00    -2.00   5.00    -1.00
Matriz alterada com pivo=3, i=1
1.00    4.00    7.00    3.00
2.00    6.00    -3.00   0.00
50.00   -11.00  33.00   0.00
8.00    -2.00   5.00    -1.00
Matriz alterada com pivo=3, i=0
25.00   -2.00   22.00   0.00
2.00    6.00    -3.00   0.00
50.00   -11.00  33.00   0.00
8.00    -2.00   5.00    -1.00
Matriz alterada com pivo=2, i=1
25.00   -2.00   22.00   0.00
6.55    5.00    0.00    0.00
50.00   -11.00  33.00   0.00
8.00    -2.00   5.00    -1.00
Matriz alterada com pivo=2, i=0
-8.33   5.33    0.00    0.00
6.55    5.00    0.00    0.00
50.00   -11.00  33.00   0.00
8.00    -2.00   5.00    -1.00
Matriz alterada com pivo=1, i=0
-15.32  -0.00   0.00    0.00
6.55    5.00    0.00    0.00
50.00   -11.00  33.00   0.00
8.00    -2.00   5.00    -1.00
mat[0][0] = -15.32
mat[1][1] = 5.00
mat[2][2] = 33.00
mat[3][3] = -1.00

Determinante = 2527.00

Matriz após o cálculo
-15.32  -0.00   0.00    0.00
6.55    5.00    0.00    0.00
50.00   -11.00  33.00   0.00
8.00    -2.00   5.00    -1.00

Para a matriz 5x5:
Matriz antes do cálculo
1.00    4.00    7.00    3.00    2.00
6.00    -3.00   0.00    2.00    1.00
3.00    6.00    8.00    -2.00   5.00
-1.00   0.00    1.00    -7.00   -5.00
4.00    6.00    -10.50  0.00    -5.00

Matriz transposta é
1.00    6.00    3.00    -1.00   4.00
4.00    -3.00   6.00    0.00    6.00
7.00    0.00    8.00    1.00    -10.50
3.00    2.00    -2.00   -7.00   0.00
2.00    1.00    5.00    -5.00   -5.00

Matriz alterada com pivo=4, i=3
1.00    4.00    7.00    3.00    2.00
6.00    -3.00   0.00    2.00    1.00
3.00    6.00    8.00    -2.00   5.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=4, i=2
1.00    4.00    7.00    3.00    2.00
6.00    -3.00   0.00    2.00    1.00
7.00    12.00   -2.50   -2.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=4, i=1
1.00    4.00    7.00    3.00    2.00
6.80    -1.80   -2.10   2.00    -0.00
7.00    12.00   -2.50   -2.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=4, i=0
2.60    6.40    2.80    3.00    -0.00
6.80    -1.80   -2.10   2.00    -0.00
7.00    12.00   -2.50   -2.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=3, i=2
2.60    6.40    2.80    3.00    -0.00
6.80    -1.80   -2.10   2.00    -0.00
8.43    13.71   -5.79   -0.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=3, i=1
2.60    6.40    2.80    3.00    -0.00
5.37    -3.51   1.19    0.00    -0.00
8.43    13.71   -5.79   -0.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=3, i=0
0.46    3.83    7.73    0.00    -0.00
5.37    -3.51   1.19    0.00    -0.00
8.43    13.71   -5.79   -0.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=2, i=1
0.46    3.83    7.73    0.00    -0.00
7.10    -0.70   -0.00   0.00    -0.00
8.43    13.71   -5.79   -0.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=2, i=0
11.72   22.15   -0.00   0.00    -0.00
7.10    -0.70   -0.00   0.00    -0.00
8.43    13.71   -5.79   -0.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
Matriz alterada com pivo=1, i=0
235.14  0.00    -0.00   0.00    -0.00
7.10    -0.70   -0.00   0.00    -0.00
8.43    13.71   -5.79   -0.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00
mat[0][0] = 235.14
mat[1][1] = -0.70
mat[2][2] = -5.79
mat[3][3] = -7.00
mat[4][4] = -5.00

Determinante = 33507.50

Matriz após o cálculo
235.14  0.00    -0.00   0.00    -0.00
7.10    -0.70   -0.00   0.00    -0.00
8.43    13.71   -5.79   -0.00   0.00
-5.00   -6.00   11.50   -7.00   0.00
4.00    6.00    -10.50  0.00    -5.00

Veja aqui funcionando no ideone.
6. Divisão por zero
Ah, a ainda um último detalhe a se ver. Observe essa linha no processo de triangularização:
double mult = (-1) * mat[i][pivo] / mat[pivo][pivo];

O que acontece se houver um zero em um dos elementos da diagonal principal? O resultado é que vai dar pau ao tentar dividir por zero!
Para resolver isso, sugiro que antes de efetuar uma etapa na triangularização, que se mat[pivo][pivo] for zero, que você faça uma permutação entre duas linhas ou duas colunas de forma a tentar nunca deixar zeros da diagonal principal. Lembre-se também que cada vez que você fizer uma permutação dessas, o sinal do determinante se inverte.
Se não for possível tirar algum zero da diagonal principal ao permutar duas linhas ou duas colunas, então isso significa que há uma linha ou uma coluna só com zeros. E se for este o caso, então você pode parar os cálculos da triangularização porque o determinante resultante será sempre zero.


AssertionFailedException while using TableColumnLayout in eclipse

Question: I have a SWT Table inside a coposite, and i have used TableColumnLayout for dynamically resizing the table columns.
I get the following error while trying to launch the jface dialog which contains the table.
org.eclipse.core.runtime.AssertionFailedException: assertion failed: Unknown column layout data

This is the corresponding code used :
TableColumnLayout layout = new TableColumnLayout();
composite.setLayout(layout);

layout.setColumnData(column1, new ColumnWeightData(30));
layout.setColumnData(column2, new ColumnWeightData(30));
layout.setColumnData(column3, new ColumnWeightData(30));
layout.setColumnData(column4, new ColumnWeightData(30));
layout.setColumnData(column5, new ColumnWeightData(30));

Can anyone let me know What is causing me the error ?
Answer: The assertion is thrown if the column data is not an instance of ColumnWeightData or ColumnPixelData for all the defined columns. So my guess is that you have not set the column data for one of your columns.
Comment: to clarify: you MUST add:   tableColumnLayout.setColumnData( mycolumn, new ColumnWeightData( ... );. If you don't the above exception is thrown.


'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead in swift

Question: This is my code:
let textRange = UETextRange(charIndex: i, length: l - i)
for j in textRange.charIndex...getCharIndexAfterEndOfRange(range: textRange) {
    if String(initialText[j - 1]) == "\n" { //error here
        hits += 1
        let hitIndex = attributeRange.index + (hits - 1)
        if hitIndex <= paragraphStyles.count {
            let charIndex = paragraphStyles[hitIndex].charIndex
        }
    }
}

How do I solve this error?
Answer: 2022
extension String {
    public subscript(_ idx: Int) -> Character {
        self[self.index(self.startIndex, offsetBy: idx)]
    }
}

Now you able to use "asdf"[4] syntax like in other languages :)
print( "asdffdsa"[0] ) // a
print( "asdffdsa"[1] ) // s
print( "asdffdsa"[2] ) // d

Answer: Accessing elements of a String in Swift works slightly differently to most languages. Swift's String subscript expects a String.Index (not an Int), as shown in the documentation:
@inlinable public subscript(i: String.Index) -> Character { get }

What we want to do instead is get the startIndex, offset that by the integer index we want, and then get that index from the string. Fixed code:
let char = initialText[initialText.index(initialText.startIndex, offsetBy: j - 1)]

if char == "\n" {
    /* ... */
}

Comment: Good answer thanks @George. Also well worth reading is the section on String Indices in The Swift Programming Language book at https://docs.swift.org/swift-book/documentation/the-swift-programming-language/stringsandcharacters/#String-Indices Explains why this approach is necessary. First character in example above would be initialText[initialText.startIndex]


PHP Redirect after Mysql Insert

Question: Below is my mySQL insert:
$sql="INSERT INTO gj (name, phone, city, zipcode, description, dateadded, website, address1, other2, payment_options, Products, email,cat1,cat2,cat3)
    VALUES
    ('$companyname','$phone','$city','$zipcode','$description',curdate(),'$website','$address','$other','$payment','$products','$email','$select1','$select2','$select3')";

    if (!mysql_query($sql,$link))
      {
      die('Error: ' . mysql_error());
      }
    echo "

1 business added
";

    mysql_close($link);
}

    ?>

Now, instead of displaying "1 business added" in green, I'd like to redirect back to the page I was on before. Thanks.
Answer: If your script is always intended to go to the same place afterwards, then you can hard-code the location.  For example:
header("Location: http://www.example.com/");

Note that per RFC 2616 (the HTTP/1.1 specification), the value of the Location header must be an absolute URI, not just a path.
If your script is for a specific purpose and always redirects to a certain section, but may vary which particular records are shown, then you can incorporate the data that was posted to your script into the URL.  For example:
header("Location: http://www.example.com/widgets/" . urlencode($_POST['id']));

If your script is used in several different ways, then you can pass along the URL to redirect to from the page that posts to it in a hidden form field, for example:
<input type="hidden" name="redirect-url" value="http://www.example.com/">

More generally, you should follow the Post/Redirect/Get pattern.
Answer: Add:
header("Location: page_you_want.php");

after your query has completed but before anything is echo'ed. You can only use the above code if headers have not already been sent including HTML etc.
Comment: Here is my code but I'm still getting an error    $sql="INSERT INTO gj (name, phone, city, zipcode, description, dateadded, website, address1, other2, payment_options, Products, email,cat1,cat2,cat3)
  VALUES
  ('$companyname','$phone','$city','$zipcode','$description',curdate(),'$website','$address','$other','$payment','$products','$email','$select1','$select2','$select3')";

  if (!mysql_query($sql,$link))
    {
    die('Error: ' . mysql_error());
    }

  mysql_close($link);
  header('Location: ' . $_SERVER['HTTP_REFERER']);
 }
Answer: I would do:
header('Location: ' . $_SERVER['HTTP_REFERER']);

after
mysql_close($link);

Comment: I get this error                                  Warning: Cannot modify header information - headers already sent by (output started at /Users/Sites/gj/doctype.php:5) in /Users/Sites/gj/addbusiness.php on line 98....and line 98 is is where I put the header('location....stuff you just gave me?? Is there any thing I might be doing wrong?
Comment: location can be set to any web address. be sure not to output anything to the browser before setting a header or you will get an error (this includes blank lines not encased in ).
Comment: yeah, that error means that you outputted something to the browser before you set the header. don't do that.
Comment: Don't do this, the Referer header is not reliable.
Comment: you need to get rid of the echo statement or the header wont work.

PHP Redirect after Mysql Insert


Reducing a dataframe to the most frequent combinations of two columns

Question: I have a json file which I import using the following code:
spark = SparkSession.builder.master("local").appName('GPS').config(conf=SparkConf()).getOrCreate()
df = spark.read.json("SensorData.json")

The result is a dataframe similar to this:
+---+---+
|  A|  B|
+---+---+
|  1|  3|
|  2|  1|
|  2|  3|
|  1|  2|
|  3|  1|
|  1|  2|
|  2|  1|
|  1|  3|
|  1|  2|
+---+---+

My task is using PySpark  to reduce the data to only the most frequent combinations of two columns (A and B)
So the wanted output is this
+---+---+-----+
|  A|  B|count|
+---+---+-----+
|  1|  2|    3|
|  2|  1|    2|
+---+---+-----+

Answer: You can do that with a combination of groupBy and limit:
spark = SparkSession.builder.master("local").appName('GPS').config(conf=SparkConf()).getOrCreate()
df = spark.read.json("SensorData.json")

df.groupBy("A","B")
  .count()
  .sort("count",ascending = False)
  .limit(2)
  .show()
+---+---+-----+
|  A|  B|count|
+---+---+-----+
|  1|  2|    3|
|  2|  1|    2|
+---+---+-----+

Comment: But I have big data and cannot do it manually. Also, I have to run it in spark for efficiency
Comment: Yes, I have it in a data frame but didn't do any SQL
Comment: Thank you. This works but please correct me if wrong. I think it is not happening in Spark (but inside python). This way, I don't get the full performance benefit from Spark.
Comment: No once your data has been converted into a dataframe it is parallelized and it is executed in Spark.
Comment: You can check with the following code

if isinstance(df, DataFrame):
        print("DataFrame")


Como customizar o Arrow do Swiper React.js em jsx ou styled.component

Question: Eu quero customizar os arrows do swiper, mas eu nao achei nada na documentacao.
Este é o codigo do meu navigation:
<code> const params = {
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    slidesPerView: 7,
    spaceBetween: 5,
    shouldSwiperUpdate: true,
    pagination: {
      clickable: true,
    },
  };
</code>
E está exibindo dessa forma:

Eu preciso mudar a cor do arrow, e seu tamanho. Eu queria usar o style={{}}, ou o styled.component.
Comment: Você está utilizando a library https://swiperjs.com/react? Se não, poderia enviar o link?
Comment: Claro, estou usando essa aqui
https://swiperjs.com/react/
Answer: Olá,
Na sua essência o swiperjs do react não possui meios de trabalhar com styledComponents ou style, conforme a documentação deles, as opções disponíveis são:

manipular os estilos do CSS
trabalhar com LESS
trabalhar com SCSS

Uma solução simples e rápida seria adicionar no seu HTML o trecho css abaixo:
<code>div.swiper-button-prev,
div.swiper-button-next {
   color: red;
}
</code>
Veja os exemplos disponíveis para mais informação