text:
Q: Wpf TabControl create only one view at all tabs TabControl's ItemsSource property binded to collection in the ViewModel. ContentTemplate is ListView - UserControl. All the tabs use only one ListView control (the constructor of ListView is called only once). The problem is that all tabs have a common visual state - for example, if you change the size of any item in the one tab, this change will be on all tabs. How to create a separate ListView for each tab, but at the same time use ItemsSource  property?
<TabControl Grid.Row="1" Grid.Column="2" TabStripPlacement="Bottom" >

    <TabControl.ContentTemplate>
        <DataTemplate DataType="viewModel:ListViewModel" >
            <view:ListView />
        </DataTemplate>
    </TabControl.ContentTemplate>

    <TabControl.ItemsSource>
        <Binding Path="Lists"/>
    </TabControl.ItemsSource>
</TabControl>

A: There's no easy way of doing this.
The problem is you have a WPF Template, which is meant to be the same regardless of what data you put behind it. So one copy of the template is created, and anytime WPF encounters a ListViewModel in your UI tree it draws it using that template. Properties of that control which are not bound to the DataContext will retain their state between changing DataSources.
You could use x:Shared="False" (example here), however this creates a new copy of your template anytime WPF requests it, which includes when you switch tabs.

When [x:Shared is] set to false, modifies Windows Presentation Foundation (WPF) resource retrieval behavior such that requests for a resource will create a new instance for each request, rather than sharing the same instance for all requests.

What you really need is for the TabControl.Items to each generate a new copy of your control for each item, but that doesn't happen when you use the ItemsSource property (this is by design).
One possible alternative which might work would be to create a custom DependencyProperty that binds to your collection of items, and generates the TabItem and UserControl objects for each item in the collection. This custom DP would also need to handle the collection change events to make sure the TabItems stay in sync with your collection.
Here's one I was playing around with. It was working for simple cases, such as binding to an ObservableCollection, and adding/removing items.
    public class TabControlHelpers
    {
        // Custom DependencyProperty for a CachedItemsSource
        public static readonly DependencyProperty CachedItemsSourceProperty =
            DependencyProperty.RegisterAttached("CachedItemsSource", typeof(IList), typeof(TabControlHelpers), new PropertyMetadata(null, CachedItemsSource_Changed));

        // Get
        public static IList GetCachedItemsSource(DependencyObject obj)
        {
            if (obj == null)
                return null;

            return obj.GetValue(CachedItemsSourceProperty) as IList;
        }

        // Set
        public static void SetCachedItemsSource(DependencyObject obj, IEnumerable value)
        {
            if (obj != null)
                obj.SetValue(CachedItemsSourceProperty, value);
        }

        // Change Event
        public static void CachedItemsSource_Changed(
            DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            if (!(obj is TabControl))
                return;

            var changeAction = new NotifyCollectionChangedEventHandler(
                (o, args) =>
                {
                    var tabControl = obj as TabControl;

                    if (tabControl != null)
                        UpdateTabItems(tabControl);
                });

            // if the bound property is an ObservableCollection, attach change events
            INotifyCollectionChanged newValue = e.NewValue as INotifyCollectionChanged;
            INotifyCollectionChanged oldValue = e.OldValue as INotifyCollectionChanged;

            if (oldValue != null)
                newValue.CollectionChanged -= changeAction;

            if (newValue != null)
                newValue.CollectionChanged += changeAction;

            UpdateTabItems(obj as TabControl);
        }

        static void UpdateTabItems(TabControl tc)
        {
            if (tc == null)
                return;

            IList itemsSource = GetCachedItemsSource(tc);

            if (itemsSource == null || itemsSource.Count == null)
            {
                if (tc.Items.Count > 0)
                    tc.Items.Clear();

                return;
            }

            // loop through items source and make sure datacontext is correct for each one
            for(int i = 0; i < itemsSource.Count; i++)
            {
                if (tc.Items.Count <= i)
                {
                    TabItem t = new TabItem();
                    t.DataContext = itemsSource[i];
                    t.Content = new UserControl1(); // Should be Dynamic...
                    tc.Items.Add(t);
                    continue;
                }

                TabItem current = tc.Items[i] as TabItem;
                if (current == null)
                    continue;

                if (current.DataContext == itemsSource[i])
                    continue;

                current.DataContext = itemsSource[i];
            }

            // loop backwards and cleanup extra tabs
            for (int i = tc.Items.Count; i > itemsSource.Count; i--)
            {
                tc.Items.RemoveAt(i - 1);
            }
        }
    }

Its used from the XAML like this :
<TabControl local:TabControlHelpers.CachedItemsSource="{Binding Values}">
    <TabControl.Resources>
        <Style TargetType="{x:Type TabItem}">
            <Setter Property="Header" Value="{Binding SomeString}" />
        </Style>
    </TabControl.Resources>
</TabControl>

A few things to note :

*

*TabItem.Header is not set, so you'll have to setup a binding for it in TabControl.Resources

*DependencyProperty implementation currently hardcodes the creation of the new UserControl. May want to do that some other way, such as trying to use a template property or perhaps a different DP to tell it what UserControl to create

*Would probably need more testing... not sure if there's any issues with memory leaks due to change handler, etc

A: Based on @Rachel answer I made a few modifications.
First of all, you now have to specify a user control type as content template which is dynamically created.
I have also corrected a mistake in collectionChanged handler removal.
The code is the following:
public static class TabControlExtension
{
    // Custom DependencyProperty for a CachedItemsSource
    public static readonly DependencyProperty CachedItemsSourceProperty =
        DependencyProperty.RegisterAttached("CachedItemsSource", typeof(IList), typeof(TabControlExtension), new PropertyMetadata(null, CachedItemsSource_Changed));

    // Custom DependencyProperty for a ItemsContentTemplate
    public static readonly DependencyProperty ItemsContentTemplateProperty =
        DependencyProperty.RegisterAttached("ItemsContentTemplate", typeof(Type), typeof(TabControlExtension), new PropertyMetadata(null, CachedItemsSource_Changed));

    // Get items
    public static IList GetCachedItemsSource(DependencyObject dependencyObject)
    {
        if (dependencyObject == null)
            return null;

        return dependencyObject.GetValue(CachedItemsSourceProperty) as IList;
    }

    // Set items
    public static void SetCachedItemsSource(DependencyObject dependencyObject, IEnumerable value)
    {
        if (dependencyObject != null)
            dependencyObject.SetValue(CachedItemsSourceProperty, value);
    }

    // Get ItemsContentTemplate
    public static Type GetItemsContentTemplate(DependencyObject dependencyObject)
    {
        if (dependencyObject == null)
            return null;

        return dependencyObject.GetValue(ItemsContentTemplateProperty) as Type;
    }

    // Set ItemsContentTemplate
    public static void SetItemsContentTemplate(DependencyObject dependencyObject, IEnumerable value)
    {
        if (dependencyObject != null)
            dependencyObject.SetValue(ItemsContentTemplateProperty, value);
    }

    // Change Event
    public static void CachedItemsSource_Changed(
        DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        if (!(dependencyObject is TabControl))
            return;

        var changeAction = new NotifyCollectionChangedEventHandler(
            (o, args) =>
            {

                if (dependencyObject is TabControl tabControl && GetItemsContentTemplate(tabControl) != null && GetCachedItemsSource(tabControl) != null)
                    UpdateTabItems(tabControl);
            });

        // if the bound property is an ObservableCollection, attach change events
        if (e.OldValue is INotifyCollectionChanged oldValue)
            oldValue.CollectionChanged -= changeAction;

        if (e.NewValue is INotifyCollectionChanged newValue)
            newValue.CollectionChanged += changeAction;

        if (GetItemsContentTemplate(dependencyObject) != null && GetCachedItemsSource(dependencyObject) != null)
            UpdateTabItems(dependencyObject as TabControl);
    }

    private static void UpdateTabItems(TabControl tabControl)
    {
        if (tabControl == null)
            return;

        IList itemsSource = GetCachedItemsSource(tabControl);

        if (itemsSource == null || itemsSource.Count == 0)
        {
            if (tabControl.Items.Count > 0)
                tabControl.Items.Clear();

            return;
        }

        // loop through items source and make sure datacontext is correct for each one
        for (int i = 0; i < itemsSource.Count; i++)
        {
            if (tabControl.Items.Count <= i)
            {
                TabItem tabItem = new TabItem
                {
                    DataContext = itemsSource[i],
                    Content = Activator.CreateInstance(GetItemsContentTemplate(tabControl))
                };
                tabControl.Items.Add(tabItem);
                continue;
            }

            TabItem current = tabControl.Items[i] as TabItem;
            if (!(tabControl.Items[i] is TabItem))
                continue;

            if (current.DataContext == itemsSource[i])
                continue;

            current.DataContext = itemsSource[i];
        }

        // loop backwards and cleanup extra tabs
        for (int i = tabControl.Items.Count; i > itemsSource.Count; i--)
        {
            tabControl.Items.RemoveAt(i - 1);
        }
    }
}

This one is used the following way:
<TabControl main:TabControlExtension.CachedItemsSource="{Binding Channels}" main:TabControlExtension.ItemsContentTemplate="{x:Type YOURUSERCONTROLTYPE}">
    <TabControl.Resources>
        <Style BasedOn="{StaticResource {x:Type TabItem}}" TargetType="{x:Type TabItem}">
            <Setter Property="Header" Value="{Binding Name}" />
        </Style>
    </TabControl.Resources>
</TabControl>


text:
Q: modelandview object in jquery Hello everybody.
I have a ModelAndView object:
@RequestMapping(value="/stage")
public ModelAndView stage(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    ...
    ModelAndView model = new ModelAndView();
    model.addObject("option","a");
    model.setViewName("product/stage");
    return model;
}

I can access from Jquery a view "product/stage" using the functions load or ajax, but, how to access the object "option" from Jquery?
Thanks for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trigger Dokku Deployment by GitHub commit to master I've used Heroku a lot, and I really like it's GitHub integration: when I commit/merge PR to master branch, the PaaS triggers the new deployment. Right now I fell in love with Dokku and I want to reproduce the same behavior there.
I've tried to find the out-of-the-box solution for this or external plugin - but failed. I've also found the GitHub Action but it also fails.
How can I set up the GitHub repo integration to trigger new Dokku deployments?


text:
Q: How many ways to choose elements from three groups then permutate them Let $A,B,C$ be three disjoint sets with $|A| = a, |B|=b,|C|=c$ elements.
You choose $k_1 \leq a$ elements from set $A$, $k_2 \leq b$ elements from set $B$ and $k_3 \leq c$ elements from set $C$ (repetition is allowed).
On how many ways can you permutate these $k_1+k_2+k_3$ chosen elements?
To choose the elements I would say you have $a^{k_1},b^{k_2},c^{k_3}$ options each.
If repetition wasn't allowed, the answer would be $(k_1+k_2+k_3)!$. But with repetition you also have to consider the cases where one, two or more elements from e.g. set $A$ were chosen twice or even more and exclude them from the permutation.
Is there a formula or efficient way which considers all the possibilities of double counting?


