text:
Q: use different but similar objects without branching Polymorphism, Code reusibility, OOP, C# question.  I would like to create a method like:
private void ManyLinesOfCode(DataContext mycontext)

but I wouldn't be able to send it my actual datacontexts because they are not of type DataContext and I haven't been able to do any casting that compiles.
var includeCustomersFlag = Request["includeCustomersFlag"];
if (includeCustomersFlag == "1")
   {
   var context = new TypeByRepGroupDataContext();
   var lines = context.TypeByRepGroups;
   .... many lines of code
   }
else if (includeCustomersFlag == "2")
   {
   var context = new TypeByRepGroupNoChainsDataContext();
   var lines = context.TypeByRepGroupsNoChains;
   .... many lines of code
   }
else
  {
   var context = new TypeByRepGroupChainsOnlyDataContext();
   var lines = context.TypeByRepGroupsChainsOnliess;
   .... many lines of code
   }

I have a workaround by using a single parameterized stored procedure in my datacontext instead of multiple datacontexts based on different views, but would prefer to have a c# solution to the bloated code above.
I am trying to work with Albin's solution.  I can compile this:
public interface IMyInterface
{

    string arcxpostyy {get; set;}
    string arcxpostmm {get; set;}
    string CustArea {get; set;}
    string type {get; set;}
    System.Nullable<decimal> amt {get; set;}

}
partial class TypeByRepGroup : IMyInterface  { }
partial class TypeByRepGroupNoChain : IMyInterface { }
partial class TypeByRepGroupChainsOnly : IMyInterface { }

But... it doesn't get me anything as is.  I highly doubt I am making this interface right but I wanted to at least make an effort, and not sure how to use it in my code (the controller snippet in my question.)  No links on the internet to an actual implementation of this solution that I could find.  Can anybody fully spell out the solution?
I start a job as Senior Software Engineer in a couple weeks and would like to be able to do this kind of thing.

A: It is not the type of the DataContexts that are the big problems here. It is that you use different entities on the different contexts.
Make sure TypeByRepGroups, TypeByRepGroupsNoChains and TypeByRepGroupsChainsOnliess implements a common interface. Create a partial class where you define that those classes implements the interface.


text:
Q: onClick button sum columns items in datagrid every time onclick button is not sum all item in the columns it's just minus 1 item from the loop DtaGridAddInvBackBill.Items.Count - 1 when i try to remove - 1 it's get in error on the decimal sum +=
all i need to every time click add the item then sum the last column Inv ItemTotal then after sum put in the Textblock TotalItemcount
decimal sum = 0m;
for (int i = 0; i < DtaGridAddInvBackBill.Items.Count - 1;i++)
{
    sum += (decimal.Parse((DtaGridAddInvBackBill.Columns[10].GetCellContent(DtaGridAddInBackBill.Items[i]) as TextBlock).Text));
}
TotalItemcount.Text = " Invoice Total : ( " + Math.Round(sum, 2).ToString() + " )";

redpajama_set_name: RedPajamaStackExchange


text:
Q: XML files transformation Background: I have not dealt with a lot of XML processing in my work. However, my current work needs me to read and transform some medium to largish XML files in the order of 10s to 100s of MBs.
Requirement: these XML documents have user IDs that I need to change to fake IDs. These mappings of user to fake IDs are given in a separate file.
What I would do: Conventionally, what I would do is read the whole file in, building a DOM tree, then recursing through the nodes in the tree and changing the user IDs to fake IDs as I go and lastly dumping the whole document out in the end.
My question: is there a cleaner to do this with technologies like XSLT, XPath, etc. than this traditional model? Since I will be developing using the .NET framework, it would be useful though not necessary if I could get an answer in the context of .NET and C#.
Apologies if this sounds like a noob question. I have never worked with XML based technologies in the past. I guess everyone needs to start somewhere and this is my cue! :)

A: This is an entirely standard XSL requirement. If you can embed the mapped names into your stylesheet, then you can use the command line msxsl.exe to prototype this. The transform will then, with varying degrees of efficiency, apply the mappings you need to pseudonymise the data.
If the names are all stored in well known elements (or attributes) then start with an identity transform and introduce additional templates to map the names as they appear in the document.

A: It sounds like XSLT might do the trick. With XSLT, you create a style sheet with all your code and the mappings of the user-fake IDs. You'd have a function that applies a replace to all user IDs.
It will require a little work in learning the XSLT way of doing things (XML syntax, a functional paradigm, learn about XPath) but if you have the time it will be useful for this and other XML tasks.
In .net, use the XSLT reference and the transformation classes to do your work. Your C# code will be minimal and all your logic will be in your XSL Transform style sheet (.xsl file you pass as a parameter). Remember to use the XSLCompiledTransform since it's faster.


text:
Q: Admob SDK integration example after apportable porting I'm planning to integrate admob SDK to show ads into my ported application from Cocos2d using apportable, did someone have example how to integrate Admob using apportable?

A: Apportable does support the AdMob APIs, but not in the Starter edition. We'll update to make this clear in an upcoming release.


text:
Q: disable notepad++ updates on install or through script - Windows 7 I deploy notepad++ to several computer labs where end users don't have administrative rights. I am able to deploy the software, but I need to turn off automatic updates so they aren't getting popups when the next version comes out. Is there a way to do this either via command line switches on install or after install by modifying the registry, or other files?
I am currently installing with:
    "npp.6.6.9.Installer.exe" /S

A: For fresh installs, a good solution is the following:
C:\Program Files (x86)\Notepad++\config.model.xml
Modify the line:
From:
< GUIConfig name="noUpdate" > no < /GUIConfig >
To:
< GUIConfig name="noUpdate" > yes < /GUIConfig >
So essentially new user profiles will be populated with a NoUpdate set to yes.
This is especially useful for SCCM and silent deployments.

A: There's a couple of ways you could do it. If you don't deploy the updater folder then the updating functionality won't work (and you don't appear to get any error messages). If you just want to disable the option you'll need to edit the user's config.xml file, e.g.
C:\Users\<user>\AppData\Roaming\Notepad++\config.xml

The line you're after is:
<GUIConfig name="noUpdate" intervalDays="15" nextUpdateDate="20140606">no</GUIConfig>

Change the 'no' to 'yes' and the auto-update checking will stop.


text:
Q: ObjectiveC saving images in tableview I currently have a tableView that the user can populate with data- both text and an image.
When the app exits I save all the text in to a plist file as always.
All the images are saved as 0, 1 ,2, 3, 4 dot jpg but the problem is that when I delete one row I can't take for granted that the indexpath.row . jpg is the correct image because it changes.
So the question is - how is the best way to save the images?
Thanks

A: Just keep an array of "image names" in your table view datasource and save this along with the  text as plist file (so you get images.plist and text.plist). when you remove rows, you remove the image name from your images.plist and the related text in the text.plist.
A nice way to store data and show it in table views is CoreData. While it seems a bit too much for now, it's worth to work with it:
http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/iPhoneCoreData01/Introduction/Introduction.html


text:
Q: Characterization of Angles Trisectable with Straightedge and Compass Lindemann's prove of the transcendence of $\pi$ has settled the question, whether an arbitrary angle can be trisected, using straightedge and compass alone, to the negative.
In the following, trisectable always means with straightedge and compass alone.
I could however find nothing but some vague statements about angles, that are trisectable; a typical such statement is, that up to a few exceptions, it is impossible to trisect angles.
Question: I would therefore like to know, whether the angles, that are trisectable have been fully characterized and, if yes, who has done that first.
Edit:
in view of the valuable feedback I got, I will try to summarize things from my perspective

*

*it can be proven, that an angle $\theta$ can be constructed if and only if $\cos(\theta) \in \mathbb{E},$ where $\mathbb E$ (for Euclidean), often called the "constructable numbers," is the smallest subfield of the real numbers that is closed under taking square roots of positive elements.

*there seems to be common agreement, that an angle $\theta$ can only be trisected with straightedge and compass, if $\cos(\frac{\theta}{3}))$ is constructable.
So either being trisectable and constructable are equivalent or, there are angles that are not constructable, but can be trisected.
I suspect however, that there are certain angles (e.g. $\frac{2\pi}{7+\frac{1}{3}}$), that can be trisected despite not being constructable, namely angles $\theta$, for which
$$ \frac{lcm(\theta,2\pi)}{\theta} = 3k, k\in\mathbb{N}$$
those angles, which I would like to call auto-trisecting, are then either all constructable or, there are exceptions which are counter examples to the characterisation via constructability (the notion of being auto-trisecting of course easily generalizes to being auto-$n$-secting).
Interestingly, the only "basic" (i.e. involving only a single Fermat prime) constructable angles, that can be trisected, but are not auto-trisecting, seem to be the ones of the form$$3k\frac{2\pi}{2^nF_0}, k\in\mathbb{N},n\in\mathbb{N}_0, F_0 := 2^{2^0}+1=3$$
With that observation in mind, and assuming that all trisectable angles are either constructable or auto-trisecting, a bullet-proof strategy for finding a trisection of an angle, that is known to be trisectable with straightedge and compass alone, is to simply to construct multiples of it, until a period has been completed.  The so generated multiples either

*

*subdivide the angle in case it is auto-trisecting and the size of a trisection is equal to the sum of $\frac{1}{3}$ of the (equal) subdivisions or,

*do not subdivide the angle, but constitute to a constructable regular n-gon and, by determining n, it is possible to determine a constructable angle that resembles a trisection.
in both cases it is possible to find a trisection and, alltogether it can be said that the topic of trisecting an angle in case that its trisectability is known, can be discussed at classroom-level.
As a remark it can be said, that there is no hope for proving the existence of further Fermat primes by demonstrating that the known Fermat primes together with auto-trisecting angles do not cover all cases of trisectable angles and thus would necessitate the existence of further Fermat primes.
Edit II:
I found the following Wiki article that elucidates the history of proving that angles are not trisectable in general:
http://en.wikipedia.org/wiki/Angle_trisection
according to that article, the proof was found by Pierre Wantzel in 1837 and is not based on Lindemann's proof of the transcendence of $\pi$, but rather on Galois theory.

A: There is an aspect of the word "construct" that comes off a bit sour here. There are infinitely many angles such that $\theta$ and $\theta/3$ are both constructable. However, the set of constructable angles $\theta$ for which $\theta/3$ is not constructable is dense. By continuity, it follows that there is no procedure for beginning with $\theta$ and using a finite number of compass and straightedge operations to actually find $\theta/3,$ even when it is constructable.
I wrote an article on the hyperbolic plane, constant curvature $-1.$ As pointed out by Bolyai, there are a countably infinite set of pairs, one circle and one square, such that the radius of the circle and the edge of the square are both constructable, and the two figures have the same area. However, there is no way to begin with one and find the other. The phrase "square the circle" is misleading, the reverse phrase "circling the square" would also be misleading if anyone ever used it.
I need to backtrack a little on that last phrase. If you have some sort of political plot going on in Moscow, Russia, and the hero is going around the perimeter of Red Square looking for the bad guys, it makes a good deal of sense to say that the hero is circling the square. The same would work with Times Square in New York.
Back to the Euclidean plane. Given an angle $\theta $ but not told what it is (in radians, say) there is no procedure for finding $\theta/3.$ Ever.

A: In a comment you wrote: ... I was hoping for a characterization via fractions of $2 \pi$ which could eventually be presented in a classroom
For this you may find the following papers useful:
Joe Dan Austin and Kathleen Ann Austin, Constructing and trisecting angles with integer angle measures, Mathematics Teacher 72 #4 (April 1979), 290-293.
Keith Robin McLean, Constructing rational angles (1), Mathematical Gazette 67 #440 (June 1983), 127-128.
David Harold Armitage, Constructing rational angles (2), Mathematical Gazette 67 #440 (June 1983), 128-129.

