text:
Q: Change WPF DataGrid column cell background color based on values I am trying to fill cells with color in certain column. Column name is "NRO" and I want to fill cells staring with 2 yellow color and cells starting with 3 blue color. I went through answer given here: Change DataGrid cell colour based on values
Also tried several other approaches but can't get any of them work. I also don't understand how to implement any of them in my setup. They all seems to have <DataGridTextColumn Binding="{Binding Name}">. What it should be in my case?
Here is my XAML:
<Window x:Class="DB_inspector_FilterTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="DB database inspector v.0.0.01" Height="600" Width="1000" Icon="logo_icon-small.jpg" Background="White">
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <DataGrid x:Name="DataGrid1" Margin="0,103,0,0" Background="White" BorderBrush="#FF38853F"/>
        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="20" Margin="22,41,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="437" TextChanged="NameSearch_TextChanged"/>
        <Button Content="Load" Margin="640,41,0,0" Click="Button_Click_1" BorderBrush="{x:Null}" Foreground="White" Background="#FF55B432" Width="66" Height="29" HorizontalAlignment="Left" VerticalAlignment="Top"/>
        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="11" VerticalAlignment="Top" Width="992" BorderBrush="{x:Null}" Background="{x:Null}"/>
        <Label Content="Customer name" HorizontalAlignment="Left" Height="25" Margin="22,11,0,0" VerticalAlignment="Top" Width="154"/>
        <CheckBox x:Name="ActiveCustomer" Content="Active" HorizontalAlignment="Left" Height="24" Margin="486,63,0,0" VerticalAlignment="Top" Width="86" Click="ActiveCustomer_Click_1"/>
        <CheckBox x:Name="Only" Content="Leave only good" HorizontalAlignment="Left" Height="17" Margin="486,41,0,0" VerticalAlignment="Top" Width="115" Click="CheckBox_Click"/>
        <Image Margin="856,0,22,520" VerticalAlignment="Bottom" Source="logo_small.jpg" Height="27"/>

    </Grid>
</Window>

ADDITION:
If anybody have time, while I will be trying to figure it out myself, give me some hints how to proceed with my application, here is my full code:
using System.Data.Odbc;
using System.Windows;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;

namespace DB_inspector_FilterTest
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                ProgressBar.IsIndeterminate = true;

                DataGrid1.ItemsSource = await GetDataAsync();

                ProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private Task<DataView> GetDataAsync()
        {
            return Task.Run(() =>
            {

                string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSSE;Uid=ADMIN;Pwd=123;";

                string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSFI;Uid=ADMIN;Pwd=123;";

                string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                DataTable dataTable = new DataTable("COMPANY");
                // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
                using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
                {
                    dbConnectionDE.Open();
                    OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                    dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                    dadapterDE.Fill(dataTable);

                }
                using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
                {
                    dbConnectionFR.Open();
                    OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                    dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                    var newTable = new DataTable("COMPANY");
                    dadapterFR.Fill(newTable);

                    dataTable.Merge(newTable);

                }

                return dataTable.DefaultView;

            });
        }

        private Dictionary<string, string> _conditions = new Dictionary<string, string>();

        private void UpdateFilter()
        {
            try
            {
                var activeConditions = _conditions.Where(c => c.Value != null).Select(c => "(" + c.Value + ")");
                DataView dv = DataGrid1.ItemsSource as DataView;
                dv.RowFilter = string.Join(" AND ", activeConditions);
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void NameSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            string filter = NameSearch.Text;
            if (string.IsNullOrEmpty(filter))
                _conditions["name"] = null;
            else
                _conditions["name"] = string.Format("NAME Like '%{0}%'", filter);
            UpdateFilter();
        }

        private void ActiveCustomer_Click_1(object sender, RoutedEventArgs e)
        {
            if (ActiveCustomer.IsChecked == true)
            {
                _conditions["active"] = string.Format("ACTIVE Like '%{0}%'", "1");
                UpdateFilter();
            }
            else
            {
                _conditions["active"] = null;
                UpdateFilter();
            }
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            if (OnlyFIandSE.IsChecked == true)
            {
                _conditions["onlyfrandde"] = string.Format("NRO Like '2%' OR NRO Like '3%'");
                UpdateFilter();
            }
            else
            {
                _conditions["onlyfrandde"] = null;
                UpdateFilter();
            }
        }
    }
}

Things I don't understand at least now: How in my case I should setup ItemSource for binding? Should I import databases to List first and then Bind to the list?

ATTEMPT 3:
Here is my latest MVVM attempt.
C#:
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Windows;
using System.Windows.Input;

namespace DB_inspector
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

    }

    public class ViewModel : INotifyPropertyChanged
    {
        public ICommand myCommand => new RelayCommand(obj =>
        {
            try
            {
                string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSSE;Uid=ADMIN;Pwd=123;";

                string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSFI;Uid=ADMIN;Pwd=123;";

                string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                DataTable dataTable = new DataTable("COMPANY");
                // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
                using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
                {
                    dbConnectionDE.Open();
                    OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                    dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                    dadapterDE.Fill(dataTable);

                }
                using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
                {
                    dbConnectionFR.Open();
                    OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                    dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                    var newTable = new DataTable("COMPANY");
                    dadapterFR.Fill(newTable);

                    dataTable.Merge(newTable);

                }

                _ = dataTable.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        });

        private bool _allowUIChanges = true;
        public bool AllowUIChanges
        {
            get => _allowUIChanges;
            set
            {
                _allowUIChanges = value;
                OnPropertyChanged(nameof(AllowUIChanges));
                OnPropertyChanged(nameof(IsReadOnlyDataGrid));
            }
        }

        private void OnPropertyChanged(string v)
        {
            throw new NotImplementedException();
        }

        public bool IsReadOnlyDataGrid
        {
            get => !_allowUIChanges;
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object, bool> _canExecute;

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }
        public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

        public void Execute(object parameter) => _execute(parameter);
    }
}

XAML:
<Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <DataGrid IsReadOnly="{Binding IsReadOnlyDataGrid}" AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}" Width="998" Margin="0,98,0,0" >
        </DataGrid>
        <Image Height="41" Margin="0,21,10,0" Width="141" Source="logo_small.jpg" HorizontalAlignment="Right" VerticalAlignment="Top"/>
        <Button Content="Go" Command="{Binding myCommand}" Width="80" Height="30" Margin="48,42,870,492"/>

    </Grid>
</Window>

Any suggestions what is still wrong here? No errors, but button does not process anything.

A: I suggest IValueConverter or IMultiValueConverter binding for Cell's Background property.
I'm not sure how it works with autogenerated columns set but with manual it looks like this. I'm providing here not a working copy but a markup example.
XAML
<Window.Resources>
    <local:MyCellBackgroundConverter x:Key="myCellBackgroundConverter"/>
</Window.Resources>
<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
<Grid>
<!-- some your markup here -->
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}">
    <DataGridTextColumn Header="Column1" Binding="{Binding Value1}">
        <DataGridTextColumn.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="Background">
                    <Setter.Value>
                        <MultiBinding Converter="{StaticResource myCellBackgroundConverter}">
                            <Binding Path="Value1"/>
                            <Binding Path="Value2"/>
                        </MultiBinding>
                    </Setter.Value>
                </Setter>
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
    <DataGridTextColumn Header="Column2" Binding="{Binding Value2}"/>
</DataGrid>
</Grid>

The ViewModel Class
using System.Collections.ObjectModel;
using System.ComponentModel;

// ...

public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<MyItem> _myCollection = new ObservableCollection<MyItem>();
    public ObservableCollection<MyItem> MyCollection
    {
        get => _myCollection;
        set
        {
            _myCollection = value;
            OnPropertyChanged(nameof(MyCollection));
        }
    }

    public ViewModel()
         // you may load or add the data to MyCollection here
    {

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Item
using System.ComponentModel;

// ...

public class MyItem : INotifyPropertyChanged
{
    private string _value1 = string.Empty;
    private string _value2 = string.Empty;

    public string Value1
    {
        get => _value1;
        set { _value1 = value; OnPropertyChanged(nameof(Value1)); }
    }

    public string Value2
    {
        get => _value2;
        set { _value2 = value; OnPropertyChanged(nameof(Value2)); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

And finally the Converter
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

//...

public class MyCellBackgroundConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[0] is string value1 && values[1] is string value2)
        {
            if (value1.Length > 0)
            {
                return Brushes.Green;
            }
            else
            if (value2.Length > 0)
            {
                return Brushes.Yellow;
            }
            else
                return Brushes.Red;
        }
        else return Brushes.White;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => null;
}

In alternative way you may use Style.DataTriggers directly in XAML.
For additional information about bindings and properties look for MVVM programming pattern. In short you're not need x:Name anymore because in MVVM pattern you interacting only with ViewModel class data instances and can't interact with contols directly there (and that's fine). Meanwhile Contols automatically sync with data binded to them. Calling OnPropertyChanged("PropertyName") here simply cause the GUI refresh.
In relation to markup of your XAML example, try wrapping the Control groups in StackPanel and learn about it. It will save your time spent fighting with margins. Simply set few colums and/or rows in Window's Grid and place StackPanels there assigning Grid.Column and Grid.Row to them.

ADDITION:

How in my case I should setup ItemSource for binding? Should I import databases to List first and then Bind to the list?

ObservableCollection<> is same as List<> and you may use it in the same way. The difference that first one implements CollectionChanged event that notifies DataGrid if any items was added or removed from the collection.
Your Button.Click event handler contains redundant async/await declaration.
Let's move forward and see how it can be done with MVVM.
XAML
<Button Content="Go" Command="{Binding myCommand}"/>

Command must implement ICommand interface. You have to do 2 things for proper implementation:
1) Add RelayCommand separate Class implementing ICommand interface
public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }
    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

    public void Execute(object parameter) => _execute(parameter);
}

2) Add the Command instance to your ViewModel class
public ICommand myCommand => new RelayCommand(obj =>
{
    // do the same here as in Button.Click above
});