text:
Q: clock period, throughput and efficiency of I2C bus If a I2C bus is runs at 400kHz what is the clock period ,data throughput in data-bits/seconds and bus efficiency? i am very new to those buses and is the clock period is 2.5 micro seconds ? any help will be appereciated.

A: There will not be an answer to get you specific throughput numbers without actually knowing what device protocol and operational procedure that you are using. Bus utilization efficiency goes up if you operate with transactions with the device that transfer more data per START / STOP sequence.
From a raw protocol perspective the I2C bus uses 8-bit data size with 9th bit acknowledge. So assuming an SCL clock generated at a uniform rate the raw transfer efficiency will be no better than 8/9 or about 88% efficiency.
To get an idea of how to address this lets take a specific example of a simple serial EEPROM that has an I2C interface and you want to read it two data bytes per transaction. There is some overhead that we could consider as follows:

*

*Start sequence (lets guess at equivalent of 2 clock times).

*Slave Address byte to set device select and upper address bits to read. (8 + 1 clocks).

*Low address bits of where to read in EEPROM. (8 + 1 clocks)

*Repeated Start condition to switch to read mode (guess at equivalent of 2 clock times).

*Slave Address Repeat with Read bit set (8 + 1 clocks).

*First byte read out (8 + 1 clocks).

*Second byte read out (8 + 1 clocks).

*Stop sequence (lets guess at equivalent of 2 clock times).

*Null time between transactions (Lets guess at 5 clock times).

If you total up all the equivalent clock times above there are 56 of them with a usable 16 clocks of actual utilization to get the data that was being read. This gives a data access efficiency of 16/56 or about 28% efficiency.


text:
Q: Событие Scroll, or MouseWheel в html Подскажите, как можно реализовать scroll, где он отсутствует? Страница построена с помощью position absoluteи сколла нету... Но необходимо знать, когда пользователь крутит колесико и насколько сильно. Например, от скролла будут передвигаться блоки.
Событие window.onscroll его не обрабатывает т.к. само окно остается неподвижным...
Заранее благодарю!
Вот пример! http://www.jandk.fr/
Нашел, как реализовать на mousewheel  , Но все же - есть какие-то другие способы реализовать это? (Говорят, что скоро не будут поддерживать этот метод), да и не адаптивный он...+ на touch устройствах будет каша... Очень надеюсь на вашу помощь!

    var elem = document.getElementById('container');
    if (elem.addEventListener) {
      if ('onwheel' in document) {
        elem.addEventListener("wheel", onWheel);
      } else if ('onmousewheel' in document) {
        elem.addEventListener("mousewheel", onWheel);
      } else {
        elem.addEventListener("MozMousePixelScroll", onWheel);}
    } else { // IE8-
      elem.attachEvent("onmousewheel", onWheel);}
    function onWheel(e) {
      e = e || window.event;
      var delta = e.deltaY || e.detail || e.wheelDelta;
      var info = document.getElementById('delta');
      info.innerHTML = +info.innerHTML + delta;
      e.preventDefault ? e.preventDefault() : (e.returnValue = false);}
 #container {
      width: 200px;
      height: 200px;
      border: 1px solid black;
      background: #0FF;
      overflow: auto;}
  Прокрутка: 0

    Прокрути надо мной.

A: Ну например вы можете следить прямо за колесиком мышки. Это событие mousewheel.
Лучше всего работать с ним с помощью этого плагина: https://github.com/jquery/jquery-mousewheel
$('#my_elem').on('mousewheel', function(e) {
    // прокрутка колесика по вертикали
    console.log(e.deltaY);

    // прокрутка по горизонтали (так умеют мышки Apple например)
    console.log(e.deltaX);
});

Delta - это переменная с помощью который вы сможете понять, в какую сторону крутят колесико (меньше нуля - вверх, больше нуля вниз). И с какой силой это делают (чем больше 1, тем быстрее крутят)


text:
Q: UISwitch in Table Row Basically I have a tableView like this:

Now, I have an NSDictionary with the keys (title of cell) and objects (UISwitch.on).
I would like to make it so that when I click a switch, it should change the object's value accordingly (YES = ON, NO = OFF).
Different question, I've created the UISwitch so it has a function and the it's called when something's switched:
[switchView addTarget:self action:@selector(switchChanged:)
 forControlEvents:UIControlEventValueChanged];

- (void) switchChanged:(id)sender {
UISwitch* switchControl = sender;
NSLog( @"The switch is %@", switchControl.on ? @"ON" : @"OFF" );
}

Now I'd like to know, how can I tell in which row was it clicked?

A: To all who have this problem, I've found the solution by:
witchView.tag = indexPath.row;

This way, by the tag, you can identify in which row was the UISwitch changed.


text:
Q: Why can't my program find the VC++ Runtime? I'm trying to package Unison (not really my program) into an easy to use installer. Tl;dr: a screenshot.

*

*When I install and run it on the test machine, it says This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix the problem.

*The event log reveals that it can't find Dependent Assembly Microsoft.VC90.CRT.

*Search reveals that the "missing" dll is in fact in C:\Windows\WinSxS

So what's wrong?


text:
Q: Вывести данные в виде исполняемого кода Помогите, пожалуйста, решить проблему
я через модель заполняю таблицу базы данных примерно таким html-кодом:
<script type="text/javascript" charset="utf-8" src="//api-maps.yandex.ru/services/constructor/1.0/js/?sid=m5-_plen-rNkoC6AZ8GbAd6R3pqL8dfi&width=590&height=270"></script>

затем я вывожу данные из базы данных и отображаю их в шаблоне. но у меня отображается не результат выполнения кода, а просто строка. скажите пожалуйста как отобразить именно результат выполнения кода?
A: используйте фильтр safe
A: Автор выше имел в виду вот такую запись в шаблоне:
    {{my_html_code|safe}}


text:
Q: Color background  on page load I have 100+ select/option boxes that I populate based on table data.  I have the options colored based on which option is selected (i.e. 'Available' is blue, 'Unavailable' is red).
However, when the page loads, the SELECT box stays white.  On the color change I use:
<script>
function setBg(sel) {
  sel.style.backgroundColor = sel.options[sel.selectedIndex].style.backgroundColor;
}
</script>

function display_day($day, $current_status, $list_of_statuses)
{
    echo "<select name=" . $day ."[] onChange=\"setBg(this)\">";
    if (!$current_status)
    {
        echo "<option disabled selected value> -- select an option -- </option>";
    }

    foreach ($list_of_statuses as $key => $row)
    {
        echo "<option value='" . $row['status'] . "'";
        echo " style = \"color: " . $row['fg_color'] . "; background-color: " . $row['bg_color'] . "\"";

        if ($row['status'] == $current_status)
        {
            echo " selected=\"selected\"";
        }

        echo ">" . $row['status'] . "</option>";
    }

    echo "</select>";
}

This obviously only changes color when the SELECT changes.  I tried to use onload, but this didn't work.  Any ideas how to get the SELECT to color on load when data is pulled from MySQL database.

A: You don't need onload, you can simply do it like you did for the options, just add style="background-color".
Instead of echoing the HTML code, save it in a string variable, and echo the variable after the loop. First save the loop to the variable and use a separate variable to save the active color when $row['status'] == $current_status. Then after the loop, add the <select ... with the color from the color variable, and then add closing </select>, then echo the result.
Here is a quick code (untested, so you may have to modify):
$select = "";
$color = "";

if (!$current_status)
{
    $select = "<option disabled selected value> -- select an option -- </option>";
}

foreach ($list_of_statuses as $key => $row)
{
    $select = $select . "<option value='" . $row['status'] . "'";
    $select = $select . " style=\"color: " . $row['fg_color'] . "; background-color: " . $row['bg_color'] . "\"";

    if ($row['status'] == $current_status)
    {
        $select = $select . " selected=\"selected\"";
        $color = $row['bg_color'];
    }

    $select = $select . ">" . $row['status'] . "</option>";
}

$select = "<select name=" . $day ."[] onChange=\"setBg(this)\" style=\"background-color: " . $color . "\">" . $select + "</select>";

echo $select;


text:
Q: How to transform a ByteArrayOutputStream in order to loop using readline I want to download a file using FTP, and then keep the file in memory and simply loop over the lines.
I am downloading the file like this so far:
ByteArrayOutputStream bos = new ByteArrayOutputStream()
ftp.retrieveFile("inventory.csv", bos)

I'm not sure how to go from a ByteArrayOutputStream to be able to loop each line.
https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#retrieveFile(java.lang.String,%20java.io.OutputStream)

A: This is the idea I had in mind, save minor overlooks, it should help you:
ByteArrayOutputStream bos;
BufferedReader bufferedReader;
FTPClient   ftp;
String line;
ArrayList<String[]> values;
try{
    bos = new ByteArrayOutputStream();
    ftp = new FTPClient();
    if (ftp.retrieveFile("inventory.csv", bos)){
        values = new ArrayList<>();
        bufferedReader = new BufferedReader(new StringReader(new String(bos.toByteArray())));
        while ((line = bufferedReader.readLine()) != null){
            values.add(line.split(","));
        }
        // Then you could switch ArrayList<String[]> for just String[]
    }

}
catch(Exception x){

}
finally{
    if (bufferedReader != null)
        bufferedReader.close();
    if (bos != null)
        bos.close();
}

A: You could use retrieveFileStream() instead and then read line by line in a try-with-resources block using a BufferedReader.
try (BufferedReader reader =
        new BufferedReader(
                new InputStreamReader(ftp.retrieveFileStream("inventory.csv"),
                        StandardCharsets.UTF_8))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // do something with line
    }
} catch (IOException e) {
    // handle error
}

The code assumes that the file is encoded in UTF-8. If a different encoding is used make sure to replace StandardCharsets.UTF_8 accordingly.
The advantage over an intermediate ByteArrayOutputStream is that at no point your program needs to have a copy of the whole file content in memory.


text:
Q: How to get base64 value outside the onloadend function? I've got an array of blobs responseArray. I need to get base64 url value of each blob and push in into array.
let finalScreenshotsArray = []

      responseArray.map(blob=> {
        var reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onloadend = function() {
          let base64data = reader.result;
          finalScreenshotsArray.push(base64data)

        }
      })

However, the value of base64data cannnot be accessed outside onloadend.
EDIT: I have read title of other question, that was linked to it and it's helpful, but doesn't address to my question