A: Ruler and Compass construction is discussed in length in 'Galois Theory' - Ian Stewart.
Essentially if a field extension of a point we wish to construct is of degree 2^k (over the rational numbers with k being a natural number) this point can be constructed by ruler and compass. When it comes to trisecting angles it reduces down to the case of whether or not the angle (x/3) can be constructed by constructing the point b=2*cos(x/3). Taking cos(x/3)=cos(y) we can use the trigonometric identity cos(3y)=4*cos^3(y)- 3*cos(y) which can be rearranged to obtain the polynomial f=b^3-3*b-2*cos(x). Which is of degree 3 over the rational numbers (hence not degree 2^k). This polynomial may be reducible to a degree 2 polynomial multiplied by a degree 1 polynomial. If this is the case the angle you wish to trisect is therefore constructible by ruler and compass.

A: An angle $\theta$ is trisectable if and only if $\cos (\theta/3)$ is constructable number and this happens just when the degree $[\mathbb{Q}(\cos (\theta/3)):\mathbb{Q}]$ is a power of 2.


text:
Q: Is the source code for svctraceviewer available I would like to customize the svctraceviewer but do not want to start from scratch. Does any one know of a custom implementation or if the source code is available ?

A: No, it's not available. The same goes for the WCF Test client (and rest of the tools).
A couple of years ago, I did a small proof of concept/hack to show that it was possible to "inject" two extra menu items into the test client to save/load test parameters. See
http://www.larswilhelmsen.com/2008/10/04/wcf-test-client-extended/


text:
Q: WPF Custom GroupBox Header OpacityMask issues I've created a custom GroupBox control that provides a button at the top right. I noticed that the border does not provide a gap for the button like it does for the header, so I wrote a custom BorderGapConverter. Everything works until the content of the header changes. The border, and I believe the opacitymask doesn't change until the window that contains the control is resized.
ButtonedGroupBox.cs
namespace My.Controls
{
    /// <summary>
    /// Interaction logic for ButtonedGroupBox.xaml
    /// </summary>
    public partial class ButtonedGroupBox : GroupBox
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(ButtonedGroupBox), new FrameworkPropertyMetadata(null));
        public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(ButtonedGroupBox), new FrameworkPropertyMetadata(null));

        protected override void OnHeaderChanged(object oldHeader, object newHeader)
        {
            base.OnHeaderChanged(oldHeader, newHeader);
            try
            {
                GetBindingExpression(OpacityMaskProperty).UpdateTarget();
            }
            catch (NullReferenceException) { }
        }

        public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } }
        public object CommandParameter { get { return GetValue(CommandParameterProperty); } set { SetValue(CommandParameterProperty, value); } }

        public ButtonedGroupBox()
        {
            InitializeComponent();
        }
    }
}

ButtonedGroupBox.xaml
<GroupBox x:Class="My.Controls.ButtonedGroupBox" x:Name="ctrlThis"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
          xmlns:cv="clr-namespace:My.ValueConverters"
          mc:Ignorable="d"
          d:DesignHeight="300" d:DesignWidth="300">
    <GroupBox.Resources>
        <BorderGapMaskConverter x:Key="BorderGapMaskConverter"/>
        <cv:BorderGapConverter x:Key="MyBorderGapMaskConverter"/>
    </GroupBox.Resources>
    <GroupBox.Style>
        <Style TargetType="{x:Type GroupBox}">
            <Setter Property="BorderBrush" Value="#D5DFE5"/>
            <Setter Property="BorderThickness" Value="1"/>
        </Style>
    </GroupBox.Style>
    <GroupBox.Template>
        <ControlTemplate TargetType="{x:Type GroupBox}">
            <Grid SnapsToDevicePixels="true">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="6"/>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="6"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="6"/>
                </Grid.RowDefinitions>
                <Border BorderBrush="Transparent" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.ColumnSpan="5" Grid.Column="0" CornerRadius="4" Grid.Row="1" Grid.RowSpan="3"/>
                <Border BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" Grid.ColumnSpan="5" CornerRadius="4" Grid.Row="1" Grid.RowSpan="3">
                    <Border.OpacityMask>
                        <MultiBinding ConverterParameter="6" Converter="{StaticResource MyBorderGapMaskConverter}">
                            <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Grid}"/>
                            <Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/>
                            <Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/>
                        </MultiBinding>
                    </Border.OpacityMask>
                    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3">
                        <Border BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2"/>
                    </Border>
                </Border>
                <Border x:Name="Header" Grid.Column="1" Padding="3,1,3,1" Grid.Row="0" Grid.RowSpan="2">
                    <ContentPresenter ContentSource="Header" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                </Border>
                <Border Grid.Column="3" Padding="3,1,3,1" Grid.Row="0" Grid.RowSpan="2">
                    <Button x:Name="CopyButton" Content="Copy" Grid.Column="3" Grid.Row="0" Grid.RowSpan="2" HorizontalAlignment="Stretch" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                        HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
                        Command="{Binding Command, ElementName=ctrlThis}" CommandParameter="{Binding CommandParameter, ElementName=ctrlThis}"/>
                </Border>
                <ContentPresenter Grid.ColumnSpan="3" Grid.Column="1" Margin="{TemplateBinding Padding}" Grid.Row="2" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
            </Grid>
        </ControlTemplate>
    </GroupBox.Template>
</GroupBox>

BorderGapConverter
public class BorderGapConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Type doubleType = typeof(double);

            // Data Validation
            if (values == null) return DependencyProperty.UnsetValue;

            foreach (var value in values)
            {
                Type valueType = value.GetType();
                if (value == null || (!typeof(FrameworkElement).IsAssignableFrom(valueType) && !doubleType.IsAssignableFrom(valueType)))
                    return DependencyProperty.UnsetValue;
            }

            Type paramType = parameter.GetType();;
            if (parameter == null || (!doubleType.IsAssignableFrom(paramType) && !typeof(string).IsAssignableFrom(paramType))) return DependencyProperty.UnsetValue;

            double offset = 0d;
            if (parameter is string)
                offset = double.Parse((string)parameter, NumberFormatInfo.InvariantInfo);
            else
                offset = (double)parameter;

            Grid hostGrid = (Grid)values[0];
            double borderWidth = (double)values[1];
            double borderHeight = (double)values[2];

            if (borderWidth == 0d || borderHeight == 0d) return null;

            // Create a 5x2 Grid
            Grid grid = new Grid() { Width = borderWidth, Height = borderHeight };
            foreach(ColumnDefinition col in hostGrid.ColumnDefinitions)
                grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(col.ActualWidth) });

            // Define rows
            grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(borderHeight / 2d) });
            grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1d, GridUnitType.Star) });

            /**
             * Cartesian Coordinates
             * - 0 1 2
             * 0|-|-|-|
             * 1|-|-|-|
             */
            // Set rectangle 1 to 0, 0 to 0, 1
            Rectangle rectangle = new Rectangle() { Fill = Brushes.Black };
            Grid.SetRowSpan(rectangle, 2);
            Grid.SetRow(rectangle, 0);
            Grid.SetColumn(rectangle, 0);

            // Set rectangle2 to 1, 1
            Rectangle rectangle2 = new Rectangle() { Fill = Brushes.Black };
            Grid.SetRow(rectangle2, 1);
            Grid.SetColumn(rectangle2, 1);

            // Set rectangle3 to 0, 2 to 1, 2
            Rectangle rectangle3 = new Rectangle() { Fill = Brushes.Black };
            Grid.SetRowSpan(rectangle3, 2);
            Grid.SetRow(rectangle3, 0);
            Grid.SetColumn(rectangle3, 2);

            // Set rectangle4 to 0, 2 to 1, 2
            Rectangle rectangle4 = new Rectangle() { Fill = Brushes.Black };
            Grid.SetRow(rectangle4, 1);
            Grid.SetColumn(rectangle4, 3);

            // Set rectangle3 to 0, 2 to 1, 2
            Rectangle rectangle5 = new Rectangle() { Fill = Brushes.Black };
            Grid.SetRowSpan(rectangle5, 2);
            Grid.SetRow(rectangle5, 0);
            Grid.SetColumn(rectangle5, 4);

            grid.Children.Add(rectangle);
            grid.Children.Add(rectangle2);
            grid.Children.Add(rectangle3);
            grid.Children.Add(rectangle4);
            grid.Children.Add(rectangle5);
            return new VisualBrush(grid);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            return new object[] { Binding.DoNothing };
        }
    }

I've tried to override the metadata on HeaderProperty, override OnHeaderChanged, changed to using a HeaderTemplate, and bound Header and set a HeaderStringFormat to no avail.
Here is how I'm using the control:
        <ctrl:ButtonedGroupBox Command="{Binding CopyContentsCommand}" Header="{Binding DynamicTitle}" HeaderStringFormat="Static - {0}">
            <TextBlock>
                Lorem ipsum sit dolorem
            </TextBlock>
        </ctrl:ButtonedGroupBox>

How do I get the opacitymask to update when the header's underlying textblock changes?
EDIT
So I added the Header element's ActualWidth to the MultiBinding, which works but it seems so unnecessary.
<MultiBinding ConverterParameter="6" Converter="{StaticResource MyBorderGapMaskConverter}">
                                        <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Grid}"/>
                                        <Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/>
                                        <Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/>
                                        <Binding ElementName="Header" Path="ActualWidth"/>
                                    </MultiBinding>


