text:
Q: how can I send data from one class to a stateful widget in Flutter I want to be able to make progress bar where the value changes based on a function. My problem is I am working with 3 different files. The first file main_page_test.dart where the code for calling the function is held. enigma_test.dart where the code for the function is held. Finally, loading_alert_dialog.dart where I keep the code for the AlertDialog containing the ProgressBar
To clarify, I want the application to display the AlertDialog when the function is called in main_page_test.dart. While the function is running I want it to update the ProgressBar and pass the filename of the file it is working on encrypting.
If there is anything else I can clarify on please let me know.
Here is the relevant code for main_page_test.dart:
import 'dart:io';

import 'package:fluent_ui/fluent_ui.dart';
import 'package:file_picker/file_picker.dart';

import '../functions/enigma_test.dart';

class MainPageTest extends StatefulWidget {
  const MainPageTest({Key? key}) : super(key: key);

  @override
  State<MainPageTest> createState() => _MainPageTestState();
}

class _MainPageTestState extends State<MainPageTest> {
  final double _buttonTextSize = 20.0;
  final double _widgetWidth = 200.0;

  List<File>? _files;

  late final TextEditingController _textController;
  late final FlyoutController _flyoutController;

  @override
  void initState() {
    super.initState();
    _textController = TextEditingController();
    _flyoutController = FlyoutController();
  }

  @override
  void dispose() {
    _textController.dispose();
    _flyoutController.dispose();
    super.dispose();
  }