text:
Q: anchor taking user to root directory? I have 3 files, packages.php, index.php and .htaccess.
packages (hastebin is down for me), index and .htaccess. This is live here. Currently, index works as you can see by the no .php extension and the extra slash. However, if you go into Packages -> Create or Manage Packages, it takes you to piggypiglet.me/packages. I have no clue why this is? It also redirects you there when trying to manually open https://www.piggypiglet.me/minepos/admin/packages. I've tried changing the anchor to ./packages but that didn't fix it. I'm really at a loss here, I have no clue what's causing it. Also, the .php extensions are necessary as I'll be using php in the files as soon as I get this issue fixed.

A: Your link to admin/packages currently works fine for me. Did you solve it? Otherwise I suspect your browser might be caching the redirect from some previous version ( [R=permanent] ). Another thing that comes to my mind is trying to play with RewriteBase.


text:
Q: What would be a type of an event in Angular 2? I'm trying to specify the types of all my methods/parameters so instead of:
someCoolFunction(param) { ... }

I try to use the type safe'ish version like this:
someCoolFunction(param: number): void { ... }

When I bounce around types that I've declared myself, it's easy. When it comes to types brought from other packages, I also often know what they are as I explicitly specify my imports.
However, I'm not sure what type to give to the event, to the object and to the output in the method below.
someBoundFunction(event, junk) {
  ...
  return {a: 1, b: 2};
}

I've seen any being used but I'm not sure if it's applicable in this case. Also, I'm sensing that it's just incorrect for the event call. (If it matters, the call binding to the function can look as below.)
<custom-thing (output)="someBoundFunction($event, {x:"x",y:"y"})">!</custom-thing>

A: 'any' is ok because function someBoundFunction in template is dynamically binding -  (via angular2 template parser) so TS don't know type (TS not parse templates - they are dynamically parsed by angular2).
Of course to 'visual clarify' you can use someBoundFunction(event: SomeType, junk: any): any the same as you use in @Output() output: EventEmitter<SomeType> = new EventEmitter(); (in custom-thing component) but it will be not check by TS parser (due to unable to parse and bind function in template). You can use 'any' as return someBoundFunction type because you not defined object {a: 1, b: 2} type as separate class (but as dynamically created object) - and the same situation is for {x:"x",y:"y"}.
=== EDIT ===
@AluanHaddad in comments below give me some new informations about TS (thanks) that I don't know before so the new version of my answer is:
Define outputData interface (or class) (because it will be used twice: on event emit and event handling) e.g.:
export interface OutputData {
    a: string;
    b: number;
}

Then in your custom-thing component define event:
@Output() public output = new EventEmitter<OutputData>();

And fire event:
this.output.emit({a:'test', b:2});

And then you can define event handler someBoundFunction in this way:
public someCoolFunction(event: OutputData, junk: {a: string, b:string}) : { a: number, b: number} {
    // ...
    return { a: 1, b:2};
}

And because you return some object in someCoolFunction so I assume that you want reuse this function in other part of code - so you can invoke it by (if you don't want to reuse this handler, defining junk type and return type is unnecessary):
let result = this.someCoolFunction({ a: 'test', b: 666}, { a:1, b:'zz'});
console.log(result.a);
// ...

And now you have pretty strong typeized code (except someCoolFunction type checking in template).

A: I may be misunderstanding your question, but in this case the type of $event can vary. $event is just a proxy for whatever is transmitted via the emit method in custom-thing.
For example, if I had an output on my component called output.
@Output() output: EventEmitter<number> = new EventEmitter<number>();

emitEvent() {
   this.output.emit(5); // $event is 5 of type number
}


text:
Q: executing commands when user first logs in So I use webmin to create ldap user. I then manually create public_html folder, and set quota for newly created home folder. Is there a way such that I can execute commands when user first logs in or is there a way I can automatically set quota and create folders when user is created through webmin?

A: Set up Home directory The common approach is to set up the template of your new user's home directory in /etc/skel.
Than you enable the PAM module pam_mkhomedir which will create the home directory for a user the first time they log in (if it's not yet present) From the man page:

The pam_mkhomedir PAM module will create a users home directory if it does not
    exist when the session begins. This allows users to be present in central database
    (such as NIS, kerberos or LDAP) without using a distributed file system or
    pre-creating a large number of directories. The skeleton directory (usually
    /etc/skel/) is used to copy default files and also sets a umask for the creation.

where the pam_mkhomedir module is enabled exactly depends on your distribution, but for example on RHEL6 it would be the file /etc/pam.d/system-auth where you would add a line
session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required    pam_mkhomedir.so skel=/etc/skel/ umask=0022
session     required      pam_unix.so

with the correct template directory (/etc/skel) and umask.
Quota Setting quota depends on the underlying file system, IIRC on the EXT[2-4] filesystems you must explicitly set quota's for each (new) user, but XFS allows you to set a default quota value for every unique user on each XFS file-system.
pam_exec Allows pam to run specific commands each time a user logs on. You could create a script (which replaces the steps above) that checks if the users home directory exists, if not prepare the home directory, configure quota and whatever else you want to set up.
session required pam_unix.so
session required pam_exec.so /sbin/setup_newuser.sh $PAM_USER

A: *

*You can use .bash_profile or .bashrc to execute commands in a users home directory.

*To Customize a new users home directory you need to modify the skeleton under /etc/skel .

Using /etc/skel

A: My answer is not very much webmin-like, but it will save you a lot of clicking work in the future because of automation.
You can automate the whole process of creating home-dirs and generating a default login script:

*

*LDAP how-to for Ubuntu regarding generation of home-folders and some other useful configuration issues. https://help.ubuntu.com/community/LDAPClientAuthentication#Automatically_create_home_folders

*In the directory /etc/profile.d/ you can put a script like "login_script.sh" which will be started after every login by each user.

*For the quota issue, adapt the suggested mkhomedir part in the ubuntu tutorial with the manual here http://www.howtoforge.com/how-to-set-up-journaled-quota-on-debian-lenny
The links I gave are for Ubuntu, but I believe that for other major distributions it is not very much different.


text:
Q: Way to get all xml element ids and count into one number? Ok so lets say i have an xml what looks like this example,
   <?xml version="1.0" encoding="UTF-8"?>

   <stats id="865" name="blaah">
       <example name="blaahblaah">
           <example1>
               <x ppoints="500"/>
           </example1>
           <example2>
               <x ppoints ="150"/>
               <x points ="500"/>
               <x ppoints ="140"/>
               <x points="200"/>
           </example2>
       </example>
   </stats>

what i am trying to do here is to get all the ppoints and round them into one number and all the points and round them into one number,
like so
Stats: "rounded up ppoints" pp & "rounded up points" p
help anyone? many thanks

A: In this case, as I understand the structure of the document can contain multiple 'example' nodes, I think the best approach is to load the XML document and use a XPath expression to get all the nodes with a ppoints attribute and a points attribute.
Using XPath there are two possible solutions. One using SimpleXMLElement::xpath to retrieve all the required nodes and sum them manually. And another one using DOMXPath::evaluate which allows to evaluate any type of XPath expression and sum the values just using XPath. The latter solutions is simpler.
DOMXPath::evaluate
<?php

$doc = new DOMDocument;
$doc->load('file.xml');
$xpath = new DOMXPath($doc);

$sum_ppoints = $xpath->evaluate('sum(//x/@ppoints)');
$sum_points = $xpath->evaluate('sum(//x/@points)');

print "Ppoints: $sum_ppoints; Points: $sum_points\n";

?>

SimpleXMLElement::xpath
<?php

// Load XML file
$file = "file.xml";
$content = file_get_contents($file);
$xml = new SimpleXMLElement($content);

// Compute sum ppoints
$sum_ppoints = 0;
$nodes = $xml->xpath('//x[@ppoints]');
foreach ($nodes as $node) {
    $sum_ppoints += $node->attributes()->ppoints;
}

// Compute sum points
$sum_points = 0;
$nodes = $xml->xpath('//x[@points]');
foreach ($nodes as $node) {
    $sum_points += $node->attributes()->points;
}

print "Ppoints: $sum_ppoints; Points: $sum_points\n";

?>


text:
Q: Can we use this symbol? We consider the ring $\mathbb{C}[e^{\lambda x} \mid \lambda \in \mathbb{C}]$ and the language $L=\{+, \cdot , \frac{d}{dx} , 0, 1\}$.
The ring consists of elements of the form $$\sum_{i=0}^N \alpha_i e^{\lambda_i x}$$ where $\alpha_i , \lambda_i \in \mathbb{C}$.
In the language there is no symbol $e^x$.
When we want to write a formula in the structure $$\left (\mathbb{C}[e^{\lambda x} \mid \lambda \in \mathbb{C}] ; +, \cdot , \frac{d}{dx} , 0, 1\right )$$ can we use the symbol $e^x$ because it is an element of the ring?
Or do we have to define it somehow using the operations of the language?

A: Note that the transformation $x\mapsto x+t$ leaves all relations defined by your language invariant.
Namely,

*

*$\sum{a_i e^{q_i x}}+\sum{b_i e^{r_i x}}=\sum{c_i e^{s_i x}}$ iff $\sum{a_i e^{q_i (x+t)}}+\sum{b_i e^{r_i (x+t)}}=\sum{c_i e^{s_i (x+t)}}$

*$(\sum{a_i e^{q_i x}})\cdot(\sum{b_i e^{r_i x}})=\sum{c_i e^{s_i x}}$ iff $(\sum{a_i e^{q_i (x+t)}})\cdot(\sum{b_i e^{r_i (x+t)}})=\sum{c_i e^{s_i (x+t)}}$

*$(d/dx)\sum{a_i e^{q_i x}}=\sum{b_i e^{r_i x}}$ iff $(d/dx)\sum{a_i e^{q_i (x+t)}}=\sum{b_i e^{r_i (x+t)}}$

*$\sum{a_i e^{q_i x}} = 1$ iff $\sum{a_i e^{q_i (x+t)}}=1$

*$\sum{a_i e^{q_i x}} = 0$ iff $\sum{a_i e^{q_i (x+t)}}=0$
Therefore, any formula in this language defines a set that is invariant under this transformation. The set $\{e^x\}$ is not and therefore not definable. In contrast, the set $\{a e^x: a\in \mathbb{C}\}$ is.


text:
Q: Use Column Header Name Within Index-Match Function VBA Macro I'd like to modify my Index-Match function to use the column header names defined in row 1, rather than the column letters.
The function resides in a sheet named AssetName Sheet and references a sheet named AMP Sheet

Here is my code for the Index-Match:
=IFERROR(INDEX('AMP Sheet'!$L:$L,MATCH("*"&B2&"*", 'AMP Sheet'!$B:$B,0)), "")

'AMP Sheet' !$L:$L - This is referring to column L in the AMP Sheet tab. I want to replace using column letter L in the formula with its column name ID

'AMP Sheet' !$B:$B - This is referring to column B in the AMP Sheet tab. I want to replace using column letter B in the formula with its column name Name

"&B2&" - This part of the function does not need to change! The function is within a sheet tab named AssetName Sheet which columns will not change. This will stay as-is.
Thank you!

A: From the comments, both Tragamor and VBasic2008 came up with a working solution. Here it is:
=IFERROR(INDEX(OFFSET('AMP Sheet'!$A:$A,,MATCH("ID",'AMP Sheet'!$1:$1,0)-1),MATCH("*"&B1&"*",OFFSET('AMP Sheet'!$A:$A,,MATCH("Name",'AMP Sheet'!$1:$1,0)-1),0)),"")


text:
Q: Is there a way to avoid using ._1 in scala slick queries? I have the following query in scala:
val query = for {
      (table1, table2) <- Customer leftJoin Transaction on (_.custID === _.custID)
      if table1.name === "ABCD"
    } yield (table1.name, table2.date)

When I use query i have to use query._1 or query._2 for name and date respectively. Is the a way to use something of this kind: query.name, query.date

A: Your for expression is returning a tuple, and tuples can be easily deconstructed using pattern matching (nothing Slick-specific here) :
val (foo, bar) = ("foo", "bar") // foo="foo", bar="bar"

You should be able to do the same with the tuple returned by the Slick query :
val (name, date) =
  for {
    (table1, table2) <- Customer leftJoin Transaction on (_.custID === _.custID)
    if table1.name === "ABCD"
  } yield (table1.name, table2.date)

A: You can use pattern matching for that issue
val (name, date) = for {...}

so when the left side matches the right side the variables will get the values
Example for a tuple:
val (a,b) = (1,2)
scala> val (a,b) = (1,2)
a: Int = 1
b: Int = 2


text:
Q: Error on Cloning a Git Repository to client machine Hi everyone I have pushed my Git bare repository to our cloud server with
    scp -r project.git root@serverip:/home/gitrepos
That worked fine. Now I am trying to clone it to another location with
    git clone root@serverip:/home/gitrepos/project.git
I enter the password when requested. Then I get this error.
stdin: is not a tty
bash: git-upload-pack: command not found
fatal: Could not read from remote repository.

I have another server which I purchased from Godaddy and it works fine when I clone from that.
Why does this happen on this server? Do I need to install anything on the server? I know similar things have been discussed in other posts but I just cant understand. Can someone explain it simply so I can understand? Thanks


text:
Q: How to Integrate blogging functionality into an HTML template for personal website? I've recently bought a HTML5 theme on Envato market and am having a lot of fun playing around with customization as a static file.
What resources can I use to making the blogging functionality work? Jekyll, Rails?
It's a personal design website that I'm making.
Here's the demo website for the theme: https://themeforest.net/item/massive-responsive-multipurpose-html5-template/12503639

A: You should use Jekyll in combination with CloudCannon. It is really great and free! You can also use Forestry.io.
Note that with CloudCannon you can just upload your HTML with some 'editable' classes on them en get going. Really easy.
Good luck!


text:
Q: How to change values and create new elements? I'm new to XQuery. Is there any way to use XQuery to turn this input
<mods>
    <subject>
        <topic> bird ; cat ; dog ; lion </topic>
    </subject>
</mods>

into following XML?
<mods>
    <subject>
        <topic> bird </topic><topic> cat </topic><topic> dog </topic><topic> lion </topic>
    </subject>
</mods>

I tried to use the function
replace(node,';','</topic><topic>' )

but it turns the angle < > brackets into its entity reference < or >.

A: replace(...) only works on strings, not on elements. '</topic><topic>' (a string) and </topic><topic> (invalid XML) are not the same!
Reconstruct the result (you might also be able to use XQuery Update), and tokenize each <topic/> element, creating new topic items for each of them:
element mods {
  element subject {
    for $topics in /mods/subject/topic
    for $topic in tokenize($topics, ';')
    return element topic { $topic }
  }
}

For constructing new elements, I prefer the computed element constructors used above. element nodeName { $content } is equivalent to using <nodeName>{ $content }</nodeName>.

A: If your XQuery Processor supports XQuery Update, you can try the following query:
copy $xml := document {
  <mods>
    <subject>
        <topic> bird ; cat ; dog ; lion </topic>
    </subject>
  </mods>
}
modify (
  let $topic := $xml/mods/subject/topic
  return replace node $topic with
    for $token in tokenize($topic, ';')
    return <topic>{ $token }</topic>
)
return $xml


text:
Q: hvplot heatmap with cartopy? A heatmap with more geo details?

Above are two visualizations of some temperature data in the Gulf of Mexico (land and deep ocean masked out). The same data are plotted here, in the top most picture using contouring with Matplotlib Basemap, while the bottom one using a heatmap with hvplot (for pandas).
I prefer the heatmap over contouring, but I enjoy the coastlines, state outlines etc details with Basemap. Is there any way to 'combine' them, as in a way to get a heatmap with the added details and customization of Basemap? I suppose overlaying an image on the heatmap might be a second best option, but I've never done that before. Any suggestions?
P.S. My data is too messy and large to include. It's a 28x68 lat/lon grid, 1904 total points but 1367 are masked out. I'm using data from a pandas df with lat, lon, and other variables that I'm manipulating.


text:
Q: How to show first image of gallery on hover, in different element I'm stuck with this for a while and can't  find any solution helping me out.
To give an idea of what's going on: I have a li containing an a element and a gallery div which will show up in #thumb on click on a. ( I cut this part out of the code for now)
I want the first image of the gallery to be visible when hovering a. If there is no content in the gallery, i want nothing to happen.
How can I achieve this in plain js? I got quite far but I'm missing the js knowledge (hence all the var's i guess :-). Help is very much appreciated.
The gallery's are automatically generated, so the amount of gallery-#'s depends on the amount of gallery's added via CMS.
JS Fiddle here

var hoverThis = document.getElementsByClassName("project-item");
var galleryId = document.querySelector(".open-gallery").getAttribute("href");
var getFirstImg = document.querySelector(galleryId).firstElementChild.getAttribute("href");
var thumb = document.getElementById('thumb');
var content = getFirstImg.includes("http");

if (content == true) {

  hoverThis.addEventListener("mouseover", function(e) {

    e.target.thumb.innerHTML = '"';

  }, false);

  hoverThis.addEventListener("mouseout", function(e) {

    e.target.thumb.innerHTML = '';

  }, false);

} else {
  console.log('empty')
};
li {
  list-style: none;
}

#thumb {
  height: 300px;
  width: 300px;
  background: beige;
}