Next, you may need some blocking UI thing that will prevent user from any actions while data is loading.
ViewModel
private bool _allowUIChanges = true;
public bool AllowUIChanges
{
    get => _allowUIChanges;
    set
    {
        _allowUIChanges = value;
        OnPropertyChanged(nameof(AllowUIChanges));
        OnPropertyChanged(nameof(IsReadOnlyDataGrid));
    }
}
public bool IsReadOnlyDataGrid
{
    get => !_allowUIChanges;
}

Finally bind your Control properties to it
XAML
<Button Content="Go" Command="{Binding myCommand}" Enabled="{Binding AllowUIChanges}"/>
<DataGrid IsReadOnly="{Binding IsReadOnlyDataGrid}" AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}">

Then set AllowUIChanges to false while data is loading.


text:
Q: git key_from_blob and key_read error I'm getting the following error when I try to pull from git.
$ git pull origin master
key_from_blob: remaining bytes in key blob 266
key_read: type mismatch: encoding error
From github.com:mea36/duca2011/group5
  * branch master -> FETCH_HEAD
Already up-to-date

but my code isn't being updated.
Any suggestions?

A: These are messages from SSH when trying to read key files:
key_from_blob: remaining bytes in key blob 266
key_read: type mismatch: encoding error

Typically you see them on the server when someone has used an invalid key format in ~/.ssh/authorized_keys (server side); however given that they are showing up client side, I'd recommend checking your keys (~/.ssh/*)
You can use ssh-keygen to validate keys:
ssh-keygen -B -f id_rsa.pub

e.g.
$ ssh-keygen -B -f /tmp/foo
2048 xipab-kikup-tanas-pahop-sihoc-lipaz-tusav-dybuf-lubuf-vasob-dyxox /tmp/foo.pub (RSA)

A: This is probably some problem with how your SSH connection is set up.
But this probably shouldn't affect the pulling. And your code isn't updated, because there is nothing to update. As the last line states, you are already up-to-date.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Addition of rasters using raster calculator I have five classes of rivers as different rasters.
I want to add them all in a new raster file using raster calculator. When I do this, it creates 16 types of classes, while I am expecting seven.
.
When the classes are combined in the raster calculator, it creates a new class on the final raster file. I want to create a map with a legend that gives me only the seven classes of each raster file.
What am I doing wrong?

A: Ok, so the statement you are using in Raster Calculator simply adds up all the cell values in order to create the new raster. Example:

*

*Raster 1 = 1, Raster 2 = 2, Raster 3 = 0, Raster 4 = 0 and Raster 5 = 7 the cell value in your new raster becomes 1 + 2 + 0 + 0 + 7 = 10
I would recommend using the Mosaic to new raster tool within the Data Management toolbox. There you can determine, which value the new raster cells should become when put togehter. I guess you want the maximum value of all of those 5 rasters, so you can select the option "MAXIMUM".


text:
Q: Resolution of javascript resources/libraries/dependencies by the Webstorm IDE I am new to the Webstorm IDE and would like to know how this IDE resolves javascript dependencies/libraries.
For instance say I have a folder/project with a number of vendor dependencies as well as my own *.js files.

*

*How Webstorm is going to find those vendor dependencies files?

*How is Webstorm going to know in which order to load those found dependencies?

*Can I use some dependency management tool such as Bower together with Webstorm?

A: By default WebStorm uses a global scope for resolving dependencies inside a given .js file. It means that all .js files (external dependencies/your own files) located in the project root will be used in one single global resolve scope by default.
You can create a library using "Settings | JavaScrit | Libraries" and associate it with a custom scope. That allows to exclude the created library from global scope - it will be used in resolve for the specified scope only.


text:
Q: Levels of an object's luminosity Is there a concise list somewhere of terms used to describe a range of "brightness" or "luminosity"? Say from dim to blinding as an example. I tried Googling it and searching Wikipedia, but all I got were thesaurus and mathematical definitions.
The closest I've found is the luminosity charts for stars, but unfortunately they don't have word designations for each range.

A: First, let me illustrate how hard this is:
I started by searching for adjectives describing light in the Oxford Historical Thesaurus. It is a powerful tool that categorizes words by functions and lists their synonyms. Because lightness and darkness are often treated as separate qualities, the words are listed under two different headers:

the world > matter > light > intensity of light >  [adjective] (91)
the world > matter > light > darkness or absence of light > dimness or absence of brightness >  [adjective] (65)

Word lists will tend towards the same flaw. This list? Or this one? It's mostly words describing light. It's hard to organize these into strict ranges, since there will be a lot of overlap between entries. (You try describing the difference between "sparkling" and "coruscating.")
This list from RhymeZone is better, since the second half of the entries cover levels of brightness as well as dimness. It isn't in order of brightness, but it's a start.


text:
Q: Upload arbitrary data in HTTP Post in Flex We currently have a Java applet that generates a lot of data and uploads it to our servers.  One of the upload methods we have is to use an HTTP POST to our server, the contents of which are just the raw data (no multipart encoding or anything).
I'm looking at implementing a Flex app that does the same thing, but I don't see a way to duplicate that network behavior.  All the HTTP-related network classes in Flex seem to work under the assumption that you're simply making a request.  I don't see a way to actually set the payload of the POST (other than setting a couple query parameters, which wouldn't work here).
What I'd really like is to be able to initiate an HTTP POST, but then be able to write to the connection like I would a socket.  Is this possible without having to write my own HTTP implementation on top of the Socket class?  Is there any way to set the payload of an HTTP POST within Flex?
Clarification:  Being able to create a data buffer and send that to the server is sufficient (which it looks like is possible).  It would be better if I could treat the connection as a socket and send data to it over time, instead of all at once, but that isn't strictly required.

A: It sounds like you're sort of asking two questions.  Yes, there is a way to set the payload of an HTTP POST within Flex, and to upload files of any format to your server:
private function doPost():void
{
    var yourData:ByteArray = new ByteArray();
    var encoder:Base64Encoder = new Base64Encoder();

    for (var i:int = 0; i < 10000; i++)
        yourData.writeByte(i);

    yourData.position = 0;
    encoder.encodeBytes(yourData);

    var req:URLRequest = new URLRequest("http://yourdomain.com/yourservice.ext");
    req.method = URLRequestMethod.POST;

    var postData:URLVariables = new URLVariables();
    postData.userData = encoder.flush();

    req.data = postData;

    var loader:URLLoader = new URLLoader();
    loader.dataFormat = URLLoaderDataFormat.BINARY;
    loader.addEventListener(Event.COMPLETE, loader_complete);
    loader.load(req);
}

private function loader_complete(event:Event):void
{
    trace("Upload complete!");
}

... but it also sounds like you want to connect, keep the connection open and then write to it arbitrarily "like a socket"; if that's the case, then other than using the Socket classes for that purpose, I don't believe there's a built-in mechanism, no.  Hope it helps nonetheless!


text:
Q: Should I better use global variables? I want to use GMainLoop. I wonder if it is better to use global or local variables. I want to call a function every 5 secs. It uses  some heap variables and I want to malloc only once. I have two ideas. I can put all arguments in a struct. But sometimes it would be struct in struct in struct. So the name nomenclature will be complex and bad readable. I can also make all data gloal. It would be something like:
typedef struct data_t
{
  unsigned char *pUncompressStreamData;
  unsigned char *pStartUncompressStreamData
  analyzers_t analyzers;
  GTree *tree;
}data_t;
main_loop(data_t data )
{
   //data_mallocs and other stuff
}
int main()
{
    data_t data;

    g_timeout_add_seconds ( 5, main_loop, data);
    /free all data member
}

OR
unsigned char *pUncompressStreamData;
unsigned char *pStartUncompressStreamData
analyzers_t analyzers;
GTree *tree;

main_loop(data_t data )
{
   //data_mallocs and other stuff
}
int main()
{

    g_timeout_add_seconds ( 5, main_loop, NULL);
    /free all data member
}

Please give me clues.

A: Use local variables or structures (more readable and more modular). Notice that you could pass them, e.g. as the address of some struct, as the client data of g_timeout_add_seconds. So prefer the first version to the second. However, you main should initialize data e.g. with calloc then free it after the Glib event loop.


text:
Q: Unable to populate input field value in AngularJS I have been trying to populate a text field in AngularJS for past few days but unable to do so. I am trying to populate this field by the selected value in a abn:tree from a modal window.
While the selection is displayed in modal window but, whenever I try to display it in the parent screen it doesn't do anything.
View:
Category

    <input type="text" class="formControl" ng-model="category" required />

            <button ng-click="open()">...</button>

Template:

                <abn-tree
                        tree-data         = "fake_data"
                        tree-control      = "fake_tree"
                        on-select         = "fake_handler(branch)"
                        expand-level      = "2"
                        initial-selection = "Wasif"
                        >
                </abn-tree>

{{output}}

Tree:
Finally my tree is something similar to this:
app.controller('AbnTreeController', function($scope, $timeout) {
    var fruit_selected, tree, treedata;
    $scope.fake_tree_handler = function(branch) {
      var _ref;
      $scope.result = "selected: " + branch.label;
      if ((_ref = branch.data) != null ? _ref.description : void 0) {
        return $scope.result += '(' + branch.data.description + ')';
      }
    };
    fruit_selected = function(branch) {
      return $scope.result = "apple! : " + branch.label;
    };
    treedata = [
       {
        label: 'Fruits',
        data: {
          bol_value: true
        },
        onSelect: function(branch) {
          return $scope.result = "Fruit: " + branch.data.bol_value;
        },
        children: [
          {
            label: 'Apples',
            children: [
              {
                label: 'Wasif',
                onSelect: fruit_selected
              }]
          }
        ]
      }
    ];
    $scope.fake_data = treedata;

    $scope.fake_tree = tree = {};
});

Whenever I select anything on my tree it displays well in the Dialog but never populate the field category which is in parent window.


text:
Q: Showing that $\sum_{k=1}^{\infty}\frac{\ln k}{k^s}$ converges for all $\Re s > 1$ I want to prove that $\sum_{k=1}^{\infty}\ln k/k^s$ converges for all $\Re s > 1$. Since $\ln k/k^\alpha\to 0$ as $k\to\infty$ for all $\alpha > 0$, there exists a $N$ such that $\ln k<k^{\alpha}$ for all $k\geq N$ and all $\alpha>0$. Then
$$\left | \sum_{k=1}^{\infty}\frac{\ln k}{k^s} \right |\leq \sum_{k=1}^{N-1}\frac{\ln k}{k^{\Re s}}+\sum_{k=N}^{\infty}\frac{1}{k^{\Re s-\alpha}},$$
on the right side, the first sum is finite, and the second sum converges for all $\Re s > 1+\alpha$. Letting $\alpha \to 0$, we are done. Is this a correct approach?


text:
Q: Store the digital data from analog to digital converter ADC(0804) in 8051 how can I store digital data from analog to digital converter ADC(0804) in 8051 for transmission purposes?
This help means a lot to me.
Any kind of help would be really appreciated.

A: I believe you should investigate and understand the ADC0804 datasheet to how an ADC works. However, I will add a simple ADC code in 8051 assembly, I believe you can write the c code by understanding the assembly code. I am not doing this just for you, also for the other people who don't know ADC and come here to search for it.
Take some time and give some effort to make your work useful. It has no meaning if you just copy it from somewhere, try to learn it. Then you will see the beautiful side of understanding.
RD BIT P2.5
WR BIT P2.6
INTR BIT P2.7
DATA EQU P1
MOV P1,#0FFh
SETB INTR
BACK: CLR WR
SETB WR
HERE: JB INTR,HERE
CLR RD
MOV A,DATA
SETB RD
SJMP BACK

PS: I am adding two diagrams from the datasheet, check them to understand how the ADC basically works.
ADC1 ADC2
Also, I am suggesting you to ask microprocessor related questions to the electrical engineering section. It's mostly their topic, so they return faster.


text:
Q: How to specify multiple dependencies using --packages for spark-submit? I have the following as the command line to start a spark streaming job.
    spark-submit --class com.biz.test \
            --packages \
                org.apache.spark:spark-streaming-kafka_2.10:1.3.0 \
                org.apache.hbase:hbase-common:1.0.0 \
                org.apache.hbase:hbase-client:1.0.0 \
                org.apache.hbase:hbase-server:1.0.0 \
                org.json4s:json4s-jackson:3.2.11 \
            ./test-spark_2.10-1.0.8.jar \
            >spark_log 2>&1 &

The job fails to start with the following error:
Exception in thread "main" java.lang.IllegalArgumentException: Given path is malformed: org.apache.hbase:hbase-common:1.0.0
    at org.apache.spark.util.Utils$.resolveURI(Utils.scala:1665)
    at org.apache.spark.deploy.SparkSubmitArguments.parse$1(SparkSubmitArguments.scala:432)
    at org.apache.spark.deploy.SparkSubmitArguments.parseOpts(SparkSubmitArguments.scala:288)
    at org.apache.spark.deploy.SparkSubmitArguments.<init>(SparkSubmitArguments.scala:87)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:105)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