text:
Q: How to use a modal as a reply to a select menu command Hi i have a slash command that reply with a select menu and i want to open a modal to the user when he select one of the options but i can't reply to an interaction twice so i wanted to know if there is a way to do it.
I tried to send the select menu as a normal message in the same channel but everytimes the command is used there will be an error message because in didn't reply directly to the commands. if there is a way to make this message not appear it could also work for my ussage.
please leave a message if you can help me thx.
const { SlashCommandBuilder } = require('@discordjs/builders');
const { ActionRowBuilder, EmbedBuilder, StringSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js');

const matches = require("../../differents-matches");

module.exports = {
    data: new SlashCommandBuilder()
    .setName('matchdisponibilities')
    .setDescription('Used to give your disponibilities for a specific match'),

async execute(interaction, client) {

    const userRoles = interaction.member.roles.cache.map((role) => role.id)
    let allMatches = await matches.find()

    let userMatches = []

    allMatches.forEach(element => {
        userRoles.forEach(role => {
            if (element._team1 === role || element._team2 === role) {
                userMatches.push(element)
            }
        })
    })

    const embed = new EmbedBuilder()
    .setTitle('Select a match')
    .setColor(0x18e1ee)

    const componentsMenu = new ActionRowBuilder().addComponents(
            new StringSelectMenuBuilder()
            .setCustomId('select')
            .setPlaceholder('Nothing selected')
        )

    userMatches.forEach(element => {
        componentsMenu.components[0].addOptions(
            {
                label: interaction.guild.roles.cache.get(element._team1).name + ' VS ' + interaction.guild.roles.cache.get(element._team2).name,
                value: element.id,
            }
        )
    })

    const modal = new ModalBuilder()
    .setCustomId('test')
    .setTitle('test2')

    const textInput = new TextInputBuilder()
    .setCustomId('test3')
    .setLabel('test4')
    .setRequired(true)
    .setStyle(TextInputStyle.Short)

    const channel = interaction.channel

    modal.addComponents(new ActionRowBuilder().addComponents(textInput))

    const message = await interaction.reply({embeds: [embed], components: [componentsMenu], fetchReply: true})

    const collector = message.createMessageComponentCollector({
        filter: (u) => {
            if (u.user.id === interaction.user.id) return true
            else{
                return false
            }
        }
    })

    collector.on('collect', async (cld) => {
        if(cld.values[0] === '63960e06ee2ff68635eff3bb'){
            await interaction.showModal(modal)
        }
    })
}

}

A: The problem is that i was using await interaction.showModal(modal) in my colector for the select menu instead of await cld.showModal(modal) so i was responding to the interaction of the slash command instead of the interaction of the select menu


text:
Q: Firefox: dynamic loading of blob url into video tag causes MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED (javascript) i'm trying to dynamically create an html5 video tag loaded with blob_url as source.
i'm listening to 2 events: loadedmetadata and error.
with Chrome browser i get loadedmetadata event fired just like i want, but with Firefox i get the error event fired, with error code of 4 (MEDIA_ERR_SRC_NOT_SUPPORTED).
code:
function add_video(blob_url, id) {
    html = '<video id="' + id + '" src="' + blob_url + '"></video>';
    $('body').append(html);
    var vid = document.getElementById(id);
    vid.addEventListener('loadedmetadata', function(){ alert('loaded!'); });
    vid.addEventListener('error', function(){ alert('error! ' + this.error.code); });
}

can anyone give me a clue why firefox throws an error for that?

A: The following snippet works for me... As you didn't provide a complete snippet yourself, I created one myself. You'd only need to have a cas.webm yourself.
<!DOCTYPE html>
<script>
addEventListener("load", function() {
  var r = new XMLHttpRequest();
  r.onload = function() {
    var vid = document.createElement("video");
    vid.addEventListener('loadedmetadata', function(){ alert('loaded!'); });
    vid.addEventListener('error', function(){ alert('error! ' + this.error.code); });
    vid.setAttribute("autoplay", "autoplay");
    vid.setAttribute("loop", "loop");
    vid.setAttribute("src", URL.createObjectURL(r.response));
    document.body.appendChild(vid);
  };
  r.open("GET", "cas.webm");
  r.responseType = "blob";
  r.send();
}, false);
</script>

So, since blob URIs work, this leaves the media format. Please note that Firefox does not necessarily support all formats yet that Chrome supports, notably H.264/MP4, AAC, MP3 and VP9 are not available on all platforms yet or at all. See Supported media formats.
Watch the Web Console for errors such as:

HTTP "Content-Type" of "video/mp4" is not supported. Load of media resource blob:d83a2aa5-0c28-f044-b3ef-dcabbf59c6ed failed. @ https://example.org/cas.html

Also, the type sniffer might mess up. You could use a <source type="..." src="..."> tag to work around that.
Make sure the blob contains the data you expect it to contain. At the very least use the Web Console or Network view to verify that any request(s) you may use to construct the blob actually succeed (or use a full blown network sniffer).
Without a reproducible, self-contained sample, I cannot really diagnose the actual problem you're seeing, but these pointers are likely good enough to let you diagnose the issue yourself.


text:
Q: Why CodeIgniter misses the url if validation is bad two times? I have this situation. For example,
Path: localhost/intranet/
If i enter this url:
localhost/intranet/usuarios/actualizar/richard

and leave all fields blank and send submit, the validation runs fine and show me the error: "all those fields are required". But, if i click send again, it will send me to:
localhost/intranet/usuarios/actualizar/

Hint: usuarios = USERS in english, actualizar = UPDATE_INFO.
So, as you can see, the argument, in this case richard is mising. Im running 2.1 CodeIgniter. Why is this happening? i don't want CodeIgniter miss the argument because it will show many errors related to CI not being able to find a argument to work with.
Is this normal? Can anyone can click two times when validation fails to see if is the same behavior?
UPDATE #1 Added method for update the data
public function actualizar() {

        // we check if the form was submited. If not, load register view.
        if($_SERVER['REQUEST_METHOD'] == "POST") {

        // translation for errors.
        $required_msg = "%s es un campo obligatorio.";
        $exact_length_msg = "%s debe contener 10 dígitos exactamente.";
        $numeric_msg = "%s debe contener solamente dígitos.";
        $email_msg = "%s debe ser una dirección válida.";
        $unique_msg = "%s ya está registrado en el sistema. Seleccione uno distinto.";

        // set the messages with translations.
        $this->form_validation->set_message('required', $required_msg);
        $this->form_validation->set_message('exact_length', $exact_length_msg);
        $this->form_validation->set_message('numeric', $numeric_msg);
        $this->form_validation->set_message('valid_email', $email_msg);
        $this->form_validation->set_message('is_unique', $unique_msg);

        // set the rules for each input field
        $this->form_validation->set_rules('userName', 'Nombre', 'trim|required');
        $this->form_validation->set_rules('userLastName', 'Apellido', 'trim|required');
        $this->form_validation->set_rules('userUsername', 'Nombre de Usuario', 'trim|required|is_unique[usuarios.userUsername]');
        $this->form_validation->set_rules('userCellphone', 'Teléfono', 'trim|numeric|exact_length[10]');
        $this->form_validation->set_rules('userEmail', 'Correo Electrónico', 'trim|required|valid_email||is_unique[usuarios.userEmail]');
        $this->form_validation->set_rules('userAddress', 'Dirección', 'trim|required');

        // set the custom delimiters for each error msg
        $this->form_validation->set_error_delimiters('
', '
');

            // we check if the validation pass the rules. If not, show the view again with errors msgs.
            if($this->form_validation->run() == FALSE) {
                $data['title'] = "Registrar Usuario";
                $data['page_title'] = "Panel de Control";
                $data['header']  = "header";
                $data['scripts'] = array('alert-dismiss');
                $data['body']    = "usuarios-actualizar";
                $this->load->view('template', $data);
            } else {

                // if validation went ok, we capture the form data.
                $fields = array(
                    'userName' => $this->input->post('userName'),
                    'userLastName' => $this->input->post('userLastName'),
                    'userUsername' => $this->input->post('userUsername'),
                    'userEmail' => $this->input->post('userEmail'),
                    'userAddress' => $this->input->post('userAddress'),
                    'userCellphone' => $this->input->post('userCellphone'),
                    'userIn' => $this->input->post('userIn'),
                    'userOut' => $this->input->post('userOut'),
                    'userLastLogin' => '',
                    'userRole' => $this->input->post('userRole')
                 );

                 $userName = $this->input->post('userName');
                 $userLastName = $this->input->post('userLastName');
                 $userEmail = $this->input->post('userEmail');
                 $userID = $this->input->post('userID');
                 $userUsername = $this->input->post('userUsername');

                // send the $data to the model
                if($this->Data_model->update_entry($userID, $fields) == TRUE) {
                    $this->session->set_flashdata('alert', 'El perfil ha sido actualizado con éxito.');
                    $this->session->set_flashdata('style', 'success');
                    redirect('usuarios/perfil/' . $userUsername);
                } else {
                    $this->session->set_flashdata('alert', 'Hubo un error actualizando el perfil. Inténtelo de nuevo.');
                    $this->session->set_flashdata('style', 'error');
                    redirect('usuarios/perfil/' . $userUsername);
                }

            }

        // If the request method is not POST, it means that form was not submitted.
        } else {
            $data['title'] = "Actualizar Datos";
            $data['page_title'] = "Actualizar Datos";
            $data['header']  = "header";
            $data['scripts'] = array('alert-dismiss');
            $data['body']    = "usuarios-actualizar";
            $data['user'] = $this->Data_model->get_profile_for_update($userUsername);
            $this->load->view('template', $data);
        }
    }
<?=form_close?>

I just told CI load the view, not redirect and lose the url. I repit: first time, it works cool. But if i don't change anything and just press SEND again, it fails :( Just noticed that tonight. Just by curiosity pressed send again and it went to hell.
Hope someone can give me some idea of whats going on. Thanks.
P.S. Maybe this guy has the same problem. Not quite sure...
CodeIgniter Set Form Validation Redirect URL
UPDATE #2 Added view code
     <?=form_open('usuarios/actualizar')?>

  <?php
      $config = array(
        'type' => 'submit',
        'content' => ' Guardar Usuario',
        'class' => 'btn btn-primary'
      );
  ?>

Actualizar Usuario

      <?=form_button($config)?>

  <?php if (validation_errors() != null) : ?>

  ×

      <?=validation_errors()?>

  <?php endif;?>

Datos Personales

        <input type="hidden" name="userID" value="<?=$user->userID ?>">
        Nombre*
        <input type="text" class="span4" name="userName" value="<?=set_value('username', $user->userName)?>">
        Apellido*
        <input type="text" class="span4" name="userLastName" value="<?=set_value('userLastName', $user->userLastName)?>">
        Teléfono
        <input type="text" class="span4" name="userCellphone" value="<?=set_value('userCellphone', $user->userCellphone)?>">
        Correo Electrónico*
        <input type="text" class="span4" name="userEmail" value="<?=set_value('userEmail', $user->userEmail)?>">
        Dirección*
        <textarea class="span4" name="userAddress"><?=set_value('userAddress', $user->userAddress)?></textarea>

It doesnt work because it can't find the argument so the $user object can't be created.
That lead like a ton of errors.
SOLUTION:
I don't have so much rep so i can't answers myself but here is the solution:
Oh my god. Maybe im falling asleep.
As Madmartigan states, i wasn't using the "argument". So, i added this:
$data['user'] = $this->Data_model->get_profile_for_update($this->uri->segment(3));

Sooo, i doesn't matter if it "lose" the argument in the URL, it works because before it loads the view, call the $data['user'] stuff :)
Thank you for your help guys, you are the best.

A: It seems pretty obvious:
<?=form_open('usuarios/actualizar')?>

This will always post to usuarios/actualizar, so you would lose any other URI segments or query string. Just leave it blank to post to the current url:
<?=form_open()?>

...although, I don't see that actualizar() actually does anything with the arguments passed to it in the url, so it's not clear why you want it to be usuarios/actualizar/richard, as richard doesn't appear to be used.
EDIT: OK, now I see it: $this->uri->segment(3). You need to be able to handle the case of this not being set, so in addition do this in your controller to prevent errors:
$userUsername = $this->uri->segment(3);
if ( ! $userUsername) show_404();

Just for the record, you can also do this to set a default "username":
public function actualizar($userUsername = 'Default Name') {
    // your code
}

Because CI is pretty strict about what it allows in the URL, you might be better off using the query string instead for names if you expect characters that aren't allowed in your $config['permitted_uri_chars'].

A: Instead of loading view on your validation fail you may use codeigniter redirect. e.g.
redirect('controller-name/method-name/parameter-name');

Load the form helper in that method and you can access all the validation messages since codeigniter store them in a log.


text:
Q: Pass a file path to a Javascript function from C# code behind I have this javascript function in a .aspx file.
<script>
function somefun(value)
{
       document.getElementById("myFlash").SetVariable("player:jsUrl", value);
       document.getElementById("myFlash").SetVariable("player:jsPlay", "");

}
</script>

I'm calling and passing a value to that function inside a onclick event in the code-behind class.
protected void DownloadFile(object sender, EventArgs e)
    {
        string filePath1 = "Audio/songname.mp3";

        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "Registering", String.Format("somefun('{0}');", filePath1), true);

    }

But when I click the button, I'm getting this error.
'Unable to get property 'SetVariable' of undefined or null reference'
The javascript function is correct and I checked it. I think something is wrong with the way I passing the parameter.

A:
The javascript function is correct and I checked it.

I don't think so. The error message suggests that document.getElementById("myFlash") return null, therefore you got an exception when trying to call SetVariable() on a null reference. This has nothing to do with the function parameter, at least not yet.


text:
Q: On 6-regular vertex-transitive graphs having 42 nodes In answering a recent Question about $6$-regular graphs with $42$ vertices, I commented that even the vertex-transitive cases afford a lot of choices.  Three such graphs were proposed, and I left it as a challenge to the interested Reader to verify non-isomorphism.
My hint was to fix a vertex $v$ and count the number of edges incident only to the six neighbors of $v$.  The three graphs gave respective counts of $9,15,6$ edges between such neighbors, proving them non-isomorphic.  A fourth example can be adduced, that of a $6$-regular vertex-transitive bipartite graph, where obviously the number of edges between neighbors of any one vertex is zero.
My question is what are the possible counts of edges between neighbors in $6$-regular vertex-transitive graphs having $42$ nodes.  All the examples described have counts that are multiples of three, which I speculate is a necessary but not sufficient condition.

I have some thoughts about attacking this problem which I'd like to share.
A nontrivial graph $G$ which is vertex transitive will have a nontrivial automorphism group $\mathscr G$.  Often the study of $G$ can be illuminated by the study of $\mathscr G$, as we see in this recent arXiv.org paper (2016) by Jing Chen AND Binzhou Xia:
On Isomorphisms of Vertex-Transitive Graphs
Note $\mathscr G$ has at least a subgroup $\mathscr H$ generated by those automorphisms which map some fixed vertex $v$ to one of its neighbors.  If $G$ is connected, then $G$ is $\mathscr H$-vertex-transitive since we can get from $v$ to any other vertex $u$ by a sequence of automorphisms in $\mathscr H$.  There is a slightly subtle concept involved here, noting that an automorphism $h$ maps $v$ to one of its neighbors if and only if $h$ maps every $u\in G$ to one of its neighbors, so that every step in the sequence outlined can be taken by one of the generators of $\mathscr H$.
If $G$ is not connected, then the components of $G$ must be equal in size, and in order for $G$ to be $6$-regular, that size must be a proper divisor $d$ of $42$ which is at least $7$.  In other words the sizes of nontrivial components are tightly restricted, and we hope these possibilities can be quickly exhausted.
Update: In checking the known vertex transitive connected graphs of regular degree $6$, I found examples with $21$ nodes where the neighbors of a fixed vertex share a number of edges not divisible by $3$ (namely $4$ or $7$ edges are shared).

A: Apologies for the roughness of this post, but it overstayed its welcome in the Sandbox!  It remains unresolved whether the neighbors of any vertex in a connected (single component) $6$-regular $42$-vertex simple graph will share only a number of edges divisible by three.
Disconnected Cases
As noted in the Question, disconnected examples will amount to vertex transitive 6-regular graphs on $v$ nodes where $v\gt 1$ is a divisor of $42$.  Thus $v=7,14,21$ are possibilities, and small enough that all have been exhaustively cataloged by McKay and Royle.
The files there are (Unix) ASCII format/gzipped.  However after extracting the files, one needs a utility showg to convert them to human-readable form.
Case $v=7$
The only $6$-regular graph on $7$ vertices is the complete one, $K_7$.  This clique achieves $\binom{6}{2}=15$ edges among the six neighbors $N$ of any fixed vertex, and thus the maximum count of such edges in the "open neighborhood" of a vertex.

Figure 1:  Complete graph on seven vertices
Case $v=14$
Among the $51$ vertex transitive connected graphs on $14$ vertices, there are eight which are $6$-regular.  Of these, one has no edges between neighbors of $v$, two have $3$ edges there, four have $6$ such edges, and one has $9$.
The graph with no edges between neighbors of a vertex is bipartite, indeed the complete bipartite $K_{7,7}$ minus a $1$-factor (matching).
Case $v=21$
Among the $235$ vertex transitive connected graphs on $21$ vertices, there are twenty-eight which are $6$-regular.  Of these, some have a number of edges between neighbors of $v$ which is not a multiple of three.  Here's a tabulation of how many of these graphs have the given number of edges $e_{N}$ in the open neighborhood $N$ of a vertex:
$$ \begin{array}{c|c}
e_{N} & \# \text{ of graphs} \\
\hline
0 & 4 \\
1 & 3 \\
2 & 1 \\
3 & 8 \\
4 & 3 \\
5 & 2 \\
6 & 4 \\
7 & 2 \\
8 & 0 \\
9 & 1 \\
\hline
\text{all} & 28
\end{array} $$
The showg output for the unique $6$-regular vertex transitive graph on $21$ nodes with $e_N = 2$ is as follows (nodes labelled $0$ to $20$):
Graph 17, order 21.
  0 : 1 2 3 4 5 6;
  1 : 0 3 7 9 14 17;
  2 : 0 4 8 10 14 18;
  3 : 0 1 8 10 13 20;
  4 : 0 2 7 9 12 19;
  5 : 0 8 10 11 12 15;
  6 : 0 7 9 11 13 16;
  7 : 1 4 6 8 16 17;
  8 : 2 3 5 7 15 18;
  9 : 1 4 6 11 12 15;
 10 : 2 3 5 11 13 16;
 11 : 5 6 9 10 19 20;
 12 : 4 5 9 14 18 20;
 13 : 3 6 10 14 17 19;
 14 : 1 2 12 13 19 20;
 15 : 5 8 9 16 17 20;
 16 : 6 7 10 15 18 19;
 17 : 1 7 13 15 18 20;
 18 : 2 8 12 16 17 19;
 19 : 4 11 13 14 16 18;
 20 : 3 11 12 14 15 17;


text:
Q: Removing some unwanted elements from the vector I have a vector that consists of some numbers in the following way:
A = [153 244 253 353 453 530 653 ...]

The pattern is that there is always 153,253,353,...,2353 (these represent time i.e. 1:53am,...11:53pm) for a day. In between these *53 numbers there are some numbers that I don't wish to keep them. For example between 353 and 453, a 433 appears which needs to be removed from the vector. So the final result I wish to get is vector
A = [153 253 353 ...2353]

(of course in the original vector I have, this pattern for one day is repeated for a whole year).
Any thought on how to do this?
I would really appreciate any answer.

A: An alternative (and possibly faster) answer to Oleg is to use the modulus operator:
A((mod(A,100))==53)

A: Keep only the 53'' of each hour:
idx = ismember(A,53:100:2353);
A(idx)


text:
Q: Is it possible to find peaks in a csv file and add the peaks in a separate column in the same csv file? (without plotting) This is a piece of my code, but I don't know how to get this array as new column Height to the original csv file in the format?

Date
Level
Height

01-01-2021
45
0

02-01-2021
43
0

03-01-2021
47
1

04-01-2021
46
0

.....

import pandas as pd
from scipy.signal import find_peaks
import matplotlib.pyplot as plt

bestand = pd.read_csv('file.csv', skiprows=1, usecols=[0, 1] , names=['date', 'level'])
bestand = bestand['level']

indices = find_peaks(bestand, height= 37, threshold=None, distance=None)

height  = indices[1]['peak_heights']
print(height)

A: I think you want to assign a column named height that takes the value 1 when level is a peak according to find_peaks(). If so:
# Declare column full of zeros
bestand['height'] = 0
# Get row number of observations that are peaks
idx = find_peaks(x=bestand['level'], height=37)[0]
# Select rows in `idx` and replace their `height` with 1
bestand.iloc[idx, 2] = 1

Which returns this:
         date  level  height
0  01-01-2021     45       0
1  02-01-2021     43       0
2  03-01-2021     47       1
3  04-01-2021     46       0

A: I'am not sure I understood your question.
You just want to save the results?
bastand['Heigth'] = indices
bastand.to_csv('file.csv')


text:
Q: Sort text data without a delimiter I have to do the following in excel. I have a multiple text files of the same format: (see below)

- Samplefile
- 1)Step 1
- XYZ
- 2)Step 2
- ABC
- 3)Step 3
- ABC1