.hidden {
  display: none
}

img {
  height 200px;
  width: 200px;
}

      01.11.17

      Image 3
      Image 2

      02.11.17

      03.11.17

      Image 1
      Image 2
      Image 3


text:
Q: How do you feed sets of connected data elements to an artificial neural network? I'm currently working on a neural network to try to predict movements of electricity prices in a big city with multiple power companies to choose from. I know from a friend in the industry that power companies base prices off of a blend of costs and competitors' prices, which means that reasonably good predictions of a company's future price could be drawn from current prices of its competitors, disregarding natural disasters and other strong external influences.
It would seem that the artificial neural network is the best machine learning structure for this type of problem, but the issue is that there are multiple relevant attributes associated with each company. For example: current electricity rates, current gas rates (which often compete residentially), derivative and integral of both above rates to include change and total with time, and other company-specific details, as well as current time of day, time of year and temperature outside (as time and heating requirements are huge factors in determining minute-to-minute rates), and a few others. So there are typical inputs like time of day, time of year and temperature and there are also input "sets" associated with each competing company.
How would these types of data be fed to an artificial neural network, or even might a different ML structure be preferable over a neural network?


text:
Q: "Loud" and "loudly": how to use them?
*

*Which one should I use?

*

*Play music loud

*Play music loudly

*

*I think "play music loudly" is right but "play music loud" is used more. Please tell me your opinion and the reason why you choose it. Thank you so much.

*Maybe my grammar is wrong 'cause I'm not good at English

A: Normally, adjectives are turned into adverbs by adding the -ly suffix to them.
But some words are used as both adjectives and adverbs, with no discernable difference in their form. For example,

*

*I like fast cars. [adjective]

*He drove fast. [adverb]

*They played a clean game. [adjective]

*They played clean. [adverb]

"Loud" is an example of a word that can be used as both an adjective and an adverb. For example, people say:

*I like loud music. [adjective]

*I play music loud. [adverb]

If you look at this google books search, you'll see plenty example of it being used as an adverb. Further, Oxford Dictionaries even lists it as an adverb.
But some people also use the clearly adverbial form "loudly", as in

*I play music loudly. [adverb]

In conclusion, both "loud" and "loudly" can be used as adverbs. The choice is yours.


text:
Q: NuGet: Possibility of adding a line of code via Powershell? I have a few NuGet packages that I've put together, with one of them being a common project referenced by all the others.
This common project inserts a configuration class into the App_Start folder, and a method on this class is then invoked by WebActivator.
For one of the other packages I wish to add one more line of code to this method but I'm struggling to find a way to do this.
I know that I could very simply add an additional class which contains just this one line of code but I'd prefer, if possible, to use an Install.ps1 powershell script to add the line of code to the existing configuration class.
Using a pro-processed *.cs.pp file will overwrite the existing file (or add a new one), and *.cs.transform doesn't work on such a file.
I know where the class is and what it's called, and I know what the method is called, so does Powershell offer a means of adding a line to the end of said method?

A: This is possible but not trivial to do. You also have to be very careful since deleting someone's code from a NuGet package is not going to make them very happy.
When installing a NuGet package you have access to the Visual Studio object model (EnvDTE). The $project variable can be used to access the specific project item you need. From that you can use the FileCodeModel which represents the code in the file. You would then need to find the class and its method. Then create an edit point and insert the text.
The following will find a class called Class1 and insert a line of code into its Foo method. Note that the line of code inserted will not be correctly indented, you would need to find that out by looking at the document.
$project.ProjectItems.Item("Class1.cs")
$namespace = $item.FileCodeModel.CodeElements | ? {$_.Kind -eq 5}
$namespace.Members.Item("Class1")
$method = $class.Members.Item("Foo")
$endPoint = $method.GetEndpoint([EnvDTE.vsCMPart]::vsCMPartBody)
$editPoint = $endpoint.CreateEditPoint()
$editPoint.Insert("int a = 0;")

Also the above code does not do any error handling.


text:
Q: Is there a better way to switch between HTML and JSON output in Pyramid? # /test{.format} no longer seems to work...
config.add_route('test', '/test.{ext}', view='ms.views.test')

views.py:
from pyramid.response import Response
from pyramid.renderers import render

import json

def test(request):
    extension = request.matchdict['ext']
    variables = {'name' : 'blah', 'asd' : 'sdf'}

    if extension == 'html':
        output = render('mypackage:templates/blah.pt', variables, request=request)

    if extension == 'json':
        output = json.dumps(variables)

    return Response(output)

Is there an easier way to do this? With Pylons, it was a simple:
def test(self, format='html'):
    c.variables = {'a' : '1', 'b' : '2'}

    if format == 'json':
        return json.dumps(c.variables)

    return render('/templates/blah.html')