I've tried removing the formatting and returning to a single line, but that doesn't resolve the issue. I've also tried a bunch of variations: different versions, added _2.10 to the end of the artifactId, etc.
According to the docs (spark-submit --help):

The format for the coordinates should be groupId:artifactId:version.

So what I have should be valid and should reference this package.
If it helps, I'm running Cloudera 5.4.4.
What am I doing wrong? How can I reference the hbase packages correctly?

A: A list of packages should be separated using commas without whitespaces (breaking lines should work just fine)  for example
--packages  org.apache.spark:spark-streaming-kafka_2.10:1.3.0,\
  org.apache.hbase:hbase-common:1.0.0

A: I found it worthy to use SparkSession in spark version 3.0.0 for mysql and postgres
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('mysql-postgres').config('spark.jars.packages', 'mysql:mysql-connector-java:8.0.20,org.postgresql:postgresql:42.2.16').getOrCreate()

A: @Mohammad thanks for this input.  This worked for me too. I had to load the  Kafka and msql packages in a single sparksession. I did something like this:
spark = (SparkSession .builder ... .appName('myapp') # Add kafka and msql package .config("spark.jars.packages", "org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.2,mysql:mysql-connector-java:8.0.26") .getOrCreate())


text:
Q: Combine multiple objects into new object For my issue, I have a list of objects (Producers).
For each producer record, there are some properties (ID, DisplayName, and StateCode).
There can be multiple items in the list that have the same ID & DisplayName, but different StateCodes.
I am having trouble querying this to give me a distinct list of Producers with each of their possible StateCodes in a new object.
I would prefer to have the new objects to have the ID, DisplayName, and a List which contains each StateCode of theirs.
Can someone point out the proper way I could create this new list?

A: you're looking for LINQ's GroupBy:
var groups = producerList.GroupBy(p => new { p.ID, p.DisplayName });

group on the 2 properties, then your groups' values will be an IEnumerable of StateCodes


text:
Q: Flatten a list using only the forms in "The Little Schemer" I'm going through The LIttle Schemer to learn Scheme (as an old C programmer) and as an exercise I tried to write a procedure to flatten a list using only the forms in The Little Schemer;  I.e., define, lambda, cond, car, cdr, and, or, etc., but not append.  I thought it would be easy but I haven't been able to come up with a solution.  How can I do this ?

A: I'm not familiar with the Little Schemer primitives, so you may need to flavor this to suit.
I'm not sure if this is the answer you want, but you can write append using primitives:
(define (append l1 l2)
  (cond
    ((null? l1) l2)
    (else (cons (car l1) (append (cdr l1) l2)))))

The flatten function could then be written in terms of this.
Not sure if this is outside the rules or not :)