  void pickFiles() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['txt'],
      allowMultiple: true,
    );

    if (result != null) {
      setState(() {
        _files = result.paths.map((path) => File(path!)).toList();
      });
    } else {
      setState(() {
        _files = null;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: SizedBox(
              width: _widgetWidth,
              child: Button(
                onPressed: () {
                  pickFiles();
                },
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12.0),
                  child: Text(
                    'Choose Files',
                    style: TextStyle(
                      fontSize: _buttonTextSize,
                    ),
                  ),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12.0),
            child: SizedBox(
              width: _widgetWidth,
              child: Button(
                onPressed: () async {
                  await EnigmaTest().encrypt(_files!);
                },
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12.0),
                  child: Text(
                    'Encrypt',
                    style: TextStyle(
                      fontSize: _buttonTextSize,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Here is the relevant code for enigma_test.dart:
import 'dart:developer';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;

import 'package:encrypt/encrypt.dart';

class EnigmaTest {
  Future<void> encrypt(List<File> files) async {
    const String keyAsString = '123';
    final String encryptedPath = p.join(await _localPath, 'encrypted');
    final Key key = Key.fromUtf8(keyAsString.padRight(32, ' '));

    try {
      for (File file in files) {
        final contents = await file.readAsLines();
        // getting the name of the file without the extension
        final filename = p.basename(file.path);

        File encrypedFile =
            await File(p.join(encryptedPath, filename)).create(recursive: true);

        var sink = encrypedFile.openWrite();

        for (String line in contents) {
          if (line == '') {
            sink.writeln();
          } else {
            var encryptedLine = _aesEncryption(line, key);
            sink.writeln(encryptedLine);
          }
        }

        await sink.flush();
        await sink.close();
      }
    } catch (e) {
      //somethibng
      inspect(e);
    }
  }

  String _aesEncryption(String line, Key key) {
    final iv = IV.fromLength(16);
    final encrypter = Encrypter(AES(key));
    final encrypted = encrypter.encrypt(line, iv: iv);
    return encrypted.base16;
  }

  Future<String> get _localPath async {
    final documentsDirectory = await getApplicationDocumentsDirectory();
    final encyptedFilesDirectory =
        p.join(documentsDirectory.path, "Dead Man's Enigma Output");

    return encyptedFilesDirectory;
  }
}

Here is the code for loading_alert_dialog.dart:
import 'package:fluent_ui/fluent_ui.dart';

class MyLoadingAlertDialog {
  static showLoadingAlert(
      BuildContext context, String filename, double progress) {
    showDialog(
      context: context,
      builder: (context) {
        return ContentDialog(
          title: const Text('Progress'),
          content: Column(
            children: [
              SizedBox(
                width: double.infinity,
                child: ProgressBar(value: progress, strokeWidth: 8),
              ),
              Padding(
                padding: const EdgeInsets.all(4.0),
                child: Text(
                  'currently encrypting $filename...',
                  style: const TextStyle(
                      fontSize: 10.0, fontStyle: FontStyle.italic),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

A: Well, that looks like a job for a simple state management solution; the simplest one you could go would be Provider and using something as simple as a ValueNotifier and a ValueListenableBuilder, that way you can have the main class trigger notifications to another class (in your case, the dialog) via the ValueNotifier.
I did a simple example of how this would play out in a Gist. Run it through DartPad and see how it works.
Pretty much is creating a provided service FileProcessingService that serves as the inter-widget communication. The MainPageTest class picks the files, launches the encryption logic (EnigmaTest) as well as the dialog MyLoadingAlertDialog; the EnigmaTest, as it processes each file, sends notifications via a ValueNotifier of type String representing the current file being processed, while the MyLoadingAlertDialog has a ValueListenableBuilder widget listening on that ValueNotifier and updating accordingly, all via the FileProcessingService provided service.
Check out the bottom animation of when you run the Gist on DartPad and how the communication goes. Hope this works for your purposes.


text:
Q: Python file search program not fast enough I wrote the following code for searching a file on your computer:
import os, sys
import win32api

x=raw_input("Enter file name: ")

drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
for drive in drives:
    for folderName, subfolders, filenames in os.walk(drive):
        for filename in filenames:
            if x.upper() in filename:
                print"FILE FOUND!"
                print('FILE INSIDE ' + folderName + ': '+ filename)
            elif x.lower() in filename:
                print"FILE FOUND!"
                print('FILE INSIDE ' + folderName + ': '+ filename)
            elif x.capitalize() in filename:
                print"FILE FOUND!"
                print('FILE INSIDE ' + folderName +': '+ filename)
a=raw_input("Press any key to exit.")
sys.exit()

As you may have noticed this program is not fast enough.
So could anyone help me make a faster and more efficient version of this program?
Thanks!

A: You can't enhance this program much - any static file search will have to do that sort of thing. By adding a lot of complexity and making it parallel, you could get it to work faster by walking different portions of the file system at a time, and possibly enabling a "lucky hit" earlier.
Applications and utilities that are designed for fast search of the file system usually resort to indexing all file system contents in a database - and they keep doing that either continuously on the background, or at a fixed time of the day. So, when there is a a search,they just perform a query on that database.
This solution however would increase the complexity of your small program several times - and it would be too complex to write here as  an answer;

A: Reducing the number of print statements should increase speed significantly. If you need to trace the files, you could write your results to a log file instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: (ExtJS 4.2.2) Can't get tab that wasn't been active I have container
items: [{
            xtype: 'container',
            layout: 'card',
            flex: 1,
            itemId: 'tab-container',
            deferredRender: false,
            items: [ {
                xtype: 'panel',
                layout: 'fit',
                dockedItems: [routessearch],
                items: [routes]
            }, {
                xtype: 'panel',
                layout: 'fit',
                forceLayout: true,
                dockedItems: [routessearch],
                items: [routesSubs]
            }]
        }]

When page loaded I can get first tab because it is already active. But I can't get second tab because it hasn't been created.
I tried to use deferredRender:false and forceLayout:true (like in code sample), but it doesn't working.

A: In ExtJs you should interact with components and not with the dom directly.
So when you replace var elements = document.querySelectorAll(query); with Ext.ComponentQuery.query(query); you get an array of the matching components and you can interact with them.
From the Sencha documentation of Ext.ComponentQuery:

Provides searching of Components within Ext.ComponentManager
  (globally) or a specific Ext.container.Container on the document with
  a similar syntax to a CSS selector. Returns Array of matching
  Components, or empty Array.

So after the component query Ext.ComponentQuery.query('#tab-container > panel') you have all inner panels.
With second = components[1] you have a reference to the second.
Now you can interact with the component.
But when you need also access to the dom of the component you get it by second.getEl().dom.
So the complete code looks like.
Ext.create('Ext.container.Container', {
    renderTo: Ext.getBody(),
    width: 200,
    height: 200,
    layout: 'card',
    itemId: 'tab-container',
    deferredRender: false,
    items: [{
        title: 'P1'
    }, {
        title: 'P2'
    }],
    listeners: {
        boxready: function () {
            var components = Ext.ComponentQuery.query('#tab-container > panel');
            var second = components[1];
            var el = second.getEl();
            var dom = el.dom;
            // code to interact with the component or with the dom
        }
    }
});

See the code in action in the Sencha Fiddle.


text:
Q: Aligning columns with bootstrap I am shure someone asked this before, but I was unable to come up with a good formulation to search for :(. Anyway.
Have a look the following code:

HELOO WORLD

                some very long text here

HELOO WORLD

Here a jsfillde. Is there any way I can pull up the third span to come directly after the first span?
Thanks,
Niklas

A: Put the third div into first column:

HELOO WORLD

HELOO WORLD

                some very long text here

A: You can change the CSS to alternate wich way each span6 div floats. Since the default float is left, just apply float right to the alternate divs. This
[class="span6"]:nth-of-type(even) {
    float: right;
}


text:
Q: Openpyxl: iterate through all rows of one column I have a worksheet file with 2 columns and thousands of rows. I want to iterate through all rows but grab only the first column.
This prints out every column, how to print e.g. only 'A':
from openpyxl import load_workbook

workbook = load_workbook('file.xlsx')
sheet = workbook['Table1']

for row in sheet:
    for cell in row:
        print(sheet[cell.coordinate].value)

Got it running like this, but is there a more efficient way without the comparison clause?
for row in sheet:
    for cell in row:
        if cell.coordinate[0] == 'A':
            print(sheet[cell.coordinate].value)

A: Using dataframe it could be simpler and should run faster:
import pandas as pd
df = pd.read_excel('file.xlsx', sheet_name="Table1")
print(df.iloc[:,[0]])

Performance testing for Loading a somehow big excel file using openpyxl vs pandas (to provide PoC of my above statement and to provide some actual test results to reply to Charlie Clark's comment below). It is solely for the purpose of learning and knowledge sharing with each other than any other reason.
Preparing a Big File:
import openpyxl as xl
wb = xl.Workbook()
ws = wb['Sheet']
wb.save("DUMMY1.xlsx")

xfile = xl.load_workbook('DUMMY1.xlsx')

# Load 100000 rows and 10 columns
sheet = xfile['Sheet']
for i in range(100001):
    for j in range(10):
        sheet.cell(row=i+1, column=j+1).value = "Hello "+str(i+1+j+1)
xfile.save('DUMMY2.xlsx')

Performance Testing:
import timeit
import openpyxl as xl
import pandas as pd
def func1():
    xl1 = xl.load_workbook("DUMMY2.xlsx")
    return xl1

def func2():
    df = pd.read_excel("DUMMY2.xlsx")
    return df

print(timeit.timeit('func1()', globals=globals(), number=1))
print(timeit.timeit('func2()', globals=globals(), number=1))

Results:
40.4193192
19.396849500000002

As you can see, loading an excel file using openpyxl takes more than double as much time as loading using pandas. If you load using xlrd and pandas combined, it is even little faster than loading to a pandas dataframe

A: You can loop through all rows and then directly access the cell in this row and in the first column:
for rowNumber in range(1, sheet.max_row + 1):
    print(sheet.cell(row=rowNumber, column=1).value)


text:
Q: template class conversion with two parameters I'm having problems converting a template class of the same typename but just with another size to the same template class. Let me explain this by code:
template<typename T, int SIZE>
class Array
{
  T aData[SIZE];
  friend Array operator+(Array &arr1, Array &arr2);
};

This is what I have as the template class. Lets assume I already overloaded operator+.
So this is what I want to do:
Array<double, 10> a1;
Array<double, 20> a2;
a1 + a2;

I know that a1 and a2 are different classes. So my question is, how can I convert a2 to Array<double, 10>? I would want to do this with a constructor, which takes an object of Array<T, SIZE2> and return object of Array<T, SIZE>. Is this doable?
In more general terms: I want to convert Array<T, SIZE2> to a class of Array<T, SIZE>.

A: The proper solution is to make operator + a template that can handle two arguments of different type.
#include <cstddef>

template
<
    typename x_Item
,   ::std::size_t x_size
>
class Array;

template
<
    typename x_Item
,   ::std::size_t x_left_size
,   ::std::size_t x_right_size
>
Array<x_Item, x_left_size + x_right_size>
operator +
(
    Array<x_Item, x_left_size> const & left
,   Array<x_Item, x_right_size> const & right
);

template
<
    typename x_Item
,   ::std::size_t x_size
>
class Array
{
    template
    <
        ::std::size_t x_left_size
    ,   ::std::size_t x_right_size
    >
    friend
    Array<x_Item, x_left_size + x_right_size>
    operator +
    (
        Array<x_Item, x_left_size> const & left
    ,   Array<x_Item, x_right_size> const & right
    );

    x_Item aData[x_size];
};

template
<
    typename x_Item
,   ::std::size_t x_left_size
,   ::std::size_t x_right_size
>
Array<x_Item, x_left_size + x_right_size>
operator +
(
    Array<x_Item, x_left_size> const & left
,   Array<x_Item, x_right_size> const & right
)
{
    // implementation...
}

A: One way is to provide conversion constructor:
template<typename T, std::size_t SIZE>
class Array
{
public:

    Array() = default;
    Array(const Array&) = default;
    Array(Array&&) = default;

    template <std::size_t N>
    Array(const Array<T, N>&) requires (SIZE < N)  { /*..*/ }

    friend Array operator+(const Array &arr1, const Array &arr2) { /*..*/ }
};

Demo

*

*requires is C++20, you might use SFINAE tricks before.

*You have to take care of expected conversion to avoid ambiguity:
(Do you want a1 + a2 to resolve to static_cast<decltype(a2)>(a1) + a2 or a1 + static_cast<decltype(a1)>(a2)?)


text:
Q: pagination на jquery Есть функция пагинации:
js
function Pagination() {
    var rowsShown = $('.quantity__link_active').data('value');
    if(rowsShown === 'all') {
        $('.table__row').show();
        $('.pageList__link').remove();
    } else {
        var rowsTotal = $('.table__row').length;
        var numPages = Math.ceil(rowsTotal/rowsShown);
        $('.pageList__link').remove();

        for(var i = 0; i < numPages; i++) {
            var pageNum = i + 1;
            $('.pageList').append(''+ pageNum +' ');
        }
        $('.pageList__link:first').addClass('pageList__link_active');
        $('.table__row').hide()
        for(var i = 0; i <= rowsShown - 1; i++) {
            $($('.table__row')[i]).show();
        }

        $('.pageList__link').on('click', function(){
            $('.pageList__link').removeClass('pageList__link_active');
            $(this).addClass('pageList__link_active');
            $('.table__row').hide();

            var currPage = $(this).attr('rel');
            var startItem = currPage * rowsShown;
            var endItem = startItem + rowsShown;
            for(var i = startItem; i < endItem; i++) {
                $($('.table__row')[i]).show();
            }

            return false;
        });
    }
};

html

    Количество задач:
    20
    50
    100
    все

table__row встраивается автоматически из json файла.
Если страниц меньше 7, выглядит адекватно, но как только страниц становится больше, то едет вёрстка.
Хотелось бы сделать так:

Объясните, пожалуйста, алгоритм "сворачивания" страниц, если их становится больше 5. Желательно, чтобы выводилась всегда первая и последняя страница.
Без готовых решений и плагинов. Хочется понять, как оно работает и своими силами написать.
Спасибо!
UPD: Сделал сворачивание, но не могу понять, как выводить следующие 2 страницы.
if($('.pageList__link').length > 5) {
            $('.pageList__link').hide();
            $('.pageList__link:first').show().after('...');
            $('.pageList__link:last').show();
        }

A: Работает это так:
Исходя из того сколько у вас элементов всего и значения (сколько элементов показать на странице) - высчитывается var numPages.
Затем идет цикл for(var i = 0; i < numPages; i++) который добавляет в DOM ссылки пагинации. Количество страниц (и соответственно ссылок) напрямую зависит от элементов в .table__row и сколько показываете на странице.
Например у вас 15 элементов и по пять на странице = получите 3 ссылки пагинации. Если 50 элементов то получите 10 ссылок и верстка поедет как вы сказали.
Поэтому для решения вашего вопроса я написал ф-ю пагинации таким образом чтобы генерировался массив чисел (ссылок). Причем если предпоследнее число списка ссылок меньше чем предпоследнее число из всего количества ссылок, то показывается многоточие. Например:
var totalElements = 600; // элементов всего
var perPage = 5; // сколько элементов на странице
var visibleLinks = 10; // сколько ссылок хотим видеть;

Для этого условия изначально генерируется массив из 10 чисел (ссылок) такого вида:
[1,2,3,4,5,6,7,8,9,120] \\ последнее число это totalElements/perPage

Так как 9 меньше чем 119 то на странице показываем многоточие после девятки
Вот пример всей пагинации на codepen jQuery pagination
Для перелистывания нужно кликать по крайним ссылкам (что внутри многоточий) или просто по начальной и конечной ссылке для быстрого перехода в начало или конец


text:
Q: Angular filter with minimum and maximum values I'm having some trouble getting angular to properly filter my results. I'm attempting to use a custom filter that gets arguments from a minimum input and a maximum input.
/index.html
<input ng-model="minHorsepower">
<input ng-model="maxHorsepower">
...
tr(ng-repeat="plane in planes | filter:horsepowerFilter")

/controllers.js
//Horsepower filter
$scope.horsepowerFilter = function(plane) {
  var ret = true;

  if($scope.minHorsepower && $scope.minHorsepower > plane.horsepower) {
    ret = false;
  }

  if($scope.maxHorsepower && $scope.maxHorsepower < plane.horsepower) {
    ret = false;
  }

  return ret;
};

$scope.planes = [
  {
      'make' : 'Piper',
      'model' : 'Arrow',
      'modelNumber' : 'PA-28R-180',
      'horsepower' : '180',
      'gear' : 'retractable',
  },
  {
      'make' : 'Piper',
      'model' : 'Arrow',
      'modelNumber' : 'PA-28R-200',
      'horsepower' : '200',
      'gear' : 'retractable',
  }
];

It works INITIALLY when I set $scope.minHorsepower/$scope.maxHorsepower in controllers.js, but only initially, not when I put something else in the <input>s. Furthermore, it prefills the inputs AND filters the results. It just doesn't work properly when I change the value of the inputs.
I've referenced this Stack Overflow thread, but I can't find any material differences in our code... AngularJS multiple filter with custom filter function
Thanks for the help.

A: To ensure the model values are numbers and not strings, change the type for your inputs to be number.
<input type="number" ng-model="minHorsepower" />
<input type="number" ng-model="maxHorsepower" />

Also, make sure your model values are numbers and not strings.
Alternatively, you can run everything through parseFloat(...) in your filter.

A: Unfortunately, I can't pinpoint exactly the problem you're having with your code. However, I think I have created a plnkr that (I believe) works as intended.
Apart from parsing the inputs with parseFloat, the logic seems to be the same. Not parsing the inputs to a numeric form shouldn't "break" it, but will possibly make it behave strangely ("9" > "10" for example).
Anyway, hopefully you can pull out the useful pieces and get it working.

A: Since you only send to the filter a function, it doesn't know to watch for any value changes, and thus to trigger the filter function when it happens.
When you define a filter as {{ filter_expression | filter : filterValue}},  angular watches the filterValue and triggers the filter function when it changes.
To achieve what you need you can define your own filter:
angular.module('myApp')
  .filter('range', function(){
    return function(items, property, min, max) {
      return items.filter(function(item){
        return item[property] >= min && item[property] <= max;
      });
    };
  });

and call it like this:
ng-repeat="plane in planes | range : 'horsepower' : minHorsepower : maxHorsepower"


text:
Q: laravel app deployment on Centos Fedora ( CPANEL) i'm planning to deploy laravel app into centos fedora with cpanel
i set the server requirements for the client to be :
4 Virtual processors  • 8 GB memory VRAM  • 500 GB SAN Storage useable Capacity (NVMe - Platinum tier) • Centos Fedora
however the infrastructre team asked me to fill this table
Please fill the below table with the disk sizing distribution;

Mount Point
Size (GB)
FileSystem

/

SWAP

swap

/U01  (Extra disk)


text:
Q: glPolygonMode not rendering in correct mode I recently started learning tessellation and today I was trying to draw a triangle after tessellation so that I can see all the tessellated smaller triangles using glPolygonMode(GL_FRONT_AND_BACK, GL_LINE). But for some reason the output is just a coloured background without any triangle in it.
For the tessellation, I make a control shader and evaluation shader and then link them to the program.(Code below)
// Source code for Tesselation Control Shader
static const GLchar * tesselation_control_shader[] =
{
    "#version 450 core                                  \n"
    "                                                   \n"
    "layout(vertices = 3) out;                          \n"
    "                                                   \n"
    "void main(void)                                    \n"
    "{                                                  \n"
    "   //Only if I am invocation 0                     \n"
    "   if (gl_InvocationID == 0)                       \n"
    "   {                                               \n"
    "       gl_TessLevelInner[0] = 5.0;                 \n"
    "       gl_TessLevelOuter[0] = 5.0;                 \n"
    "       gl_TessLevelOuter[1] = 5.0;                 \n"
    "       gl_TessLevelOuter[2] = 5.0;                 \n"
    "   }                                               \n"
    "                                                   \n"
    "   // Everybody copies their input to their input  \n"
    "   gl_out[gl_InvocationID].gl_Position =           \n"
    "       gl_in[gl_InvocationID].gl_Position;         \n"
    "}                                                  \n"
};

// Source code for tesselation evaluation shader
static const GLchar * tesselation_evaluation_shader[] =
{
    "#version 450 core                                          \n"
    "                                                           \n"
    "layout(triangles, equal_spacing, cw) in;                   \n"
    "                                                           \n"
    "void main(void)                                            \n"
    "{                                                          \n"
    "   gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position +  \n"
    "       gl_TessCoord.y * gl_in[1].gl_Position +             \n"
    "       gl_TessCoord.z * gl_in[2].gl_Position);             \n"
    "}                                                          \n"
};

I then call the glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) in my render function right before draw the triangle using glDrawArrays(GL_TRIANGLE, 0, 3).
I initially thought that the glPolygonMode was defaulting to GL_FILL but I don't think that's the issue since I am just following a book (OpenGL Superbible 7th Edition).
How can I fix this?
Edit:
I have added the code of my entire program below:
GLuint compile_shaders(void)
{
    GLuint vertex_shader;
    GLuint fragment_shader;
    GLuint control_shader;
    GLuint evaluation_shader;
    GLuint program;

    // Source code for Vertex Shader
    static const GLchar * vertex_shader_source[] =
    {
        "#version 450 core                                                      \n"
        "                                                                       \n"
        "// offset and color are input vertex attribute                         \n"
        "layout (location = 0) in vec4 offset;                                  \n"
        "layout (location = 1) in vec4 color;                                   \n"
        "                                                                       \n"
        "//Declare VS_OUT as an output interface block                          \n"
        "out VS_OUT                                                             \n"
        "{                                                                      \n"
        "   vec4 color; //Send color to next stage                              \n"
        "}vs_out;                                                               \n"
        "                                                                       \n"
        "void main(void)                                                        \n"
        "{                                                                      \n"
        "   //Decalre a hardcoded array of positions                            \n"
        "   const vec4 vertices[3] = vec4[3](vec4(0.25, -0.25, 0.5, 1.0),       \n"
        "                                    vec4(-0.25, -0.25, 0.5, 1.0),      \n"
        "                                    vec4(0.25, 0.25, 0.5, 1.0));       \n"
        "                                                                       \n"
        "   //Index into our array using gl_VertexID                            \n"
        "   gl_Position = vertices[gl_VertexID] + offset;                       \n"
        "                                                                       \n"
        "//color = vec4(1.0, 0.0, 0.0, 1.0);                                    \n"
        "//Output fixed value for vs_color                                      \n"
        "vs_out.color = color;                                                  \n"
        "}                                                                      \n"
    };

    // Source code for Fragment Shader
    static const GLchar * fragment_shader_source[] =
    {
        "#version 450 core                                                              \n"
        "                                                                               \n"
        "//Declare VS_OUT as an input interface block                                   \n"
        "in VS_OUT                                                                      \n"
        "{                                                                              \n"
        "   vec4 color; //Send color to next stage                                      \n"
        "}fs_in;                                                                        \n"
        "                                                                               \n"
        "//Ouput to the framebuffer                                                     \n"
        "out vec4 color;                                                                \n"
        "                                                                               \n"
        "void main(void)                                                                \n"
        "{                                                                              \n"
        "// Simply assign the color we were given by the vertex shader to our output    \n"
        "   color = fs_in.color;                                                        \n"
        "}                                                                              \n"
    };

    // Source code for Tesselation Control Shader
    static const GLchar * tesselation_control_shader[] =
    {
        "#version 450 core                                  \n"
        "                                                   \n"
        "layout(vertices = 3) out;                          \n"
        "                                                   \n"
        "void main(void)                                    \n"
        "{                                                  \n"
        "   //Only if I am invocation 0                     \n"
        "   if (gl_InvocationID == 0)                       \n"
        "   {                                               \n"
        "       gl_TessLevelInner[0] = 5.0;                 \n"
        "       gl_TessLevelOuter[0] = 5.0;                 \n"
        "       gl_TessLevelOuter[1] = 5.0;                 \n"
        "       gl_TessLevelOuter[2] = 5.0;                 \n"
        "   }                                               \n"
        "                                                   \n"
        "   // Everybody copies their input to their input  \n"
        "   gl_out[gl_InvocationID].gl_Position =           \n"
        "       gl_in[gl_InvocationID].gl_Position;         \n"
        "}                                                  \n"
    };

    // Source code for tesselation evaluation shader
    static const GLchar * tesselation_evaluation_shader[] =
    {
        "#version 450 core                                          \n"
        "                                                           \n"
        "layout(triangles, equal_spacing, cw) in;                   \n"
        "                                                           \n"
        "void main(void)                                            \n"
        "{                                                          \n"
        "   gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position +  \n"
        "       gl_TessCoord.y * gl_in[1].gl_Position +             \n"
        "       gl_TessCoord.z * gl_in[2].gl_Position);             \n"
        "}                                                          \n"
    };

    // Create and compiler Vertex Shader
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, vertex_shader_source, NULL);
    glCompileShader(vertex_shader);

    // Create and compiler Fragment Shader
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, fragment_shader_source, NULL);
    glCompileShader(fragment_shader);

    // Create and compile tesselation control shader
    control_shader = glCreateShader(GL_TESS_CONTROL_SHADER);
    glShaderSource(control_shader, 1, tesselation_control_shader, NULL);
    glCompileShader(control_shader);

    // Create and compile tesselation evaluation shader
    evaluation_shader = glCreateShader(GL_TESS_CONTROL_SHADER);
    glShaderSource(evaluation_shader, 1, tesselation_control_shader, NULL);
    glCompileShader(evaluation_shader);

    // Create program, attach shaders to it, and link it
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glAttachShader(program, control_shader);
    glAttachShader(program, evaluation_shader);
    glLinkProgram(program);

    // Delete shaders as program has them now
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    glDeleteShader(control_shader);
    glDeleteShader(evaluation_shader);

    return program;
};

class TesselationCSOne : public sb7::application
{
public:

    void startup()
    {
        rendering_program = compile_shaders();
        glCreateVertexArrays(1, &vertex_array_object);
        glBindVertexArray(vertex_array_object);
    }

    void shutdown()
    {
        glDeleteVertexArrays(1, &vertex_array_object);
        glDeleteProgram(rendering_program);
        glDeleteVertexArrays(1, &vertex_array_object);
    }

    // Our rendering function
    void render(double currentTime)
    {
        // Sets colour
        static const GLfloat color[] = { (float)sin(currentTime) * 0.5f + 0.5f, (float)sin(currentTime) * 0.5f + 0.5f, 0.0f, 1.0f };

        glClearBufferfv(GL_COLOR, 0, color);

        //Tell OpenGL to draw only the outlines of the resulting triangle
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

        // Use program object we created for rendering
        glUseProgram(rendering_program);

        GLfloat attrib[] = { 1.0, 0.0, 0.0, 0.0 };/*{ (float)sin(currentTime) * 0.5f, (float)sin(currentTime) * 0.6f, 0.0f, 0.0f };*/

        // Update value of input attribute 0
        glVertexAttrib4fv(0, attrib);

        // Draw pathes for tesselation shaders
        glPatchParameteri(GL_PATCH_VERTICES, 3);
        // Draw one triangle
        glDrawArrays(GL_PATCHES, 0, 3);
    }

private:

    GLuint rendering_program;
    GLuint vertex_array_object;
};

// Only instance of DECLARE_MAIN to state entry point
DECLARE_MAIN(TesselationCSOne);

A: If you use a tessellation shader then you have to draw Patches. You have to set the size of the patches by glPatchParameteri( GL_PATCH_VERTICES, ...) and the primitive type has to be GL_PATCHES.
If the the number of vertices in a patch is 3, then you have to do it like this:
glPatchParameteri(GL_PATCH_VERTICES, 3);
glDrawArrays(GL_PATCHES, 0, 3)

See OpenGL 4.6 API Core Profile Specification; 10.1.15 Separate Patches; page 342:

Separate patches are specified with mode PATCHES. A patch is an ordered collection of vertices used for primitive tessellation (section 11.2). The vertices comprising a patch have no implied geometric ordering. The vertices of a patch are used by tessellation shaders and the fixed-function tessellator to generate new point, line, or triangle primitives.

void PatchParameteri( enum pname, int value );

with pname set to PATCH_VERTICES

Your shader program doesn't even link, because the fragment shader tries to read from an input interface block,
which is not declared as an output from the previous shader stage.
You have to pass the vertex attributes, through the tessellation control and evaluation shader to the fragment shader:
Tessellation control shader:
#version 450 core

layout(vertices = 3) out;

in VS_OUT
{
   vec4 color;
} tesc_in[];

out TESC_OUT
{
   vec4 color;
} tesc_out[];

void main(void)
{
   if (gl_InvocationID == 0)
   {
       gl_TessLevelInner[0] = 5.0;
       gl_TessLevelOuter[0] = 5.0;
       gl_TessLevelOuter[1] = 5.0;
       gl_TessLevelOuter[2] = 5.0;
   }

   tesc_out[gl_InvocationID].color     = tesc_in[gl_InvocationID].color;
   gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}

Tessellation evaluation shader:
#version 450 core

layout(triangles, equal_spacing, cw) in;

in TESC_OUT
{
   vec4 color;
} tese_in[];

out TESE_OUT
{
   vec4 color;
} tese_out;

void main(void)
{
   tese_out.color = ( gl_TessCoord.x * tese_in[0].color +
                      gl_TessCoord.y * tese_in[1].color +
                      gl_TessCoord.z * tese_in[2].color ) / 3.0;

   gl_Position = ( gl_TessCoord.x * gl_in[0].gl_Position +
                   gl_TessCoord.y * gl_in[1].gl_Position +
                   gl_TessCoord.z * gl_in[2].gl_Position ) / 3.0;
}

Fragment shader:
#version 450 core

in TESE_OUT
{
   vec4 color;
} fs_in;

out vec4 color;

void main(void)
{
   color = fs_in.color;
}

Further, I recommend to check if a shader object was successfully compiled:
GLuint shaderObj = .... ;
glCompileShader( shaderObj );

GLint status = GL_TRUE;
glGetShaderiv( shaderObj, GL_COMPILE_STATUS, &status );
if ( status == GL_FALSE )
{
    GLint logLen;
    glGetShaderiv( shaderObj, GL_INFO_LOG_LENGTH, &logLen );
    std::vector< char >log( logLen );
    GLsizei written;
    glGetShaderInfoLog( shaderObj, logLen, &written, log.data() );
    std::cout << "compile error:" << std::endl << log.data() << std::endl;
}

and a shader program object was successfully linked:
GLuint progObj = ....;
glLinkProgram( progObj );

GLint status = GL_TRUE;
glGetProgramiv( progObj, GL_LINK_STATUS, &status );
if ( status == GL_FALSE )
{
    GLint logLen;
    glGetProgramiv( progObj, GL_INFO_LOG_LENGTH, &logLen );
    std::vector< char >log( logLen );
    GLsizei written;
    glGetProgramInfoLog( progObj, logLen, &written, log.data() );
    std::cout  << "link error:" << std::endl << log.data() << std::endl;
}

By the way, read about Raw string literals, which simplify the declaration of the shader source code strings:
e.g.
std::string fragment_shader_source = R"(
#version 450 core

in TESE_OUT
{
    vec4 color;
} fs_in;

out vec4 color;

void main(void)
{
    color = fs_in.color;
}
)";

Further note, the the offset probably moves the the triangle out of the viewport. Either change the value of the offset in the attribute initialization:
GLfloat attrib[] = { 0.0, 0.0, 0.0, 0.0 };

or get rid of the offest in the vertex shader for debug reasons
gl_Position = vertices[gl_VertexID];

You have to ensure that the color attribute is set too:
GLfloat attrib1[] = { 1.0, 1.0, 0.0, 1.0 };
glVertexAttrib4fv(1, attrib1);

The result may look like this:

A: So after checking a lot of sources and the Superbible's code repository I realized I have a lot of unnecessary code (For example, the interface blocks in the shaders) and even quite a few mistakes (For example I had two program varibles).
But, after fixing all that the code that produces the required output (A tessellated triangle) is:
/**
        Program to draw a triangle with tesselation.
**/
#include <sb7.h>

class TesselatedTriangle : public sb7::application
{
    void init()
    {
        static const char title[] = "Tessellated Triangle";

        sb7::application::init();

        memcpy(info.title, title, sizeof(title));
    }

    virtual void startup()
    {
        static const char * vertex_shader_source[] =
        {
            "#version 450 core                                                 \n"
            "                                                                  \n"
            "void main(void)                                                   \n"
            "{                                                                 \n"
            "    const vec4 vertices[] = vec4[](vec4( 0.25, -0.25, 0.5, 1.0),  \n"
            "                                   vec4(-0.25, -0.25, 0.5, 1.0),  \n"
            "                                   vec4( 0.25,  0.25, 0.5, 1.0)); \n"
            "                                                                  \n"
            "    gl_Position = vertices[gl_VertexID];                          \n"
            "}                                                                 \n"
        };

        static const char * tesselation_control_shader_source[] =
        {
            "#version 450 core                                                                 \n"
            "                                                                                \n"
            "layout (vertices = 3) out;                                                        \n"
            "                                                                                \n"
            "void main(void)                                                                   \n"
            "{                                                                                \n"
            "    if (gl_InvocationID == 0)                                                     \n"
            "    {                                                                             \n"
            "        gl_TessLevelInner[0] = 5.0;                                               \n"
            "        gl_TessLevelOuter[0] = 5.0;                                               \n"
            "        gl_TessLevelOuter[1] = 5.0;                                               \n"
            "        gl_TessLevelOuter[2] = 5.0;                                               \n"
            "    }                                                                             \n"
            "    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;     \n"
            "}                                                                                \n"
        };

        static const char * tesselation_evaluation_shader_source[] =
        {
            "#version 450 core                                                                 \n"
            "                                                                                \n"
            "layout (triangles, equal_spacing, cw) in;                                         \n"
            "                                                                                \n"
            "void main(void)                                                                   \n"
            "{                                                                                \n"
            "    gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) +                       \n"
            "                  (gl_TessCoord.y * gl_in[1].gl_Position) +                       \n"
            "                  (gl_TessCoord.z * gl_in[2].gl_Position);                        \n"
            "}                                                                                \n"
        };

        static const char * fragment_shader_source[] =
        {
            "#version 450 core                                                 \n"
            "                                                                  \n"
            "out vec4 color;                                                   \n"
            "                                                                  \n"
            "void main(void)                                                   \n"
            "{                                                                 \n"
            "    color = vec4(0.0, 0.8, 1.0, 1.0);                             \n"
            "}                                                                 \n"
        };

        rendering_program = glCreateProgram();

        // Compile shaders
        GLuint vs = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vs, 1, vertex_shader_source, NULL);
        glCompileShader(vs);

        GLuint tcs = glCreateShader(GL_TESS_CONTROL_SHADER);
        glShaderSource(tcs, 1, tesselation_control_shader_source, NULL);
        glCompileShader(tcs);

        GLuint tes = glCreateShader(GL_TESS_EVALUATION_SHADER);
        glShaderSource(tes, 1, tesselation_evaluation_shader_source, NULL);
        glCompileShader(tes);

        GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fs, 1, fragment_shader_source, NULL);
        glCompileShader(fs);

        // Attach shaders to the program
        glAttachShader(rendering_program, vs);
        glAttachShader(rendering_program, tcs);
        glAttachShader(rendering_program, tes);
        glAttachShader(rendering_program, fs);

        // Link the program
        glLinkProgram(rendering_program);

        // Generate vertex arrays
        glGenVertexArrays(1, &vertex_array_object);
        glBindVertexArray(vertex_array_object);

        // Declare the drawing mode for the polygons
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    }

    virtual void render(double currentTime)
    {
        static const GLfloat green[] = { 0.0f, 0.25f, 0.0f, 1.0f };

        glClearBufferfv(GL_COLOR, 0, green);

        glUseProgram(rendering_program);

        glDrawArrays(GL_PATCHES, 0, 3);
    }

    virtual void shutdown()
    {
        glDeleteVertexArrays(1, &vertex_array_object);

        glDeleteProgram(rendering_program);
    }

private:

    GLuint          rendering_program;
    GLuint          vertex_array_object;

};

// One and only instance of DECLARE_MAIN
DECLARE_MAIN(TesselatedTriangle)

Hopefully this helps somebody else with the same problem.


text:
Q: Download Throttle in node.js I am running a server on node using Connect. The server returns a response of around 50,000 records for a particular request say www.sample.com/service/store_id. once the server receives a request, it interacts with mongoDB to fetch the store details and returns the store details(50,000 records) as response.
I am exposing the URL to a mobile. The mobile user tries to get the response by requesting the URL. The mobile starts to retrieve or download 50,000 records. The download stops when it retrieves around 25,000 records. The mobile user resumes the download after some time. How do i start the download from 25000 to 50000 records as the user already have the first 25000 records?
How can i use download throttle in the above scenario?

A: You are looking for pagination :)
Here is how to do it with the mongoDB driver.


text: Q: How to change/set priority of NSG rule using powershell how to create an PowerShell script to get lowest priority nsg rule in nsg group in azure and set the specific nsg priority according to the lowest priority.


text:
Q: Why are these two complex exponentials equal? Why is $$e^{i(\theta+\pi)} = -e^{i\theta}$$
I saw this but I'm not sure why it works. If someone could show me the steps I would really appreciate it.

A: Use $e^{i \theta} = \cos \theta + i \sin \theta$.

A: To show : $$e^{i(\theta+\pi)}=-e^{i\theta}$$
Now $$e^{i \theta} = \cos \theta + i \sin \theta \cdots  (1)$$
so    $$e^{i(\theta+\pi)}=\cos (\theta+\pi) + i \sin (\theta+\pi) \cdots  (2)$$
Also , recall that $$\cos (\pi+\theta) = -\cos \theta $$
and $$\sin (\pi+\theta) = -\sin \theta $$
From the above results $(2)$ modifies to $$e^{i (\theta+\pi)} = -(\cos \theta + i \sin \theta)$$
Therefore from $(1)$ $$e^{i(\theta+\pi)}=-e^{i\theta}$$

A: Hint: this is wrong as it is, it should read
$$e^{i(\theta+\pi)}=-e^{i\theta}$$
(theta and pi in the same brackets - edited).
Hint2: what functional equation does the exponential map satisfy? $e^{a+b}=\ldots$


text:
Q: Extracting table of holdings from (Edgar 13-F filings) TXT (pre-2013) with python I am working on extracting a table of holdings from 13-F form on EDGAR. Before 2013 holdings were given in a txt file (see example).
The output I am aiming for is a pd.DataFrame with same shape as the "Form 13F Information Table" in txt file (10 columns and each line in a separate row).
I have tried to use BeautifulSoup, which turned table into a tag object, but I can't figure out how to format this to go into the dataframe as described above.
This is my code attempt:
soup2 = BeautifulSoup(requests.get(filing_url_13f).content, 'lxml')
holdings = soup2.find_all('table')

#This is my attempt to turn the content into a list:
lixt=[]
for x in soup2.find_all(['c','c','c','c','c','c','c','c','c']  ):
    for line in x:
        lixt.append(line)
x=lixt[1]
l=[]
for string in x.strings:
    l.append(repr(string))
el=l[7]

And this is where I get stuck as el returns the below. I can't split it by \n, as there are often \n within company name (AMERICAN\n  EXPRESS CO).

\nAMERICAN\n  EXPRESS CO        COM           025816109      112,209     1,952,142 Shared-Defined 4           1,952,142       -        -\nAMERICAN\n  EXPRESS CO        COM           025816109      990,116    17,225,400 Shared-Defined 4, 5       17,225,400       -        -\nAMERICAN\n  EXPRESS CO        COM           025816109       48,274       839,832 Shared-Defined 4, 7          839,832       -        -\nAMERICAN\n  EXPRESS CO        COM           025816109      111,689     1,943,100 Shared-Defined 4, 8, 11    1,943,100       -        -\nAMERICAN\n  EXPRESS CO        COM           025816109      459,532     7,994,634 Shared-Defined 4, 10       7,994,634       -        -\nAMERICAN\n  EXPRESS CO        COM           025816109    6,912,308   120,255,879 Shared-Defined 4, 11     120,255,879       -        -\nAMERICAN\n  EXPRESS CO        COM           025816109       80,456     1,399,713 Shared-Defined 4, 13       1,399,713       -        -\nARCHER DANIELS\n  MIDLAND CO        COM           039483102      163,151     5,956,600 Shared-Defined 4, 5        5,956,600       -        -\nBANK OF NEW\n  YORK MELLON\n  CORP              COM           064058100      206,661     8,041,300 Shared-Defined 4           8,041,300       -        -\nBANK OF NEW\n  YORK MELLON\n  CORP              COM           064058100       46,104     1,793,915 Shared-Defined 2, 4, 11    1,793,915       -        -\nBANK OF NEW\n  YORK MELLON\n  CORP              COM           064058100      251,827     9,798,700 Shared-Defined 4, 8, 11    9,798,700       -        -\nCOCA COLA CO        COM           191216100       29,000       800,000 Shared-Defined 4             800,000       -        -\n

I will be very grateful for any suggestions.

A: Yes, these old EDGAR filings are terrible (not that the new ones are much better). This one is particularly bad, since longer entry lines were split into separate lines in order to get them to fit the page.
So the following should get you close enough to what you want:
import pandas as pd
from bs4 import BeautifulSoup as bs
import requests

req = requests.get('https://www.sec.gov/Archives/edgar/data/1067983/000119312512470800/d434976d13fhr.txt')

#next is a helper function to put back those longer entires
def lst_bunch(l,lenth=4):
    i=0
    while i < len(l):
        if len(l[i])<lenth:
            l[i] += l.pop(i+1)
        i += 1
    for item in l:
        if len(item)<lenth:
            lst_bunch(l,lenth)
    else:
        return l

tabs = req.text.replace('<TABLE>','xxx<TABLE>').split('xxx')
for tab in tabs[2:]:
    soup = bs(tab,'lxml')
    table = soup.select_one('table')
    lines = table.text.splitlines()
    lst_bunch(lines,30)
    for line in lines:
        print(line.strip())

Output:
Name of Issuer  Class  CUSIP     (In Thousands)   Amount      Discretion   Managers     Sole      Shared  None
AMERICAN  EXPRESS CO    COM    025816109      110,999     1,952,142 Shared-Defined 4           1,952,142       -   -
AMERICAN  EXPRESS CO    COM    025816109      979,436    17,225,400 Shared-Defined 4, 5       17,225,400       -   -

etc.


text:
Q: How can I make a bar graph displaying y-min and y-max data along with custom colors for each bar? I would like to make a bar graph that displays each bar as the bottom of the bar being y-min and the top of the bar being y-max. In addition I'd like each bar to have its own color fill and custom tics where xtic(1). Thank you
Similar to this below:
How to make range bar graphs in gnuplot?
ex.
#number #y-min #y-max #rgb
1        2      5      1
2        2.5    5.4    2
3        4      6      3
4        4.3    7      4

A: Here is what I ended up doing in case someone else needs it
set termoption font ",22"
boxwidth = 0.5
set style fill solid
set xtics nomirror
set ytics nomirror
set xtics font "{/:Bold,22}"
set ytics font "{/:Bold,22}"
set xlabel "Structure"
set xlabel  font "{/:Bold,30}"
set ylabel "Potential (V vs. RHE)"
set ylabel  font "{/:Bold,30}"
set xrange [-1:4.5]
set yrange [0:7]
set arrow from -1,2.5 to 4.5,2.5 nohead lc rgb 'black' dt 3
plot 'poten-range-plot' u 0:(($2+$3)/2.):(boxwidth/2.):(($3-$2)/2.):4:xtic(1) w boxxyerrorbars notitle lw 3 lc variable, 1/0 t "Pt (111)" lt 1 lc rgb 'black'


text:
Q: Smallest packet sniffer for an embedded device? Are there tiny packet sniffers out there? I'm looking for something that can be compiled for a embedded device with very limited space.
I thought of tcpdump but a dynamically linked and stripped tcpdump is still nearly 1mb, and that's without libpcap.
So far my research for a tiny sniffer have led me nowhere so I'm asking you guys.

A: You could look at netsniff-ng, which is not built atop libpcap and directly uses Linux PF_PACKET sockets, but you'll probably want to (and possibly have to) further trim it down yourself to make it sufficiently minimal.
I don't know of any "here's the source, just compile" minimal sniffers of that sort.


text:
Q: Trying to download remote image with php I've trying to download remote images(from more than one site) but any of these codes worked
allow_url_fopen is on but these code will return 0 bytes
$url = 'http://example.com/image.php';
$img = 'teste.jpg';
file_put_contents($img, file_get_contents($url));

or
copy('http://example.com/image.php', 'teste.jpg');

When I use curl(that is enabled on host) this error appears:
Error: The requested resource could not be loaded. libcurl returned the error: Empty reply from server
curl code :
$ch = curl_init('http://example.com/image.php');
$fp = fopen('teste,jpg, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Edit: Tried following curl opt too:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
curl_setopt($ch, CURLOPT_FILE, $lfile);

site is hosted by 000webhost, and after trying my whole day with differents codes I had to use a proxy to access my site because it was blocking me
Edit 2:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"h.mhcdn.net/store/manga/10738/thumb_cover.jpg?v=1476422230");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
//die("here1");
$data = curl_exec($ch);
die("here2");
file_put_contents("test.jpg", $data);
die("here3");
//curl_setopt($ch, CURLOPT_FILE, "test.jpg");

Tried code above but it wont reach  "die("here2");"(page wont load) only the  die("here1");
Edit 3:
$url = "http://h.mhcdn.net/store/manga/10738/thumb_cover.jpg?v=1476422230";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
        //die("here1");
        $data = curl_exec($ch);
        file_put_contents("local_file.jpg", $data);
        die("here2");

Can't reach here2, only here1
Edit 4: here's the problem: port 80 has been blocked for outgoing connections at 000web : https://www.habschned.com/000webhost-com-blocking-port-80-for-outbound-traffic-no-more-curl/

A: I guess it's pretty obvious, but did you try to open the URL in your browser? Can you see the image?
If the answer to the above is YES (most likely), most likely the remote party is blocking scripts from fetching the resource. The solution is to use cURL emulating as best as possible the behaviour of a regular browser, in terms of HTTP headers.
I would start from the most obvious ones which are CURLOPT_USERAGENT and CURLOPT_USERAGENT, set them at the values they expect and you should be fine. More complex access controls involve cookies and sessions, which is more complicated because you would have to fetch the referring page, store the cookie, and send it while fetching the resource.
UPDATE:
While the above is true, it was not the problem the asker had, this simple script should work as-is:
$url = "http://h.mhcdn.net/store/manga/10738/thumb_cover.jpg?v=1476422230";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
$data = curl_exec($ch);
file_put_contents("local_file.jpg", $data);


text:
Q: Texture descriptors in OpenCV Does anyone know if OpenCV has some kind of texture descriptors implemented? I googled "opencv texture descriptors" but not much to see.
Thanks in advance.

A: You can use the Gabor filter to extract texture descriptors
cv::Mat kernel = cv::getGaborKernel(cv::Size(kernel_size,kernel_size), sig, th, lm, gm, ps);
cv::filter2D(src_f, dest, CV_32F, kernel);

This is the C++ code, but it's the same for every other language. You have to get the Gabor filter kernel and than use the filter2d function.
I hope it helps


text:
Q: How do I create a tar.gz file with the contents of the webpack output directory? I have this React front end all nicely packed, uglified and chunked in my /build folder. And I want to automate the process of gzipping the directory into a snapshot and uploading it to my maven repository.
I've been looking through the documentation and cannot for the life of me figure out if I can set this up in my webpack.config.js and automate it after the contents have been packed.

A: I used webpack-shell-plugin to archive compiled files. My compiled files were is 'dist' directory.

*

*I installed this plugin using npm.

*Imported it with const WebpackShellPlugin = require('webpack-shell-plugin').

*Created "archive" shell command:
const CREATE_ARCHIVE = 'tar czvf --ignore-failed-read ' + paths.base() +        '/bundle.tar.gz' + ' -C ' + paths.dist() + ' . '

*Created and added shell plugin with
webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    //.. other plugins,
    new WebpackShellPlugin({
      onBuildExit: [CREATE_ARCHIVE],
      safe: true
    })
  )
It creates build.tar.gz in the root of the project after you run your webpack build.


text:
Q: live date time countdown problem from php/mysql database I have php site and mysql database with date/time field with date/time in future.
I need to count down from that future time till now.
Example:
Jimmy 31.12.2011 21:00:00 birthday
Mary 21.11.2011 19:30:00 wedding
Billy 12.03.2012 10:25:30  to NY
......
must show live counter:
Jimmy 123 days 20 hours 15 min 25 sec (and live counting)
Mary 89 days 15 hours 25 min 12 sec (and live counting)
Billy 183 days 12 hours 56 min 15 sec (and live counting)
......
how to do that?
I know that on stackoverflow is answer for my question, but I haven't find it yet. I used a lot of JavaScripts, try them and find them very nice. But something I do wrong and I don't know what is it. I'm quite new and I'm confused and lost. So, please, help me.
Thanks
DZvonko

A: the time-span from "now" to a given date and time shouldn't be that hard to calculate ...
so on your javascript part, create a timed event that fires every 1000 msec ... in the event handler re-calculate all timespans (date & time in the future vs local date & time +- time zone offset) and write them to the page ... for an example on timed events have a look here
this approach depends on the clock on the client system ... to fix this error-source you could send the local time to the server, and calculate an offset to the actual server time that gets delivered back to the client together with the page and the dates and times for the countdown ...


text:
Q: Angular: ¿Cómo iterar sobre un arreglo? Tengo una duda tal vez alguien me podría explicar:
Recibo el siguiente arreglo:
afiliado{
    "attentionSchedules": [
        {
            "room": "200",
            "floor": 2,
            "schedules": [
                {
                    "days": [
                        "MO",
                        "TU",
                        "FR",
                        "TH",
                        "WE"
                    ],
                    "_id": "x",
                    "initialTimeStr": "07:00 am",
                    "finalTimeStr": "04:00 pm",
                    "initialTime": "2020-11-12T13:00:00.000Z",
                    "finalTime": "2020-11-12T22:00:00.000Z"
                }
            ],
            "place": {
                "loc": {
                    "type": "Point",
                    "coordinates": [
                        -88.0351328,
                        15.4876832
                    ]
                },
                "_id": "x",
                "name": "x",
                "address": "x"
            }
        },
        {
            "room": "",
            "schedules": [
                {
                    "days": [
                        "MO",
                        "TH",
                        "FR",
                        "TU"
                    ],
                    "_id": "x",
                    "initialTimeStr": "01:00 pm",
                    "finalTimeStr": "11:00 pm",
                    "initialTime": "2020-10-15T19:00:00.000Z",
                    "finalTime": "2020-10-16T05:00:00.000Z"
                }
            ],
            "place": {
                "loc": {
                    "type": "Point",
                    "coordinates": [
                        -88.01386190000001,
                        15.5038827
                    ]
                },
                "_id": "x",
                "name": "x",
                "address": "x"
            }
        }
    ],
}

Yo quiero acceder a "days", pero quiero iterar sobre "x" cantidad de objetos que venga dentro del arreglo. Es decir, que si en el arreglo "attentionSchedules" viene hasta 5 objetos, yo deberia poder iterarlos y obtener days, ¿Cómo puede iterar sobre este tipo de arreglos?
Agradeceria mucho su ayuda, ya que estoy un poco confundida con el tema porfavor

A: Puedes hacer un arreglo de los afiliados e iterar de esta manera:

let afiliados = [{
  "attentionSchedules": [{
      "room": "200",
      "floor": 2,
      "schedules": [{
        "days": [
          "MO",
          "TU",
          "FR",
          "TH",
          "WE"
        ],
        "_id": "x",
        "initialTimeStr": "07:00 am",
        "finalTimeStr": "04:00 pm",
        "initialTime": "2020-11-12T13:00:00.000Z",
        "finalTime": "2020-11-12T22:00:00.000Z"
      }],
      "place": {
        "loc": {
          "type": "Point",
          "coordinates": [-88.0351328,
            15.4876832
          ]
        },
        "_id": "x",
        "name": "x",
        "address": "x"
      }
    },
    {
      "room": "",
      "schedules": [{
        "days": [
          "MO",
          "TH",
          "FR",
          "TU"
        ],
        "_id": "x",
        "initialTimeStr": "01:00 pm",
        "finalTimeStr": "11:00 pm",
        "initialTime": "2020-10-15T19:00:00.000Z",
        "finalTime": "2020-10-16T05:00:00.000Z"
      }],
      "place": {
        "loc": {
          "type": "Point",
          "coordinates": [-88.01386190000001,
            15.5038827
          ]
        },
        "_id": "x",
        "name": "x",
        "address": "x"
      }
    }
  ],
}]

afiliados.forEach(afiliado => {
  afiliado.attentionSchedules.forEach(attentionSchedule => {
    attentionSchedule.schedules.forEach(schedules => {
      console.log(schedules.days)
    })
  })
})

A: Primero: debemos analizar la estructura del objeto afiliado para entender qué funciones podríamos ir usando para sacar los items que necesitemos.
Segundo: al entender la estructura vemos que tenemos dos niveles a trabajar: schedules y finalmente days.
Tercero: accedemos al primer elemento que necesitamos extraer (schedules)
Cuarto: Al tener schedules definido, podemos hacer otro bucle (en este caso sobre schedules) y extraer days. Con ello, ya tenemos resuelto el problema.

const afiliado = {
    "attentionSchedules": [
        {
            "room": "200",
            "floor": 2,
            "schedules": [
                {
                    "days": [
                        "MO",
                        "TU",
                        "FR",
                        "TH",
                        "WE"
                    ],
                    "_id": "x",
                    "initialTimeStr": "07:00 am",
                    "finalTimeStr": "04:00 pm",
                    "initialTime": "2020-11-12T13:00:00.000Z",
                    "finalTime": "2020-11-12T22:00:00.000Z"
                }
            ],
            "place": {
                "loc": {
                    "type": "Point",
                    "coordinates": [
                        -88.0351328,
                        15.4876832
                    ]
                },
                "_id": "x",
                "name": "x",
                "address": "x"
            }
        },
        {
            "room": "",
            "schedules": [
                {
                    "days": [
                        "MO",
                        "TH",
                        "FR",
                        "TU"
                    ],
                    "_id": "x",
                    "initialTimeStr": "01:00 pm",
                    "finalTimeStr": "11:00 pm",
                    "initialTime": "2020-10-15T19:00:00.000Z",
                    "finalTime": "2020-10-16T05:00:00.000Z"
                }
            ],
            "place": {
                "loc": {
                    "type": "Point",
                    "coordinates": [
                        -88.01386190000001,
                        15.5038827
                    ]
                },
                "_id": "x",
                "name": "x",
                "address": "x"
            }
        }
    ],
}

let schedules = []
let days = []

afiliado.attentionSchedules.forEach(element => {
    schedules.push({
        days: element.schedules[0].days
    })
});

schedules.forEach(element => {
    days.push(element.days)
});

console.log(days)


text:
Q: How to check email is exist or not in node js by using sendgrid I want to check the signup email is valid or not. (Here "valid" means the email exists.) I think if I receive the result from the SendGrid mailer then I can see it. But when I send the message to the signup email the result was always successful even though the email doesn't exist. Below is my code and I always got the result as status 202, instead of getting an error.
I will be very appreciative if someone solve this problem or teach me another validation method.
const sgMail = require("@sendgrid/mail");
require("dotenv").config();

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const sendEmail = async (options) => {
  const msg = {
    from: process.env.FROM_EMAIL,
    to: options.email,
    subject: options.subject,
    text: options.message,
    html: options.html,
  };

  console.log(msg);
  try {
    let result = await sgMail.send(msg);
    return true;
  } catch (err) {
    console.log("email sending error ==> ", err.response.body);
    return false;
  }
};

export { sendEmail };

A: Sendgrid has a separate api for email validation. You can find it here.
Syntax for request and response can be found here.


text:
Q: Why is formatting my KendoGrid columns not working? I'm learning Kendo UI, and following one of the walkthroughs.  I've got a grid working, but the date formatting is not working, for some reason.
$("#archiveGrid").kendoGrid({
    columns: [
        { field: "SentDate", title: "Sent", format: "{0:MM/dd/yyyy}" },
        { field: "SenderName", title: "Sender" },
        { field: "SenderEmail", title: "Email" },
        "Subject"
    ],
    dataSource: new kendo.data.DataSource({
        transport: {
            read: "api/messages"
        },
        pageSize: 15,
        serverPaging: true,
        schema: {
            data: "Data",
            total: "Count"
        }
    }),
    pageable: true
});

But my dates still come out looking like 2014-02-07T21:06:03.993.  I tested the theory that the grid is ignoring the format property and changed the format string to "foo {0:MM/dd/yyyy}", which made the dates appear as foo 2014-02-07T21:06:03.993.
So what am I doing wrong?

A: You are missing the model in DataSource. try adding a proper model and set the type as date. then the format will work properly and also don't forget to mention the id.
schema: {
                id: "Id",
                data: "Data",
                total: "Count",
                fields: {
                        SentDate: { editable: true, type: "date"},
                        SenderName: { editable: true},
                        SenderName: { editable: true}
                    }
            }


text:
Q: Is there a method for finding the common factor between two polynomials? For two polynomials, there exist a method to find their monic GCD by a variation of Euclid's algoritm, is there any method exist for finding the exact nonmonic factor between two polynomials?
reference: https://en.wikipedia.org/wiki/Greatest_common_divisor_of_two_polynomials

A: If you do not allow the full rational field, you expect to lose the Euclidean property. That is, $\mathbb Z[x]$ is not a PID or a Euclidean domain.
A Euclidean domain $R$ is when we have some sort of degree function, Rotman calls it $\partial,$ with $\partial: R \setminus \{0\} \rightarrow \mathbb N,$ such that $\partial(f) \leq \partial(fg) $ for all nonzero $f,g \in R,$ and as soon as $f \neq 0$ we can always write
$$ g = q f + r,$$
with either $r=0$ or $\partial(r) < \partial(f).$
Anyway, in  $\mathbb Z[x]$ we take $\partial$ to be the degree of a polynomial. Suppose we then take $g=x$ and $f=2.$ We are asking about writing
$$ x = q \; 2 + r    $$
with either $r=0$ or $\partial(r) < \partial(f) = \partial(2) =0.$
The latter is impossible, so we need $r=0$ and $x = 2 q$ for some polynomial $q.$ This is fine in $\mathbb Q[x],$ but the evident solution $q = x/2$ is not a legal element of $\mathbb Z[x].$ We could be more formal about proving there is no $q,$ but in the end  $\mathbb Z[x]$ is not a Euclidean domain.
Meanwhile, in case you wonder about some exotic degree map that makes $\mathbb Z[x]$ into a Euclidean domain, be aware that $\mathbb Z[x]$ is not a PID either, which rules out that strategy. Indeed, the ideal generated by $(2,x)$ is not principal.


text:
Q: Check if at least one checkbox is checked Using C# I have a web form using custom validators (to set textbox borders to red) and I would like to check that at least one of a group of eight checkboxes have been checked (and possibly set the borders for the checkboxes to red too).
As I have a set of if statements making sure a true or false is returned for each checkbox, I thought I could add a counter and if the counter equals 0 to set Page.IsValid to false. Well that idea didn't work. Doesn't look like you can set Page.IsValid directly.
Then I thought to pop the counter value into a hidden field and validate that, but I can't seem to get the syntax right to use a custom validator on a hidden field.
What is the best solution for this?
Thanks

A: what's wrong with you customvalidator? all you need is something like

protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
{
   if(!CheckBox1.Checked && !CheckBox2.Checked && !CheckBox3.Checked)
      args.IsValid = false;
   else
      args.IsValid = true;
}

the if is saying 'if none of the checkboxes are checked, then we have a problem.'


text:
Q: I want to login to a Linux host as user "admin"/password="admin then sudo as root and change root password And all of this needs to be scripted in perl so this functionality is available to the 4 internal test hosts that i work with.

A: http://search.cpan.org/perldoc?Net::SSH::Expect


text:
Q: Xcode 6.3 Parse SDK 1.7.1 PFTableViewCell Error "has incompatible type" My code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell{

    var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as!
        CustomTableViewCell!
    if cell == nil {
        cell = CustomTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CustomCell")
    }

    // Extract values from the PFObject to display in the table cell
    if let username = object["username"] as? String {
        cell.customUser.text = username
    }
    if let title = object["Title"] as? String {
        cell.customTitle.text = title
    }

    // Display image
    var initialThumbnail = UIImage(named: "Swarm_Bee.png")

    if let thumbnail = object["imageFile"] as? PFFile {

        thumbnail.getDataInBackgroundWithBlock{
            (imageData, error) -> Void in
            if error == nil {
                let image = UIImage(data: imageData!)
                cell.customImage.image = image
            }}
    }

    return cell

}
receives the following error
 overriding method with selector 'tableView:cellForRowAtIndexPath:object:' has incompatible type '(UITableView,NSIndexPath,PFObject) -> PFTableViewCell'

I have looked up all the compatibility errors (removing !). Another post had a similar issue:
Parse SDK 1.7.1 not working in Xcode 6.3
But only their number 3 error.  All other issues in that post were addressed, but this error remains.  Any solutions or recommendations of where to look?

A: I figured it out. Use the following override function:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
  //...
}

The difference is making the PFObject and the PFTableViewCell optionals.


text:
Q: Converting SQL Server string to datetime for import into Oracle I am using automation designer in TOAD to import data from SQL Server via an odbc connection into an Oracle table.
One of the columns is a string ssdatetimestr of the form yyyy-mm-dd hh24:mi:ss.mmmmm. I want to use an expression in the import wizard to convert this to an Oracle date.
I have tried the expression
to_date(substr(ssdatetimestr,1,19),'yyyy-mm-dd hh24:mi:ss')

but this throws an error

'to_date' is not a valid date and time

Any suggestions

A: I suggest using DATE/TIMESTAMP literals:

To specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal, as shown in this example:
DATE '1998-12-25'

The TIMESTAMP datatype stores year, month, day, hour, minute, and second, and fractional second values. When you specify TIMESTAMP as a literal, the fractional_seconds_precision value can be any number of digits up to 9, as follows:
TIMESTAMP '1997-01-31 09:26:50.124'

A: The error message you gave (it would have been better if you had included the ORA-nnnn number) suggests the problem is not in the construction of the to_date function (I see nothing wrong with it, BTW) but rather how it was used in context.  But you don't give us the context ... the full statement that included your to_date


text:
Q: How do I keep the items from hiding in connected sortable lists inside scrolling panes with jQuery? I have a couple of jQuery sortable list connected to each other. Since both lists are quite long, they are inside divs that are set to scroll on overflow. Dragging from one and dropping on another works, but the item is not visible during the process. It becomes invisible when it tries to leave the scrolling section.
Here's the list:

and here I'm dragging an item to the outside and it starts to be hidden by the outside of the scrollable pane:

Here's a video of the issue: https://vimeo.com/40218644
Any ideas how to make that item not being hidden by the rest of the page?


text:
Q: To draw an Underline below the TextView in Android I want to draw the underline below my TextView. I have searched a few content but couldn't find out anything fruitful.
Can anyone please help me out here?

A: A simple and sustainable solution is to create a layer-list and make it as the background of your TextView:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp">
        <shape>
            <stroke
                android:width="1.5dp"
                android:color="@color/colorAccent" />
        </shape>
    </item>
</layer-list>

A: just surround your text with  tag in your string.xml resource file
<string name="your_string">Underlined text</string>

and in your Activity/Fragment
mTextView.setText(R.string.your_string);

A: There are three ways of underling the text in TextView.

*

*SpannableString

*setPaintFlags(); of TextView

*Html.fromHtml();
Let me explain you all approaches :
1st Approach
For underling the text in TextView you have to use SpannableString
String udata="Underlined Text";
SpannableString content = new SpannableString(udata);
content.setSpan(new UnderlineSpan(), 0, udata.length(), 0);
mTextView.setText(content);

2nd Approach
You can make use of setPaintFlags method of TextView to underline the text of TextView.
For eg.
mTextView.setPaintFlags(mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
mTextView.setText("This text will be underlined");

You can refer constants of Paint class if you want to strike thru the text.
3rd Approach
Make use of Html.fromHtml(htmlString);
String htmlString="This text will be underlined";
mTextView.setText(Html.fromHtml(htmlString));

OR
txtView.setText(Html.fromHtml("underlined text"));

A: If your TextView has fixed width, alternative solution can be to create a View which will look like an underline and position it right below your TextView.
<RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent">

        <TextView
            android:id="@+id/myTextView"
            android:layout_width="20dp"
            android:layout_height="wrap_content"/>

        <View
            android:layout_width="20dp"
            android:layout_height="1dp"
            android:layout_below="@+id/myTextView"
            android:background="#CCCCCC"/>
</RelativeLayout>

A:
5 Amazing Ways To Underline A TextView In Android - Kotlin/Java & XML

*

*String html = "Underline using Html.fromHtml()";
textview.setText(Html.fromHtml(html));
But Html.fromHtml(String resource) was deprecated in API 24.
So you can use the latest android support library androidx.core.text.HtmlCompat. Before that, you need to include the dependency in your project.
`implementation 'androidx.core:core:1.0.1'`

*String html = " 1.1 Underline using HtmlCompat.fromHtml()";
        //underline textview using HtmlCompat.fromHtml() method
        textview11.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY));
Using strings.xml,

*<string name="underline_text">1.3 <u>Underline using HtmlCompat.fromHtml() and string resource</u></string>
textview13.setText(HtmlCompat.fromHtml(getString(R.string.underline_text), HtmlCompat.FROM_HTML_MODE_LEGACY));
using PaintFlags

*textview2.setPaintFlags(textview2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        textview2.setText("2. Underline using setPaintFlags()");
using SpannableString
`String content1 = "3.1 Underline using SpannableString";
        SpannableString spannableString1 = new SpannableString(content1);
        spannableString1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
        textview31.setText(spannableString1);`

A: Its works for me.
tv.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);

A: For anyone still looking at this querstion. This is for a hyperlink but you can modify it for just a plain underline:
Create a drawable (hyperlink_underline.xml):
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:top="-10dp"
        android:left="-10dp"
        android:right="-10dp">
    <shape android:shape="rectangle">
      <solid android:color="@android:color/transparent"/>

      <stroke android:width="2dp"
              android:color="#3498db"/>
    </shape>
  </item>
</layer-list>

Create a new style:

Then use this style on your TextView:
<TextView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    local:MvxBind="Text Id; Click ShowJobInfoCommand"
    style="@style/HyperLink"/>

A: You can use Kotlin Extension and type your own drawUnderLine method.
fun TextView.drawUnderLine() {
    val text = SpannableString(this.text.toString())
    text.setSpan(UnderlineSpan(), 0, text.length, 0)
    this.text = text
}

yourTextView.drawUnderLine()

A: In Kotlin you can create extension property:
inline var TextView.underline: Boolean
    set(visible) {
        paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
        else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
    }
    get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG

And use:
textView.underline = true

A: If you want to under line Email Address Text and want to open Email related app when user click on that particular Email address then here is best way. Simply use below property.
android:autoLink="email"

Similarly you can you for website
android:autoLink="web"

Additionally if you want to set text colour you can you below property
android:textColorLink="@color/email_text_color"


text:
Q: How to aggregate a collection and find min/max values I have an "orders" collection which is like this:
{ typeID: 1, buyOrder: true, price: 100 },
{ typeID: 1, buyOrder: false, price: 120 },
{ typeID: 1, buyOrder: false, price: 130 },
{ typeID: 1, buyOrder: false, price: 250 },
{ typeID: 2, buyOrder: true, price: 500 },
{ typeID: 2, buyOrder: false, price: 610 },
{ typeID: 2, buyOrder: false, price: 690 },
{ typeID: 2, buyOrder: false, price: 590 }

and I want to aggregate this collection and find the best buy/sell price for each typeid.
The result should be:
{ typeID: 1, bestBuy: 100, bestSell: 120 }
{ typeID: 2, bestBuy: 500, bestSell: 610 }

Define bestBuy / bestSell
bestBuy  = (buyOrder = true && max price)
bestSell = (buyOrder = false && min price)

This is what I have so far but I know that its wrong. Any ideas ?
db.orders.aggregate([
    { $sort : { typeID : 1 }},
    { $group:
        { _id: { typeID : "$typeID", buyOrder : "$buyOrder"},
        price: { $max: "$price" },
        }
     },
     { $project:
         { _id: 0,
             typeID: "$_id.typeID",
             price: "$price",
             buyOrder: "$_id.buyOrder",
         }
     }
    ])

Thanks for your time.

A: You may not yet be aware of the $cond operator which works as a ternary condition. So basically if a condition given a as a first argument is true then use the value in the next argument. If the condition evaluates to false then use the value in the last condition in the operator.
This turns out to be perfect as you already have an indicator of true or false to determine the field
db.orders.aggregate([
    { "$project": {
        "typeID": 1,
        "bestBuy": { "$cond": [
            "$buyOrder",
            "$price",
            null
        ]},
        "bestSell": { "$cond": [
            "$buyOrder",
            null,
            "$price"
        ]}
    }},
    { "$group": {
        "_id": "$typeID",
        "bestBuy": { "$max": "$bestBuy" },
        "bestSell": { "$min": "$bestSell" }
    }},
    { "$sort": { "_id": 1 } }
])

So the use of $max and $min here can negate the null values in the results where the condition was not met.

A: Maybe with a mapreduce you can achieve this with something like that :
var mapFunction1 = function() {
 emit(this.typeID , this.buyOrder, this.price);
};

var reduceFunction1 = function(key, values) {
 reducedValue = { bestBuy: 0, bestSell: 0 };
 for (var idx = 0; idx < values.length; idx++) {
  if(values[idx].buyOrder && reducedValue.bestBuy < values[idx].price) {
   reducedValue.bestBuy = values[idx].price
  }
  if(!values[idx].buyOrder && reducedValue.bestSell > values[idx].price) {
   reducedValue.bestSell = values[idx].price
  }
 }
 return reducedValue;
};

db.orders.mapReduce(
 mapFunction1,
 reduceFunction1,
 { out: "your_result" }
)

Hope it helped


text:
Q: Custom Command Passing Converstation Text Does anyone know if it is possible for a custom Lync command to pass the conversation text in as an argument? I know I can pass in the %user-id% and %contact-id% but as far as I know those are the only arguments that I can pass.  Ultimately what I am looking to do is have a C# console application that gets executed via a lync custom command.  The console app then would take the conversation, user id and contact id and log it to a database. Is this even possible?  Are there any other ways that this can be achieved?
Thanks in advance

A: You could get a reference to the Lync client automation from your console client. Since you know all parties involved in the conversation, it should be possible to enumerate the active conversations and find the one which send the command.


text:
Q: QGIS GRASS Processing Not Working on MacOS? Recently upgraded to QGIS3 (3.0.2) for MacOS (High Sierra) and encountered GRASS (7.2.2) issues. Tried adding a custom variable and now when running GRASS algorithms (e.g. r.reclass) I get the following error:

WARNING: Default locale settings are missing. GRASS running with C locale.
Starting GRASS GIS...
ERROR: Path '//' doesn't exist
Default locale not found, using UTF-8
Exiting...

The GRASS7 Path in Settings --> Options --> Processing seems to be correct. What am I missing?

A: Please try installing the new QGIS 3.4. I had the same issue, it has now been fixed.

A: I had a similar issue recently on windows. QGIS and QGIS with GRASS have separate launchers, and making sure I was launching "QGIS with GRASS" solved my issue.


text:
Q: Issue sending routed POST params I have problems with a submit form (or with the routing design) that deletes N table based on id.
I've a made a simple routing function that use the index php file:
function relativeRouter ($controller,$action,$query_data=""){
    $param = is_array($query_data) ? http_build_query($query_data) : "$query_data";
    $url = "index.php?controller=$controller&action=$action&$param";
    return $url;

The index create instances of controllers using controller=?&action=?.
It also bind the POST/GET params to the methods arguments (in an array, $params). (im already aware to not use directly calls to superglobals)
$params=array();
if(isset($_GET['controller'])&&isset($_GET['action'])){
    $c = $_GET['controller'];
    $a = $_GET['action'];
    // add all query string additional params to method signature i.e. &id=x&category=y
    $queryParams = array_keys($_GET);
    $queryValues = array_values($_GET);
        for ($i=2;$i<count($queryParams);$i++) {
            $params[$queryParams[$i]] = $queryValues[$i];
        }

if ($_POST) {
print_r($_POST); // THIS CONTAINS ONLY 1 PASSED ID.
// add all query string additional params to method signature i.e. &id=x&category=y
$queryParams = array_keys($_POST);
$queryValues = array_values($_POST);
        for ($i=0;$i<count($_POST);$i++) {
            $params[$queryParams[$i]] = $queryValues[$i];
        }
        }
include_once APP_ROOT."/controller/$c.php";
$controller = new $c();//CombustibiliController
$controller->$a($params);//inserimento

}  else {
//attiva controller predefinito
$controller = new Admin();
$controller->index();
}

The routing works well in a form with different HTML form item names. (name='') but i'm expriencing problems by passing an array of id that are used for a multi-checkbox delete.
The $_POST is arriving with an array with only one items instead of many :
Array ( [ids] => 110 )

While works with no hassle with the insert form:
Array ( [title] => 435 [desc] => 5534 )

Here the table view:
   <?php
if (isset($products)) {
$action = relativeRouter("ProductsController", "deleteProducts");
$html="<form id='multiselect' action='$action' method='POST'>\n";
foreach ($products as $product) {
    $html.= "
\n"
            ."<input type='checkbox' name='ids' value='".$product->id."'>	\n"
            ."".$product->id."	\n"
            ."".$product->title."	\n"
            ."".$product->description."	\n"
            ."".$product->image."	\n"
            ."
\n";
}
$html.="</form>\n";
echo $html;
}
?>

And here the jQuery that runs the form from a button:

Hope someone can help. Firefox networks show module params but the POST only contains one of them, always the last.

A: <input type='checkbox' name='ids[]' value='".$product->id."'>
replace this and check. name should contain array operator for multivalue


text:
Q: How to show s with caron in RTF file [PHP]? I have template rtf text, that I open in PHP and replace some strings with some other.
I have latin2 database where I get some text that needs to be replaced in file. Result from database contains latin2 characters (s with caron (š), c with caron (č), z with caron (ž)).
When I print the result from database in web browser, it prints fine (it shows š č and ž), but when I save it in rtf file, I get copyright sign instead of s caron.
What am I doing wrong?
I tried to convert string from UTF-8 to ISO-8859-2 and vice-versa, but it doesn't work anyway.
Let's say I have string Ajdovščina.
Converting from UTF-8 to ISO-8859-2//TRANSLIT with iconv shows only Ajdov.
Converting from UTF-8 to ISO-8859-2//IGNORE with iconv shows Ajdovina.
Converting from UTF-8 to ISO-8859-2 with iconv shows the same as translit - Ajdov.
What do I need to check and fix to save it properly in file?
I'm saving it with file_put_contents.


text:
Q: Does std::deque actually have constant time insertion at the beginning? The Standard says:

A deque is a sequence container that supports random access iterators (27.2.7). In addition, it supports
  constant time insert and erase operations at the beginning or the end; insert and erase in the middle take
  linear time.

However, it also says in the same Clause:

All of the complexity requirements in this Clause are stated solely in terms of the number of operations on the contained objects. [ Example: The copy constructor of type vector<vector<int>> has linear complexity, even though the complexity of copying each contained vector<int> is itself linear. — end example ]

Doesn't this mean that insertion at the beginning of, say, deque<int> is allowed to take linear time as long as it doesn't perform more than a constant number of operations on the ints that are already in the deque and the new int object being inserted?
For example, suppose that we implement a deque using a "vector of size-K vectors". It seems that once every K times we insert at the beginning, a new size-K vector must be added at the beginning, so all other size-K vectors must be moved. This would mean the time complexity of insertion at the beginning is amortized O(N/K) where N is the total number of elements, but K is constant, so this is just O(N). But it seems that this is allowed by the Standard, because moving a size-K vector doesn't move any of its elements, and the "complexity requirements" are "stated solely in terms of the number of operations" on the contained int objects.
Does the Standard really allow this? Or should we interpret it as having a stricter requirement, i.e. constant number of operations on the contained objects plus constant additional time?

A:
For example, suppose that we implement a deque using a "vector of size-K vectors".

That wouldn't be a valid implementation. Insertion at the front of a vector invalidates all of the pointers/references in the container. deque is required to not invalidate any pointers/references on front insertion.
But let's ignore that for now.

But it seems that this is allowed by the Standard, because moving a size-K vector doesn't move any of its elements, and the "complexity requirements" are "stated solely in terms of the number of operations" on the contained int objects.

Yes, that would be allowed. Indeed, real implementations of deque are not so dissimilar from that (though they don't use std::vector itself for obvious reasons). The broad outline of a deque implementation is an array of pointers to blocks (with space for growth at both the front and back), with each block containing up to X items as well as a pointers to the next/previous blocks (to make single-element iteration fast).
If you insert enough elements at the front or back, then the array of block pointers has to grow. That will require an operation that is linear time relative to the number of items in the deque, but doesn't actually operate on the items themselves, so it doesn't count. The specification has nothing to say about the complexity of that operation.
Without this provision, I'm not sure if the unique feature-set of deque (fast front/back insert and random-access) would be implementable.

A: I think you're reaching a bit, in how you interpret the meaning of complexity domains. You're trying to make a distinction between "linear time" and "linear complexity" which I'm not convinced makes much sense.
The standard's clear that insertion at the front is constant-time, and I think we all agree on that. The latter passage just tells us that what each of that "constant" quantity of operations involves underneath is simply not specified or constrained by the standard.
And this is not unusual. Any algorithm works on some basis of abstraction. Even if we were to write an algorithm that came down to individual machine instructions, and we said that there were only ever N machine instructions generated by our algorithm, we wouldn't go investigating what sort of complexity each individual complexity has inside the processor and add that into our results. We wouldn't say that some operations end up doing more on the quantum molecular level and thus our O(n) algorithm is actually O(N×M3) or somesuch. We've chosen not to consider that level of abstraction. And, unless said complexity depends on the algorithm's inputs, that's completely fine.
In your case, the size of the moved/copied inner vectors isn't really relevant, because these do not inherently change as the deque grows. The number of inner vectors does, but the size of each one is an independent property. Thus, it is irrelevant when describing the complexity of inserting a new element into the outer vector.
Does the actual execution time (which could itself be described in some algorithmical terms if you so chose) vary depending on the contents of the copied inner vectors? Yes, of course. But that has nothing to do with how the task of expanding the outer vector grows in workload as the outer vector itself grows.
So, here, the standard is saying that it will not copy N or N2 or even log N inner vectors when you put another one at the front; it is saying that the number of these operations will not change in scale as your deque grows. It is also saying that, for the purposes of that rule, it doesn't care what copying/moving the inner vectors actually involves or how big they are.
Complexity analysis is not about performance. Complexity analysis is about how performance scales.