I suspect I'm approaching this the wrong way...?

A: Is this what you're looking for?  Pylons and Pyramid have different API's.  So they will be different.  You can make them a little more similar, but you can't make them identical.
def test(request):
    extension = request.matchdict['ext']
    variables = {'name' : 'blah', 'asd' : 'sdf'}

    if extension == 'json':
        return Response( json.dumps(variables) )

    return Response( render('mypackage:templates/blah.pt', variables, request=request) )

A: I think, the better way is to add the same view twice with difference renderers. Suppose we have the following view:
def my_view(request):
    return {"message": "Hello, world!"}

Now in our configuration we can add the same view twice:
from pyramid.config import Configurator
config = Configurator()
config.add_route('test', '/test', my_view, renderer="templates/my_template.mako")
config.add_route('test', '/test', my_view, renderer="json", xhr=True)

What we have now:

*

*View my_view will render template "templates/my_template.mako" with returned dict provided as context if we will point our browser to url /test.

*If we will make XHR request with my_view will be called again, but now returned dict will be encoded as JSON and transmitted back to caller (please read docs about checking if request was done via XHR).

The same idea we can use for defining different routes but with the same view attached to them:
from pyramid.config import Configurator
config = Configurator()
config.add_route('test', '/test', my_view, renderer="templates/my_template.mako")
config.add_route('test_json', '/test.json', my_view, renderer="json")

Now /test will trigger template rendering, but /test.json will return just JSON encoded string.
You can go further and make dispatching to the right renderer via accept argument of add_router method:
from pyramid.config import Configurator
config = Configurator()
config.add_route('test', '/test', my_view, renderer="templates/my_template.mako")
config.add_route('test', '/test', my_view, renderer="json", accept="application/json")

If request comes with header Accept set to application/json value JSON will be returned, otherwise you got rendered template.
Note, this will work only if you have predefined set of data formats in which you want to encode responses from your views, but it's the usual case. In case you need dynamical dispatching you can decorate your views with decorate argument of add_route which will choose the right renderer with your rules.

A: Pyramid's URL Dispatch is very powerful and flexible mechanism. First of all, we'll write correct url pattern. In route pattern syntax we can use regular expressions for replacement markers.

'/test{ext:\\..*}'

Here we can see that url path should contain . (period) and then any symbols. All symbols including . (period) will be under the key ext in request.matchdict.
Of course, we can complicate the regular expression in order to specify what extensions there may be:

'/test{ext:\\.(html|json)}'

Then we adding route with our pattern:

config.add_route('test',
                 pattern='/test{ext:\\.(html|json)}')

Want to add, that we can specify the set of extensions using custom predicates.
In order to specify the default extension we can use simple pregenerator.

def default_extension(ext):
    def pregenerator(request, elements, kw):
        if 'ext' not in kw:
            kw['ext'] = ext

        return elements, kw

    return pregenerator

config.add_route('test',
                 pattern='/test{ext:\\.(html|json)}',
                 pregenerator=default_extension('.html'))

request.route_path('test')
# '/test.html'
request.route_path('test', ext='.json')
# '/test.json'

After that we'll Traversal to help us switch between html and json output:

config.add_route('test',
                 '/test{ext:\\.(html|json)}',
                 pregenerator=default_extension('.html'),
                 traverse='{ext}')

With the traverse argument in add_route we force our application to be hybrid. And we should understand that the factory which will provide context for our views must not contain the keys matching our extensions. The default root factory doesn't.
views.py:

from pyramid.view import view_config, view_defaults

@view_defaults(route_name='test')
class Test(object):
    def __init__(self, request):
        self.request = request
        self.variables = {
            'name': 'blah',
            'asd': 'sdf'
        }

    @view_config(name='.html', renderer='mypackage:templates/blah.pt')
    def html(request):
        return {
            'request': request,
            'variables': self.variables
        }

    @view_config(name='.json', renderer='json')
    def json(request):
        return {
            'request': request,
            'variables': self.variables
        }

Here we've created class Test and specify route name for it. And then we've separated methods by names of our extensions.

A: Try this way:
def test(self, format='html'):
    c.variables = {'a' : '1', 'b' : '2'}

    if format == 'json':
        return Response(json = c.variables)

    return render_to_response('/templates/blah.html')

This is the most similar to your pylons example.  Also it shows some more friendly way to render a template or some JSON to a response.


text:
Q: How do I implement Sequence (to allow Swift's for-in syntax) from Objective-C? I'm writing an API in Objective-C and would like it to play nicely in Swift. I'm having trouble getting "for..in" syntax working though. I think I need to implement the Sequence protocol, but I can't find any examples doing this from Objective-C. Just referencing Sequence gives me error: no type or protocol named 'Sequence'. Is there a special #import to get access to it or something?
I tried implementing the NSFastEnumeration protocol, thinking maybe it'd magically convert to Sequence in Swift, but that didn't work.
///// Obj-C Code
@interface Foo : NSObject<NSFastEnumeration>
...
@end

///// Swift Code
var foo: Foo = Foo()

// ERROR: Type 'Foo' does not conform to protocol 'Sequence'
for y in foo {
    print("Got a y.")
}

EDIT: It looks like inheriting from NSEnumerator gets me closer, but doesn't quite work either:
///// Obj-C Code
@interface Foo : NSEnumerator<NSString *>
...
@end

///// Swift Code
// ERROR: 'NSFastEnumerationIterator.Element' (aka 'Any') is not convertible to 'String'
for y: String in foo {
    print("Got \(y)")
}

EDIT 2: I still don't have a good solution and have logged a bug: https://bugs.swift.org/browse/SR-2801

A: The Swift extension of Foundation includes some support for making classes that adopt NSFastEnumeration also support the Swift Sequence protocol... but not automatically.
One way to do it is to extend your ObjC type in Swift and pass through to the NSFastEnumerationIterator type:
extension Foo: Sequence {
    public func makeIterator() -> NSFastEnumerationIterator {
        return NSFastEnumerationIterator(self)
    }
}

NSFastEnumerationIterator (and all forms of ObjC enumeration) are type erasing, though, so they don't provide any insight on the element type you're iterating through. That means that you can do this (after adding the above extension):
var foo: Foo = Foo()
for y in foo {
    print("Got a y.")
}

... but the static type of y is always Any. If you want typed access to the members of foo, you'll need a cast or a filtered loop:
for y in foo where y is String {
    print("Got \(y)")
}

Sadly, if your class adopts ObjC generics, there doesn't seem to be a way to make this work — you'll get an error "Extension of a generic Objective-C class cannot access the class's generic parameters at runtime", even if you adopt the runtime type introspection method(s) in SE-0057. For non-generic ObjC classes you're good, though.


text:
Q: Where can I find unit tests for Java standard library classes? I'm planning on subclassing certain classes in the Java standard library (my immediate use case is extending java.io.File), and I'd like to be able to test that I haven't broken any contracts of the class. I thought there must be some unit tests for the Java standard library classes available under a permissive licence that I can use, however I can't seem to find any.
This question was asked 4 years ago, but no good answer was given.

A: It turns out extending java.io.File was a bad idea, so never mind that.
For the standard collections, guava-tests has some excellent interface contract tests. For example, https://github.com/google/guava/blob/master/guava-tests/test/com/google/common/collect/CompactHashSetTest.java uses SetTestSuiteBuilder to test that CompactHashSet complies with Set contracts.

A: You may want to have a look at this: http://openjdk.java.net/groups/quality/collaborate/testing.html


text:
Q: Rewrite set theory formal I'm having trouble with rewriting this expression only with the use of:
Brackets, variables, $A$, $B$, $\neg$,$\exists$,$\lor$,$\in$

I tried various solution but the only one that convinces me a little bit is the following one:
$$\forall a \in A \to \neg \exists b \in B \space (a \in B) \equiv \neg(\forall a \in A) \lor \neg \exists b \in B\space (a\in B) \equiv\exists a \in A \lor \neg \exists b \in B (a \in B)$$
Is this right? Could you otherwise give me a hint on how to translate those expressions only with the use of symbols?
•B=$\emptyset$
•$\bigcup A$
•If A and B are sets than exists $C=\{A,B\}$

A: Basically, make sure you know the definitions of all the involved symbols, expand them, and see where you end up.
Here is the expanding part:
\begin{align}
& A \not\subseteq \mathcal P(B) \\
\equiv & \qquad \text{"definition of $\;\not\ \;$"} \\
& \lnot (A \subseteq \mathcal P(B)) \\
\equiv & \qquad \text{"definition of $\;\subseteq\;$"} \\
& \lnot \langle \forall V : V \in A : V \in \mathcal P(B) \rangle \\
\equiv & \qquad \text{"definition of $\;\mathcal P\;$"} \\
& \lnot \langle \forall V : V \in A : V \subseteq B \rangle \\
\equiv & \qquad \text{"definition of $\;\subseteq\;$"} \\
& \lnot \langle \forall V : V \in A : \langle \forall x : x \in V : x \in B \rangle \rangle \\
\equiv & \qquad \text{"..."} \\
\end{align}
Now get rid of the $\;\forall\;$ using the rules of predicate logic, and you are done.

A: Hint:
We want to say that there is an $x$ such that $x\in A$ and $x$ is not in the powerset of $B$.
Recall that $P\land Q$ is equivalent to $\lnot(\lnot P\lor \lnot Q)$.
So the "and" can be eliminated.
Now we want to say that $x$ is not in the powerset of $B$. This says that there is a $t$ such that $t\in x$ and $t$ is not in $B$. Eliminate "and" as before, and put the pieces together.

A: As answer on your first question: the following statements are equivalent
$A\nsubseteq\wp\left(B\right)$
$\exists a\left[a\in A\wedge\neg a\in\wp\left(B\right)\right]$
$\exists a\left[a\in A\wedge\exists x\left[x\in a\wedge\neg x\in B\right]\right]$
$\exists a\neg\left[\neg a\in A\vee\neg\exists x\left[x\in a\wedge\neg x\in B\right]\right]$
$\exists a\neg\left[\neg a\in A\vee\neg\exists x\neg\left[\neg x\in a\vee x\in B\right]\right]$


text:
Q: Increment each pixel in BitmapData Let me explain what I'm trying to achieve. I want to create a kind of "age map" of an image. This means that every frame

*

*Each pixel's value is incremented by 1.

*Modified pixels are set to 0.

Is there a way to do this efficiently without looping through all pixels and calling getPixel/setPixel?
For resetting the modified pixels I'm thinking of using bitmapData.draw(), with a combination of blendModes/colorTransform; e.g. draw the shape over the age map using a 0 colorTransform, preserving shape but making the shape black, i.e. 0x000000.
However, incrementing each pixel by 1 is maybe more tricky. I could create an image with all 0x000001 values, and use .draw() to add it each frame, but using BlendMode.ADD clips each channel at 0xFF, allowing only 255 different age values.
Any suggestions for going about this efficiently? Can I maybe apply a ColorTransform or ColorMatrixFilter to the whole image?

A: Write a custom PixelBender filter, this will be much, much quicker than iterating over pixels:
This may be of some use if you've never used before:
http://tv.adobe.com/watch/adc-presents/pixel-bender-custom-filters/
I'm a bit rusty with PB myself, sorry I can't offer more specific advice, but know this is possible and the GPU-support means it'll be quick enough to be useable.


text:
Q: TLS protocol detection by using client hello message I need to detect https packets in network traffic . Until now I were marking all "443" as https but I don't want to use port information for this case any more .
Will it be enough to check client hello message like :
//Check 22 and version info 0300 0301 or 0302
if (packet->payload[0] == 0x16 && packet->payload[1] == 0x03
  && (packet->payload[2] == 0x00 || packet->payload[2] == 0x01 || packet->payload[2] == 0x02)

{
    int temp = ntohs(get_u16(packet->payload, 3)) + 5;//Get lenght
    //Check lenght is valid and 6th byte is client hello(which is 1)
    if (temp < packet->payload_length && temp > 50 && packet->payload[5]) == 1)
        MARK AS HTTPS
}

Because of my project design, I can't check more than one packet. Can you please advise if just checking client hello like above is ok or not ?

A:
Because of my project design, I can't check more than one package .
  Can you please advise if just checking client hello like above is ok
  or not ?

I assume you mean "packet" not "package."  Given that we're using TCP here, being able to reassemble fragmented messages is essential.  So long as you have a tool which only operates on single packets, you cannot expect to reliably (as in 100% of the time) detect message content longer than a single byte.  That's because it's perfectly legal for the TCP sender to dribble the bytes to you one-by-one...so you need to be prepared to reassemble them or know that you'll miss some information.


text:
Q: Types error with AxiosResponse and UseQueryResult I am using react query in my typescript project.
export type CarouselData = {
  name: string;
  body: string;
  imgOne: string;
  imgTwo: string;
};

export const getCarouselData = async (): Promise<
  AxiosResponse<CarouselData[]>
> => {
  return await (
    await publicAPI.get('/carouselData')
  );
};

export const useGetCarouselData = (): UseQueryResult<
  Promise<AxiosResponse<CarouselData[]>>
> => {
  return useQuery('getCarouselData', getCarouselData);
};

In my component, I am consuming this as follows.
type Item = {
    name: string,
    body: string,
    imgOne: string,
    imgTwo: string,
}

export const HomeCarousel: FC = () => {
    const {Root} = useStyles();

    const result = useGetCarouselData();

    console.log(result.data.data); //data.data is giving an error
    return (
        <Root>
            <Carousel<Item[]>>
                {result.data.data.map((item, index)=> {
                    return <CarouselItem key={index} name={item.name} body={item.body} imgOne={item.imgOne} imgTwo={item.imgTwo}/>
                })}
            </Carousel>
        </Root>
    )
}

Now, I am getting an error Property 'data' does not exist on type 'Promise<AxiosResponse<CarouselData[], any>>'.ts(2339) that shouldn't be there?
I want to know why this is happening or how to resolve this. : )
Any help is appreciated.