A: Here's an attempt. It gets away with using cons and avoiding append, because it only chips away the first non-pair it can get to and conses that to the flatten of a new tail it has built. Sometimes it rewrites the list then just calls flatten again. Def not the most efficient way.
Fixed code:
(define (flatten x)
  (cond
    ((null? x) x)
    ((and (pair? x)
          (not (pair? (car x))))
     (cond
       ((null? (car x)) (flatten (cdr x)))
       (else (cons (car x) (flatten (cdr x))))))
    ((and (pair? x)
          (pair? (car x)))
     (flatten (cons (caar x)
                    (cons (cdar x) (cdr x)))))
    (else (cons x '()))))

A: I have a version that uses only "first-principles" operations and is efficient (does not require more than one pass through any of the lists, unlike append-based solutions). :-)
It does this by defining two simple building blocks (fold and reverse), and then defining flatten (and its helper, reverse-flatten-into) atop those (and notice how each function is just one or two lines long):
;; Similar to SRFI 1's fold
(define (fold1 kons knil lst)
  (if (null? lst)
      knil
      (fold1 kons (kons (car lst) knil) (cdr lst))))

;; Same as R5RS's reverse
(define (reverse lst)
  (fold1 cons '() lst))

;; Helper function
(define (reverse-flatten-into x lst)
  (if (pair? x)
      (fold1 reverse-flatten-into lst x)
      (cons x lst)))

(define (flatten . lst)
  (reverse (reverse-flatten-into lst '())))

The only external functions used are: cons, car, cdr, null?, and pair?.
The key insight from this function is that fold is a very powerful operation, and should be part of any Schemer's toolkit. And, as seen in the code above, it's so simple to build from first principles!


text:
Q: How to load the static files of django+nginx+gunicorn application using docker? I can't get my static files to come up. I've tried various settings and directory configurations and so on, but they just turn up as 404s.
Directory structure of application
.
├── config
│   └── nginx
│       └── conf.d
│           └── local.conf
├── docker-compose.yml
├── Dockerfile
├── aggre
│   ├── aggre
│   └── manage.py
|   └── static
├── requirements.txt

I have included static_url and root in settings.py and it looks like
STATIC_URL = '/static/'

STATICFILES_DIRS = [os.path.join(BASE_DIR),'static']

STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'static')

Dockerfile
FROM python:3.6
ENV PYTHONUNBUFFERED 1
RUN mkdir -p /opt/services/django/src
WORKDIR /opt/services/django/src
COPY requirements.txt /tmp/
RUN pip install --requirement /tmp/requirements.txt
COPY . /tmp/
COPY . /opt/services/django/src
RUN python aggre/manage.py collectstatic --no-input  # <-- here
CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"
EXPOSE 8000
ADD . /opt/services/django/src
CMD ["gunicorn", "--chdir", "aggre", "--bind", ":8000", "aggre.wsgi:application"]

docker-compose.yml
version: '2'
services:
  djangoapp:
    build: .
    volumes:
      - .:/opt/services/django/src
      - static_volume:/opt/services/django/static/
    networks:
      - nginx_network

  nginx:
    image: nginx:1.13
    ports:
      - "80:80"
    volumes:
      - ./config/nginx/conf.d:/etc/nginx/conf.d
      - static_volume:/opt/services/django/static/
    depends_on:
      - djangoapp
    networks:
      - nginx_network

networks:
  nginx_network:
    driver: bridge

volumes:
  static_volume:

local.conf
server {
    listen 80;
    server_name ***.***.io;

    location / {
        proxy_pass http://djangoapp:8000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /static {
        alias /opt/services/django/static;
    }
}

I am building and running using
**

docker-compose up --built

Application is starting successfully but static files are not loading.
I am getting

"/opt/services/django/src/static/js/bootstrap.js" failed (2: No such
  file or directory)

**

A: *

*in urls.py add
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

then append to urlpatterns like:
urlpatterns = [
YOUR_CONFIG
] + staticfiles_urlpatterns()

in Nginx config update like
location /static {
 root /opt/services/django;
}


text:
Q: Android How to obtain media player progress bar and also how to show it on each activity top screen Am working on certain app XYZ. In that app having a audio player module. I launch a player launch from an activity using some following code:
playButton = (ImageButton) findViewById(R.id.play_image_button);
        playButton.refreshDrawableState();
        playButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (playCount % 2 == 0) {
                    if (Data.songProfileArrayList.size() > 0) {
                        SongProfileBean songData = Data.songProfileArrayList
                                .get(0);
                        if ("audio".equals(songData.getSongFileType())) {
                            playButton
                                    .setBackgroundResource(R.drawable.pause_button);
                            playBackgroundMP3(Data.URL_BASE
                                    + songData.getSongName());
                        } else if ("video".equals(songData.getSongFileType())) {
                            Intent intent = new Intent(mContext,
                                    VedioViewActivity.class);
                            intent.putExtra("VideoUrl", Data.URL_BASE
                                    + songData.getSongName());
                            startActivity(intent);
                        }
                    }
                } else {
                    // stopPlay();
                    pauseSong();
                    // playerLayout.setVisibility(View.INVISIBLE);
                    // playButton.setImageDrawable(getResources().getDrawable(R.drawable.play_button));
                    playButton.setBackgroundResource(R.drawable.play_button);
                }
                playCount++;

            }
        });

To explain more about the code:
Currently I'm using an same Image Button on click on that the audio song starts from Data.songProfileArrayList an Array list and on another click of same button the song is stoped.
Now My Requirement or gist of question:
Actually I'm looking for following:
1.Is there any things available to also get the progress state of audio . I have gone through 1.developer docs 2.android docs on media
If yes Also suggest the way to have that status bar on each activity of application.
2.Should be able to progress the audio ,start,stop from each activity.
Please suggest a valid answer only after going through all details mentioned.
Only suggest answer If you have a deep knowledge over that and have done earlier so far
Valid Help and suggestions are most welcome
Regards,
Arpit

Hello After R & D over the problem I am able to get default controllers and progress state .But still want this to be on each activity and should be custom Controllers
package com.APP_NAME_XYZ.app;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.MediaController;
import android.widget.TextView;

public class AudioPlayer extends Activity implements OnPreparedListener,
        MediaController.MediaPlayerControl {
    private static final String TAG = "AudioPlayer";

    public static final String AUDIO_FILE_NAME = "audioFileName";

    private MediaPlayer mediaPlayer;
    private MediaController mediaController;
    private String audioFile;

    private Handler handler = new Handler();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audio_player);

        // audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);

        audioFile = "Provide URL of song";

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(this);

        mediaController = new MediaController(this);

        try {
            mediaPlayer.setDataSource(audioFile);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        mediaPlayer.stop();
        mediaPlayer.release();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // the MediaController will hide after 3 seconds - tap the screen to
        // make it appear again
        mediaController.show();
        return false;
    }

    // --MediaPlayerControl
    // methods----------------------------------------------------
    public void start() {
        mediaPlayer.start();
    }

    public void pause() {
        mediaPlayer.pause();
    }

    public int getDuration() {
        return mediaPlayer.getDuration();
    }

    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    public void seekTo(int i) {
        mediaPlayer.seekTo(i);
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public int getBufferPercentage() {
        return 0;
    }

    public boolean canPause() {
        return true;
    }

    public boolean canSeekBackward() {
        return true;
    }

    public boolean canSeekForward() {
        return true;
    }

    // --------------------------------------------------------------------------------

    public void onPrepared(MediaPlayer mediaPlayer) {
        Log.d(TAG, "onPrepared");
        mediaController.setMediaPlayer(this);
        mediaController.setAnchorView(findViewById(R.id.main_audio_view));

        handler.post(new Runnable() {
            public void run() {
                mediaController.setEnabled(true);
                mediaController.show();
            }
        });
    }
}

The audio_player layout is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_audio_view" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:orientation="vertical">
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_gravity="center"
        android:text="Now playing:" android:textSize="25sp" android:textStyle="bold" />
    <TextView android:id="@+id/now_playing_text"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_marginTop="20dip" android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip" android:layout_gravity="center"
        android:text="Now playing.." android:textSize="16sp"
        android:textStyle="italic" />
</LinearLayout>

A: You will need to change your approach. Use fragments and have one fragment show the progressbar and remain visible throughout. You can have just one activity and change the UI using fragments depending on different states of the application. When the application goes into background use Notification bar to show the media progress bar and allow user to relaunch the application from there.
Please refer how google music app works and follow the recommended approach.


text:
Q: TypeError: list indices must be integers or slices, not str with a jsonl file I have a jsonl file, which looks like this:
with open('myfile.jsonl', 'r') as f:
    dicts = json.load(f)

# it's a list of dictionaries
[{'date': '2018-12-11',
  'base_currency': 'EUR',
  'target_currency': 'USD',
  'exchange_rate': 1.1379},
 {'date': '2018-12-11',
  'base_currency': 'EUR',
  'target_currency': 'JPY',
  'exchange_rate': 128.75},..]

# or like this:
with open('myfile.jsonl', 'r') as f:
    lines = f.readlines()

['[{"date": "2018-12-11", "base_currency": "EUR", "target_currency": "USD", "exchange_rate": 1.1379}, {"date": "2018-12-11", "base_currency": "EUR", "target_currency": "JPY", "exchange_rate": 128.75},..,{..}]\n']

then I have this test function:
def jsonl_to_list(filename):
    with open(filename, 'r') as f:
        lines = f.readlines()

    return sorted(
        [json.loads(l.strip()) for l in lines],
        key=lambda x: (x["target_currency"], x["date"])
    )

when I run it, I get this error:
jsonl_to_list('myfile.jsonl')

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_40452/1757437785.py in <module>
----> 1 jsonl_to_list('myfile.jsonl')

~\AppData\Local\Temp/ipykernel_40452/2518347130.py in jsonl_to_list(filename)
      3         lines = f.readlines()
      4
----> 5     return sorted(
      6         [json.loads(l.strip()) for l in lines],
      7         key=lambda x: (x["target_currency"], x["date"])

~\AppData\Local\Temp/ipykernel_40452/2518347130.py in <lambda>(x)
      5     return sorted(
      6         [json.loads(l.strip()) for l in lines],
----> 7         key=lambda x: (x["target_currency"], x["date"])
      8     )

TypeError: list indices must be integers or slices, not str

also, if it helps, previously I saved a list of dictionaries into a jsonl file like this:
    # store the new version of the file
        with open(myfile, 'w') as f:
            f.write(json.dumps(dicts) + '\n')

Can somebody pinpoint my error with this?  I don't have much practice with json. thank you.

A: As you noticed, opening the file as text and using f.readlines() returns a list of 1 element: the full json content as str (a list of dicts)
So in the function
def jsonl_to_list(filename):
    with open(filename, 'r') as f:
        lines = f.readlines()

    return sorted(
        [json.loads(l.strip()) for l in lines],
        key=lambda x: (x["target_currency"], x["date"])
    )

inner variable x is not a single dict, but a list of all your dicts. That's why you got an error TypeError: list indices must be integers or slices, not str when trying to access single dict value on a list of dicts.
A possible solution would be to rebuild your list of dicts after reading lines (actually, the single line of your file).
def jsonl_to_list(filename):
    with open(filename, 'r') as f:
        lines = f.readlines()
    single_line = lines[0].strip()
    dicts = json.loads(single_line)
    return sorted(
        dicts,
        key=lambda x: (x["target_currency"], x["date"])
    )

Or better, directly parse the whole file using json.load() then sort the sorted list of dicts
def jsonl_to_list(filename):
    with open(filename, 'r') as f:
        dicts = json.load(f)

    return sorted(
        dicts,
        key=lambda x: (x["target_currency"], x["date"])
    )


text:
Q: Rails not recognizing commands I have created a Rails project but when I issues commands such as rails s, or rails c from within the project directory I get:
The program 'rails' can be found in the following packages:
 * ruby-railties-3.2
 * ruby-railties-4.0
Try: sudo apt-get install <selected package>
Do I need to set my path variable? Please help!

A: You need to install the gems in your gemfile, using bundler. From the root of your app, type bundle. Next, run your commands using bundler, like bundle exec rails c or bundle exec rails s.


text:
Q: Get random number from set deprecation I am trying to get a random n number of users from a set of unique users.
Here is what I have so far
users = set()

random_users = random.sample((users), num_of_user)

This works well but it is giving me a deprecated warning. What should I be using instead? random.choice doesn't work with sets
UPDATE
I am trying to get reactions on a post and want them to be unique which is why I used a set. Would it be better to stick with a list for this?
users = set()
    for reaction in msg.reactions:
        async for user in reaction.users():
            users.add(user)

A: Convert your set to a list.

*

*by using the list function:
random_users = random.choices(list(users),k=num_of_user)

*by using * operator to unpack your set or dict:
random_users = random.choices([*users],k=num_of_user)

Solution 1. is 3 char longer than the 2., but solution 1. is more literal - to me.
It is not guaranteed that you will get the same result for the list order through different executions, python versions and platforms, therefore you may end up with different random result, despite a careful random number generator initialization. To resolve this issue, order your list.
You can also store the users in a list, and make the elements unique later with set, and then convert again to a list. For this, a common way is to convert your list to a set, and back to a list again.

A: FWIW, random.sample() in Python 3.9.2 says this when passed a dict:
TypeError: Population must be a sequence.  For dicts or sets, use sorted(d).

And this solution does seem to work for both set and dict inputs.


text:
Q: Oracle 12c query performance varies based on schema/user I have a strange (to me) performance issue. Based on the schema that runs the query I received very different performance. Here's my setup.
Oracle 12c DB
    SAMPLE schema/user
       WIDGET table (300,000 rows/10 columns of varchars, nvarchars, dates, and numbers)
    USER1 schema/user
    USER2 schema/user
    DBA1 schema/user
--SELECT granted on WIDGET table to USER1 and USER2.
--DBA1 already has access to all table accross all schemas and has many more privs.

When I execute either of the following:
select * from SAMPLE.WIDGET;
select count(1) from SAMPLE.WIDGET;

It takes about 0.5 seconds in SAMPLE schema or DBA1 schema. It takes about 10 seconds in USER1 and USER2 schema.
So I'm looking for the following:
Under what condition(s) can query performance in Oracle differ based on the user you are logged in to when you execute a query?

A: You can try to check what the current consumer group for the different sessions are. I.e. log in as SAMPLE and USER1 and run
SELECT SID,SERIAL#,USERNAME,RESOURCE_CONSUMER_GROUP FROM V$SESSION
    WHERE USERNAME IN ('SAMPLE','USER1','DBA1');

You can also check what the actual plans are assigned as DBA:
SELECT * FROM DBA_RSRC_CONSUMER_GROUP_PRIVS
    WHERE GRANTEE IN ('SAMPLE','USER1','DBA1');

This is designed to grant different resources for users (and admins) and might explain what you see. The plan should actually be shared across all executing users (it remembers the user which parsed it first). Just to be sure, auto trace the execution for the two different users.


text:
Q: Splitting Python MeshGrid Into Cells Problem Statement
Need to split an N-Dimensional MeshGrid into "cubes":
Ex)
2-D Case:
(-1,1) |(0,1) |(1,1)
(-1,0) |(0,0) |(1,0)
(-1,-1)|(0,-1)|(1,-1)
There will be 4 cells, each with 2^D points:
I want to be able to process the mesh, placing the coordinate points of each cell into a container to do further processing.
Cells =   [{(-1,1) (0,1)(-1,0),(0,0)},

          {(0,1),(1,1),(0,0),(1,0)},

          {(-1,0),(0,0)(-1,-1),(0,-1)}

          {(0,0),(1,0)(0,-1),(1,-1)}]

I use the following to generate the mesh for an arbitrary dimension d:
grid = [np.linspace(-1.0 , 1.0, num = K+1) for i in range(d)]
res_to_unpack = np.meshgrid(*grid,indexing = 'ij')

Which has output:
[array([[-1., -1., -1.],
   [ 0.,  0.,  0.],
   [ 1.,  1.,  1.]]), array([[-1.,  0.,  1.],
   [-1.,  0.,  1.],
   [-1.,  0.,  1.]])]

So I want to be able to generate the above cells container for a given D dimensional mesh grid. Split on a given K that is a power of 2.
I need this container so for each cell, I need to reference all 2^D points associated and calculate the distance from an origin.
Edit For Clarification
K should partition the grid into K ** D number of cells, with (K+1) ** D points. Each Cell should have 2 ** D number of points. Each "cell" will have volume (2/K)^D.
So for K = 4, D = 2
Cells = [ {(-1,1),(-0.5,1),(-1,0.5),(-0.5,0.5)},
          {(-0.5,1),(-0.5,0.5)(0.0,1.0),(0,0.5)},
            ...
          {(0.0,-0.5),(0.5,-0.5),(0.0,-1.0),(0.5,-1.0)},
          {(0.5,-1.0),(0.5,-1.0),(1.0,-0.5),(1.0,-1.0)}]

This is output for TopLeft, TopLeft + Right Over, Bottom Left, Bottom Left + Over Left. There will we 16 cells in this set, each with four coordinates each. For increasing K, say K = 8. There will be 64 cells, each with four points.

A: This should give you what you need:
from itertools import product
import numpy as np

def splitcubes(K, d):
    coords = [np.linspace(-1.0 , 1.0, num=K + 1) for i in range(d)]
    grid = np.stack(np.meshgrid(*coords)).T

    ks = list(range(1, K))
    for slices in product(*([[slice(b,e) for b,e in zip([None] + ks, [k+1 for k in ks] + [None])]]*d)):
        yield grid[slices]

def cubesets(K, d):
    if (K & (K - 1)) or K < 2:
        raise ValueError('K must be a positive power of 2. K: %s' % K)

    return [set(tuple(p.tolist()) for p in c.reshape(-1, d)) for c in splitcubes(K, d)]

Demonstration of 2D case
Here's a little demonstration of the 2D case:
import matplotlib.pyplot as plt

def assemblecube(c, spread=.03):
    c = np.array(list(c))
    c = c[np.lexsort(c.T[::-1])]

    d = int(np.log2(c.size))
    for i in range(d):
        c[2**i:2**i + 2] = c[2**i + 1:2**i - 1:-1]

    # get the point farthest from the origin
    sp = c[np.argmax((c**2).sum(axis=1)**.5)]
    # shift all points a small distance towards that farthest point
    c += sp * .1 #np.copysign(np.ones(sp.size)*spread, sp)

    # create several different orderings of the same points so that matplotlib will draw a closed shape
    return [(np.roll(c, i, axis=1) - (np.roll(c, i, axis=1)[0] - c[0])[None,:]).T for i in range(d)]

fig = plt.figure(figsize=(6,6))
ax = fig.gca()

for i,c in enumerate(cubesets(4, 2)):
    for cdata in assemblecube(c):
        p = ax.plot(*cdata, c='C%d' % (i % 9))

ax.set_aspect('equal', 'box')
fig.show()

Output:

The cubes have been shifted slightly apart for visualization purposes (so they don't overlap and cover each other up).
Demonstration of 3D case
Here's the same thing for the 3D case:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')

for i,c in enumerate(cubesets(2,3)):
    for cdata in assemblecube(c, spread=.05):
        ax.plot(*cdata, c=('C%d' % (i % 9)))

plt.gcf().gca().set_aspect('equal', 'box')
plt.show()

Output:

Demonstration for K=4
Here's the output for the same 2D and 3D demonstrations as above, but with K=4:


text:
Q: How to call the API using OAuth 1.0? I'm having a bad time calling the API after successfully retrieving the user's access_token and his secret_token, like so:
{
    oauth_token: '4xxxxxxxx-asdasdasd......',
    oauth_token_secret: 'XXX........',
    user_id: '4xxxxxxxx'
}

I retrieved those in a user sign-in in behalf of my application. For example, like Twitter sign-in implementation.
Now for retrieving data from an API
I am not sure about the specification for OAuth 1.0, but I know in OAuth 2.0 you can simply use 'Authorization: Bearer ' . $accessToken in the header. Is OAuth 1.0 requires generating another signature for each API call?
I Have searched in this matter and did not found a clear solution.
Thanks before

A: Generally for OAuth1.0 the Authorization header is sent with a value of OAuth and a bunch of fields. There is a spec about it, and also a signature is generated and added to that string, but you don't have to do that yourself.
You can use the request module. For example here is how you can get the user's profile for Twitter:
request.get('https://api.twitter.com/1.1/users/show.json', {
  oauth:{
    consumer_key:'...',
    consumer_secret:'...',
    token:'...',
    token_secret:'...'
  },
  qs:{user_id:'...'} // or screen_name
}, function (err, res, body) {})

You can use the above code with any OAuth1.0 provider. All you need to pass is your application and user credentials. In very rare cases you might need to pass additional options (check out the oauth signing section).


text:
Q: I don't understand the working principle of this metal detector circuit? The circuit below is a metal detector circuit. The inductor serves as a "sensor" to detect metal. The tone of the speaker changes when a metal is detected. However, I don't know anything about how the circuit works internally. I can only do the circuit connection. Please can someone explain how how the internal circuit of the 555 time makes this possible? What mode is the IC operating? How does each passive component (resistors, inductors and capacitors) in the circuit functions? I need it urgently!

A: It's based on the fairly common 555 feedback astable circuit.
this uses the output pin instead of the discharge pin in the timing circuit.

https://www.electronics-tutorials.ws/waveforms/555-circuits-part-1.html
this circuit has been modified with a capacitor and the sense coil inductor in parallel with the timing resistor  this allows conductors and magnetic materials that come close to the sense coil to change its inductance and that change the allow less or more current to flow changing the frequency


text:
Q: I thought, I've thought or I've been thinking? For example,
1. I have been thinking I wanna go abroad since I was a child.
2. I have thought I wanna go abroad since I was a child.
3. I thought I wanna go abroad since I was a child.
Which is better?

A: "I thought" tends to refer to a single, momentary idea, or a long-held belief, for example:

*

*I thought we'd go to the zoo today.

*I always thought pasta grew on trees

When we say "I've been thinking" it is to indicate a prolonged and specific period of thought, for example:

*

*I've been thinking, and I've reached a decision.

Neither of these really fit your example well, because you're trying to convey that this isn't an idea that came into your head overnight, but neither can you point to a specific period of deep thought.
That doesn't matter though - because you don't need either in your example as you can just say "I have wanted to go abroad since I was a child". This draws out the desire to go, rather than the thought to go.
In fact, saying "I think I want to..." sounds like you're not sure.


text:
Q: add namespace to your javascript I have worked on google map api few years ago and wrote a little reusable utility. At that time adding google map api reference does add all the api classses in your page's global namespace. As this is working sample
<script src="http://maps.google.com/maps?SOMEPARAMETERS">
<script>
var map= new GMap2(document.getElementById("map_canvas"));
var point= new LatLng(31,75);
var line= new Polyline(OPTIONS);
</script>

In v3, all Google Maps JavaScript API code is stored in the google.maps.* namespace instead of the global namespace. Most objects have also been renamed as part of this process and some more changes are done.
Now you have to write the above code as follows
<script src="APIURL">
<script>
var map= new google.map.Map(document.getElementById("map_canvas"));
var point= new google.mapLatLng(31,75);
var line= new google.map.Polyline(OPTIONS);
</script>

ISSUE
I wrote a library back in Google v2  API time and used in number of projects and was working great. But now I am working on a new project and using Google V3 API and want to reuse that old v2 library. But adding v3 library doesn't add the API classes in global namespace and my library doesn't work. Is there any way we can add namespace to our JavaScript file like we did in C# on top and it allows us to write the classes without appending the namespace

A: You might be able to just use references:
(function() { // A scoping function to avoid creating glboals
    var GMap2 = google.map.Map;
    var LatLng = google.map.LatLng;
    var Polyline = googlemap.Polyline;

    // ...your code using the above here...
})();

This assumes, though, that the arguments haven't changed.
Alternately, you could use the Facade pattern:
function GMap2(/*...relevant args...*/)

    return new google.map.Map(/*...relevant args here, possibly modified...*/);
}

(And similar for others.)
(That works even if you use new with GMap2 because the result of the new expression will be the object you return from the constructor function if you return an object.)


text:
Q: How to make this javascript work? I'm trying to make a recursive anonymous function.
Here is the function :
(function (i) {
    console.log(i);
    if (i < 5) this(i + 1)
})(0)

I know "this" is the window object. Is there a way to call the function ?

A: The arguments.callee property can be used.
(function(i){console.log(i);if(i<5)arguments.callee(i+1)})(0)

Another method to achieve the same functionality is by naming function. Outside the scope, the name will not be available:
(function tmp(i){console.log(i);if(i<5)tmp(i+1)})(0); //OK, runs well
alert(typeof tmp); // Undefined

Note that use of the arguments.callee property is forbidden in strict mode:

"use strict";
(function(){arguments.callee})();

throws:

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

A: Ah... the functional forms of recursion.... [[[flashback to comp sci class]]]
You could use a helper function:
function X(f) { return f.apply(this, arguments); }
X(function(me, n) { return n<=1 ? n : n*me(me,n-1); }, 6);

(which returns 720; this is the factorial function, the canonical example of recursion)
This could in turn be anonymized:
(function (f) { return f.apply(this, arguments); })(
  function(me, n) { return n<=1 ? n : n*me(me,n-1); },
  6);

or specialized to functions of one argument, to avoid apply and arguments:
(function (f,x) { return f(f,x); })(
  function(me, n) { return n<=1 ? n : n*me(me,n-1); },
  6);

(both of which also return 720)
This trick of using a helper function allows your function to receive itself as its first argument, and thereby call itself.
To adapt your example:
(function (f,x) { return f(f,x); })(
  function(me, i) { console.log(i); if (i<5) me(me,i+1); },
  0)

which works as expected in Firebug (logs 0,1,2,3,4,5 to console)

A: You give a name to anonymous function, here I give it a name "_", although it is named, but it is still anonymous.
(function _( i ) {
  console.log(i);
  if (i < 5){ _(i + 1); }
})(0);


text:
Q: What type of column will support datetime with offset? During liquibase script execution I'm filling the table with data. Data has one column with the next value: 2017-10-03T07:11:00.0000000Z which I'm struggling with to parse into the column:
liquibase.exception.MigrationFailedException: Migration failed for change set /changelog/00000000000001.xml::00000000000001::IAmUser:
 Reason: java.lang.NumberFormatException: For input string: "0000000Z"

I've tried multiple column types but none of them worked: datetime, datetime2, timestamp (datetimeoffset doesn't work with MySQL).
How can I parse this date into SQL column?

A: Use datetime(6) / timestamp(6) where 6 is the precision for fractional seconds. Also, leave out the Z from the end of the date string.


text:
Q: Exception in task 0.0 in stage 0.0 when running pyspark when I was running pyspark in python, and the traceback:
17/02/17 00:01:25 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
org.apache.spark.SparkException: Python worker did not connect back in time
at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:138)
at org.apache.spark.api.python.PythonWorkerFactory.create(PythonWorkerFactory.scala:67)
at org.apache.spark.SparkEnv.createPythonWorker(SparkEnv.scala:116)
at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:128)
at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.SocketTimeoutException: Accept timed out
at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
at