- Name: Samplefile2
- 1)Step 1
- XYZ2
- 2)Step 2
- ABC2
- 3)Step 3
- DEF2

I wanted to write a code to import all the files and give me a final output as below in different excel columns
 1. Name         Step1  Step2  Step3
 3.  Samplefile   XYZ    ABC    ABC1
 4.  Samplefile2  XYZ2   ABC2   DEF2

A: I got some progress with this.I am able to import the files and split it.
For my next step, I wanted some help in modifying this code so that I can change the  of the sheet that I import the recipes files  to sheet 1, sheet 2 and so on, instead of the text file namme?
See code below:
Sub CombineTextFiles()
    Dim FilesToOpen
    Dim x As Integer
    Dim wkbAll As Workbook
    Dim wkbTemp As Workbook
    Dim sDelimiter As String

    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    sDelimiter = "|"

    FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Text Files (*.txt), *.txt", _
      MultiSelect:=True, Title:="Text Files to Open")

    If TypeName(FilesToOpen) = "Boolean" Then
        MsgBox "No Files were selected"
        GoTo ExitHandler
    End If

    x = 1
    Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
    wkbTemp.Sheets(1).Copy
    Set wkbAll = ActiveWorkbook
    wkbTemp.Close (False)
    wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
      Destination:=Range("A1"), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=False, _
      Tab:=False, Semicolon:=False, _
      Comma:=False, Space:=False, _
      Other:=True, OtherChar:="|"

    x = x + 1

    While x <= UBound(FilesToOpen)
        Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
        With wkbAll
            wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
            .Worksheets(x).Columns("A:A").TextToColumns _
              Destination:=Range("A1"), DataType:=xlDelimited, _
              TextQualifier:=xlDoubleQuote, _
              ConsecutiveDelimiter:=False, _
              Tab:=False, Semicolon:=False, _
              Comma:=False, Space:=False, _
              Other:=True, OtherChar:=sDelimiter

        End With
        x = x + 1
    Wend

ExitHandler:
    Application.ScreenUpdating = True
    Set wkbAll = Nothing
    Set wkbTemp = Nothing
    Exit Sub

ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler

End Sub