A: react-query unwraps the Promise, so you'd want: UseQueryResult<AxiosResponse<CarouselData[]>>
Or, you can just use type inference. Leave out the type and let the compiler figure it out :)


text:
Q: Is competitive Fortnite cross-platform? I'm aware that fortnite can be played cross-platform. Does the primary/official eSports format feature cross-platform play?

A: Yes and no.
The Arena modes, which are ranked and are required to qualify for tournaments, are fully cross-platform.
The online tournaments are separated by region and by platform, so mobile players play against mobile players, console players play against console players, PC players play against PC players, etc.
The major World Cup event in summer 2019 was played on PC. Most players used keyboard and mouse and some used controllers.


text:
Q: How do I use jQuery promise/deffered in a custom function? I have a function that gets the location through navigator.geolocation:
var getLocation = function( callback ){

    navigator.geolocation.getCurrentPosition( callback || function( position ){

        // Stuff with geolocation

    });

};

I would like to make it so that I could chain this function using jQuerys' Deffered object but I have still not managed to grasp the concept and usage of Deffered.
I'm looking for something similar to this Pseudo Code:
getLocation().then(function(){
    drawMarkerOnMap();
});

Is this syntax even possible without flipping over backwards and drowning in code?

A: You have to instantiate a new deferred object and return it (or its promise) from the function. Call its .resolve method once you get the response:
var getLocation = function() {
    var deferred = new $.Deferred();

    navigator.geolocation.getCurrentPosition(function( position ){
        // Stuff with geolocation
        deferred.resolve(position);
    });

    // return promise so that outside code cannot reject/resolve the deferred
    return deferred.promise();
};

Usage:
getLocation().then(drawMarkerOnMap);

Reference: jQuery.Deferred

Addendum:
I would advise against using both approaches, deferred objects and passing callbacks to the function, to keep the interface simple. But if you have to stay backwards compatible, you can simply register the passed callback at the deferred object:
var getLocation = function(callback) {
    var deferred = new $.Deferred();

    if ($.isFunction(callback)) {
        deferred.then(callback);
    }

    navigator.geolocation.getCurrentPosition(function( position ){
        // Stuff with geolocation
        deferred.resolve(position);
    });

    // return promise so that outside code cannot reject/resolve the deferred
    return deferred.promise();
};

A: Even though the above example did help me I had to do a bit more reading to wrap my head around the concept.
Below is example based on my code that contains comments to assist me when I come back to it and hopefully anyone reading this Stackoverflow question:
/* promise based getFilter to accommodate getting surrounding suburbs */
oSearchResult.fPromiseOfFilterSetting = function fPromiseOfFilterSetting(sId) {
    var self = this;
    self.oPromiseCache = self.oPromiseCache || {}; // creates a persistent cache
                                                   // across function calls
    var oDeferred = $.Deferred(); // `new` keyword is optional
    var oPromise = oDeferred.promise();

    // leverage the cache (it's ok if promise is still pending), you can key
    if (self.oPromiseCache[sId] !== undefined) {
        return self.oPromiseCache[sId];
    }
    else {
        self.oPromiseCache[sId] = oPromise;
    }

    // do our asynchronous action below which at some point calls
    // defered.resolve(...) and hence complete our promise
    $.cmsRestProxy.doAjaxServiceRequest('ocms_searchProperties_Extension', {
        action : 'getSurroundingSuburbs',
        sSuburbIds : 'a0RO0000003BwWeMAK'
    }, function(result, json) {
        console.log("doAjaxServiceRequest(
                       'ocms_searchProperties_Extension')", json);
        oDeferred.resolve(json); // `json` is our result and `.resolve(json)`
                                 // passes the value as first argument to
                                 // the `oPromise.done`, `oPromise.fail`
                                 // and `oPromise.always` callback functions
    })

    // We can now return the promise or attach optional `oPromise.done`,
    // `oPromise.fail`, and `oPromise.always` callbacks which will execute first
    // in the chain.
    //
    // Note that `oPromise.then(doneCallback, failCallback, alwaysCallback)`
    // is short form for the below
    oPromise.done(function(value) { // returned by promise.resolve(...); call
        console.log('will run if this Promise is resolved.', value);
    })
    oPromise.fail(function(value) {
        console.log("will run if this Promise is rejected.", value);
    });
    oPromise.always(function(value) {
        console.log("this will run either way.", value);
    });

    // return a promise instead of deferred object so that
    // outside code cannot reject/resolve it
    return oPromise;
}

// then to use one would do
oSearchResult.fPromiseOfFilterSetting().done(function(value) {alert(value)});

// or using $.when chaining
$.when(
    oSearchResult.fPromiseOfFilterSetting()
)
.done(
      function fDoneCallback(arg1, arg2, argN) {
          console.debug(arguments) // `arguments` is an array of all args collected
      }
);

A: I know it says jQuery in the title but when I asked this question promises were new to the web and jQuery was the de facto library. Here's a more modern answer without jQuery.
Use a native Promise
All modern browsers (except for IE11 and below; use a polyfill if needed) enable you to use a native Promise construct.
let getLocation = () => {

  return new Promise( ( resolve, reject ) => {

    try {
      navigator.geolocation.getCurrentPosition( position => {
        resolve( position )
      })
    } catch ( err ) {
      reject( err )
    }

  })

};

Usage:
let runGetLocation = () => { getLocation().then( position => console.log( position ) ) }

You can also use ES2016 async/await instead of .then():
let runGetLocation = async () => {

  try {
    let position = await getLocation()
    console.log( position )
  } catch ( err ) { console.log( err ) }

}


text:
Q: How to make a private call when using SSR Nuxt? I am writing a headless solution for a WordPress website and noticed that for one particular endpoint, I need to authenticate to pull some data that will be used publicly. But, I'm concerned that where I'm using it will expose it to the web.
In my store/index.js I use the nuxtServerInit action method to execute some actions and I pass them some objects they need to fulfill their tasks:
async nuxtServerInit ({ dispatch }, { $axios, app }) {
  await dispatch('initialize', { $axios, app })
},

$axios is passed because it will be used to query the API, and app is passed to help build the options to authenticate the request.
Is this a security vulnerability in Nuxt SSR? I think it is. If so, where are the only valid areas you can use secrets? asyncData ()?

A: If you're using SSR, you can use the privateRuntimeConfig runtime object and pass your secret in the  nuxt.config.js file
export default {
  privateRuntimeConfig: {
    apiSecret: process.env.API_SECRET
  }
}

If you read the documentation of nuxtServerInit, you can see that

Vuex action that is called only on server-side to pre-populate the store

Since this method is server-side only, you can use apiSecret (in my example) and it should be totally fine security-wise.
PS: Keep in mind that everything beyond what is generated on the server (hence, with NodeJS or nuxtServerInit) is "public". So your VueJS's client code lifecycle hooks are public: mounted(), fetch(), asyncData() because they will be visible on your browser's devtools.

Also, should your endpoint be that critical? If so, nuxtServerInit is the good way to go. If you need to fetch some more data in a "private way", you'll need to proxy it through some backend to hide the sensitive info and retrieve only the useful public data.


text:
Q: Cannot read file with "#" and space using read.table or read.csv in R I have a file where the first row is a header. The header can have spaces and the # symbol (there may be other special characters as well). I am trying to read this file using read.csv or read.table but it keeps throwing me errors:
undefined columns selected

more columns than column names

My tab-delimited chromFile file looks like:
Chromosome# Chr chr Size    UCSC NCBI36/hg18    NCBIBuild36 NCBIBuild37
1   Chr1    chr1    247199719   247249719   247249719   249250621
2   Chr2    chr2    242751149   242951149   242951149   243199373

Command:
chromosomes <- read.csv(chromFile, sep="\t",skip =0, header = TRUE,  )