How can I solve it?


text:
Q: Probability of transmitting a signal through a network of transmitters. We have a network of four transmitters $A$, $B$, $C$ and $D$. What is the probability of transmitting a signal through the network if all transmitters work independently and the probabilities of transmitting a signal by each transmitter are $0.7$, $0.8$, $0.9$ adn $0.6$, respectively.

My take is the following. The probability of transmitting a signal through $C$ and then $D$ is $P(C \cap D) = 0.9 \cdot 0.6 = 0.54$. The event "a signal transmitted through $A$ or $B$" consists of three disjoint events: $\overline A \cap B$, $A \cap \overline B$ and $A \cap B$. We have $P(A \cup B) = P(\overline A \cap B) + P(A \cap \overline B) + P(A \cap B) = 0.3 \cdot 0.8 + 0.7 \cdot 0.2 + 0.7 \cdot 0.8 = 0.94$.
So the probability of transmitting a signal through the entire network is:
$$P(A \cup B) \cdot P(C \cap D) = 0.94 \cdot 0.54 = 0.5076$$. Is that correct?

A: Yes that is correct
Another calculation could be $$P\left(\overline{(\overline A \cap \overline B)} \cap C \cap D\right)=(1-(1-0.7)\times (1-0.8))\times 0.9\times0.6 = 0.5076$$