text:
Q: Form validation exclusion for a word I am trying to add a validation to a simple form in a Rails 4.1 project. I need to reject a form submission if a text field contains a forbidden word. My other validations work but not this one. So if the user enters no value or too long of a value it is rejected and the error message is displayed.
I have it setup similarly to the edge guide (http://edgeguides.rubyonrails.org/active_record_validations.html#exclusion) but the form submit still goes through if I enter "My favorite color is red." What should I do differently?
My model:
class ColorEntry < ActiveRecord::Base
  validates :body, presence: true
  validates :body, length: { maximum: 255 }
  validates :body, exclusion: { in: %w(red) }
end

A: Try to use a regex validation for format with the "without" attribute. So, if it does not match, the form can't be submitted.
validates :body, format: {without: /example/}

Other syntax
validates_format_of :body, without: /example/

More references in:
http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html


text:
Q: Mysql Regexp with array I am getting an array of category id eg. ['1','2','3']
and in my database table it is stored as 1_abc eg : category : 1_Sameer
Now it is easy if i get one value
ie. WHERE category like 1_%;

But since this is an array how can i use like or regex to compare with the database values

A: In this case you can do as many queries as you have array elements and merge these results together if needed to get single collection of elements.
$results = new Collection();
foreach($ids as $id) {
$categories=Category::where("id","like","$id_%")->get();
    $results=$results->merge($categories);
}

A: you have to do looping for that
for($i=0;$i<=count($array_result)-1;$i++)
{
$result=mysql_query("select * from table_name where category like  '{$array_result[$i]}_%' ");
}


text:
Q: PHP libgd crash without feedback I'm working on a very large number of images. I have to create four JPEG versions of each image:

*

*original size JPEG

*700x430 version

*57x57 thumbnail

*167xN thumbnail (variable height, maintain aspect ratio)

I used the following two helper functions:
function thumbFixed($srcfile, $dstfile, $dstWidth, $dstHeight) {
    $srcImg = imagecreatefromstring(file_get_contents($srcfile));
    list($srcWidth, $srcHeight) = getimagesize($srcfile);
    $srcAR = $srcWidth / $srcHeight;

    $dstAR = $dstWidth / $dstHeight;

    $dstImg = imagecreatetruecolor($dstWidth, $dstHeight);

    if($srcAR >= $dstAR) {
        $cropHeight = $dstHeight;
        $cropWidth = (int)($dstHeight * $srcAR);
    } else {
        $cropWidth = $dstWidth;
        $cropHeight = (int)($dstWidth / $srcAR);
    }

    $cropImg = imagecreatetruecolor($cropWidth, $cropHeight);
    imagecopyresampled($cropImg, $srcImg, 0, 0, 0, 0, $cropWidth, $cropHeight, $srcWidth, $srcHeight);

    $dstOffX = (int)(($cropWidth - $dstWidth) / 2);
    $dstOffY = (int)(($cropHeight - $dstHeight) / 2);

    imagecopy($dstImg, $cropImg, 0, 0, $dstOffX, $dstOffY, $dstWidth, $dstHeight);
    imagejpeg($dstImg, $dstfile);
}

function thumbGrid($srcfile, $dstfile, $dstWidth) {
    $srcImg = imagecreatefromstring(file_get_contents($srcfile));
    list($srcWidth, $srcHeight) = getimagesize($srcfile);
    $srcAR = $srcWidth / $srcHeight;

    $dstHeight = $dstWidth / $srcAR;

    $dstImg = imagecreatetruecolor($dstWidth, $dstHeight);

    imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
    imagejpeg($dstImg, $dstfile);
}

Those function are used in this context:
$img = imagecreatefromstring(file_get_contents($local));
imagejpeg($img, 'temp.jpg', 100);
thumbFixed($local, 'gallery.jpg', 700, 430);
thumbFixed($local, 'thumbsmall.jpg', 57, 57);
thumbGrid($local, 'grid.jpg', 167);

Where $local holds the pathname of the image.
The code works okay for most of the pictures, but misbehaves in one particular case, which is a 1792x1198, 356Kb JPEG file. I'm quite worried by the misbehavior, though, because I can't seem to trace it in any way: running gdb on PHP interpreter results in Program exited with code 0377. (which means PHP has exit(-1)ed) and nothing else - no stack trace, no errors, no feedback whatsoever.
I figured out, by inserting various echos before every libgd call, that the script "crashes" PHP when executing $cropImg = imagecreatetruecolor($cropWidth, $cropHeight); in the thumbFixed function, but I can't seem to figure out a way around this since I can't control it from my code, nor backtrace it from a debugger. Has anybody had similar experiences with this and can give me some pointers?


text:
Q: What I should to do with not subscriptable problem in python? My idea is prepare an US map with information which state "born" highest number of NBA players.

and I found this tutorial https://plot.ly/python/choropleth-maps/
I tried to modify code like this:
import plotly.plotly as py
import pandas as pd

df = pd.ExcelFile('playersnba.xlsx')

data = [ dict(
type = 'choropleth',
locations = df['State'],
z = df['Numbers'],
text = df['State'],
colorscale = [[0,"rgb(5, 10, 172)"],[0.35,"rgb(40, 60, 190)"],[0.5,"rgb(70, 100, 245)"],\
    [0.6,"rgb(90, 120, 245)"],[0.7,"rgb(106, 137, 247)"],[1,"rgb(220, 220, 220)"]],
autocolorscale = False,
reversescale = True,
marker = dict(
    line = dict (
        color = 'rgb(180,180,180)',
        width = 0.5
    ) ),
colorbar = dict(
    autotick = False,
    tickprefix = '#',
    title = 'players'),
 ) ]

My problem is:
...line 8, in <module>
    locations = df['State'],
TypeError: 'ExcelFile' object is not subscriptable

A: It should be written this way
import pandas as pd

df = pd.ExcelFile('playersnba.xlsx').parse()

A: The way to read an excel file into a dataframe is to use ExcelFile.parse(), not just ExcelFile. So:
df = pd.ExcelFile.parse('playersnba.xlsx')


text:
Q: htaccess redirect to a maintainance file I have an htaccess in the public directory:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteBase /sub/web1/

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # HERE I NEED SOM MAGICAL ONELINER TO REDIRECT STUFF TO MAINTENANCE.HTML
    # BUT NO IDEA HOW TO WRITE IT ;(

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

and I want to add some rule inside, so when I uncomment the rule, all links that hit http://example.com/sub/web1/ or any files down that line, will be redirected to http://example.com/sub/web1/maintenance.html
I have tried to add:
DirectoryIndex maintenance.html
but this only redirects http://example.com/sub/web1/, if I have some subfolder or specific files like http://example.com/sub/web1/posts, it is useless.
Is there some oneliner that can even pull the domain name so it hasn't have to be typed absolutely? So, the example.com - or whatever domain - is not needed to type in the rule?

A: You can have a rule like this:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteBase /sub/web1/

    # uncomment line below to route everything to maintenance.html
    # RewriteRule !^maintenance\.html$ maintenance.html [L,NC]

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # HERE I NEED SOM MAGICAL ONELINER TO REDIRECT STUFF TO MAINTENANCE.HTML
    # BUT NO IDEA HOW TO WRITE IT ;(

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

A: Although this has already been answered and accepted, it's worth mentioning that if your maintenance page is temporary, you really should be returning the right http response, otherwise search engines might drop or re-index pages incorrectly.
At my company we use something like this:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/holding/holding.html -f
RewriteCond %{DOCUMENT_ROOT}/holding/holding.enable -f
RewriteCond %{SCRIPT_FILENAME} !holding.html
RewriteRule ^.*$ /holding/holding.html [R=503,L]
ErrorDocument 503 /holding/holding.html

We create holding.html as the maintenance page, and then touch holding.enable to make the server switch to it without requiring a restart (not forgetting to rm it when we're done).  The 503 return code on the rewrite rule, and the ErrorDocument 503 ensure that search engines see this a temporary outage and don't start de-listing our pages.

A: You can use the %{HTTP_HOST} variable to get  the current domain that was used when hitting the given htaccess file - here's a handy cheat sheet of things:
askapache - cheatsheet
And some examples
askapache - examples
Although it's worth trying this out as it'll use root ^$ and rewrite that to the sub directory you want to use:
RewriteBase /
ReqwriteRule ^$ /sub/web1/


text:
Q: Смена фона с js Написал код
function randColor() {
var red = Math.round(Math.random()*255);
var blue = Math.round(Math.random()*255);
var green = Math.round(Math.random()*255);
document.getElementById('boby').style.backgroundColor = "rgb+"("+txt+")"";

var txt = (+red+", "+blue+", "+green);
alert("rgb"+"("+txt+")");
}

чтобы менять  фон боди по клику.
Через alert видно что rgb передает правильный и если вместо того что выдает "rgb+"("+txt+")"" написать то что выдает alert то все заработает, но вот сам код при этом не работает.
Кто может подсказать почему?

A: Все-таки лучше сначала присвоить переменной значение, а уж потом ее использовать.

function randColor() {
  var red = Math.round(Math.random() * 255);
  var blue = Math.round(Math.random() * 255);
  var green = Math.round(Math.random() * 255);

  var txt = (+red + ", " + blue + ", " + green);
  //alert("rgb"+"("+txt+")");
  document.getElementById('boby').style.backgroundColor = "rgb(" + txt + ")";
}

setInterval(randColor, 500);
#boby {
  width:200px;
  height:100px;
  border:1px solid black;
}

<button onclick="randColor()">Click</button>


text:
Q: Is there a way to code a chainl function in idris lightyear library? I'm trying to formalise a regular expression based string search tool in Idris
(current status here). But I'm fighting with the problem of parsing regular expressions. I've tried to build a small parsing library but gave up on this in favor to use Lightyear, a parsing combinator library for Idris.
Since I'm used to Haskell, I've tried to use a similar strategy that I would do using Parsec. My main problem is how to handle left recursion on Lightyear parsers? I've tried several encodings but pretty much all parsers end up looping and causing segmentation faults in generated code.

A: I don't know Lightyear, but I had some success porting Parsec to Idris:
module Parser

data Parser : Type -> Type where
     P : (String -> List (a, String)) -> Parser a

unP : Parser a -> String -> List (a, String)
unP (P f) = f

total stripPrefix : (Eq a) => List a -> List a -> Maybe (List a)
stripPrefix [] ys = Just ys
stripPrefix (x::xs) (y::ys) = if (x == y) then stripPrefix xs ys else Nothing
stripPrefix _ _  = Nothing

total token : String -> Parser ()
token tk = P $ \s => case stripPrefix (unpack tk) (unpack s) of
      Just s' => [((), pack s')]
      Nothing => []

total skip : Parser ()
skip = P $ \s => case unpack s of
     [] => []
     (_::s') => [((), pack s')]

instance Functor Parser where
  map f p = P $ \s => map (\(x, s') => (f x, s')) (unP p s)

instance Applicative Parser where
  pure x = P $ \s => [(x, s)]
  (P pf) <*> (P px) = P $ \s => concat (map (\(f, s') => map (\(x, s'') => (f x, s'')) (px s')) (pf s))

instance Alternative Parser where
  empty = P $ \s => []
  (P p1) <|> (P p2) = P $ \s => case p1 s of
     [] => p2 s
     results => results

instance Monad Parser where
  px >>= f = P $ \s => concat (map (\(x, s') => unP (f x) s') (unP px s))

total runParser : Parser a -> String -> Maybe a
runParser (P p) s = case p s of
  [(x, "")] => Just x
  _         => Nothing

This allows a straight copy-paste implementation of chainl:
chainl1 : Parser a -> Parser (a -> a -> a) -> Parser a
chainl1 p op = p >>= rest
  where
    rest x = do { f <- op; y <- p; rest $ f x y } <|> return x

chainl : Parser a -> Parser (a -> a -> a) -> a -> Parser a
chainl p op x = chainl1 p op <|> return x

We can then take a straight transliteration of the expression parser from the chainl docs (I'm too lazy to implement a proper integer parser so we'll just use unary):
parens : Parser a -> Parser a
parens p = token "(" *> p <* token ")"

symbol : String -> Parser ()
symbol = token

integer : Parser Nat
integer = P $ \s => case unpack s of
     ('Z'::s') => [(Z, pack s')]
     ('S'::s') => map (\(n, s'') => (S n, s'')) $ unP integer (pack s')
     _ => []

mutual
    expr : Parser Nat
    expr = term   `chainl1` addop

    term : Parser Nat
    term = factor `chainl1` mulop

    factor : Parser Nat
    factor  = parens expr <|> integer

    mulop : Parser (Nat -> Nat -> Nat)
    mulop = (symbol "*" *> pure (*)) <|>
            (symbol "/" *> pure div)

    addop : Parser (Nat -> Nat -> Nat)
    addop = (symbol "+" *> pure (+)) <|>
            (symbol "-" *> pure (-))

Now, if you try this:
main : IO ()
main = do
  s <- getLine
  printLn $ runParser expr s

then it will have the same divergant behaviour that you've observed. However, we can make two small changes:

*

*Introduce a lazy alternative combinator:
orElse : Parser a -> Lazy (Parser a) -> Parser a
orElse p1 p2 = P $ \s => case unP p1 s of
   [] => unP p2 s
   results => results

*Make sure the recursive part of factor, i.e. the parens expr part, is in this lazy position, by flipping the two alternatives:
factor = integer `orElse`  parens expr

This then works as expected:
13:06:07 [cactus@galaxy brainfuck]$ idris Expr.idr -o Expr
13:06:27 [cactus@galaxy brainfuck]$ echo "SZ+(SSZ*SSSZ)" | ./Expr
Just 7

A: The chainl and chainl1 combinators can be used with the Lightyear package. However, they are provided by default. I've added the combinators to my own modules where I've needed them:
chainl1 : Parser a -> Parser (a -> a -> a) -> Parser a
chainl1 p op = p >>= rest
  where rest a1 = (do f <- op
                      a2 <- p
                      rest (f a1 a2)) <|> pure a1