I want to first look for a way to read the file as it as without replacing the space or # with some other readable symbol.

A: From the documentation (?read.csv):

comment.char character: a character vector of length one containing a single character or an empty string. Use "" to turn off the interpretation of comments altogether.

The default is comment.char = "#" which is causing you trouble. Following the documentation, you should use comment.char = "".
Spaces in the header is another issue which, as mrdwab kindly pointed out, can be addressed by setting check.names = FALSE.
chromosomes <- read.csv(chromFile, sep = "\t", skip = 0, header = TRUE,
                        comment.char = "", check.names = FALSE)


text:
Q: How do I make my tweet button pull a string from my page into a newly composed tweet? My codepen - http://codepen.io/illpill/pen/VbeVEq
For the sake of stacks policy, here is an example of code
<button class="btn btn-default btn-md pull-right" id="tweetButton">Tweet This</button>

My question is, how do I have it pull the quote from the page and compose it into a readily made tweet with added hashtags?

A: Start by adding a unique class to your Tweet button, then when someone clicks that button, get the current quote and pass it into a Tweet URL:
function tweet(message) {
  window.open('https://twitter.com/intent/tweet?hashtags=hashtagshere&text=' + encodeURIComponent(message));
}

$('button.tweet').click(function() {
  var currQuote = $('#quote').text();
  tweet(currQuote);
});

Updated Codepen


text:
Q: How do I change find result highlight color with VS2010 and Resharper? I just installed Resharper and it's changed the highlight color for find results. Normally when I place my cursor on a particular symbol, say a variable called 'goat', all onscreen references to goat will be highlighted with a gray background. When I hit Ctrl+F to move through all references to goat in the document the current find result has the same gray background as all others on screen. So I have no idea which goat I'm currently at until I close the find dialog at which point the currently selected goat highlights in blue.
This makes it really difficult for me to quickly check all references to a given variable in file. I know you can change color settings in Tools->Options->Environment->Fonts And Colors, however I've been unable to find a setting that corresponds to the currently selected find result.
If the currently selected find result was any color other than gray, it would stand out, but as it is it makes Find as effective as simply clicking on a variable and having VS2010 highlight all current onscreen references.

A: The setting to change is "Inactive Selected Text". It is in Tools->Options->Environment->Fonts And Colors, Show Settings for Text Editor, third option down.


text:
Q: How to subtract X rows in a dataframe with first value from another dataframe? I am using pandas for this work.
I have a 2 datasets. The first dataset has  approximately 6 million rows and 6 columns. For example the first data set looks something like this:

Date
Time
U
V
W
T

2020-12-30
2:34
3
4
5
7

2020-12-30
2:35
2
3
6
5

2020-12-30
2:36
1
5
8
5

2020-12-30
2:37
2
3
0
8

2020-12-30
2:38
4
4
5
7

2020-12-30
2:39
5
6
5
9

this is just the raw data collected from the machine.
The second is the average values of three rows at a time from each column (U,V,W,T).

U
V
W
T

2
4
6.33
5.67

3.66
4.33
3.33
8

What I am trying to do is calculate the perturbation for each column per second.
U(perturbation)=U(raw)-U(avg)
U(raw)= dataset 1
U(avg)= dataset 2
Basically take the first three rows from the first column of the first dataset and individually subtract them by the first value in the first column of the second dataset, then take the next three values from the first column of the first data set and individually subtract them by  second value in the first column of the second dataset. Do the same for all three columns.
The desired final output should be as the following:

Date
Time
U
V
W
T

2020-12-30
2:34
1
0
-1.33
1.33

2020-12-30
2:35
0
-1
-0.33
-0.67

2020-12-30
2:36
-1
1
1.67
-0.67

2020-12-30
2:37
-1.66
-1.33
-3.33
0

2020-12-30
2:38
0.34
-0.33
1.67
-1

2020-12-30
2:39
1.34
1.67
1.67
1

I am new to pandas and do not know how to approach this.
I hope it makes sense.

A: a = df1.assign(index = df1.index // 3).merge(df2.reset_index(), on='index')
b = a.filter(regex = '_x', axis=1) - a.filter(regex = '_y', axis = 1).to_numpy()
pd.concat([a.filter(regex='^[^_]+$', axis = 1), b], axis = 1)

         Date  Time  index   U_x   V_x   W_x   T_x
0  2020-12-30  2:34      0  0.00  0.00 -1.33  1.33
1  2020-12-30  2:35      0 -1.00 -1.00 -0.33 -0.67
2  2020-12-30  2:36      0 -2.00  1.00  1.67 -0.67
3  2020-12-30  2:37      1 -1.66 -1.33 -3.33  0.00
4  2020-12-30  2:38      1  0.34 -0.33  1.67 -1.00
5  2020-12-30  2:39      1  1.34  1.67  1.67  1.00

A: You can use numpy:
import numpy as np

df1[df2.columns] -= np.repeat(df2.to_numpy(), 3, axis=0)

NB. This modifies df1 in place, if you want you can make a copy first (df_final = df1.copy()) and apply the subtraction on this copy.


text:
Q: How to add comment in CSV while using scikit-learn I am currently doing Natural Language Processing project.
I need to transform the word into vector format for computer to process.
For debugging I need to know the relation between vector and word, so there must be some comment after each row of data.
How to add comment in CSV while using scikit-learn?


text:
Q: File Upload not working in Magento from custom admin module I created a custom admin module in magento. The module has a form which on submitting posts to a controller which handles the file upload.
I am getting the following error on submitting the form:
a:5:{i:0;s:22:"File was not uploaded.";i:1;s:1030:"#0 C:\wamp\www\magento-PhpDevGuide-packt\app\code\local\Endosoft\Categoryupdate\controllers\Adminhtml\CategoryupdateController.php(11): Varien_File_Uploader->__construct('uploadcsv')
#1 C:\wamp\www\magento-PhpDevGuide-packt\app\code\core\Mage\Core\Controller\Varien\Action.php(418): Endosoft_Categoryupdate_Adminhtml_CategoryupdateController->formPostAction()
#2 C:\wamp\www\magento-PhpDevGuide-packt\app\code\core\Mage\Core\Controller\Varien\Router\Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('formpost')
#3 C:\wamp\www\magento-PhpDevGuide-packt\app\code\core\Mage\Core\Controller\Varien\Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#4 C:\wamp\www\magento-PhpDevGuide-packt\app\code\core\Mage\Core\Model\App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#5 C:\wamp\www\magento-PhpDevGuide-packt\app\Mage.php(684): Mage_Core_Model_App->run(Array)
#6 C:\wamp\www\magento-PhpDevGuide-packt\index.php(87): Mage::run('', 'store')
#7 {main}";s:3:"url";s:78:"/index.php/admin/categoryupdate/formpost/key/d91e6825136ce2206d7c72bbd1b7af34/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:5:"admin";}

Here is the form:
<?php $url = Mage::helper("adminhtml")->getUrl('adminhtml/categoryupdate/formpost'); ?>

Upload Your CSV

<form action="<?php echo $url ?>" method="post" enctype="multipart/form-data">

<input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />

<input type="file" name="csvupload" />

<input type="submit" name="submit" value="Submit" />

</form>

Here is the controller method:
public function formPostAction() {
  $uploader = new Varien_File_Uploader('uploadcsv');
  $uploader->setAllowedExtensions(array('json'));
  $uploader->setAllowRenameFiles(false);
  $uploader->setFilesDispersion(false);
  $path = Mage::getBaseDir('media');
  $fileName = $_FILES['uploadcsv']['name'];
  $uploader->save($path, $fileName);

  $this->loadLayout();
  $this->renderLayout();
}

I could not understand why the file is not uploaded.
Could someone please clarify what is going wrong?
Additional Info:

*

*Instead of using magento form container and form i am using my own form by calling a phtml file from the layout..

A: I see that your file input looks like this:
<input type="file" name="csvupload" />

Notice the name csvupload.
But in the formpostAction you are trying to read the uploadcsv field.
Make sure that what you submit matches what you process.


text:
Q: Android keyboard problems on textedit I have problems with keyboard on numeric textedit
on textedit click keyboads appears ok , numeric keyboard, but after pressing ready keyboard dont dissapear , she is switched to alphabetical,
this problem apeared after I added a list view bellow in my layout, on pressing on alphabetical keyboard I navigate into listview
can anyone help me ?

A: I think if you add android:focusable="false" to the ListView XML file, it should fix it.


text:
Q: How can I concatenate a bunch of numbers with commas, without adding a trailing comma? PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
));
for(int i = start; i <= 100; i = i + 2) {
    fout.print(i + ", ");
}

Right now my output is like this:
2, 4, 6, 8, 10,

What I want:
2, 4, 6, 8, 10

A: Here's a neat way of doing it:
PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
));

String sep = "";
for(int i = start; i <= 100; i += 2) {
    fout.print(sep + i);
    sep = ", ";
}

Here's another way:
PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
));

for(int i = start; i <= 100; i += 2) {
    fout.print((i == start ? "" : ", ") + i);
}

Without being too sure of the function of PrintWriter, it may be more efficient to produce the string with a StringBuffer first:
PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
));

StringBuffer buffer;

for(int i = start; i <= 100; i += 2) {
    buffer.append(i == start ? "" : ", ").append(i);
}

fout.print(buffer);

Or more efficiently still:
PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
));

StringBuffer buffer;

for(int i = start; i <= 100; i += 2) {
    buffer.append(i).append(", ");
}

buffer.setLength(buffer.length()-1);

fout.print(buffer);

A: Print the first number and then print "," + number afterwards. Starting from i = start + 2;

A: try this:
 PrintWriter fout = new PrintWriter(new BufferedWriter(new FileWriter("numbers.dat")));
 for(int i = start; i <= 100; i += 2)    {
     if(i + 2 <= 100)
        fout.print(i+",");
 }

A: Do something like -
fout.print(i);
if (i < 100) {
    fout.print(",");
}

Or write to a StringBuffer and delete trailing comma after the loop
StringBuffer sb = new StringBuffer();
for(...){
...
}

sb.deleteCharAt(sb.length() -1);
fout.print(sb.toString());

Hope this helps!


text:
Q: Bind not working as expected. Possible misconfiguration I have two Raspberry Pis with me - one works as a media player, another as a home server (I call it plug).
In the plug I have installed a couple of applications that has web interfaces - SickBeard (TV Library), CouchPotato (Movie Library), Sabnzbd (Usenet downloader) & Transmission (torrent downloader). I use NGINX as a proxy in front. So my basic idea is that any domain pointing to my "Plug's IP" will route to NGINX, which, based on the domain name used, routes (proxies) the call to the respective application's web interface. For example, dl.plug.example.com (I don't wish to reveal the domain name) will take me to Transmission web interface while usenet.plug.example.com will take me to Sabnzbdplus web interface, pi.plug.example.com will point to the "remote" interface for my other PI (used as media player) & modem.plug.example.com will point to my router's admin page. It does work as expected.
Now I installed and configured BIND and then set my Modem to use Plug's IP as DNS server so that all requests go through Plug's BIND installation. My aim is:

*

*From any device connected to my home network, .plug.example.com should take me to the corresponding machine hosting the application byt through local IP. Means, if I am at home and I type in dl.plug.example.com on my phone's browser it should route to 192.168.1.x. While if I am accessing from outside home it should route to my public ip.

*Any request for any other domain name not hosted inside my network, I want BIND to go through Google DNS (8.8.8.8) and resolve it.

The public IP part works. Means when I access from outside my network it does work. When I try from inside network - it fluctuates. That is, at times it routes via my internal IP but other times it takes me through the whole web (routes via public IP). This is one problem I am trying to resolve.
Another problem is that sometimes plug.example.com fails to resolve at all. Through BIND is up and running. When I SSH from terminal via domain name it sometimes doesn't resolve but if I use IP it works smooth. So I am guessing it is some issue with my BIND configuration. As per my modem config, all DNS traffic goes through Plug where BIND is installed. So this shouldn't have happened.
I have uploaded my BIND configuration to:
https://drive.google.com/file/d/0B8TuY1aaTEhmbXRGVUkwbUh1bVU/view?usp=sharing

A: Primer
This is the Hosts file from my working Gentoo installation.  I've removed the actual routing instructions, in favor of the comments.  More on the routing momentarily:
# /etc/hosts: Local Host Database
#
# This file describes a number of aliases-to-address mappings for the for
# local hosts that share this file.
#
# In the presence of the domain name service or NIS, this file may not be
# consulted at all; see /etc/host.conf for the resolution order.
#
# Imaginary network.
#10.0.0.2               myname
#10.0.0.3               myfriend
#

# According to RFC 1918, you can use the following IP networks for private
# nets which will never be connected to the Internet:
#
#       10.0.0.0        -   10.255.255.255
#       172.16.0.0      -   172.31.255.255
#       192.168.0.0     -   192.168.255.255
#
# In case you want to be able to connect directly to the Internet (i.e. not
# behind a NAT, ADSL router, etc...), you need real official assigned
# numbers.  Do not try to invent your own network numbers but instead get one
# from your network provider (if any) or from your regional registry (ARIN,
# APNIC, LACNIC, RIPE NCC, or AfriNIC.)

Problem
Notice the last comment block regarding private networks.  What most people forget when configuring network services for their private network is that there is an imaginary line that splits their internal network (Those  IP Addresses covered by RFC 1918, and RFC 6761), and the external network (the Internet for all practical purposes), where the domain IP Addresses are mostly maintained and updated by the Internet Assigned Numbers Authority, aka the IANA.  This is also the accepted practice because the IANA is in charge of the DNS Root Zone,  The IANA DNS Server has the final say in where a domain resolves to.  Imagine your DNS server as the top branch of a tree.  If your Server can't resolve a host, your request is sent down the tree, to subsequent branches.  Each branch grows in size  At the bottom of the tree is the IANA DNS Server.

Solution
It's up to the maintainer/creator of the private network to handle routing inside the private network.  In Linux this is done by updating the hosts file, usually stored at /etc/hosts  Please note that the OP had only solved half the problem by installing and configuring BIND.  BIND properly routes names to hosts and hosts:ports and the other way around.  In most servers, one of it's many uses is to bind an external DNS zone (one outside your private network) to an internal DNS zone.  See Linux DNS server BIND configuration for more on this. I'll also be referring back to that link when certain sections below warrant.
Since routing internally is governed by different rules (RFC 1918/6761), one must setup static routing so that the address-to-name mappings work in BIND.  If the etc/hosts file isn't configured for this, the bind mapping only knows to route the request internally, but not where to route it to.  In order to fix this we must add our local mapping (assuming the OP has set the external BIND mapping correctly):
# IPv4 and IPv6 localhost aliases
127.0.0.1       bedroom-gentoo.myISP.net     bedroom-gentoo  localhost
::1             bedroom-gentoo.myISP.net     bedroom-gentoo  localhost

and then our local resolution (in the OP's case)
192.168.1.x    sickbeard.plug.example.com   sickbeard.plug    sickbeard
192.168.1.x    dl.plug.example.com          dl.plug           download
# Add others as needed.

Notice that the private network resolution above can resolve to the FQDN, plus only the host names.  The OP and others can adjust this accordingly for the desired behavior. I find that using the FQDN inside the private network is easier than remembering all the host names created.
Step 2 - Optional but Preferred
I'm adding the links below, as readers will see this networking term in most answers connected to network setup. If you're new here, have a read.  If you've been around awhile, you may want to skip.

*

*The Dynamic Host Configuration Protocol - RFC2131

*DHCP - Wikipedia for short

As you can see after reading or not, DHCP is very good at what it does.  It's main function from here to eternity will be to give out addresses, whether Public or Private.  What DHCP is not good at is remembering the addresses it gives out may actually belong to a server of any sort.  In the OP's case, and many other readers, this is the case. That case applies here, as we have "software reserved" the IP address 192.168.1.x to the plug device.  In order to make sure that DHCP doesn't stupidly override the server's address after a reboot/restart or power outage, one should use MAC Address Binding in one's router.  I took the following screenshot from my Motorola Surfboard, but I've seen the same type of entry screen in most major router brands (D-LINK, NetGear, LinkSys/Cisco).  Also, some may name it Reserve, some name it Binding, some MAC Binding:

The MAC Address of the server, plug in the OP's case would go in the first box, and the last octet, x from the /etc/hosts file would go into the IP Address box.  I believe the Host Name is filled in automatically, but you could use a name from etc/hosts if wanted.  This will ensure that we will never have to modify our hosts file because we are forcing DHCP to hand out a Static IP Address.  On a side note, this may slightly increase caching of streaming media services.  I've used the same concept for my Roku device before.

For Fun
How TCP/IP Works - Youtube


text:
Q: How can I link my Bootstrap buttons to php code that receives data from client I am new to bootstrap, I need to connect each bootstrap button to a certain value that is received by server from a client using (GET request).
Values are receives by server and stored in mysql database to be displayed later in the bootstrap webpage that contains buttons for each value.
What is the easiest way to do so?
I will attach the php code that receives the value (Steinhart) and store it in the database.
  <?php

   include("connect.php");

   $link=Connection();

      $timeStamp="";
      $result="";
       $query="";

      $Steinhart = isset($_GET['Steinhart']) ? $_GET['Steinhart'] : '';

      date_default_timezone_set("Asia/Dubai");
      $timeStamp = date('Y-m-d H:i:s', time());

     $query= "INSERT INTO `time` (`id`, `timeStamp`, `Steinhart`) VALUES  (NULL, '$timeStamp','$Steinhart')";

     mysqli_query($link, $query);
     mysqli_close($link);

        header("Location: ../indexx.php");
      ?>

Bootstrap code for the button:

Ambient Temperature

                                View Details

A: Use jQuery with Ajax to send request to your php code like:
make you button like this:
<button id="mybutton" data-steinhart="your insert data">Do!</button>

make your jQuery code
$("#mybutton").Click(function(){
    var data = $(this).data('steinhart');

    $.ajax({
        type: 'GET',
        url: 'yourphpfile.php',
        data: {
            'data': data
        },
        success: function (data) {
            console.log(data);
        }
    });
});


text:
Q: AlarmManager doesn't start after boot is complete I need to set the AlaramManager if user chose something from preferences. but I get Unfortunately, stopped Error , where do you think my problem is? thanks
Receiver :
public class StartMyServiceAtBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(context);
            if (prefs.getString("autoSend", null) != null) {
                if (prefs.getString("autoSend", "").equals("true")) {
                    AlarmManager am = (AlarmManager) context
                            .getSystemService(Context.ALARM_SERVICE);
                    Intent i = new Intent(context, AutoSender.class);
                    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
                    am.setRepeating(AlarmManager.RTC_WAKEUP,
                            System.currentTimeMillis(), 1000 * 10, pi);
                }
            }
        }
    }
}

the Intent:
@SuppressLint("Wakelock")
public class AutoSender extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {

        PowerManager pm = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        Toast.makeText(context, "Test" , Toast.LENGTH_LONG)
                .show();

        wl.release();
    }

}

manifest:
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
------------------
 <receiver android:name="AutoSender" >
        </receiver>
        <receiver
            android:name=".StartMyServiceAtBootReceiver"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

Edit:
and Here is the Exception :
08-07 11:21:46.825: E/AndroidRuntime(668): FATAL EXCEPTION: main
08-07 11:21:46.825: E/AndroidRuntime(668): java.lang.RuntimeException: Unable to start receiver com.aps.safirsms.StartMyServiceAtBootReceiver: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
08-07 11:21:46.825: E/AndroidRuntime(668):  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2383)
08-07 11:21:46.825: E/AndroidRuntime(668):  at android.app.ActivityThread.access$1500(ActivityThread.java:141)
08-07 11:21:46.825: E/AndroidRuntime(668):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
08-07 11:21:46.825: E/AndroidRuntime(668):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-07 11:21:46.825: E/AndroidRuntime(668):  at android.os.Looper.loop(Looper.java:137)
08-07 11:21:46.825: E/AndroidRuntime(668):  at android.app.ActivityThread.main(ActivityThread.java:5041)
08-07 11:21:46.825: E/AndroidRuntime(668):  at java.lang.reflect.Method.invokeNative(Native Method)
08-07 11:21:46.825: E/AndroidRuntime(668):  at java.lang.reflect.Method.invoke(Method.java:511)
08-07 11:21:46.825: E/AndroidRuntime(668):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-07 11:21:46.825: E/AndroidRuntime(668):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-07 11:21:46.825: E/AndroidRuntime(668):  at dalvik.system.NativeStart.main(Native Method)
08-07 11:21:46.825: E/AndroidRuntime(668): Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
08-07 11:21:46.825: E/AndroidRuntime(668):  at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:224)
08-07 11:21:46.825: E/AndroidRuntime(668):  at com.aps.safirsms.StartMyServiceAtBootReceiver.onReceive(StartMyServiceAtBootReceiver.java:18)
08-07 11:21:46.825: E/AndroidRuntime(668):  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2376)
08-07 11:21:46.825: E/AndroidRuntime(668):  ... 10 more

A: Use LogCat to examine the Java stack trace associated with your "stopped Error".
In this case, the problem is probably that you have  android:permission="android.permission.RECEIVE_BOOT_COMPLETED", which is incorrect. It requires that whoever sends that broadcast have that permission, which is not necessarily true.

A: one thing i notice is that you forget the dot in android:name="AutoSender" so it should be android:name=".AutoSender".
Also when your BroadcastReceiver isn't in the main package (don't know if it is in your case) you should put the package name in front of it like this android:name="my.package.name.AutoSender"