text:
Q: Laravel Dusk Connection refused after clear install using Sail

*

*Dusk Version: v6.15.0

*Sail Version: v1.7.0

*Laravel Version: v8.43.0

*PHP Version: 8.0.5

*Docker Engine Version: 20.10.6

*O.S.: macOs BigSur 11.3.1

Scenario:
After a clear install of Dusk on a new Laravel project that uses Sail a "Connection Refused" error is thrown
./vendor/bin/sail artisan dusk
PHPUnit 9.5.4 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 00:00.855, Memory: 20.00 MB

There was 1 error:

1) Tests\Browser\ExampleTest::testBasicExample
Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session with params: {"capabilities":{"firstMatch":[{"browserName":"chrome","goog:chromeOptions":{"args":["--window-size=1920,1080","--disable-gpu","--headless"]}}]},"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"args":["--window-size=1920,1080","--disable-gpu","--headless"]}}}

Failed to connect to localhost port 9515: Connection refused

/var/www/html/vendor/php-webdriver/webdriver/lib/Remote/HttpCommandExecutor.php:332
/var/www/html/vendor/php-webdriver/webdriver/lib/Remote/RemoteWebDriver.php:135
/var/www/html/tests/DuskTestCase.php:46
/var/www/html/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:218
/var/www/html/vendor/laravel/framework/src/Illuminate/Support/helpers.php:234
/var/www/html/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:219
/var/www/html/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:97
/var/www/html/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:65
/var/www/html/tests/Browser/ExampleTest.php:21

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

I followed all instructions I found at Sail Docs and at Dusk Docs with no changes. My docker environment was completely cleared from old images and containers used by Laravel Sail Projects.
At first glance I tried editing anything on the project simply running dusk, so the APP_URL was the default one on .env file
APP_URL=http://selenium.test

But, after I read the docs at Dusk Docs the following sentence "Next, set the APP_URL environment variable in your application's .env file. This value should match the URL you use to access your application in a browser." I set it to the one I use on the browser
APP_URL=http://localhost

Steps To Reproduce:

*

*curl -s "https://laravel.build/selenium?with=selenium" | bash

*cd selenium && ./vendor/bin/sail up -d

*./vendor/bin/sail composer require --dev laravel/dusk

*./vendor/bin/sail artisan dusk:install

*./vendor/bin/sail artisan dusk

*Try changing the APP_URL in .env and run the 5 point again

I cannot figure out why the problem occurs


text:
Q: Does free iWork iOS entitle older devices? I wonder whether old iOS devices would become entitled to install a free copy of iWork after purchasing a new device.

A: Yes, providing you use the same Apple ID. When you purchase iWork for free on your new device, it is added to your purchases and then available to download on your other devices.


text:
Q: How do I loop through the elements of an object and return its value in TypeScript&React? I have the following enum and state:
enum FilterId {
    filter1,
    filter2,
    filter3,
    filter4,
    filter5,
}

type FiltersInComponent = { [key in FilterId]: boolean };

const [appliedFilters, setAppliedFilters] = React.useState<FiltersInComponent>()

Question 1: How do I initialise the appliedFilters state to (in short notation):
{
  filter1: false,
  filter2: false,
  filter3: false,
  filter4: false,
  filter5: false
}

Question 2: How do I loop through appliedFilters and display a checkbox?
I have the following so far:
{Object.keys(appliedFilters)
    .filter((v) => !isNaN(Number(v)))
    .map((option) => {
        const isChecked: boolean = appliedFilters[option];
        return (
            <>
                <Checkbox checked={isChecked} />
                <Typography>
                    {optionMessage(Number(option))}
                </Typography>
            </>
        );
     })}

But I'm getting the following error for appliedFilters[option]
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FiltersInComponent'.
  No index signature with a parameter of type 'string' was found on type 'FiltersInComponent'.

A: The problem is in the way you've defined this enum.
You're looking for something more along these lines:
type FilterId = 'filter1' | 'filter2' | 'filter3' | 'filter4' | 'filter5'

const foo = () => {
  type FiltersInComponent = { [key in FilterId]: boolean }

  const [appliedFilters, setAppliedFilters] =
    React.useState<FiltersInComponent>({
      filter1: false,
      filter2: false,
      filter3: false,
      filter4: false,
      filter5: false,
    })

As you have it right now [key in FilterId] evaluates to
type FiltersInComponent = {
    0: boolean;
    1: boolean;
    2: boolean;
    3: boolean;
    4: boolean;
}

as your enum values are the defaults of 0,1,2 etc. You could if you wanted, add enum values of 'filter1' etc  and then use a string template literal to extract type FilterIdType = ${FilterId}; But if you're going to modify your enum and have control over it you're better off just going for the simpler union type.


text:
Q: apply lamba to df based on condition If I can make up a df with some random data
import numpy as np
import pandas as pd
np.random.seed(11)

rows,cols = 24,3
data = np.random.rand(rows,cols)
tidx = pd.date_range('2019-01-01', periods=rows, freq='H')
df = pd.DataFrame(data, columns=['Temperature1','Temperature2','Value'], index=tidx)

How could I use the lamba function to add 5000 to each row to the columns Temperature1 & Temperature2 only if the df index hour is less than 6?
If I use
for hour in df.index.hour:
    if hour < 6:# and name contains 'Temperature'
        df = df.apply(lambda x: x + 5000)

The above code isnt correct it adds 5000 to all rows in the df. Any tips greatly appreciated..

A: You can do with loc:
# get the temperature columns
temp_cols = [x for x in df.columns if 'Temperature' in x]

# update with loc access
df.loc[df.index.hour<6, temp_cols] += 5000

Output:
                     Temperature1  Temperature2     Value
2019-01-01 00:00:00   5000.180270   5000.019475  0.463219
2019-01-01 01:00:00   5000.724934   5000.420204  0.485427
2019-01-01 02:00:00   5000.012781   5000.487372  0.941807
2019-01-01 03:00:00   5000.850795   5000.729964  0.108736
2019-01-01 04:00:00   5000.893904   5000.857154  0.165087
2019-01-01 05:00:00   5000.632334   5000.020484  0.116737
2019-01-01 06:00:00      0.316367      0.157912  0.758980
2019-01-01 07:00:00      0.818275      0.344624  0.318799
2019-01-01 08:00:00      0.111661      0.083953  0.712726
2019-01-01 09:00:00      0.599543      0.055674  0.479797
2019-01-01 10:00:00      0.401676      0.847979  0.717849
2019-01-01 11:00:00      0.602064      0.552384  0.949102
2019-01-01 12:00:00      0.986673      0.338054  0.239875
2019-01-01 13:00:00      0.796436      0.063686  0.364616
2019-01-01 14:00:00      0.070023      0.319368  0.070383
2019-01-01 15:00:00      0.290264      0.790101  0.905400
2019-01-01 16:00:00      0.792621      0.561819  0.616018
2019-01-01 17:00:00      0.361484      0.168817  0.436241
2019-01-01 18:00:00      0.732825      0.062888  0.020733
2019-01-01 19:00:00      0.770548      0.299952  0.701164
2019-01-01 20:00:00      0.734668      0.932905  0.400328
2019-01-01 21:00:00      0.358438      0.806567  0.764491
2019-01-01 22:00:00      0.652615      0.810967  0.642215
2019-01-01 23:00:00      0.957444      0.333874  0.738253

A: Boolean select contains Temperature
m=df.columns.str.contains('Temperature')
m

Select rows with hour<6 and Update by;
df.loc[df.index.hour<6, m] += 5000
df


text:
Q: How to use function on every item row in specific column with Pandas/Python I have a simple DataFrame in Pandas that one of the column contains date in this format day-month-year.
I need to make another column that contains which weekday is that. I wrote this function that works with simple argument like '12-3-1999':
def convert_date_to_weekday(date_string):
  # convert string to date object
  date_object = datetime.strptime(date_string, '%d-%m-%Y').date()
  # convert date object to weekday string
  print(date_object.strftime("%A"))

Unfortunetely this doesn't work:
df['Weekday'] = convert_date_to_weekday(df['Date'])

How to make it work?

A: You can use apply , which also a recommended way with pandas
def convert_date_to_weekday(date_string):
  # convert string to date object
  date_object = datetime.strptime(date_string, '%d-%m-%Y').date()
  # convert date object to weekday string
  # print(date_object.strftime("%A"))
  return date_object.strftime("%A")

df['Weekday'] = df['Date'].apply(lambda x: convert_date_to_weekday(x)))

A: try
df['Weekday'] = df['Date'].apply(lambda x: convert_date_to_weekday(x))

and use return in your function instead of print

A: Try:
def convert_date_to_weekday(date_string):
  # convert string to date object
  date_object = datetime.strptime(date_string, '%d-%m-%Y').date()
  # convert date object to weekday string
  return date_object.strftime("%A")

Along with your apply line.

A: You probably want to use apply() method of the pandas dataframe:
df['Weekday'] = df['Date'].apply(convert_date_to_weekday)

But your convert_date_to_weekday should return the result instead of printing.

A: You can use the apply() function.
df['Weekday'] = df['Date'].apply(lambda d: convert_date_to_weekday(d))

Also, change your print(date_object.strftime("%A"))  to return date_object.strftime("%A")


text:
Q: how to count the words of a string in ruby I want to do something like this
def get_count(string)
 sentence.split(' ').count
end

I think there's might be a better way, string may have built-in method to do this.

A: I believe count is a function so you probably want to use length.
def get_count(string)
    sentence.split(' ').length
end

Edit: If your string is really long creating an array from it with any splitting will need more memory so here's a faster way:
def get_count(string)
    (0..(string.length-1)).inject(1){|m,e| m += string[e].chr == ' ' ? 1 : 0 }
end

A: If the only word boundary is a single space, just count them.
puts "this sentence has five words".count(' ')+1 # => 5

If there are spaces, line endings, tabs , comma's followed by a space etc. between the words, then scanning for word boundaries is a possibility:
puts "this, is./tfour   words".scan(/\b/).size/2

A: I know this is an old question, but this might help someone stumbling here. Countring words is a complicated problem. What is a "word"? Do numbers and special characters count as words? Etc...
I wrote the words_counted gem for this purpose. It's a highly flexible, customizable string analyser. You can ask it to analyse any string for word count, word occurrences, and exclude words/characters using regexp, strings, and arrays.
counter = WordsCounted::Counter.new("Hello World!", exclude: "World")
counter.word_count #=> 1
counted.words      #=> ["Hello"]

Etc...
The documentation and full source are on Github.

A: using regular expression will also cover multi spaces:
sentence.split(/\S+/).size

A: String doesn't have anything pre-built to do what you wanted. You can define a method in your class or extend the String class itself for what you want to do:
def word_count( string )
  return 0 if string.empty?

  string.split.size
end

A: Regex split on any non-word character:
string.split(/\W+/).size

...although it makes apostrophe use count as two words, so depending on how small the margin of error needs to be, you might want to build your own regex expression.

A: I recently found that String#count is faster than splitting up the string by over an order of magnitude.
Unfortunately, String#count only accepts a string, not a regular expression. Also, it would count two adjacent spaces as two things, rather than a single thing, and you'd have to handle other white space characters seperately.

A: p "  some word\nother\tword.word|word".strip.split(/\s+/).size #=> 4

A: I'd rather check for word boundaries directly:
"Lorem Lorem Lorem".scan(/\w+/).size
=> 3

If you need to match rock-and-roll as one word, you could do like:
"Lorem Lorem Lorem rock-and-roll".scan(/[\w-]+/).size
=> 4


text:
Q: ffmpeg - create video from images - has no audio in output video 1) I have created the few images from my original xyz.mp4 (using ffmpeg)
2) I am again creating the video from the images but the output.mp4 does not have the audio.
I use the following command to create the video from images.
ffmpeg -b:v 850 -r 10 -i out%d.png -s 640X480 -vcodec libx264 -sameq output.mp4
Kindly let me know the the way for following steps
1) create images from video (.mp4)
2) create video(.mp4) from those images ( with audio in output file)
Thank you.