chainl : Parser a -> Parser (a -> a -> a) -> a -> Parser a
chainl p op a = (p `chainl1` op) <|> pure a

Seems to work fine. Hope that helps.


text:
Q: OpenGL texture mapping on sides cube using GL_QUADS I am trying to map a different texture on each side of a cube using a GL_QUADS. My first problem is that I cannot even get a texture to display on the side of a GL_QUADS. I can however get a texture to display using GL_TRIANGLES but I do no understand how to draw things very well using triangles and I want to use QUADS. I also can only use GLUT for this. I need an example that works because I do not know enough about OpenGL for someone to simply explain this to me. Someone please help. Thanks!

A: Oops didn't realize I forgot to use glTexCoord2f. It works now.

A: If you post the code that you are having trouble with, perhaps I can help you.  Most likely, you need to set the appropriate texture coordinates per-vertex.


text:
Q: Trying to salvage a messed up dataset I've been tasked with the tedious job of salvaging a mangled dataset that looks like this in its .txt file form
 "DATE"|"ID"|"TITLE"|"NAME"|"SURNAME"|"INCOME"|"ADDRESS1"|"JOB"
||MR|ROBIN|WILLIAMS|291029102|
2019-01-01||MRS||DREW||SECOND_TO_THE_RIGHT_AND_STRAIGHT_ON_TILL_MORNING||
2021-02-04|||JONATHAN|SIMMONS|3012000|SOMEWHERE_IN_BEVERLY_HILLS|
|MARK|ZUCKERBURG||SILICON_VALLEY|
|||PARKER|JONES||SOMEWHERE_IN_HIS_HOMETOWN_IN_
NORTHERN_ITALY
2019-06-03|4444301243451|MRS|CARMEN|SANDIEGO||WHERE_IN_THE_WORLD_IS_
CARMEN_SANDIEGO|THIEF
2018-02-25|2395022812223|MR|ARNOLD|SCHWARZENEGGER|MUSCLE_BEACH_VENI
CE_CALIFORNIA_USA|ACTOR
|DOCTOR|STRANGE|NEW_YORK_SA
NCTUM|SORCERER_SUPREME
||HAL|JORDAN||EARTH|GREEN_LANTERN
2019-01-02|0212931229475|MR|KEVIN|BACON|129340212|SOME_PLACE_IN_THE_US|ACTOR
2019-01-03|2939583749642|MRS|NICOLE|KIDMAN|291928494|BEVERLY_HILLS|ACTOR
2019-03-15|2947959371923|MR|WARREN|BUFFET|2000000000|OMAHA_NEBRASKA|INVESTOR
2020-02-45|2847939172394|MRS|JULIE|ARIS|200034|SOMEWHERE_IN_THE_UK|LECTURER

There are two major problems with this dataset that I've been struggling with, the first of which is that there aren't enough delimiters in certain rows (e.g. the first row) and the second being that long values in the address column have somehow caused the address value to "spill over" into the next row. When I asked the people in charge of extracting the data from their databases why the data looked like this, this was apparently caused by people pressing "Enter" while inputting long addresses, which also meant that the data was stored this way in the database to begin with, thus ruling out any possibility of a re-extraction rectifying these errors. According to them, the easiest way to rectify the second problem is to press backspace at the head of each problematic row like this.
 "DATE"|"ID"|"TITLE"|"NAME"|"SURNAME"|"INCOME"|"ADDRESS1"|"JOB"
||MR|ROBIN|WILLIAMS|291029102|
2019-01-01||MRS||DREW||SECOND_TO_THE_RIGHT_AND_STRAIGHT_ON_TILL_MORNING||
2021-02-04|||JONATHAN|SIMMONS|3012000|SOMEWHERE_IN_BEVERLY_HILLS|
|MARK|ZUCKERBURG||SILICON_VALLEY|
2019-01-02|0212931229475|MR|KEVIN|BACON|129340212|SOME_PLACE_IN_THE_US|ACTOR
2019-01-03|2939583749642|MRS|NICOLE|KIDMAN|291928494|BEVERLY_HILLS|ACTOR
2019-03-15|2947959371923|MR|WARREN|BUFFET|2000000000|OMAHA_NEBRASKA|INVESTOR
2020-02-45|2847939172394|MRS|JULIE|ARIS|200034|SOMEWHERE_IN_THE_UK|LECTURER

While technically not a bad solution, I'm not about to do this manually for a dataset that has over 2 million rows.
My first idea was to look for escape characters in the datafile using Notepad++, but there were no signs of escape characters in the dataset at all. My second idea was to try to read the datafile row by row and append it to a dataframe using the following lines of code.
import time
start = time.time()

with open("DATAFILE.txt", 'rt', encoding = 'UTF8') as f:
    data = f.read()

fl = data.splitlines()

# 350231 rows
len(fl)

df1 = pd.DataFrame()

for i in range(0, 10000):
    df1 = df1.append([fl[i+1].split('|')], ignore_index=True)
print('Total Time:',round((time.time() - start),2), '(sec)')

This did absolutely nothing as it gave me the exact same results as read_csv, which is why I'd very much appreciate some advice on how to solve this problem.
Example of a row with empty values filled in with NaN:
"DATE"|"ID"|"TITLE"|"NAME"|"SURNAME"|"INCOME"|"ADDRESS1"|"JOB"
NaN |NaN|MR|ROBIN|WILLIAMS|291029102|NaN

Note that this row is also missing a delimiter for the JOB column