A: For the output video to have an audio, you must have an audio source that has the audi recorded for the video. You cannot expect the images to produce the sound right? So will also need a sound recorder along with the screen recorder, and then use ffmpeg to convert the video and audio file together into output.mp4.
Here are some links to audio recorders :
[Link1], [Link2]...
The second link I have tried and works fine, just compile and run. Once you have this audio file you can convert the images and audio file to an output video with the help of these links.
[Link1],[Link2],[Link3]..
or use:
ffmpeg -r 4 -i img%d.png -i audio.wav -acodec copy -r 30 output.avi


text:
Q: Alternative to replace all html entities by characters in Web Worker I'm trying to get my script (jQuery Terminal library) to run in Web Worker with minimal jQuery replacement and no JS-DOM. I have bare_text functions like this:
// -------------------------------------------------------------------------
function bare_text(string) {
    if (!string.match(/&/)) {
        return string;
    }
    return $('<span>' + safe(string) + '</span>').text();
}
// -------------------------------------------------------------------------
function text(string) {
    return bare_text($.terminal.strip(string));
}
// -------------------------------------------------------------------------
function safe(string) {
    if (!string.match(/[<>&]/)) {
        return string;
    }
    return string.replace(/&(?![^;]+;)/g, '&')
        .replace(/>/g, '>').replace(/</g, '<');
}

I need to change this function to do the same but without DOM and jQuery. Any options?
Also if you know how to simplify the other way those functions I would be very thankful. So what those functions do (the code is very old) it replace any html entities with proper characters and it ignore html tags that are treated as normal text.

A: My solution was to go to website that show all html entites (example: https://www.freeformatter.com/html-entities.html)
and run this code in console:
[].concat.apply([], [...document.querySelectorAll('.bordered-table')].map(table => {
    var t = [...table.querySelectorAll('tbody tr')];
    return t.map(tr => ({
      entity: tr.querySelector('td:nth-child(2)').innerText,
      char: tr.querySelector('td:nth-child(1)').innerText
    })).filter(o => o.entity);
})).reduce((acc, obj) => (acc[obj.entity] = obj.code, acc), {});

then you can convert that to string using JSON.stringify(arr, true, 4); you can copy/paste into your code and use like this:
var entities = {...}; // map from above

function renderEntities(str) {
    return str.replace(/&#(x?)([0-9]+);/g, function(_, hex, code) {
        code = parseInt(code, hex ? 16 : 10);
        return String.fromCharCode(code);
    }).replace(/(&[^;]+;)/g, function(_, entity) {
        // if entity is not recognized it need to be
        // inserted as is example &foo;
        return entities[entity] || entity;
    });
}


text:
Q: Write a docx file using Apache POI Word JAVA I am using Apache POI Word to create a docx file in java.
Right now I am using the following code
XWPFDocument document = new XWPFDocument();
  XWPFParagraph tmpParagraph = document.createParagraph();
  XWPFRun tmpRun = tmpParagraph.createRun();
  tmpRun.setText(newDocxData);

  try {
     document.write(new FileOutputStream(new File("C:\\test.docx")));
  } catch (FileNotFoundException ex) {
     Logger.getLogger(PersonnelFileHandlingStreamAttributesHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
  } catch (IOException ex) {
     Logger.getLogger(PersonnelFileHandlingStreamAttributesHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
  }

But this puts the whole text under one paragraph.
But I want to put the given sttring into the document as it is.
I tried converting the string to a input stream and passing it when creating the document
XWPFDocument document = new XWPFDocument(inputstream);

But it also gives an error. Any solution for this?
This is a sample of the string I want to write.

10 - SchaumburgIllinois - US       xxx                                                                                2018-06-28
Certificate of employment
This is to certify that John is currently employed at xxx as Manager.
John has worked at xxx since 07-DEC-00.
Current salary is SalaryPerMonth SalaryCurrencyCode per month, working
  100 % of a 40-hour week.

A: The Problem here is that you are retrieving all the text in one String. you should parse all the body element from your document by using "getBodyElements" and then loop through all of them and initiate a paragraph for each element. here is an example of how to do that:
 public static XWPFDocument MergeDocument(XWPFDocument source, XWPFDocument output){

        for(IBodyElement element : source.getBodyElements()) {
           if(element instanceof XWPFParagraph) {
                XWPFParagraph paragraph = (XWPFParagraph)element;
                if(paragraph.getStyleID()!=null){
                    XWPFStyles styles= output.createStyles();
                    XWPFStyles stylesdoc2= source.getStyles();
                    styles.addStyle(stylesdoc2.getStyle(paragraph.getStyleID()));
                }
                XWPFParagraph x= output.createParagraph();
                x.setStyle(((XWPFParagraph) element).getStyle());
                XWPFRun runx=x.createRun();
                runx.setText(((XWPFParagraph) element).getText());
            }
        }
return output;
    }


text:
Q: The use of the present perfect and the past parfect in context Let's say that I have just experieced a sharp pain and want to say that this is the worst pain by now. Do I say

I have never experienced such a pain before

or

I had never experienced such a pain before?

I think that should use the present perfect because the pain have just happened. But my native English speking friend says that either can actually be used. I am curious to know what other native English speakers have to say about that. He also said that if it were yesterday it definetly has to be the past perfect. For example:

I had a terrible pain yesterday. I had never experieced anything like that before.

Could the present perfect be used in this sentence?

A: Although I'm not a native speaker, here's my take:
A) Yes, both can be used. If you choose Present Perfect, you're talking about an experience you had in your life - that's it. If you choose Past Perfect, you're also talking about an experience in your life, but with a specific moment in time (in the past).
B) No, Present Perfect can't be used in this case, because (as said in (A)) you're mentioning a specific moment in the past.

A: If you say " I have never experienced a pain like that before", you are speaking from the present. You have never felt such a pain before in your life, before this present moment.  If you use "I had never felt such a pain before" you are talking about the pain you felt yesterday, which is now the past and you had never felt such a pain before that past moment yesterday. So, you use present perfect for the now and past perfect for the past. You can't change sentence 3 into present perfect, in my opinion.

A: This question is very simple, as regards speech:
I have never experienced such a pain before. [Ok,past, non-specific]
or
1) I had never experienced such a pain before.
[Ok in a specific conversation or context, like the one below. It presupposes a conversation where the simple past event is implied or mentioned. The event is not provided here by the OP.)]
There is no rule that states you can't use the past perfect as the sole verb. However, when it is the sole verb, it implies some other event occurred before it. And the speakers are aware of it OR the event is mentioned earlier in a written text.
2) I had a terrible pain yesterday. I had never experienced anything like that before.
Remember the timeline, taken from the website of Tony Hartley.
http://tonyeosenglish.weebly.com/


text:
Q: javascript split or regex How can I split this string "q.attributes['case.ticketnumber'].value.keyValue" so I get an array with these elements?
["q", "attributes['case.ticketnumber']", "value", "keyValue"]

A: You can use String#match method, with following regex /[^.]+\[[^\]]+\][^.]*|[^.]+/g

console.log("q.attributes['case.ticketnumber'].value.keyValue".match(/[^.]+\[[^\]]+\][^.]*|[^.]+/g));

Regex explanation here.

Or use much better regex \w+(?:\['[^']*'\])? (@IsmaelMiguel suggested)

console.log("q.attributes['case.ticketnumber'].value.keyValue".match(/\w+(?:\['[^']*'\])?/g));

Regex explanation here.

Or use regex /\w+(\[[^\]]+\])?/g

console.log("q.attributes['case.ticketnumber'].value.keyValue".match(/\w+(\[[^\]]+\])?/g));

Regex explanation here.


text:
Q: Delphi - synhronize BitBlt with vsync (screen tearing) I've some problem with my Delphi (10.4) application, and I'm stuck for a few days now. So I hope someone can help me. I'm rewriting some old code.
Basically, I've a problem with BitBlt command and screen tearing.
My code is drawing some .bmp images (five images in five columns) on application main form (form is maximized). Resolution is 1920x1080 and screen is 27".
I prepare each .bmp image (each image is 300x900 px) in the background and then just BitBlt that .bmp to the main form canvas using BitBlt. I'm using 60 FPS. That is OK. My monitor refresh rate is 60 Hz.
But I'm seeing from time to time screen tearing.
I'm looking for a few days how to synchronize my BitBlt operations with sync but no luck.
I've read something about flip scree but that should be the same as BitBlt in the way I'm using it right now?
I've found some old posts to read HW port, WaitForVerticalBlank, move to OpnGL (that is not an option for me), ....
But I'm not able to solve this.
Thanks....


text:
Q: Using request scoped managed bean in Primefaces JSF2.x JSF + Primefaces newbie. (using JSF 2.1, Primefaces 3.4.2)
I have a form that has an inner panelGroup that uses a Primefaces commandButton to fetch data to populate various form components. The partialSubmit gets around the validation issues of fields not yet populated so that works well. The page functions as intended but now I'm trying to tweak the implementation to be be 'cleaner'.
My question pertains to the JSF scoping I'm using for the backing bean the form is using. Using session scope, all is well but not when using request scoping. It is my understanding that both the 'final' submit (via another p:commandButton component) and this fetch button are both invoking a submit so that the response to either constitutes the completion of the request lifecycle. If I'm correct, it explains why I get (using requst scope) the following:
    java.lang.IllegalStateException: Cannot create a session after the response has been committed
when using the fetch button.
But clearly this 'breaks' my intent for the fetch request to merely cause the form to use updated data via the bean.
So, am I correct in my understanding that any design pattern that has the use of an intermediate submission (via the partialSubmit="true" commandButton (ajax behavior is enabled by default) will require the use of at least session scoped backing beans?
Ideally, a mechanism for having an implementation request versus a navigation level request would allow for these intermediate submits to be done within the context of 1 request.
Or do I need to do some additional research? (get a JSF 2.x book rather than use my 1.2 copy?)
MTIA for any feedback.
my fetch component:
<p:commandButton id="returningBtn" partialSubmit="true" value="Hit if returning"
    process="nameInfo" actionListener="#{player.loadReturning}" update="registrationForm">
    <p:resetInput target="registrationForm" />
</p:commandButton>

my final submit:
<p:commandButton tabindex="0" id="SubmitButton" value="Register"
   action="#{player.register}" update="regPage"/>

A:
The partialSubmit gets around the validation issues of fields not yet populated so that works well.

No it doesn't do that. It only sends the input fields specified in process attribute to the server instead of all input fields of the current form. It's exactly the process attribute which tells which inputs needs to be processed (converted, validated and updated). The partialSubmit="true" merely reduces the network bandwidth and request parameter parsing overhead. See also PrimeFaces blog on the subject.

The page functions as intended but now I'm trying to tweak the implementation to be be 'cleaner'. My question pertains to the JSF scoping I'm using for the backing bean the form is using. Using session scope, all is well but not when using request scoping.

The session scope is indeed the wrong scope for forms. You need either the request or the view scope. If your form has a certain state which needs to be remembered across subsequent submits on the same form, then you need the view scope. See also How to choose the right bean scope?

java.lang.IllegalStateException: Cannot create a session after the response has been committed

This is recognizeable as a bug in Mojarra which is fixed in 2.1.8. See also Adding <h:form> causes java.lang.IllegalStateException: Cannot create a session after the response has been committed for several workarounds if you can't upgrade.

So, am I correct in my understanding that any design pattern that has the use of an intermediate submission (via the partialSubmit="true" commandButton (ajax behavior is enabled by default) will require the use of at least session scoped backing beans? Ideally, a mechanism for having an implementation request versus a navigation level request would allow for these intermediate submits to be done within the context of 1 request.

As said, you need the view scope.

Or do I need to do some additional research? (get a JSF 2.x book rather than use my 1.2 copy?)

Definitely. Not only is the view scope new since JSF2, but also many, many other things are done differently (read: more elegantly) in JSF2 as compared to JSF1. You can find several links to sane JSF2 resources at the bottom of our JSF wiki page.


text:
Q: Push DependencyProperty back to ViewModel upon DataContext Change I dont know if I have some kind of design flaw in what I am writing but im a little stuck as to the approach I am currently trying to use.
I have a case in my ViewModel where I want to do clamping on certain values based on the current state of the user-control. For this to work, I need to bind to properties on that control and ensure that the ViewModel always knows about its current state.
In one instance, this works great. If a value changes on the control, the DependencyProperty of the View says, hey, ive changed. And the data is pushed to my ViewModel. Brilliant!
The problem arises when my ViewModel is switched out, and the View doesn't change. A great example of this would be the View's ActualWidth and ActualHeight. Upon a ViewModel switch (effectively removing the old one, and reinstantiating a new one). The DependencyPropertys will not change. Thus my new view model never recieves the data of the view.
This means that somehow my Control MUST know when its ViewModel changes. Right?
If this all makes sense, how do I go about "pushing" the new values to my view model. Even if they haven't changed?


text:
Q: Vue 2 with Quasar I am starting new project with Vue 2 and Quasar.
I am doing this npm install -g @quasar/cli , then quasar create app-name.
Quasar creates an application, but when I open some components,there is setup(){ } function. As I know it is a composition API feature and only in Vue 3. My vue-cli version is 4.5.15. How can I install Quasar, and start with Vue 2?

A: You can use an older Quasar version, try using the package @quasar/cli@1.2.2

A: you can use:
quasar create <folder_name> --branch v1

A: vue2 does now support the composition api (script setup), although it wouldn't have at the time the OP asked the question
https://blog.vuejs.org/posts/vue-2-7-naruto.html
The latest quasar v1 also supports this too