text:
Q: How do I wait for response of Volley? To summarize my problem i have a request written with Android Volley Library.
I need fill chartDataList . But there is a problem whenever i call the method it return a null array after 3 seconds it filling itself asynchronously. I want to wait for response but i dont have any idea how can i do that?
Here is my codes:
 public List<ChartData> getVolleyResponse() {
        requestQueue = Volley.newRequestQueue(getApplicationContext());
        JsonObjectRequest req = new JsonObjectRequest(
                Request.Method.GET,
                urlCreator(getCoinName()),
                null,
                response -> {
                    try {
                        JSONArray arr = response.getJSONArray("prices");
                        ChartData chartData = new ChartData();
                        for (int i = 0; i < arr.length(); i++) {
                            JSONArray jsonArray = arr.getJSONArray(i);
                            chartData.setTimeStamp(timeStampConverter(jsonArray.getString(0)));
                            chartData.setCost(jsonArray.getDouble(1));
                            chartDataList.add(chartData);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                },
                error -> {
                    Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show();
                });
        requestQueue.add(req);
        return chartDataList;
}

A: The Response function is a callback that will be executed after your request has processed/server has responded. I would recommend executing your logic that depends on the response data within your Response function callback. This is non-blocking but works with the asynchronous design of Volley:
 public List<ChartData> getVolleyResponse() {
    requestQueue = Volley.newRequestQueue(getApplicationContext());
    JsonObjectRequest req = new JsonObjectRequest(
            Request.Method.GET,
            urlCreator(getCoinName()),
            null,
            response -> {
                try {
                    JSONArray arr = response.getJSONArray("prices");
                    ChartData chartData = new ChartData();
                    for (int i = 0; i < arr.length(); i++) {
                        JSONArray jsonArray = arr.getJSONArray(i);
                        chartData.setTimeStamp(timeStampConverter(jsonArray.getString(0)));
                        chartData.setCost(jsonArray.getDouble(1));
                        chartDataList.add(chartData);
                    }

                    // The request has processed/server has responded.
                    // Do something with your response here.
                    // ...

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            },
            error -> {
                Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show();
            });
    requestQueue.add(req);

    // We're handling the response asynchronously, so there shouldn't be anything to return here.
}


text:
Q: Sumar dos elementos de un desplegable en javascript Tengo dos listas (select) con distintos valores. Me gustaria que el usuario escoja un valor de cada lista y que al pulsar un botón el programa mostrase el resultado de la suma. Aqui va lo que tengo hecho hasta ahora. :)

// Añadiendo los tipos de tea

//Escogiendo el elemento
var selectTea = document.getElementById('tea');

//Array
var teas = [180, 300, 240]

//Loop
for (var i = 0; i < teas.length; i++) {

    // creando la nueva option
    var opt = document.createElement('option');

    // Añadiendo texto al elemento (opt)
    opt.innerHTML = teas[i];

    //Añadiendo un valor al elemento (opt)
    opt.value = teas[i];

    // Añadiendo opt al final del selector (sel)
    selectTea.appendChild(opt);

}

// Añadiendo las personas

//Escogiendo el elemento
var selectPeople = document.getElementById('ho');

//Array
var people = [-50, +80, +30]

//Loop
for (var i = 0; i < people.length; i++) {

    // creando la nueva option
    var opt = document.createElement('option');

    // Añadiendo texto al elemento (opt)
    opt.innerHTML = people[i];

    //Añadiendo un valor al elemento (opt)
    opt.value = people[i];

    // Añadiendo opt al final del selector (sel)
    selectPeople.appendChild(opt);

}
.wrapper {
    background-color: white;
    width: 100%;
    height: 100%;

}

body {
    background-color: ;
}

.title {

    text-align: center;
    color: black;
    font-family: 'Roboto';

}

.tea {
    width: 50%;
    float: left;
}

.likeho {
    width: 50%;
    float: left;
}

.resultado {
    text-align: center;
    margin-top: 100px;
    font-family: 'Roboto';
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,600" rel="stylesheet" type="text/css">
    <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
    <link type="text/css" rel="stylesheet" href="style.css">

    <title>Teassistant</title>

Teassistant

            <select id="tea" name="tea">

            </select>

            <select id="ho" name="ho">

            </select>

Resultado en segundos

                <input type="button" onClick="totalTime()" Value="Suma" />

A: Solo debes obtener cada valor seleccionado por medio del atributo value, convertirlos a número (ya que son string) y luego sumarlos.

// Añadiendo los tipos de tea

//Escogiendo el elemento
var selectTea = document.getElementById('tea');

//Array
var teas = [180, 300, 240]

//Loop
for (var i = 0; i < teas.length; i++) {

    // creando la nueva option
    var opt = document.createElement('option');

    // Añadiendo texto al elemento (opt)
    opt.innerHTML = teas[i];

    //Añadiendo un valor al elemento (opt)
    opt.value = teas[i];

    // Añadiendo opt al final del selector (sel)
    selectTea.appendChild(opt);

}

// Añadiendo las personas

//Escogiendo el elemento
var selectPeople = document.getElementById('ho');

//Array
var people = [-50, +80, +30]

//Loop
for (var i = 0; i < people.length; i++) {

    // creando la nueva option
    var opt = document.createElement('option');

    // Añadiendo texto al elemento (opt)
    opt.innerHTML = people[i];

    //Añadiendo un valor al elemento (opt)
    opt.value = people[i];

    // Añadiendo opt al final del selector (sel)
    selectPeople.appendChild(opt);

}

// esto te falta
function totalTime() {
  var tea = Number(selectTea.value);
  var peo = Number(selectPeople.value);
  alert(tea + peo);
}
.wrapper {
    background-color: white;
    width: 100%;
    height: 100%;

}

body {
    background-color: ;
}

.title {

    text-align: center;
    color: black;
    font-family: 'Roboto';

}

.tea {
    width: 50%;
    float: left;
}

.likeho {
    width: 50%;
    float: left;
}

.resultado {
    text-align: center;
    margin-top: 100px;
    font-family: 'Roboto';
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,600" rel="stylesheet" type="text/css">
    <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
    <link type="text/css" rel="stylesheet" href="style.css">

    <title>Teassistant</title>

Teassistant

            <select id="tea" name="tea">

            </select>

            <select id="ho" name="ho">

            </select>

Resultado en segundos

                <input type="button" onClick="totalTime()" Value="Suma" />


text:
Q: Why columns value change into NULL when try to update only one column? This is my table which I created in sql server...
CREATE TABLE [dbo].[Addresses_Table](
[AddressID] [int] IDENTITY(1,1) NOT NULL,
[BuildingName] [varchar](300) NULL,
[UnitNumber] [nvarchar](50) NULL,
[StreetNumber] [varchar](20) NULL,
[StreetName] [varchar](200) NULL,
[Suburb] [varchar](100) NULL,
[POBox] [varchar](20) NULL,

   CONSTRAINT [PK_Addresses_Table] PRIMARY KEY CLUSTERED (
[AddressID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = OFF, ALLOW_PAGE_LOCKS = OFF) ON [PRIMARY] ) ON [PRIMARY]

INSERT INTO [dbo].[Addresses_Table] (BuildingName,UnitNumber,StreetNumber, StreetName, Suburb) VALUES ('mybuilding', '101', '12','Street 1', 'TEST12')

When I try to update 'POBox' column value into '1234' (any value),
BuildingName, UnitNumber, StreetNumber, StreetName turn into NULL values.
I have attached my sql update query and results of it.
Please help me out to solve this problem....

A: It seems there is a trigger on the table that sets StreetName to NULL after the update. This is evidenced by the SSMS output that shows 2 rowcount messages, one when the row is updated directly and the other when the same row is updated by the trigger.
The trigger makes sense from a data perspective since StreetName does not apply to a PO box address.


text:
Q: Javah Error android.app.Activity not found I'm trying to create a .h header file for a simple NDK project. Using cygwin I browse to myprojectDIR\jni directory, then execute this command:
javah -o com_myproject_MyActivity.h -classpath  myprojectDIR\bin\classes com.myproject.MyActivity

then this error message appears:
Error: cannot access android.app.Activity
class file for android.app.Activity not found

I have a native method inside MyActivity class, so I tried to create a new class called NativeAccess (does not extend any class from the android SDK) and it worked fine, the .h file was created, ndk-build and test on device where successful!
So my problem is that I need my native methods inside android activities and services that I create, but I cant do that because the Javah command cannot access classes from inside the android-sdk itself. Please notice that I'm using (Windows-7 x64) and I have these environment variables:
ANDROID_NDK : C:\Android\android-ndk-r7b
ANDROID_SDK : C:\Android\android-sdk
ANT_HOME    : C:\ANT\apache-ant-1.8.3
JAVA_HOME   : C:\Program Files\Java\jdk1.7.0_02
PATH        : %JAVA_HOME%\bin;%ANDROID_SDK%\tools;%ANDROID_SDK%\platform-tools;%ANDROID_NDK%;%ANT_HOME%\bin; (other unrelated stuff)

Thanks in advance

A: Try the following in Eclipse,
Go to > Run | External Tools| External Tool Configurations
   Under Program create new configuration by clicking small icon.
Name it.
Location would be : C:\Program Files\Java\jdk1.7.0_04\bin\javah.exe
Working Directory would be: ${workspace_loc:/My_First_NDK/bin/classes} and
Arguments would be: -classpath ${workspace_loc:/My_First_NDK/bin/classes} -bootclasspath "C:\adt-bundle-windows-x86-20140624\sdk\platforms\android-19\android.jar" -v -d ${workspace_loc:/My_First_NDK/jni} com.mypackage.ndk.HelloNDK

A: Try adding to your classpath:
-classpath <android-sdk-location>/platforms/android-8.jar

A: I found it, this is how it goes:
javah -o com_myproject_MyActivity.h -classpath <android-sdk-location>/platforms/android-8.jar;myprojectDIR\bin\classes com.myproject.MyActivity

A: In order to generate native header files javah needs:

*

*your classes (usually under build/intermediates/classes)

*Android classes (usually under $ANDROID_HOME/platforms/android-%ver%/android.jar)

So you simply pass them in -classpath argument
The main challenge for me was basically passing both of them - you have to use : as a separator and paths must be absolute.
See Oracle docs
Thus you may end up with something like this: javah -classpath <full path to app>build/intermediates/classes/debug:<full path to sdk>/platforms/android-26/android.jar com.myproject.MyActivity

A: I found it, this is how it goes:
   E:\workspeaceResearch\DAMMADARJNI\src>javah -classpath "E:\Software\sdk\platform
   s\android-19/platforms/android-8.jar"; -jni com.dammadar.jni.Home_Screen


text:
Q: How can I access the Express app instance to set CORS origin in a Probot app? The probot documentation mentions that I can use routes just like I would in a vanilla Express server.
I wantr to set CORS origin headers for these routes. In a vanilla Express server I would use the cors package:
const cors = require('cors')

...

app.use(cors())

But the probot app does not have the function use.
module.exports = app => {
  app.use(cors(corsOptions));
// ...

causes the error:
ERROR (event): app.use is not a function
    TypeError: app.use is not a function

How do I set CORS?

A: You must start the app programmatically. This way you can access the Express app AFTER probot loads but BEFORE Probot starts running:
const cors = require("cors");
const bodyParser = require("body-parser");
const { Probot } = require("probot");
const { corsOptions } = require("./src/util/init-server.js");
const endpoint = require("./src/controller/endpoint");
const { handleWhatever } = require("./src/controller/controller");

// https://github.com/probot/probot/blob/master/src/index.ts#L33
const probot = new Probot({
  id: process.env.APP_ID,
  port: process.env.PORT,
  secret: process.env.WEBHOOK_SECRET,
  privateKey: process.env.PRIVATE_KEY,
  webhookProxy: process.env.WEBHOOK_PROXY_URL,
});

const probotApp = app => {
  /** Post a comment on new issue */
  app.on("issues.opened", async context => {
    const params = context.issue({ body: "Hello World!" });
    return context.github.issues.createComment(params);
  });

  /** --- Express HTTP endpoints --- */
  const router = app.route("/api");
  router.use(cors(corsOptions)); // set CORS here
  router.use(bodyParser.json());
  router.use(bodyParser.urlencoded({ extended: true }));
  // router.set("trust proxy", true);
  // router.use(require('express').static('public')); // Use any middleware
  router.get("/ping", (req, res) => res.send("Guten Tag! " + new Date()));
  router.post(endpoint.handleWhatever , handleWhatever );
};

/** --- Initialize Express app by loading Probot --- */
probot.load(probotApp);

/* ############## Express instance ################ */
const app = probot.server;
const log = probot.log;
app.set("trust proxy", true);

/** --- Run Probot after setting everything up --- */
Probot.run(probotApp);

Here some GitHub issues and docs that helped me answer my question:

*

*probot index.js https://github.com/probot/probot/blob/master/src/index.ts#L33

*Alternate way of running a probot app @see https://probot.github.io/docs/development/#alternate-way-of-running-a-probot-app

*Programmatic access for starting probot @see https://github.com/probot/friction/issues/8

*Programmatic start @see https://github.com/probot/probot/issues/794

*Access to Express app object @see https://github.com/probot/probot/issues/878

*HTTP routes @see https://probot.github.io/docs/http/


text:
Q: Accessing Json Object : Node-Red I am using Node-Red to count the number of people. For this purpose, I have designed a flow which is successfully detecting faces using visual recognition node. I have attached the output of Visual Recognition node from Debug window.
Debug Window Output:
msg : Object

  object
  _msgid: "dca9625c.8e531"
  topic: ""
     payload: buffer[117939]
     filename: "/usr/lib/node_modules/node-red/public/campi/image1.jpg"
     headers: object
     result: object
      images: array[1]
       0: object
         faces: array[3]
         image: "11734-1409-1shmx8t.yjcfu07ldi.jpg"
         images_processed: 1

I intend to count faces.
For Example:
I have counted the attributes of my SensorTag by the following command.
To Get Count:
 var count = {};
 count = Object.keys(msg.payload.d).length;
 return {payload:count};

Sensor Output:
 msg.payload : Object
 object
  d: object
    myName: "ti-sensortag2"
    ambientTemp: "31.50"
    objectTemp: "25.41"
    humidity: "43.93988"
    pressure: "1017.73"
    altitude: "-0.08634908"

I have received correct answer. i.e. 6 in above case.
For facial recognition, I don't know how to extract desired info. that is the total number of faces. Can you please provide an insight into this?
Regards,
Hamza

A: After reading a documentation from this forum, I have wrote the following to fetch desired result.
 var count = {};

 count = Object.keys(msg.result.images[0].faces).length;

 return {payload:count};

Output:
msg : Object
object
 payload: 3
 _msgid: "dca9625c.8e531"


text:
Q: Multiple COUNT and GROUP BY in a single Statement I am using DISTINCT, LEFT JOIN, COUNT and GROUP BY in single statement, like this:
SELECT distinct r.sid as sid, s.name as sname, s.image as simage,
COUNT(r.sid) as scount FROM batch_request r LEFT JOIN student_info s ON s.id = r.sid
WHERE r.tid='22' group by r.sid

Encoded JSON Looks like this:
{ "students":
[
{
"sid":"1",
"sname":"Sonali Kohli",
"simage":"22",
"scount":"3",
"sconfirmed":null,
"sdeclined":null
},
{
"sid":"2",
"sname":"Sona Ali Khan",
"simage":"22",
"scount":"3",
"sconfirmed":null,
"sdeclined":null
}
],"success":1
}

Table:

As you can see in above image, I have total 6 records in a table (3 for sid = 1 and 3 for sid = 2)
Status for sid 1 records (2 Confirmed  [where value is 1] and 1 Declined [where value is 2]), in a same way Status for sid 2 records (1 Confirmed [where value is 1] and 2 Declined [where value is 2])
Same thing I want to get through my QUERY which I have posted above to encode data into JSON, as you can see, still I am getting null for both the JSON objects (i.e: Confirmed and Declined)
QUESTION 1: What should be the values of sconfirmed and sdeclined for both the objects of JSON ?
ANSWER 1: In case of sid = 1 (sconfirmed = 2 and sdeclined = 1) and for sid = 2 (sconfirmed = 1 and sdeclined = 2)
QUESTION 2: What is sconfirmed and sdeclined in a database table ?
ANSWER 2: sconfirmed is just the count of records where status is 1 for a particular sid and sdeclined is the count of records where status is 2 for a particular sid

A: Try something like this:
SELECT distinct r.sid as sid, s.name as sname, s.image as simage, COUNT(r.sid) as scount,
SUM(CASE r.status WHEN 1 THEN 1 ELSE 0 END) as sconfirmed,
SUM(CASE r.status WHEN 2 THEN 1 ELSE 0 END) as sdeclined,
SUM(CASE r.status WHEN 0 THEN 1 ELSE 0 END) as spending
FROM batch_request r LEFT JOIN student_info s ON s.id = r.sid
WHERE r.tid='22'
GROUP BY r.sid


text:
Q: Modal não abre no HTML Boa madrugada!!
Tenho um modal criado em minha pagina, mas quando clico no link que o referenciei ele não funciona, simplesmente acontece nada. Tenho ele em uma outra
pagina e ele funciona normal, mas nesta pagina que coloquei o código ele não funfa. Alguém sabe o que pode ser?
<?php
    session_start();
?>

        <link rel="icon" href="../app/resources/logo_icon.png" type="image/x-icon">
        <title>Fatec SIS</title>

        <link href="../../app/node_modules/bootstrap/compiler/bootstrap.css" rel="stylesheet">
        <link href="css/recuperar_senha.css" rel="stylesheet">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

Redefinir sua senha

                    <form id="Recupera" action="../src/model/recupera_senha.php" method="POST">

 Digite seu endereço de e-mail e nós lhe enviaremos um link para redefinir sua senha.

                            <input name="email" id="txtEmail" type="email" class="form-control" aria-label="Small" aria-describedby="inputGroup-sizing-sm" placeholder="Digite seu endereço de email">

                        <button type="submit" class="btn btn-success">Enviar email de redefinição de senha</button>
                    </form>

 Title

                            <button type="button" class="close" data-dismiss="modal">
                                ×
                            </button>

TESTE

                            <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>

                        Termos

                        Privacidade

                        Segurança

                        Entre no sistema FatecSis

A: Não vejo a Tag do  bootstrap.min.js verifique se na sua pagina existe!
como o Bootstrap e um pacote você tem que importa-los se quiser que funcione direito

A: Pessoal eu consegui resolver, como eu estou utilizando o gerenciador de pacotes do node.js precisei importar estes arquivos. Eu estava esquecendo mesmo de importar. Valeu o comentário de vocês ajudou bastante.


text:
Q: Proving $\int_{0}^{\frac{\pi}{2}}\text{erf}(\sqrt{a}\cos(x))\text{erf}(\sqrt{a}\sin(x))\sin(2x)dx=\frac{e^{-a}-1+a}{a}$ How to prove that for $a>0$:

*

*$\int_{0}^{\frac{\pi}{2}}\text{erf}(\sqrt{a}\cos(x))\text{erf}(\sqrt{a}\sin(x))\sin(2x)dx=\frac{e^{-a}-1+a}{a}$

*$\int_{0}^{\frac{\pi}{2}}\text{erf}\ ^2(\sqrt{a}\cos(x))\cos^2(x)dx+\int_0^1 \frac{e^{-\frac{a(1+x^2)}{2}}}{1+x^2}\left(I_0\left(\frac{a(1+x^2)}{2}\right)-I_1\left(\frac{a(1+x^2)}{2}\right)\right)dx=\frac{\pi}{4}$
Here erf denotes error function and $I_\nu$ Bessel. These identities arises from J. M. Borwein's Experiments in mathematics: Computational paths to discovery but the literature offers no proof. Any help will be appreciated!

A: As noted by @Zacky the first result can be adapted from this answer from @DrZafarAhmedDSc. Using the series expansion
\begin{equation}
 \operatorname{erf}(z)= e^{-z^2} \sum_{n=0}^{\infty} \frac{z^{2n+1}}{\Gamma(n+3/2)}.
\end{equation}
we have
\begin{align}
\mathcal{I}_1&=\int_{0}^{\frac{\pi}{2}}\operatorname{erf}(\sqrt{a}\cos(x))\operatorname{erf}(\sqrt{a}\sin(x))\sin(2x)dx\\
&=2e^{-a}\int_{0}^{\frac{\pi}{2}}\sum_{n=0}^\infty\sum_{m=0}^\infty a^{n+m+1}\frac{\cos^{2n+2}x}{\Gamma(n+3/2)}\frac{\sin^{2m+2}x}{\Gamma(m+3/2)}\,dx\\
&=e^{-a}\sum_{n=0}^\infty\sum_{m=0}^\infty a^{n+m+1}\frac{B(n+3/2,m+3/2)}{\Gamma(n+3/2)\Gamma(m+3/2)}\\
&=e^{-a}\sum_{n=0}^\infty\sum_{m=0}^\infty\frac{a^{n+m+1}}{(n+m+2)!}
\end{align}
where the Beta integral was used. Now the double summation can be rearranged as
\begin{align}
 \mathcal{I}_1&=a^{-1}e^{-a}\sum_{m=0}^\infty\sum_{p=m}^\infty\frac{a^{p+2}}{(p+2)!}\\
 &=a^{-1}e^{-a}\sum_{p=0}^\infty\sum_{m=0}^{p}\frac{a^{p+2}}{(p+2)!}\\
 &=a^{-1}e^{-a}\sum_{p=0}^\infty\frac{(p+1)a^{p+1}}{(p+2)!}\\
 &=a^{-1}e^{-a}\left( a\sum_{p=0}^\infty\frac{a^{p+2}}{(p+1)!} -\sum_{p=0}^\infty\frac{a^{p+2}}{(p+2)!}\right)\\
 &=a^{-1}e^{-a}\left[a\left( e^a-1 \right)-\left( e^a-1-a \right)\right]\\
 &=\frac{1}{a}\left(  e^{-a}-1+a\right)
\end{align}
as proposed.

For the second formula, we use the integral representation of $\operatorname{erf}^2$ here:
\begin{equation}
\int_{0}^{1}\frac{e^{-\alpha t^{2}}}{t^{2}+1}\mathrm{d}t=\frac{\pi}{4}e^{a}\left(1-(%
\operatorname{erf}\sqrt{\alpha})^{2}\right)
\end{equation}
(This expression can be derived from the integral definition of $\operatorname{erf}$, by interpreting the product of integrals as a double integral in the unit square and by expressing it in polar coordinates). Then,
\begin{equation}
 \operatorname{erf}^2(\sqrt{a}\cos(x))=1-\frac{4}{\pi}\int_0^1e^{-a(1+t^2)\cos^2x}\frac{dt}{1+t^2}
\end{equation}
which can be plug into the integral
\begin{align}
 \mathcal{I}_2&=\int_{0}^{\frac{\pi}{2}}\operatorname{erf}^2(\sqrt{a}\cos(x))\cos^2(x)\,dx\\
 &=\int_{0}^{\frac{\pi}{2}}\left[1-\frac{4}{\pi}\int_0^1e^{-a(1+t^2)\cos^2x}\frac{dt}{1+t^2}\right]\cos^2x\,dx\\
  &=\frac{\pi}{4}-\frac{2}{\pi}\int_0^1\frac{e^{-\frac{a}{2}(1+t^2)}dt}{1+t^2}\int_{0}^{\frac{\pi}{2}}e^{-\frac{a}{2}(1+t^2)\cos2x }\left( 1+\cos 2x \right)\,dx\\
 &=\frac{\pi}{4}-\frac{1}{\pi}\int_0^1\frac{e^{-\frac{a}{2}(1+t^2)}dt}{1+t^2}\int_{0}^{\pi}e^{\frac{a}{2}(1+t^2)\cos y }\left( 1-\cos y \right)\,dy\\
 &=\frac{\pi}{4}-\int_0^1\frac{e^{-\frac{a}{2}(1+t^2)}}{1+t^2}\left[I_0\left(\frac{a}{2}(1+t^2)  \right)-I_1\left(\frac{a}{2}(1+t^2)  \right)\right]\,dt
\end{align}
where the classical integral representation for the modified Bessel functions (DLMF) was used. This result corresponds to te proposed formula.


text:
Q: Android Camera Flash Control
Possible Duplicate:
How Turn on only Camera flash light programmatically in android?

okay guys, I have been looking for a little while and I cant seem to find this anywhere, I would like to grant my camera application access to the flash bulbs or whatever you want to call them, If anyone knows and would like to share that would be greatly appreciated. Or if anyone can point me into the right direction that would be great.

A: I'll take a stab at this...
From http://developer.android.com/reference/android/hardware/Camera.html
you need to grant permission to use the camera and use the <uses-feature> for camera features you want to use:
  <uses-permission android:name="android.permission.CAMERA" />
  <uses-feature android:name="android.hardware.camera" />
  <uses-feature android:name="android.hardware.camera.autofocus" />

The features supported are here
http://developer.android.com/guide/topics/manifest/uses-feature-element.html
and the camera ones you want are
android.hardware.camera
android.hardware.camera.autofocus
android.hardware.camera.flash


text:
Q: How to align hybrid number in vim? The original beahvior of :set num rnu is:

But I want  instead.
(The difference is the space behind the line number)

A: Seems there is no way to change it by an option.
Related questions:
Current line number aligned to the left with number and relativenumber
Alignment of current line number in Vim


text:
Q: ¿Cómo mostrar imágenes con PHP y MySql mostrado con una hoja de estilo? Lo que quiero es que me muestre la imagen con unos div pero no logro que se me salga en fila de 3, sino que me lo muestra en una sola columna.

Me sale de esa manera y la quiero de esta forma...

Código HTML:

Código PHP:
<?php
    echo '
';
    echo '
';
    echo'
';
    echo'
';
    echo'
';
    $sql=  mysql_query("SELECT * FROM repuesto");

    while($res=  mysql_fetch_array($sql)){

        echo'
';
        echo'
';
        echo '';
        echo'
';
        echo'

';
        echo '
';
        echo'
'.$res["nombre_repuesto"].'
';
        echo'
'.$res["precio_repuesto"].'
';
        echo'
'.$res["descripcion_repuesto"].'
';
        echo'Leer Mas';
        echo'
';
    }
?>

A: Te dejo un ejemplo completo como podria quedar.
En primer lugar estas utilizando mysql que ha quedado absuelto y para ello debería utilizar mysqli, o personalmente te aconsejo sentencias preparadas.

Manual sentencia prepare():

*

*https://secure.php.net/manual/es/mysqli.prepare.php

Ejemplo:
Hoja de estilos CSS:
/* Eliminamos flujo flotante (CSS3). */
.holder-clear {
    height:   1%;
    width: 100%;
    overflow: hidden;
}

/* Reglas estandares para nuestras cajas flotantes. */
.col2, .col3, .col4 {
    float:left;
    width: 100%;
}

/* 2 cajas flotantes */
.col2 { max-width: 50%; }

/* 3 cajas flotantes */
.col3 { max-width: 33.3%; }

 /* 4 cajas flotantes */
.col4 { max-width: 25%; }

.padding { padding: 1rem; }

Código PHP:
<?php
    //Conexión MySQL
    require_once'tu_conexion.php';

    //Sentencia
    $sql=  mysqli_query($tu_conexion, "SELECT * FROM repuesto");
    //Si existe registros en la Base de datos.
    if (mysqli_num_rows($sql) > 0) {

        //Caja, para añadir cajas flotantes (No puede ir dentro de while, si no en cada registro te elimina el flujo flotante de tus caja).
        echo "
";

        while($res= mysqli_fetch_array($sql)) {

            //Es importante añadir la caja flotante en tu bucle while.
            echo "

".$res['nombre_repuesto']."

".$res['precio_repuesto']."

                        ".$res['descripcion_repuesto']."

                    Leer más

            ";

        }

        echo "
";//Fin eliminación cajas flotantes.

    } else { //Caso falso.
        echo "0 registros encontrados";
    }
    //Cerramos conexión despues de no utilizarlo.
    mysqli_close($tu_conexion);

?>

A: Esto es cosa de Css. Podría quedar así:
while($res=  mysql_fetch_array($sql)){
   echo '
';
   //Todo el dom de las imgs
   echo '
';
}

Donde css:
.col{
  margin: 1px;
  padding: 10px;
  width:33%;
}

El width 33% porque tomará una tercera parte de la pantalla, sea cual sea su resolución, y así puedes tener 3 columnas.
Esto puede solucionar el problema que planteas en tu pregunta.
Nota: El problema nuevo que te enfrentarás es que debes hacerlo responsivo para smarthphones y tablets. Te recomiendo mucho que mejor uses Bootstrap , es muy sencillo de usar.

A: de una manera sencilla:
article
{
    float: left;
    width: 30%;
}

A: Lo he resuelto agregando este css:
CSS:
.col{
  float: left;
  margin: 1px;
  padding: 10px;
  width:25%;
}

PHP:
<?php
require_once 'clases/conexion.php';
?>
<!DOCTYPE html>

<link rel="stylesheet" href="css/styleimag.css" type="text/css" media="screen">
<title></title>

<?php

$sql=  mysql_query("SELECT * FROM repuesto");

while($res=  mysql_fetch_array($sql)){

    echo '
';
    echo '';
    echo'
'.$res["nombre_repuesto"].'
';
    echo'
'.$res["precio_repuesto"].'
';
    echo'
'.$res["descripcion_repuesto"].'
';
    echo'Leer Mas';

    //Todo el dom de las imgs
    echo '
';
}
?>