text:
Q: (Can I minimize the) Footprint of template in my C++ Code? I have a large class which basically handles one buffer of variable (numeric) datatype. So it seems a good choice to use a class template with this datatype as the only parameter. I'm not experienced in C++ and I wonder/worry a bit about the "footprint" such a template makes in my code.
There are three implications of templates which in my (C++ unexperienced) eyes are not necessary and make code ugly. I tried to avoid them, but neither did I find a good example how to do it nor did I manage to find it out by myself.
So the goal of this question is: Can you either confirm the following statements or give a counterexample?

*

*When using a class template, all class methods have to go into the header file. Even if they have no templated type in their interface or implementation.

*When using a static method or member of the class, I always have to specify a template parameter (MyClass< double > :: MY_STATIC), even if the templatization does not affect any of the static properties of the class.

*When using the class as a parameter for a function, I always have to give a template parameter, even when this function does not access any of the templated members? (function myFunc(MyClass< double> & myClass){ do something } )

A: As a general rule, don't have functions/data members in a template class which does not use the template parameters. Have a base class, put all non-template related things there, your template class should derive from it.
To answer your questions:

*

*yes, everywhere where you need to instantiate the template, you need to see the full definition of the class and it's functions

*yep, but put that into the base class

*yes, see above

EDIT: One of the reasons to move to base class is code bloating (this expression actually exist, you can google it for more info): If you don't move the template unrelated code to a base class, the very same template independent code will be copied for all instantiation of your template, which means a lot of unnecessary code. If you put it to a base class, you will only have this code once.

A: *

*Yes. On the plus side, the code is only generated when the metod is actually used for the specialization.

*Yes. However, there is no (other then design choice) need for a static method to be a memeber of the templated class if it has no use for the templated parameter.

*Yes. The size and memory layout of the structure is determined by the template parameter.


text:
Q: Как при записи данных в файл, убрать последний элемент? У меня есть скрипт:
count = 0
with open('final_1.geojson', 'w') as fin:
    fin.write('{"type": "FeatureCollection","features": [')
    with open('long_1.txt', 'r') as long:
        for i in long:
            i_1, i_2 = i.split()
            with open('short_1.txt', 'r') as short:
                for k in short:
                    k_1, k_2 = k.split()
                    string = '{"type": "Feature", "properties": {"area": ' +str(count)+'}, "geometry": {"type": "Polygon", "coordinates": [[['+str(i_1) + ',' + str(k_1)+ ']'+',' + '[' + str(i_2)+','+str(k_1) + ']'+',' + '['+str(i_2)+ ',' + str(k_2) +'],'  + '[' + str(i_1)+ ',' + str(k_2) +']]]}},'
                    fin.write(string)
                    count+=1
    end = ']}'
    fin.write(end)

Общая логика такая: Скрипт проходит по файлам, вытягивает из них нужные значения и складывает в новый файл в нужном мне виде.
В скрипте есть перменная string. В конце переменной есть запятая ','
Мне надо, чтобы эта запятая была у всех string, кроме последнего значения.
Сейчас у меня вот так:
"geometry": {"type": "Polygon", "coordinates": [[[5.009,10.005394],[5.01,10.005394],[5.01,10.006293],[5.009,10.006293]]]}},{"type": "Feature", "properties": {"area": 86}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.006293],[5.01,10.006293],[5.01,10.007192],[5.009,10.007192]]]}},{"type": "Feature", "properties": {"area": 87}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.007192],[5.01,10.007192],[5.01,10.008091],[5.009,10.008091]]]}},{"type": "Feature", "properties": {"area": 88}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.008091],[5.01,10.008091],[5.01,10.00899],[5.009,10.00899]]]}},{"type": "Feature", "properties": {"area": 89}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.00899],[5.01,10.00899],[5.01,10.009889],[5.009,10.009889]]]}},]}

Должно быть вот так:
"geometry": {"type": "Polygon", "coordinates": [[[5.009,10.005394],[5.01,10.005394],[5.01,10.006293],[5.009,10.006293]]]}},{"type": "Feature", "properties": {"area": 86}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.006293],[5.01,10.006293],[5.01,10.007192],[5.009,10.007192]]]}},{"type": "Feature", "properties": {"area": 87}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.007192],[5.01,10.007192],[5.01,10.008091],[5.009,10.008091]]]}},{"type": "Feature", "properties": {"area": 88}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.008091],[5.01,10.008091],[5.01,10.00899],[5.009,10.00899]]]}},{"type": "Feature", "properties": {"area": 89}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.00899],[5.01,10.00899],[5.01,10.009889],[5.009,10.009889]]]}}]}

Посмотрите в конец двух строк.
Вместо '}},]}' в первой строке я хочу сделать '}}]}' для последнего значения.
Как убрать запятую с последнего значения в цыкле?

A: Честно говоря, писать JSON можно гораздо проще, работая с dict.
import json

count = 0
data = {
    'type': 'FeatureCollection',
    'features': []
}

with open('long_1.txt', 'r') as long:
    for i in long:
        i_1, i_2 = i.split()
        with open('short_1.txt', 'r') as short:
            for k in short:
                k_1, k_2 = k.split()
                data['features'].append({
                    'type': 'Feature',
                    'properties': {
                        'area': str(count),
                    },
                    'geometry': {
                        'type': 'Polygon',
                        'coordinates': [[
                            [str(i_1), str(k_1)],
                            [str(i_2), str(k_1)],
                            [str(i_2), str(k_2)],
                            [str(i_1), str(k_2)]
                        ]]
                    }
                })
                count += 1

with open('final_1.geojson', 'w') as fin:
    fin.write(json.dumps(data))

Upd.
Решение:
Добавить переменную file_is_empty, которая будет говорить нам о том, что в файл мы ничего не записывали, и убрать в конце строки запятую.
При первой итерации - запишется строка без запятой. При второй и последующих итерациях переменная file_is_empty уже будет иметь значение False, а тогда в переменную string добавится запятая в самое начало. По окончанию цикла будет валидный json без проблемной запятой в конце.
count = 0
file_is_empty = True
with open('final_1.geojson', 'w') as fin:
    fin.write('{"type": "FeatureCollection","features": [')
    with open('long_1.txt', 'r') as long:
        for i in long:
            i_1, i_2 = i.split()
            with open('short_1.txt', 'r') as short:
                for k in short:
                    k_1, k_2 = k.split()
                    string = '' if file_is_empty else ','
                    string += '{"type": "Feature", "properties": {"area": ' +str(count)+'}, "geometry": {"type": "Polygon", "coordinates": [[['+str(i_1) + ',' + str(k_1)+ ']'+',' + '[' + str(i_2)+','+str(k_1) + ']'+',' + '['+str(i_2)+ ',' + str(k_2) +'],'  + '[' + str(i_1)+ ',' + str(k_2) +']]]}}'
                    fin.write(string)
                    file_is_empty = False
                    count+=1
    end = ']}'
    fin.write(end)

redpajama_set_name: RedPajamaStackExchange


text:
Q: trying to get a console script in cakephp to access a controller So, I have been trying to get a console script working in CAKEPHP. But it won't let me access controllers using the $uses member.
I have tried assigning an array to $uses, and a non array to $uses, both outside and inside of a method inside of my JobManagerClass, and nothing works.
Right now, I have...
<?php

class JobManagerShell extends AppShell {
public $uses;

public function main() {
    $this->_processJobs();
}

public function _processJobs() {

    $this->uses = array("Job");

    $jobs = $this->Job->find("all");

    foreach ($jobs as $job) {
        if ($job["is_running"] == 1) exit;
    }

    foreach ($jobs as $job) {
        $id = $this->Job->id = $job["id"];
        $this->Job->saveField(array("Job" => array("is_running" => 1)));
        exec($job["command"] . "2> errors.txt");
        $errorsFile = fopen("errors.txt");
        $errorsText = fread($errorsFile);
        fclose($errorsFile);
        $this->Job->delete($this->Job->id);
        $this->uses = array("Error");
        $this->Error->save(array("Error" => array("job_id" => $i, "error" => $errorsText)));
    }*/
}

}
?>
and that gives the error:
PHP Fatal error:  Class 'AppModel' not found in /home/webdev/webroot/Cake/lib/Cake/Utility/ClassRegistry.php on line 185

If I try changint the line that says:
$this->uses = array("Job");

to
$this->uses = "Job";

I get the error:
Notice Error: Undefined property: JobManagerShell::$Job in [/home/webdev/webroot/Vehicle_Scrapper/lib/Cake/Console/Shell.php, line 491]

I've been trying to find an answer to this, but I can't seem to.

A: in your shell script/file, which may be here(src/shell/your-script-file). (for cake-php 3.X)
on top use this:
use Cake\Core\App;
use App\Controller\ReportsController; //(path to your controller).

and under initialize() function create object of your controller.
public function initialize() {
    parent::initialize();
    $this->reports = new ReportsController();
}

after this you can call any of your controller function in shell file.
for-example i have get_reports_details() function in my ReportsController so i will call this function like:
publict function main(){
 $this->reports->get_reports_details();
}

A: If you need use other model use:
$this->loadModel('ModelName')
Read more: loadModel in CakeBook
Also, I don't recommend using controller action in shell.
Use model methods instead.
(In case if you don't have in model things that you need - move them to model [this is their place].)


text:
Q: How to run a code through each column (containing information) within excel? I'm working on a document where I need to remove duplicate values from several hundreds of columns independently of one another.  My data begins in column H. I know I can use

Range("H1:H100").RemoveDuplicates Columns:=1, Header:=xlYes

to do it on that column, but is there a way to start with H and then run that code on every column which contains data?
I've searched extensively on this issue and haven't been able to find code that successfully does what I'm looking for

A: With the following code, the variable c starts at 8 because you have said your code needs to run from column H - you can change this to suit.
Option Explicit
Sub RemoveDuplicates()
Dim c As Long, LastCol as Long
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

For c = 8 To LastCol
    If Cells(Rows.Count, c).End(xlUp).Row <> 1 Then
        Cells(1, c).EntireColumn.RemoveDuplicates Columns:=Array(1), Header:=xlYes
    End If
Next

End Sub

A: It's pretty basic, something like this should do the trick:

For Each Rng In ReplaceRng.Columns(1).Cells
    InputRng.replace what:=Rng.Value, replacement:=Rng.Offset(0, 1).Value, Lookat:=xlPart
Next


text:
Q: I'm getting 'module' object is not callable error when i try to run my code def define_discriminator(in_shape=(100, 100, 3)):
    model = Sequential()
    model.add(Conv2D(64, (3, 3), strides=(2, 2), padding='same', input_shape=in_shape))
    model.add(LeakyReLU(alpha=0.2))
    model.add(Dropout(0.4))
    model.add(Conv2D(64, (3, 3), strides=(2, 2), padding='same'))
    model.add(LeakyReLU(alpha=0.2))
    model.add(Dropout(0.4))
    model.add(Flatten())
    model.add(Dense(1, activation='sigmoid'))
    opt = adam_v2(lr=0.0002, beta_1=0.5)
    model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
    return model

but in the end i keep getting -
*in define_discriminator
    opt = adam_v2(lr=0.0002, beta_1=0.5)
TypeError: 'module' object is not callable*

someone please help me out with this!

A: Replace
opt = adam_v2(lr=0.0002, beta_1=0.5)

with
opt = tf.keras.optimizers.Adam(learning_rate=0.0002, beta_1=0.5)


text:
Q: Logitech MX Master 2S Configure Horizontal (Side) Scroll and Thumb Button Ubuntu 18.04 Any ideas on how to make the Logitech MX Master 2S mouse thumb button to show desktop and the horizontal scroll to be zoom in/out?
Thanks a lot!!!


text:
Q: Read csv file give weird result with encoding UTF8 So i have a problem while doing my project,i'm trying to read my csv file,i have try using encoding utf16 and utf8,and both give me weird result.
Below is the result from utf8
:�4^xr7zd5fixekg_2020-01-31T190000_88ffa7d6bd0e31b86d9c3ac3d7c601f5_c3575d.csv�[o�8���ST}��6Ɨ��U��msQ��j4!c�ԛ" U���k$�;���l�����ǿ��vp���;�a0.�Ggݳ���u�"�
��G��?
      �No��u^���%8>>v��ο9_�L��7燘�C���
��韊��m���9��Yn��Z���",2!':��T�dJ1�
                                    3N�d�Ea����l�鼼u�\�͙<L��H��F��ֲ(O�
                                                                      �Urj�$,Lu��ަ����:<ME�&u�B��DQuO'c1�3���<�v��өV�(�M�L�:��tl��悍�T_����~k%�.�5�D�����n^�J/���L$�X�b�=�T����id(S�W�%����>u#���m�y㯴-�s��z�M�2]�쩉uU��   ��|j��J��UC���Օ2=O��$����/�۰H':i.�p���k�Q����i����}81IIB/K!��S����<��������-�q�:�6ы������V:�_g�t����s��"��nN�MY��H9���sL?;�{:
                                                                             ��epΕV3�O
                                                                                ����R[�g���I�����'}�/]B��b��y��P��G
                                                                                ƜqB!#��TzHcJ�XBI�����b�b�A]��3�1��y]y8��'�� ��(�S;iw����f�B�3��9�y�!�c�J��G.�(v#D��
x��9����a�:�w�`|�&o]��#�hL%+ybc`y���B��f��3hK�'1�9G0��d
o�s����5�=�'����x��U�^_t��_�˳A�^�]u:�wH����Q;��G�����'��m�&-����U�ӗp0�c�{H��
                    ������l�;�^�~��j��!��t��!"���e�=�����eݼ�)k�r���Y�=��!;�~/Y�}�!�
                                                                                ��6Ѷ�"��1��Y�}�C�֖�����-���ԮB^U|�I�ۈ�㹑����;E������6�,7��K�7�(�䒺�Ş���,\y,c)-��<�"��ǩ�e#@Ƒ��`o
                                                    ���3�q�[�ĝ(N����˿��t�K�|���t���"C��ë����f;�J�=Z�o_��i�����g��;��y4o_;�����U��%��!�� �`������dZ>!;��ԉw�/,

and Below is my code
function readFile(req, res, next) {
  const csvString = fs.readFileSync('./server/components/engagement/downloaded.csv', { encoding: 'utf8' })
  console.log(csvString.toString())
};

I can open the file with excel,but if i try to open it in visual studio code it says The file is not displayed in the editor because it is either binary or uses an unsupported text encoding
UPDATE
So i try to use package neat-csv https://flaviocopes.com/node-read-csv/ , it gives me weird string again,but i think i get closer to my goals this time(maybe ?). Below is the output from the package.
[ { '\u001f�\b\b:�4^\u0000\u0003xr7zd5fixekg_2020-01-31T190000_88ffa7d6bd0e31b86d9c3ac3d7c601f5_c3575d.csv\u0000�[o�8\u0014���ST}��6Ɨ��U��msQ��j4\u001a!c�ԛ\u0004" \u0019U���k\u0002$�;���l��\u0001���ǿ��vp���;�a0�\b.�Ggݳ���u�"�': '��G��?\f�No��u^\u0006���%8>>v��ο9_�L��7燘�C���' },
  { '\u001f�\b\b:�4^\u0000\u0003xr7zd5fixekg_2020-01-31T190000_88ffa7d6bd0e31b86d9c3ac3d7c601f5_c3575d.csv\u0000�[o�8\u0014���ST}��6Ɨ��U��msQ��j4\u001a!c�ԛ\u0004" \u0019U���k\u0002$�;���l��\u0001���ǿ��vp���;�a0�\b.�Ggݳ���u�"�':
     '��韊�\u0012�m���9��Yn��Z���",2!\':��T�dJ1�\u000b3N�\u0006d�Ea����l�鼼u\u0018�\\�͙<L��H��F��ֲ(O�\u000b�U\u0000rj�$,Lu��\u0011ަ���\u001d�:\u000f<ME�&u�B��DQuO\'c1�3�\u0014��\u000f<�v��\u0010өV�(\u001e�M�L�:��t\u001dl��悍�T_����~k%�.�5�D\u0017�����n^�J/���L$�X�b�=�T���\u001e�i\u0019d(S�W�%����>u#���m�y㯴-\u0019�s��z�\u0019M�2]�쩉uU��\t��|j��J��UC���Օ2=O��$����/�۰H\':i\u001a.�p���k�Q����i����}81IIB/K!��S����<\u000f��������\u001e-�q�:�6ы������V\u000e:�_g�\u0001\u000et�\u000f�\u0019��s��"�\u0000�nN\u0019�M\u0011Y��H9���sL?;�{:\u000b��\u0010epΕV3�O\u000b�\u0007\u000f�\u0015��R[\u0003\u0002\u001b�g���I�����\'}\u0000�/]B��b�\u0011�y��P��G\fƜq\u0007B!\u0014#��TzHcJ\u0004�X�\bBI�����b�b�A]��\u00063�1��y]y8��\'�\u0001\u0002�\t��(�S;\u0010iw����f�B\u000e�3��\u001d\u00079�\u001dy�!�c��\bJ��G.�(v#D�\u0007\u0011�' },
  { '\u001f�\b\b:�4^\u0000\u0003xr7zd5fixekg_2020-01-31T190000_88ffa7d6bd0e31b86d9c3ac3d7c601f5_c3575d.csv\u0000�[o�8\u0014���ST}��6Ɨ��U��msQ��j4\u001a!c�ԛ\u0004" \u0019U���k\u0002$�;���l��\u0001���ǿ��vp���;�a0�\b.�Ggݳ���u�"�':
     '\u0000�\u0011�\bS\u0000\u0003�$�\\!�X�V\'A�\u001f�J�m�\u001f&x����;\u0010�\u0006~5\\8���n?<�\u0019�\u0006�w(\u0001��;\t<�HPR�d\rx��9����a\u001b�:�\u0006w�\u001c`\u001b\u0003|\to]��#�hL%+yb\u0017c`y���B��\u0000f��3hK�\'1�9�\bG0�' },
  { '\u001f�\b\b:�4^\u0000\u0003xr7zd5fixekg_2020-01-31T190000_88ffa7d6bd0e31b86d9c3ac3d7c601f5_c3575d.csv\u0000�[o�8\u0014���ST}��6Ɨ��U��msQ��j4\u001a!c�ԛ\u0004" \u0019U���k\u0002$�;���l��\u0001���ǿ��vp���;�a0�\b.�Ggݳ���u�"�':
     '2�bfg+�W�����U�-�E�5�U�^_t��_�˳A�\u0013^�]u:�wH���\u0013�Q;��G�����\'��m�&-����U�ӗp0\u001a�c�{H�\u0003�\ro�s���\u0003�5�=�\'����\u0011x�\u000b����\u000e�\u001b�l\u000f�\u0019;�^�~��j��!�\u001b7�t��!"���e�=�����eݼ\u0017�)k�r���Y�=��!;�~/Y�}�!�\u000b�\u0003�6Ѷ�"\u0010��1��Y�}�C\u0010�\u0007֖�����-\u0017���Ԯ\u0003\u0010B^U\u0004|�I�ۈ�㹑��\u0002��;E������6�\u0010,7��K�7\u001b�(�\u001e䒺�Ş���,`\b\\\u0004y,c\u001d)-��<\u0002�"\u0011��ǩ�e\u000f#@\u0000Ƒ��`o\u0005\f\u0018�\u0018\u0012�\u001e�3�q�[�ĝ(N��\u0014��˿\u0016��t�K\u001d\u001e�|���t���"C��ë����f;�J�=Z�o_\u0012��i�\u001f����g��;�\u001f�y4\u0017o_\u0018;\u0007�\u0012���\u001b�\u001fU\u0010��%��\u0005!�� �`����\u0001��d\u0002Z>!;\u001c��\u0005ԉw�/,\u0000\u0000' } ]

A: Your file looks like an xlsx, you should read the file using https://www.npmjs.com/package/exceljs package.
Check out the demo below:

const Excel = require('exceljs');
// read from a file
var filename = '/absolute/or/relative/path/to/file.xlsx';
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
  .then(function() {
    // use workbook

    workbook.eachSheet(function(worksheet, sheetId) {

      worksheet.eachRow(function(row, rowNumber) {
        console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));

        // Iterate over all cells in a row (including empty cells)
        row.eachCell({
          includeEmpty: true
        }, function(cell, colNumber) {
          console.log('Cell ' + colNumber + ' = ' + cell.value);

          // update the current cell value
          worksheet.getCell(cell.fullAddress).value = cell.value + ' ' + cell.value;

        });

      });

    });

    // target a specific cell
    worksheet.getCell('A1').value = 'new value';

    // after everything is done you can write the data to another file
    workbook.xlsx.writeFile('/path/to/my_new_file.xlsx')
      .then(function() {
        // done
      });

  });


text:
Q: If Java application has a memory leak, the JVM would eventually run out of memory and flag, right? I think the answer to this question should be yes...but I guess I'm not really sure, since I'm asking about it:)
I'm just trying to determine if my webapp has a memory leak somewhere. If the memory usage continues to increase, an Out of Memory error should be produced eventually, right?

A: Yes.
If you have a substantial leak you eventually get an OutOfMemoryError.
Although, if you have a small leak, it's possible to run for a long time without running out of memory. It depends on the size of the leak, heap size, and how long your servers run before an update or restart.

A: Yes if the memory usage continues to increase.
However, a memory leak is a situation where memory has been allocated and not released when it is no longer relevant. The definition does not mean that it has to be recurring or growing.
For instance, if you had 4GB of RAM in your JVM, had a bunch of leak events that ate up 3GB and are not going to have any more memory leak events, you are still restricted to the limited 1GB.
Therefore, you could very well have a leak, even a serious one, but not spot it until you've had enough events that would cause you to run out of memory or until the performance of other parts degenerates too much.
In my experience, these situations are more common that one would expect, making them notorious to track down.

A: Eventually.  The JVM has a notion of maximum heap size, meaning if it reaches the limit and tries to allocate more and can't, it will try to garbage collect; if it still can't allocate memory, you will get an exception thrown.

A: If you are trying to find a memory leak, monitoring your webapp using jconsole might be a good idea. Also JProbe can be used to identify leaks.

A: There are many tools available for analyzing, and many times automatically isolating, possible memory leaks. jhat ships with the JDK; Eclipse Memory Analyzer is free, and an example commercial offering is YourKit.


text:
Q: Does Refit work with Asp.net MVC or must it be used only in Asp.net Core I am attempting to create an SDK for an Asp.net Core 3.1 Web Api.  Everything I have found through internet searches suggest and provide examples using Refit.  I am trying to test the SDK in an Asp.net MVC project, however, when I attempt to install the latest version, it throws several errors and says that "Refit" cannot be found:

Is there a particular version of Refit that must be used?


text:
Q: Compiling a static QT application on Windows I am new to QT and I am enjoying the experience except for the fact I cannot manage to statically link the QT library to the output binaries. When I run the output file outside of the QT directory, I get The program can't start beacuse QtCored4.dll is missing. Obviously QT is dynamically linking their libraries and requesting a .dll I do not have. Is there a way to statically compile QT's libraries into a static binary so none of QT's dlls are required? I ask this because I am already up to 11 .dlls for my project, and I would really like to cut down the amount of files that have to be distributed with my software. Size is not a problem for me. Thanks.
I have tried adding CONFIG += static to the .pro file, but to no avail.

A: First off, you can't statically link Qt unless you've bought a commercial license. To do so would put you in violation of the LGPL license under which the non-commercial version is distributed. I feel your pain, I've got many, many DLL's to go with my software.
Thankfully, you probably do have the DLL's if you used the installer: you don't need to build from source, that should have been done automatically. You'll find them in Qt\Version\bin, where Qt is the directory you installed Qt, and version is the version of Qt you installed. For example, mine is found in G:\Libraries\Qt\4.7.1\bin.
I did, however, have some issues with not having one of the DLL's built - one for working with OpenGL - and performed a rebuild to do so. I've also done so when I've switched versions of Visual Studio. I think it's handy to be able to do so, it's easy, Open a terminal in the Qt directory, and execute:
configure.exe -platform XXX'

Where XXX denotes the type of build you want to perform. Valid options include win32-msvc2005, win32-msvc2008, win32-msvc2010. So I use:
configure.exe -platform win32-msvc2010'

Other options are detailed here. These instructions apply if you've downloaded the source code, however you might have to add the current directory to the path variable like so:
set PATH=%cd%\bin;%PATH%

The whole procedure should take about an hour.

A: You need to download the source packet of QT and compile it. It takes some time but is not really complicated.

*

*Download and unzip QT source

*Start a compiler shell (Visual Studio or mingw)

*Execute configure in the QT source directory - add a flag for static compile here

*execute make (Visual Studio nmake)

*Wait some hours depending on the speed of your machine


text:
Q: How to move a view to another view using animation in Android? I have a circle at the center of the screen inside which there's an ImageView + TextView. I have another two ImageView+TextView, one at the top and another at bottom of the screen.
My requirement is :
I want a copy of the top ImageView+TextView and a copy of the bottom ImageView+TextView to move in animation into the center of the circle, thereby changing the value of the textView inside the circle.
For example:
Say top textView has value 200 and bottom textview has value 300. I want a portion of those values (say 100 or 150) to animate and move into the circle, but the original values 200 and 300 should remain on the same position.
I've tried using TranslateAnimation. However I face issues finding the x and y coordinates of the center circle. It is not exactly going to the center of the circle. Also original view's position is not retained.
    TranslateAnimation animation = new
TranslateAnimation(startLayout.getX(),endLayout.getX(),
startLayout.getY(),endLayout.getY);
                    animation.setDuration(1000);
                    animation.setFillAfter(false);
                    startView.startAnimation(animation);

startLayout is the linearlayout in which ImageView and TextView reside.
Please help! Thanks!

A: I had the same issue and I fixed by using the next code (sorry is in Kotlin, but works the same in Java).Let's say viewFirst wants to reach viewTwo position:
(DON'T USE):
               viewFirst.animate()
                        .translationX(viewSecond.x)
                        .translationY(viewSecond.y)
                        .setDuration(1000)
                        .withEndAction {
                        //to make sure that it arrives,
                        //but not needed actually these two lines
                            viewFirst.x = viewSecond.x
                            viewFirst.y = viewSecond.y
                        }
                        .start()

(USE THIS SOLUTION):
               viewFirst.animate()
                        .x(viewSecond.x)
                        .y(viewSecond.y)
                        .setDuration(1000)
                        .withEndAction {
                        //to make sure that it arrives,
                        //but not needed actually these two lines
                            viewFirst.x = viewSecond.x
                            viewFirst.y = viewSecond.y
                        }
                        .start()

A: Using the getX() and getY() methods define the position of the view in pixels, but the constructor you use defines Float type values that must be values from 0.0f to 1.0f
TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
This is another option using the view`s position in pixels:
viewFirst.animate()
        .x(viewSecond.getX())
        .y(viewSecond.getY())
        .setDuration(1000).withEndAction(new Runnable() {
    @Override
    public void run() {
        viewFirst.setX(tv2.getX());
        viewFirst.setY(tv2.getY());
    }
}).start();

A: Try this for accurate coordinates
private fun moveView(viewToBeMoved: View, targetView: View) {
val targetX: Float =
    targetView.x + targetView.width / 2 - viewToBeMoved.width / 2
val targetY: Float =
    targetView.y + targetView.height / 2 - viewToBeMoved.height / 2

viewToBeMoved.animate()
    .x(targetX)
    .y(targetY)
    .setDuration(2000)
    .withEndAction {
        targetView.visibility = View.GONE
    }
    .start()

}


text:
Q: UICollectionViewFlowLayout (incorrect layout when targeting iOS7 under xcode6) I have a requirement to layout an array of photos as shown.  The code to generate the required layout is as follow where UICollectionViewFlowLayout is a super class of PhotoLayoutReordering:
@implementation PhotoLayoutReordering

-(instancetype) initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
    ;// additional set up here
    self.scrollDirection = UICollectionViewScrollDirectionVertical;
}
return self;
}

-(CGSize) calculateSecondaryCellSizeAndMargin {
CGSize cellSize;
cellSize.width = self.collectionView.frame.size.width/NUMBER_OF_COLUMNS;
cellSize.width = cellSize.width - 2*SPACE_BETWEEN_CELLS;
CGSize secondaryCellSize = CGSizeMake(cellSize.width,cellSize.width);
//    NSLog(@"cell width:%1.0f\t cell height:%1.0f\t   margin:%1.0f\n",secondaryCellSize.width,secondaryCellSize.height,_spaceBetweenCells);
//    NSLog(@"number of cells are: %d",(int)[self.collectionView numberOfItemsInSection:0]);
return secondaryCellSize;
}

-(CGSize) calculatePrimaryCellSize {
CGFloat width;
CGSize secondaryCellSize = [self calculateSecondaryCellSizeAndMargin];
width = (NUMBER_OF_COLUMNS-1)* secondaryCellSize.width + NUMBER_OF_COLUMNS*SPACE_BETWEEN_CELLS;
return CGSizeMake(width, width);
}

-(UICollectionViewLayoutAttributes*) layoutAttributesAtIndexPath:(NSIndexPath*) indexPath {
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
return attributes;
}

#pragma mark - UICollectionViewLayout overridden methods
-(CGSize) collectionViewContentSize {
CGSize primaryCellSize = [self calculatePrimaryCellSize];
CGFloat heightForPrimaryCell = primaryCellSize.height + NUMBER_OF_COLUMNS*SPACE_BETWEEN_CELLS;
if ([self.collectionView numberOfItemsInSection:0] > NUMBER_OF_COLUMNS) {
    NSUInteger nubmerOfSecondaryRows = [self.collectionView numberOfItemsInSection:0]/NUMBER_OF_COLUMNS;
    CGFloat heightForSecondaryCells = nubmerOfSecondaryRows * [self calculateSecondaryCellSizeAndMargin].height;
    heightForPrimaryCell += heightForSecondaryCells;
}
//    NSLog(@"height of collectionview %1.0f",heightForPrimaryCell);
return CGSizeMake(self.collectionView.frame.size.width, heightForPrimaryCell);
}

-(NSArray*) layoutAttributesForElementsInRect:(CGRect)rect {
NSLog(@"layoutAttributesForElementsInRect");
NSMutableArray *attributesInRect = [NSMutableArray array];
NSInteger numberOfCell = [self.collectionView numberOfItemsInSection:0];
for (int index=0; index < numberOfCell; index++) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [attributesInRect addObject:[self calculateLayouAttributes:indexPath]];
}

for (UICollectionViewLayoutAttributes *attribute in attributesInRect) {
    NSLog(@"%@",attribute);
}
return attributesInRect;
}

-(UICollectionViewLayoutAttributes*) layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"layoutAttributesForItemAtIndexPath");
return [self calculateLayouAttributes:indexPath];
}

I am using Xcode6.  When running the simulator with iOS8, the layout is correct for iPhone4s, iPhone5, iPhone6, and iPhone6 Plus.  The array of attributes returned from -(NSArray*) layoutAttributesForElementsInRect: shown below is correct.
2014-09-16 09:47:30.600 Postlets[3606:212466]    layoutAttributesForElementsInRect
2014-09-16 09:47:30.600    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1880>    index path: (<NSIndexPath: 0x7afb0dc0> {length = 2, path = 0 - 0});    frame = (2 2; 236 236);
2014-09-16 09:47:30.600    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1950>    index path: (<NSIndexPath: 0x7afb1900> {length = 2, path = 0 - 1});    frame = (242 2; 76 76);
2014-09-16 09:47:30.600    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb19d0>    index path: (<NSIndexPath: 0x7afb1910> {length = 2, path = 0 - 2});    frame = (242 82; 76 76);
2014-09-16 09:47:30.600    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1a60>    index path: (<NSIndexPath: 0x7afb1a50> {length = 2, path = 0 - 3});    frame = (242 162; 76 76);
2014-09-16 09:47:30.600    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1af0>    index path: (<NSIndexPath: 0x7afb1ae0> {length = 2, path = 0 - 4});    frame = (2 242; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1b90>    index path: (<NSIndexPath: 0x7afb0be0> {length = 2, path = 0 - 5});    frame = (82 242; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1c20>    index path: (<NSIndexPath: 0x7afb1c10> {length = 2, path = 0 - 6});    frame = (162 242; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1ca0>    index path: (<NSIndexPath: 0x7afb1920> {length = 2, path = 0 - 7});    frame = (242 242; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1d20>    index path: (<NSIndexPath: 0x7afb1930> {length = 2, path = 0 - 8});    frame = (2 322; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1de0>    index path: (<NSIndexPath: 0x7afb1940> {length = 2, path = 0 - 9});    frame = (82 322; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1e70>    index path: (<NSIndexPath: 0x7afb1e60> {length = 2, path = 0 - 10});    frame = (162 322; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1f00>    index path: (<NSIndexPath: 0x7afb1ef0> {length = 2, path = 0 - 11});    frame = (242 322; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb1f90>    index path: (<NSIndexPath: 0x7afb1f80> {length = 2, path = 0 - 12});    frame = (2 402; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb2020>    index path: (<NSIndexPath: 0x7afb2010> {length = 2, path = 0 - 13});    frame = (82 402; 76 76);
2014-09-16 09:47:30.601    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb20b0>    index path: (<NSIndexPath: 0x7afb20a0> {length = 2, path = 0 - 14});    frame = (162 402; 76 76);
2014-09-16 09:47:30.602    Postlets[3606:212466] <UICollectionViewLayoutAttributes: 0x7afb2140>    index path: (<NSIndexPath: 0x7afb2130> {length = 2, path = 0 - 15});    frame = (242 402; 76 76);

However, when running against iOS7.1, the layout for the first cell is incorrect for iPhone4s/iPhone5.

I am not sure if I overlooked something or if there's a bug with UICollectionViewFlowLayout?  Thanks for your input.
UPDATE:  The subclass of UICollectionViewCell has a UIImageView.  In the storyboard, I am using autolayout to constrain the size of UIImageView to be flushed to the subclass of UICollectionViewCell on all 4 sides.  The interpretation of the constraints in Xcode6 targeting iOS7 is misinterpreted somehow (at least that's a guess on my part.)  I decided to use the Visual Format Language to add the constraints as shown below:
-(void) layoutViews {
_imageView = [[RemoteImageView alloc] init]; // this is a subclass of UIImageView
_imageView.translatesAutoresizingMaskIntoConstraints = NO;
_imageView.contentMode = UIViewContentModeScaleAspectFill;
_imageView.clipsToBounds = YES;

[self addSubview:_imageView];
NSDictionary *views = NSDictionaryOfVariableBindings(_imageView);//,spinner);
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_imageView]|" options:0 metrics:nil views:views]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_imageView]|" options:0 metrics:nil views:views]];
}

The UIImageView now is properly sized to be flushed with the UICollectionViewCell on all 4 sides for iOS7/8.  Hope this is useful to some developers out there...
Filed bug report with Apple (#18415152).
UPDATE 10/7/14:  Closed by Apple (duplicate of bug #18312246)

A: Where are you setting the size of the cells? It looks like you're missing the collectionView:layout:sizeForItemAtIndexPath: delegate method. This is where you set the size of an individual cell.


text:
Q: Replace Content in place using sed in a JSON file My JSON file is as follows:
{
 "Name":"SA",
 "Password":"yyyyy",
 "Mappings" : {
 "RegionMap" : {
     "us-east-1"      : { "AMI" : "xxxxxx" },
     "us-east-2"      : { "AMI" : "" },
     "us-west-1"      : { "AMI" : "" },
     "us-west-2"      : { "AMI" : "" },
     "ca-central-1"   : { "AMI" : "" },
     "eu-central-1"   : { "AMI" : "" },
     "eu-west-1"      : { "AMI" : "" },
     "eu-west-2"      : { "AMI" : "" },
     "ap-south-1"     : { "AMI" : "" },
     "ap-southeast-1" : { "AMI" : "" },
     "ap-southeast-2" : { "AMI" : "" },
     "ap-northeast-1" : { "AMI" : "" },
     "ap-northeast-2" : { "AMI" : "" },
     "sa-east-1"      : { "AMI" : "" }
    }
  }
}

My task is to update the value of the AMI key of us-east-1 in the given json file. I have used jq to solve this issue . Here is the link. I am having problems with jq no being stable on my windows server machine. So now I want to obtain the same using sed commands.
My expected output is as follows
{
"Name":"SA",
"Password":"yyyyy",
"Mappings" : {
"RegionMap" : {
   "us-east-1"      : { "AMI" : "abcd" },
   "us-east-2"      : { "AMI" : "" },
   "us-west-1"      : { "AMI" : "" },
   "us-west-2"      : { "AMI" : "" },
   "ca-central-1"   : { "AMI" : "" },
   "eu-central-1"   : { "AMI" : "" },
   "eu-west-1"      : { "AMI" : "" },
   "eu-west-2"      : { "AMI" : "" },
   "ap-south-1"     : { "AMI" : "" },
   "ap-southeast-1" : { "AMI" : "" },
   "ap-southeast-2" : { "AMI" : "" },
   "ap-northeast-1" : { "AMI" : "" },
   "ap-northeast-2" : { "AMI" : "" },
   "sa-east-1"      : { "AMI" : "" }
   }
 }
}

I have referred many questions relating to this on stackoverflow relating to this issue but I am unable to get the desired output. The links of the questions referred are as follows

*

*Find and replace text within a file using commands

*Find and replace for JSON with sed or awk

*How to replace value of key in json file using sed

*Use Sed to find and replace json field

*Replace value in json during run time
Can somebody help me with this? Also is it possible that I can use environment variables value for replacing the contents of the file in place? If so, how?
Edit
I have already got the answer using jq. The link is mentioned above. Since jq is unstable on my windows server machine I am trying to achieve the same using sed commands.

A: This may be just a soap box of mine, but sed does not modify files in place.  The --in-place option of gnu-sed is completely misnamed, as it does not modify the file, but creates a new one.  If you want to edit a file, use ed.  (sed is the streaming version of ed).
Now, also with the caveat that using either ed or sed to edit json data is a bad idea, you might try this (non-robust) solution:
printf '/us-east-1/s/: ".*"/: "abcd"/\nw\nq\n' | ed input

(This works for your input, but relies on the space between the : and the ", and is fragile because of that.)

A: One simple way to achieve it in sed is to create the following sed file
/AMI/ {
 /us-east-1/ {
    s/"AMI".*/"AMI" : "abcd" },/
 }
}

And execute it as such
sed -f <above_file.sed> <json file>

If xxxxxx is the actual text in the file and you want to replace it, use the following :
/AMI/ {
 /us-east-1/ {
    s/xxxxxx/abcd/
 }
}


text:
Q: Splitting json array into mutiple json file in node js Am new to node JS I need to write a two files for below json.
[{

    {
         sourcePguid: '1',
      'urn:reference:000000000000000000000000019318': 'General'
    },
    {
      sourcePguid: '2',
      'urn:reference:000000000000000000000000019318123': 'General2'
    }

}]

Output excepted:
{     sourcePguid: '1',
      'urn:reference:000000000000000000000000019318': 'General'
    }
This should be as one file and  below Json should as another file
{
      sourcePguid: '2',
      'urn:reference:000000000000000000000000019318123': 'General2'
    }

Kindly if any one help me to achieve the output in node JS.

A: You should start from this simple snipped to dig deeper Node.js
const fs = require('fs').promises // this is the standard module to work with files

const array = [{
  sourcePguid: '1',
  'urn:reference:000000000000000000000000019318': 'General'
},
{
  sourcePguid: '2',
  'urn:reference:000000000000000000000000019318123': 'General2'
}]

// Array has many functions to help you, like .map in this case.
// https://devdocs.io/javascript-array/
const arrayOfPromises = array.map(jsonFileContent => {
  // I get each occurrence of `array` as parameter and I return back a Promise to avoid to block the Nodejs event loop:
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
  return fs.writeFile(`./file-${jsonFileContent.sourcePguid}.json`, JSON.stringify(jsonFileContent, null, 2))
})

// I need to wait for async operation to understand when it is finished
Promise.all(arrayOfPromises)
  .then(() => {
    console.log('files created')
  })
  .catch(err => {
    console.log('error creating the files', err)
  })

console.log('this print first')


text:
Q: How to re-use projects in SonarQube We have multiple repos and whenever the developer runs the sonarQube scanner through Jenkins job, it is creating one project with build number along with the date, is there anyway I can re-use the same project name ..?
developers are running sonarQube reports through Jenkins jobs.
sonar.projectKey=portal1-sonar:1stiteration-${BUILD_NUMBER}
sonar.projectName=SonarQube nodeJS portal1 Build : ${BUILD_NUMBER}_${BUILD_TIMESTAMP}

anyway, I can change and use same project name, whenever developer runs sonarQube.

A: every project is defined in SonarQube with it's own key. That means if the key is the same, it is the same Project, and you will have a "history" of analyses and can compare parameters.
Although the idea of buildnumbers seems to be interesting, i recommend to use Branch names instead. There are currently two ways of doing this, for the first one, you need to have a SonarQube installation with a paid price. Than you are entitled to use the branch plugin. Which is actually the more superior way, because your project will show branches. The sonarQube docs are quiet helpful regarding this.
The old/Deprecated way will create a new project per branch, which you can than compare. the property you need to set is sonar.branch and this will be automatically added to your project key. So if the project key is Project and the sonar.branch is set to develop your new project will have the key Project:develop. This parameter is deprecated, and i am not sure, how long it will stay in the system.


text:
Q: need assistance with homework This is the assignment: Write a method that sorts the elements of a matrix with 2 dimensions. For example
sort({{1,4}{2,3}})

would return a matrix
{{1,2}{3,4}}.

I dont know what im doing wrong in my code cause the output i get is 3.0, 3.0, 4.0, 4.0.
This is what i have so far any help would be appreciated.
public static void main(String[] args) {
    double[][] array =  { {1, 4}, {2, 3} };
    double[][] new_array = sort(array);
    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            System.out.print(new_array[i][j] + " ");
        }
    }

}

public static double[][] sort(double[][] array) {
    double[] storage = new double[array.length];
    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            storage[i] = array[i][j];
        }
    }
    storage = bubSort(storage);
    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array.length; j++) {
            array[i][j] = storage[i];
        }
    }
    return array;
}

public static double[] bubSort(double[] list) {
    boolean changed = true;
    double temp;
    do {
    changed = false;
    for (int j = 0; j < list.length -1; j++)
    if (list[j] > list[j + 1]) {
        temp = list[j];
        list[j] = list[j + 1];
        list[j + 1] = temp;
        changed = true;
    }
    } while (changed);
    return list;
}

}

A: The main problem that you are experiencing is how you are copying the values from the 2d array into the 1d array. You are actually only copy two values into an array of length 2. The length of a 2d array is not the full m x n length.
I will give a small hint how you can go about copying from the 2d array into the 1d array, but it is up to you to figure out how to copy back from the 1d array into the 2d array. Also, how would you go about finding the full length of the array?
    double[] storage = new double[4];//You should calculate this value
    int k = 0;
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            storage[k++] = array[i][j];
        }
    }

Your bubble sort works fine, but then you are copying the values back wrong. Try printing the array storage after the sort and you will see that it is now correct.

A: You are overwriting your storage array you have it set to array[i]. Because it is in the for loop you are setting storage[0] = array[0][0] then setting storage[0] = array[0][1]. This causes you to only pick up the last number in that dimension of the array. Likewise, when you are reading them back out you are inserting the same number twice. Since 4 and 3 are the last two numbers in their respective dimensions this shows that you are sorting the array. You need a for loop for storage that is set < array.length and store your values inside that.


text:
Q: Multiple variable to store on a column of database Flask I'm working on an app for Transport Company and on the client page, we can add Delivery Tour and these Delivery Tours can be planned on different days and hours :
exemple :
A delivery tour is planned on Monday at 4pm and Thursday 10am.
Currently, I store this in my SQLAlchemy Delivery Tour database in JSON Format like this :
{'Monday':10,'Thursday':16}
But the thing is when I rendered the HTML file I can't success to iterate through the JSON file and have the correct day and hour associated to the correct Delivery Tour...

So I was wondering is there a more efficient way to do this ? Like maybe create a new table but I have no idea how to arrange columns.

EDIT

My HTML :

                    Delivery Tour

                        Add New

                    Title
                    Description
                    Schedule
                    Driver

                        {% for deliv in delivery %}
                            {{ deliv.title }}
                            {{ deliv.description }}
                            {{ deliv.schedule }}
                            {% if deliv.driver_assigned %}
                                {% for d in driver %}
                                    {% if d.id == deliv.driver_assigned %}
                                    {{d.first_name}}
                                    {% endif %}
                                {% endfor %}
                            {% else %}

                            {% endif %}

                        {% endfor %}

And here is a photo of my Delivery database :

A: You have the basics of it already:
{% for day, hour in eval(deliv.schedule).items() %}

You would have to do eval because unless I'm wrong, you have that column stored as a string in the table.
If it were me, I'd create a table just for the schedules and make a one-to-many relationship to your delivery_tour table: (note: drop the schedule column on your delivery_tour table)
class TourSchedule(Base):
    __tablename__ = 'tour_schedules'
    id = Column(Integer, primary_key=True)
    tour_id = Column(Integer, ForeignKey('delivery_tour.id'))
    tour = relationship('DeliveryTour', backref='schedule')
    day = Column(String(16))
    hour = Column(Integer)

Then you can just iterate over it like you otherwise would:

        {% for sched in deliv.schedule %}

{{sched.day}}: {{sched.hour}}

        {% endfor %}


text:
Q: soap client не может подконнектиться Все работало, пока в один прекрасный момент не решили поменять все коннекты, в итоге 1с-ник настроил связь через другой порт и дал ссылку вида (раньше работало без порта, подразумеваю по стандартному):

http://00.000.000.000:55/Trade/ws/SiteExchange?wsdl
  (не пишите, типо, как оно работает с 0-лями... Это замененные данные)

И теперь постоянно ошибка. Может кто-то что-то подскажет...
Вот кусок кода:
try {
    $client = new SoapClient('http://00.000.000.167/Trade/ws/SiteExchange?wsdl',
        array('login'        => 'user',
            'password'       => 'pass',
            'soap_version'   => SOAP_1_2,
            'cache_wsdl'     => WSDL_CACHE_NONE, //WSDL_CACHE_MEMORY, //, WSDL_CACHE_NONE, WSDL_CACHE_DISK or WSDL_CACHE_BOTH
            'exceptions'     => true,
            'trace'          => 1));
} catch(SoapFault $e) {
    trigger_error('Ошибка подключения или внутренняя ошибка сервера. Не удалось связаться с базой 1С.', E_ERROR);
    var_dump($e);
}

P.S. Если вбить ссылку просто в браузер то запросит логин и пасс, и введя их отдаст информацию...

A: Клиент не может загрузить wsdl. Я так понимаю, что сам wsdl у вас тоже закрыт за http basic авторизацией.
SoapClient не пытается использовать параметры login и password для получения wsdl и предполагает, что документ доступен по прямой ссылке без авторизации. Но стандартную запись авторизации непосредственно в URL понимает и может использовать:
$client = new SoapClient(
    'http://' . urlencode($login) . ':' . urlencode($password)
      . '@00.000.000.167/Trade/ws/SiteExchange?wsdl',
    array('login'        => $login,
        'password'       => $pass,
        'soap_version'   => SOAP_1_2,
        'cache_wsdl'     => WSDL_CACHE_NONE,
        'exceptions'     => true,
        'trace'          => 1));

A: В параметрах soap добавил 'verifyhost' => false и все пошло!


text:
Q: How to prepend the header to a CSV file in PHP? I have a situation where my headers aren't predefined, so I would like to add columns dynamically as I process the input without having to read all the input before writing.
It makes sense to keep track of just the header as an Array and prepend it at the end, but I'm yet to see an easy way to do this.
I've cut my code down to the minimum to understand how it is currently, pretty standard PHP csv writing. I haven't yet added any code to process the dynamic part of it.
$handle = fopen($this->path, 'w');

fputcsv($handle, ['initial', 'header', 'values']);

foreach($data as $datum){
    fputcsv($handle, $datum));
}


text:
Q: Apache mod_rewrite is removing slashes and generally ignoring my rules I'm at my wit's end, Stack Overflowers. Trying to do what I thought was a simple rewrite rule to replace slashes in the URL with tilde, then add a ".html" at the end.
So my .htaccess is thus:
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/(.+)/(.+)$ $1~$2 [N]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/([^/]+)$ $1.html [L]

Basically I'm running a repeated rule to replace all slashes with tildes one at time, then my final rule adds the ".html" -- because all our web files need to be in one folder (client request--silly, I know).
I've tested the pattern "part-one/part-two/part-three" here: http://martinmelin.se/rewrite-rule-tester/ and it only works if I chop off the initial slash and remove the rewrite conditions (which makes no sense b/c no filename I put in there should exist on that server), but that's not the case on my local server.
It should eventually read the file "part-one~part-two~part-three.html" but when I look at the Apache error log on my local machine, I get this:

File does not exist: /path/to/website/part-one

So it basically chops off the final two parts and never tries to add a ".html" -- so what on earth is going on?? Please help, mod_rewrite gurus!!

A: The reason why it wants you to remove the leading / is because the rewrite engine strips off the prefix (the leading slash of an URI) before it runs them through rules in an htaccess file. If you were using apache 1.3 or if the rules were in a non-per-directory context in the server or vhost config, then you'd need the leading slash in the rule's pattern:
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/(.+)$ /$1~$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^/]+)$ /$1.html [L]

Additionally, you probably don't want the N flag, as you want rewrite to stop immediately in its current iteration. Also, a condition which first checks if the .html actually exists before you rewrite will prevent 500 internal server errors.


text:
Q: Validador console Boa noite, preciso programar um validador de usuário em C# (Possuo visual studio). No estilo console.
Preciso que a partir de uma lista .txt o valor de "id=" na URL seja alterado.
https://www.sitevalidador.com.br/bi5/Paginas/cliente/Login.aspx?id=idatualnalista&pc=05
Se possuir uma tal mensagem na página web como por exemplo um "OK", então pegar o valor do id atual e apresentar um log no console dizendo que é valido.
Por exemplo adicionei uma lista possuindo três id's sendo dois deles inválidos
2446
4452
4445
Pelo o fato da última id da lista ser a válida, apresentar a mensagem no console:

VÁLIDA 4445

E por fim, salve todas as ids "válidas" em um .txt no mesmo diretório do .exe.
Muito obrigado!
Espero que tenham entendido, não tenho a  minima ideia de como fazer isto. Se possível, me ajudem, por favor!

A: Sua pergunta é um pouco ampla, mas vou colocar um exemplo aqui pra você de como ler esse arquivo e pegar exatamente o pedaço que você precisa.
public void ReadFile()
{
    string line;
    using (StreamReader reader = new StreamReader(@"c:\temp\filelist.txt"))
    {
        line = reader.ReadLine();
        Console.WriteLine(line.Substring(line.IndexOf("id=", StringComparison.Ordinal), 7).Replace("id=", ""));
    }
    Console.ReadKey();
}

Aí você adapta no seu código e faz suas validações.. isso vai retornar o pedaço do ID da sua URL dentro do arquivo.


text:
Q: Double-checked locking not thread-safe? I've experienced a very odd behavior in a WPF application, when I was using  double-checked locking to create a thread-safe singleton. My code represents a usual implementation of that technique:
  Private _graphics As Contracts.Interfaces.Components.IGraphics
    ReadOnly Property Graphics As Contracts.Interfaces.Components.IGraphics
        Get
            If _graphics Is Nothing Then
                SyncLock lock
                    If (_graphics Is Nothing) Then
                        _graphics = New GFX.Application()
                    End If
                End SyncLock
            End If
            Return _graphics
        End Get
    End Property

When I was running the program, I got an exception, because the Application-object was constructed twice. I couldn't believe my eyes, since my understanding of how locks work, tells me that this should be thread-safe.
My presumption was, that this code was running twice on the same thread (asynchronously), so I ended up modifying my code to analyse this problem. I was adding a List in order to put a Thread-object into it every time a thread steps into the locking statement. Next, I just had to compare the contained Thread-object with the current thread:
ReadOnly Property Graphics As Contracts.Interfaces.Components.IGraphics
    Get
        If _graphics Is Nothing Then
            SyncLock lock
                If (_graphics Is Nothing) Then
                    If (threadList.Any() AndAlso (threadList.First() IsNot Threading.Thread.CurrentThread)) Then
                        Stop ' Program is stopping here.
                    End If
                    threadList.Add(Threading.Thread.CurrentThread)
                    _graphics = New GFX.Application() ' Object construction takes around 70 ms.
                End If
            End SyncLock
        End If
        Return _graphics
    End Get
End Property

As you might guess, the program stopped, because multiple threads ran into the same locking statement. How can this be true? I have absolutely no explanation for this behavior, let me know if you have any idea. thanks.
UPDATE:
I want to add some more details. This is the initialization routine that causes two anonymous methods to run asynchronously. Each of them accesses the readonly property of the Singleton holder.
 Task.Factory.StartNew(Sub() Graphics.Init(...)
 Task.Factory.StartNew(Sub() Graphics.Run(...)

And here are the related disassembly instructions. Perhaps they give an indication. Is anybody here able to follow these instructions:
 If _graphics Is Nothing Then
002D91ED  cmp         dword ptr ds:[38E3430h],0
002D91F4  sete        al
002D91F7  movzx       eax,al
002D91FA  mov         dword ptr [ebp-48h],eax
002D91FD  cmp         dword ptr [ebp-48h],0
002D9201  je          002D9297
                SyncLock lock
002D9207  nop
002D9208  mov         eax,dword ptr ds:[038E3438h]
002D920D  mov         dword ptr [ebp-40h],eax
002D9210  mov         ecx,dword ptr [ebp-40h]
002D9213  call        518DCE8C
002D9218  nop
002D9219  xor         edx,edx
002D921B  mov         dword ptr [ebp-44h],edx
002D921E  nop
002D921F  lea         edx,[ebp-44h]
002D9222  mov         ecx,dword ptr [ebp-40h]
002D9225  call        7301A2B0
002D922A  nop
                    If _graphics Is Nothing Then
002D922B  cmp         dword ptr ds:[38E3430h],0
002D9232  sete        al
002D9235  movzx       eax,al
002D9238  mov         dword ptr [ebp-48h],eax
002D923B  cmp         dword ptr [ebp-48h],0
002D923F  je          002D9264
                        _graphics = New GFX.Application()
002D9241  mov         ecx,47D664h
002D9246  call        73E601D2
002D924B  mov         dword ptr [ebp-4Ch],eax
002D924E  mov         ecx,dword ptr [ebp-4Ch]
002D9251  call        002D8C10
002D9256  mov         eax,dword ptr [ebp-4Ch]
002D9259  lea         edx,ds:[38E3430h]
002D925F  call        73E52360
                    End If
002D9264  nop
                End SyncLock


text:
Q: Make a function in a Typescript bundle created with webpack, globally accessible in JS I'm developing a plugin for a tool. The plugin is just a zip file, and the tool only looks for and loads main.html file. Thefore, any JS must be inlined in the HTML file.
I'm trying to develop with separate Typescript files and then have webpack bundle all the .ts files into a bundle.js and inline it in the HTML.
I managed to this but there's one problem. How to call the logic in the bundle from the HTML?
Webpack creates __webpack_modules__ IIFE variables for the code in the bundle.
<head>
<script>bundled JS</script>
</head>

<body>
</body>

<script>
// How to call here an init() function in the bundle?
</script>

I tried to setup iife: false with no luck:

A: You'll need to explicitly export to the global object by assigning to window.

<script>
  (() => {
    function myFn() { console.log('myFn ran') }
    window.myFn = myFn // assign to global object here.
  })()
</script>

<script>
  myFn()
</script>

Then if you want typescript type available for that, see: Create a global variable in TypeScript

A: It looks like you want to export your bundle as a library that we can use in a different script. If so, the option output#library comes to help so the only thing you need to do is to export it as library with umd format which works great for both node and browser envs.
{
   output: {
    // ...
    library: {
      name: 'yourLib', // you then can access it via window: `window.youLib`
      type: 'umd',
      umdNamedDefine: true,
    },
}


text:
Q: Delete UILocalNotification from iOS Notification Center automatically
I'm trying to send UILocalNotifications and delete them automatically after a certain interval from the Notification Center.
My app sends information to users that in about 5 minutes since sending would be irrelevant.
There are going to be at least 3 notifications a day.
Since the information of the notifications would be irrelevant in a few minutes, it would be much better to delete those notifications from Notification Center - because they would be irrelevant to the user.
Is there any way to achieve this? Sort kind of a "self-destruction" option of local notifications?
Thank you!

A: If your question is to remove the notifications from the notification centre even without bringing the application to foreground(new notification to clear the old notifications), then the answer is straight forward "NO".

Without user accepting the older notification or manually brings the
  application to foreground - It is not possible.

A possibility if this feature may come out with iOS7!


text:
Q: Inconsistent tf.print results I was trying to understand the executing order in tensorflow graph. When I was running the following code. tf.print prints undetermined results.
import tensorflow as tf

for _ in range(20):
    tf.reset_default_graph()
    use_resource = False
    v = tf.Variable(0, trainable=False, use_resource=use_resource, name='v')
    v_op1 = v.assign_add(1, name='v_op1')
    v_op2 = v.assign_add(2, name='v_op2')

    with tf.control_dependencies([v_op1]):
        w1 = tf.print('msg1:', v, name='v--w')
    with tf.control_dependencies([w1, v_op2]):
        w2 = tf.print('msg2:', v, '\n', name='w--w')
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(w2)

Here are the output of 20 repetitions. Sometimes, it prints "msg1: 3", sometimes it prints "msg1: 1". So what's going on here?
msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 1
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 3
msg2: 3

msg1: 1
msg2: 3

A: I think what's happening is you're creating a race between w1 and v_op2, and they're both being executed simultaneously. (with theses lines)
with tf.control_dependencies([w1, v_op2]):

for example if v_op2 is executed before w1 then 2 is added to v then when w1 is executed it adds 1 to it making msg_1 print 3. However when w1 is able to be completed before v_op2 is executed then 2 is added to v after.
e.g. case 1
v_op2 executed:
v = 2
w1 executed:
v = 3
print(v)

case 2
w1 executed
v = 1
print(v)
v_op2 executed
v=3


text:
Q: Implement Entity Framework level one caching explicitly Can we implement first level caching in Entity framework 6 (later on 7) explicitly,
Idea may be; by intercepting add or get call in Entity framework.


text:
Q: Vuetify text-area empty OR less than 200 character rule Im using Vuetify and trying to get a text-area to validate ONLY if there are more than 200 characters.
I want to ONLY make the field validate if the user has 1 or more characters, but be less than 200 characters IF it is at least 1 character. This filed is not required BUT if they choose to type data into it i want to make sure its is 200 characters or less.
<v-textarea
    v-model="description"
    :counter="200"
    :rules="[v => (v && v.length <= 200) || 'Description must be 200 characters or less']"
    label="Description"
    height="125"
    no-resize
    outline
/>

A: According to this example provided in official docs, i see that you should do something like :
:rules="[v => (v || '' ).length <= 200 || 'Description must be 200 characters or less']"

A: For shorter strings, I ended using something like this:
min: v => (v || 'aaaa' ).length >= 4 || '4 chars minimum'


text:
Q: Question about symplectic tranformations Suppose I know that two vectors $\vec{a}$ and $\vec{b}$ are perpendicular in a given basis spanned by basis vectors $\vec{x}$. Now suppose I transform to another basis $\vec{x'}$ using a symplectic transformation matrix S (i.e. $SJS^{T} = J$ for some skew-symmetric matrix J). Will the transformed vectors a and b still be perpendicular after the transformation? If not, is there a way to figure out a relation between the dot products between the two vectors in the two bases?
Thanks!

A: Perhaps I misunderstand your question, but here is an example that shows the answer is no to what I think you are asking.
Consider $\mathbb{R}^2$ with the standard symplectic structure given by $\omega( (a,b), (a',b')) = ab' - ba'$. This corresponds to saying $\omega = < J \cdot, \cdot>$ where $J$ is the almost complex structure given by $$ \begin{pmatrix} 0 & -1\\1 & 0 \end{pmatrix}$$
An easy symplectic and orthogonal basis for $\mathbb{R}^2$ is given by $e_1 = (1,0)$ and $e_2 = (0,1)$. A symplectic transformation is given by $e_1 \mapsto e_1 + e_2, e_2 \mapsto e_2$. (i.e. in matrix form $ \begin{pmatrix} 1 & 0 \\ 1 & 1 \end{pmatrix}. )$
The image of this basis is clearly no longer orthogonal.

A: The answer is no in general. For a general (nonlinear) symplectic transformation, the vectors will be pushed-forward by the Jacobian of the transformation. We also know that jacobian of a symplectic transformation is a symplectic linear transformation. So in general, if what you propose is true, then it should hold for ALL symplectic transformations, and not just linear ones like you propose.


text:
Q: Can I use a physical copy of a psn plus free game to play it? So I got cities skylines for free with psn plus trial, I do not plan to renew my psn plus, but if I went and bought cities skylines for ps4 from a store such as eb games. Will I be able to play it using the physical copy?

A: You will be able to play the game but not without the disk. The only way you can play it without the disk (without PS plus) is if you buy the digital version.


text:
Q: Erro no Xampp 3.22 Olá, eu uso o Xampp há mais de 1 ano e nunca tive nenhum problema com o mesmo, porém hj tive de formatar meu desktop e reinstalei uma versão mais nova do Xampp, a 3.22, ao iniciar o mesmo ele apresentou um erro:

Já fiz o tutorial da pergunta erro no xampp e não funcionou, eu coloquei a porta 12344 no Skype. Alguma ideia?

Perdão pela minha falta de atenção, não sabia que o gerenciador de tarefas mostrava esse 'PID' mas ao abrir o gerenciador não mostra esse processo com PID 3632, como pode ver no print, e eu abri o XAMPP para testar se funcionava e ele deu o mesmo erro, PID 3632.
O Sistema operacional é Windows 7 Ultimate.

A: Este erro é devido a porta 80 e a 443 que já está sendo usada.

*

*Abra o arquivo httpd.conf no bloco de notas e altere a linha listen 80 para outra porta, por exemplo: listen 8080

*Após alterar a porta 80, abra o arquivo httpd-ssl.conf no bloco de notas procure pela linha listen 443 e altere a porta 443 por outra.
Espero ter ajudado.


text:
Q: Expected value of a product of 2 random multinomial variables Suppose the following situation:

*

*We have $n$ marbles and these are tossed so that each marble lands in one of the $k$ boxes.

*The probability that a marble lands in box $\#i$ is
$p_{i}\,,\ i=1,...,k\,,\ \sum_{i = 1}^{k}p_{i} = 1$.

*Then let $X_{l}$ be the number of marbles landing in box $\#l\,,\ l = i,j$. Define $Y_{l} = 1$ if $l^{th}$ marble lands in box $\#i,0$ otherwise. Similarly $Z_{l} = 1$ if $l^{th}$ marble lands in box $\#j,0$ otherwise.Here $i\neq j$. Also, write $X_i = \sum_{l = 1}^{n}Y_{l}$ and $X_{j} = \sum_{l = 1}^{n}Z_{l}$.

*Now follows a computation of $\mathrm{Cov}\left(X_{i},X_{j}\right)$ which ends with
$=n\left
\{E\left[Y_{1}Z_{1}\right]-E\left[Y_{1}\right]E\left[Z_{1}\right]\right\}$ and they claim:

"It is not hard to see that $E\left[Y_{1}Z_{1}\right] = 0$".
I do not understand here why ?.
To see the source type
"It is not hard to see that E" inference nitis
into Google.


text:
Q: Set values in jquery multiselect dropdown I want to set the multiple ITEMS in jQuery multiselect dropdown depending on the VALUE of that item, which I'm getting from database, separated by ",".
I'm saving this fetched data in hidden field.
Ex.
Hidden field: hdnLots = 64,65
, Items for lot No.: 64 = Lot 1, 65 = Lot2
So when I get the hdnLot=65, then in jQuery Multiselect dropdown only Lot2 needed to be selected. And same for 64,65. i.e. When multiple values are selected than all those values needed to seleted.
I've tried: JQuery multiselect - Set a value as selected in the multiselect dropdown
Code I've wrote for this is:
if ($("#<%= btnUpdateProject.ClientId %>").css('display') == "inline-block")
{
   debugger;
   var dataarray = document.getElementById('<%= hdnLots.ClientId %>').value.split(",");
   $("#<%= ddlNoOfLots.clientid %>").val(dataarray);
}

A: The one thing you would need to ensure is that the values in the array are strings:
<select id='multipleSelect' multiple='multiple'>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<script type='text/javascript'>
    $('#multipleSelect').val(['1', '2']);
</script>

Check my Fiddle: https://jsfiddle.net/luthrayatin/jaLygLzo/

A: var selectedOptions = hidValue.split(",");
typeof (selectedOptions != 'undefined' && $("#hidSelectedOptions").multiselect('select', selectedOptions));

A: I hope this will help you:
Demo
$(document).ready(function() {
$("select").multiselect({
   selectedText: "# of # selected"
});
var hidValue = $("#hidSelectedOptions").val();
alert(hidValue);
var selectedOptions = hidValue.split(",");
for(var i in selectedOptions) {
    var optionVal = selectedOptions[i];
    $("select").find("option[value="+optionVal+"]").prop("selected", "selected");
}
$("select").multiselect('reload');
});

EDIT
refresh has been removed from latest jQuery-MultiSelect. Using reload will solve the question now.


text:
Q: Design question: Polling on process in java spring boot I have a java / spring boot question about designing an app I have in mind.
The functional flow is this:
FE calls endpoint 'start process x' -> response ok/process (id?)
FE polls until status 'finished' endpoint 'get process status' -> response % progression
FE calls endpoint 'post process' -> post process result, response result
If endpoint 'start process x' is called again while one is already processing, it should queu that process and start processing after first one is finished.(Or better, allow max number of processes to run at same time, queuing the remainder)
How would I do this?
Do I need to start new threads, completable features?
How do I create a poll endpoint that can retrieve a status about this process?
How to create a queu?
I would love to have some examples, maybe an open repository where I can see a working example.


text:
Q: Where did org.apache.cassandra.auth.Auth go in Cassandra 3? We have an authenticator implementation which was made for Cassandra 2.1. There, we used org.apache.cassandra.auth.Auth#isSuperuser() method to see whether the user is superuser or not.
In Cassandra 3 (namely 3.11.2), there is no org.apache.cassandra.auth.Auth class, and I could not find any isSuperuser() static method in it.
Is it still possible to achieve the same goal (determine whether a user is a superuser or not)? If not, what is the correct way to do it in Cassandra 3?
The artifact I'm using is cassandra-all.

A: It turned out to be easy:
new AuthenticatedUser(username).isSuper()

This determines whether the user with login username is a superuser.


text:
Q: Render a subset of model elements in Autodesk Forge Viewer We need to be able to render a subset of BIM model elements and also dynamically color some elements. Based on this article it looks like it's possible to render a subset of elements given you can provide a list of their dbIds. It also looks like Forge viewer API uses dbIds to interact with rendered elements.
Before converting the BIM model to SVF2, we assign our own ids to model elements. I can see our own ids as properties of model objects when accessing the properties database of the model in the browser. It would be great if we could generate a list of associations between our ids and forge dbIds.
Does autodesk provide an API to fetch custom properties or is there a way to correlate the dbId at upload time?

A: You can use this endpoint GET Properties from the ModelDerivative API and search for your own id in properties.
You will get the dbid of your object and then build your collection of associations.


text:
Q: ParseError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file. (read_csv) I cannot use read_csv method of pandas properly on kaggle. Error that I get is:
ParseError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file.
I found some suggestions about this (read_excel, read by column). However, they do not help me to solve this error.

A: I solved the same problem just by adding engine='python':
df = pd.read_csv(fname, sep='\t',
                 engine='python',
                 header=None)


text:
Q: Matlab: how to export "date time" data to an external file? "Error using fprintf. Function is not defined for 'cell' inputs." I'm running Matlab 2016a and I'm a bit of a newbie.
I imported certain columns of data from a very large external .txt file.  The first column is "date time."  When I print it to screen, this is how it appears:
'2019-07-10 20:00:00'

The other imported columns all consist of numbers.  I want to print only the columns I imported to a .txt file.  For the columns of numbers, this works:
fileID = fopen('fag_1.txt','w'); fprintf(fileID,'%f\n',fag_1); fclose(fileID);

However, I have tried all afternoon and can't find a way to print the date time column.  For example, this is a solution that worked for someone at a forum:
fileID = fopen('DT.txt','w'); fprintf(fileID, '%23s\n', DT); fclose(fileID);

It gave me this error (which is similar to the error I get for all the other methods I have tried):
Error using fprintf
Function is not defined for 'cell' inputs.

Error in XXX (line 230)
fileID = fopen('DT.txt','w'); fprintf(fileID, '%23s\n', DT); fclose(fileID);

Does anyone have any ideas on how to deal with this?  Thank you.

Reply to Paolo
The text file is huge, Paolo, so I will only show the first four columns on the first row.  Please feel free to let me know if that is insufficient.  I would be interested to know how to do this in Matlab so it would be great if you could help!  Thanks very much.
DT  MOD UNMOD   PRESS
2015-07-01 00:00:00 -999.0  -999.0  -999.0

A: I was not able to figure out how to do it in Matlab, but found a different solution here at Stackoverflow that uses awk (below).
awk '{print $1}' test.txt > test2.txt

This doesn't really answer my question, but it solves my problem!  If anyone has an opinion on whether to mark my question as answered or delete it, it would be great to know.  I don't want to leave it open, as that deters people who like to answer questions from those who have a record of choosing an answer. Thank you.

A: Using matlab to extract a few columns from a text file is like using your car to drive one city block. You can do it, but it will take a lot of extra work and resources (money, gas), and there are much better tools for the job (walk, ride your bike). In this case, awk is a good choice. It is designed specifically for this type of task and it works well.
However, the direct answer to your Matlab question is exactly what the error message says: you are trying to give fprintf a cell to print, and fprintf cannot print cells.  For example, make a text file that consists of four lines of the sample data from your question ("2015-07-01 00:00:00 -999.0  -999.0  -999.0"). If you import this file and look at the result in Matlab, we see:
>> fin = fopen('sline.txt','r');
>> sin = textscan(fin,'%s %s %f %f %f')

sin =

  1×5 cell array

{4×1 cell}    {4×1 cell}    {4×1 double}    {4×1 double}    {4×1 double}

>> fclose(fin);

We can see that the imported data has been placed in cells. If you want to reference the items inside the cells (in this case, the strings, so they can be printed), use {}. For example:
fout2 = fopen('sout2.txt','w');
for k=1:4
    fprintf(fout2,'%s %s %f %f %f\n',sin{1,1}{k},sin{1,2}{k},sin{1,3}(k),sin{1,4}(k),sin{1,5}(k))
end
fclose(fout2);

So you can do it Matlab, but it takes eight lines of ugly code.


text:
Q: Why would Int32 work to hold a pointer in a 64-bit .NET 4.0 application Any experts in .NET PInvoke marshalling know why using an int to hold a 64-bit pointer value works most of the time in a 64-bit app?  Embarrassingly we found some code that wasn't properly ported to 64-bit.  We have a native DLL that returns a "struct foo *" and we've been holding that value in a C# int. We later return that to the native DLL to close the "handle". Amazingly it has been working and passing our 64-bit tests.
When I look at the pointer value returned from the native code it always stay within the range of an int.  What is odd about this is a customer found the issue by running their 64-bit app in the VS debugger. The app crashes with an AccessViolationException.  We've subsequently found that it only fails when debugged using vshost.exe.  Something about the app running in vshost.exe excites the problem.  If you uncheck "Enabled the Visual Studio hosting process" or enable native debugging, the application doesn't crash.  This is under .NET 4.0.
I'm a bit mystified that this works at all and why would the vshost.exe process excite the crash.  Any theories as to why vshost.exe would excite this bug?  I'm also a bit disappointed the VS managed debug assistants didn't catch this issue.

A: It works most of the time because it so happens the address is less than 2^31 and so fits into a 32 bit integer.
For instance, if the address is heap allocated, then perhaps the heap is allocating bottom-up. In other words it allocates low addresses first. Or perhaps the address is the address of code or data in a module, and the module load address is less than 2^31.
When you pass an address to the native function, and the address is held in an int, it is truncated from 64 bits to 32 bits when assigned to the int. When you assign to a 64 bit variable in the native code, the value is extended to 64 bits. So long as the original value is less than 2^32, the truncation does not lose the original value.
One way to flush out some of these pointer truncation bugs is to configure your machine to allocate memory top-down. More details here: http://msdn.microsoft.com/en-us/library/bb190527.aspx. If you do attempt to use the top-down debugging option, do not be surprised if your machine has problems. I've experienced many problems with AV software that cannot handle running in top-down mode. And some versions of Windows itself have pointer truncation bugs that are affected by top-down memory allocation.

A: A 64-bit process can use addresses < 4GB as well as > 4GB.  There is no particular guarantee either way, it is up to the operating system's memory manager.  The hosting process is not much of a lead, the Windows version is a stronger one.  Windows 8 tends to allocate at high addresses more frequently than 7 for example.
An MDA cannot catch this, it has no idea that the native code actually expects a 64-bit value.  The 64-bit calling convention helps to hide this, the first 4 arguments are passed through registers so there is no stack imbalance.  And the upper 32-bits of the register are very often 0 by accident.  If it is passed through a structure or object then you tend to get lucky (well, unlucky) because of structure packing.  The next field can get aligned and leave enough space to still have the layout that the native code expects.  These padding bytes are 0 due to the way the CLR initializes memory.


text:
Q: How can I exit this loop? I'm a beginner and can't work out why this loop won't break.
I need to delete some users and for each user i'm prompted if i'm sure i want to delete the user.
so i made the following loop:
while (!alert && delete_button_is_present)
{
    clickDeleteBtn;

    if(alert)
    {
        driver.switchTo().alert().accept();
    }

    else if(delete_button_is_not_present)
    {
        break;
    }
}

Problem is after all users are deleted and delete button is not present anymore  the test is still looking for the button.

A: Lets walk through your code
while (!alert && delete_button_is_present)
    {
    clickDeleteBtn;

    if(alert)
    {
        driver.switchTo().alert().accept();

        else if(delete_button_is_not_present)
        {
            break;
        }
    }

You're saying that you want to continue this loop as long as there is no alert, and there is a delete button present on the screen. First, you click the delete button. Without any information about what this button does, I'll assume it is not relevant to the loop. You say if(alert), but if there was an alert you wouldn't be in the loop in the first place...So the loop repeats

A: Make sure delete_button_is_present is or at least can be modified in either clickDeleteButton or driver.switchTo().alert().accept(), or that condition can never be met.
Some questions I have about your code though, which might help if they get cleaned up: you have delete_button_is_present and delete_button_is_not_present.  You can get rid of not_present and just use !delete_button_is_present.  Why do you have an else if which isn't paired with an if inside if(alert)?  If you mean for this to be if(alert), then if(!delete_button_present) then you just need an if statement.  Otherwise you want that else if outside the if(alert).


text:
Q: Overwrite a javascript function in Kendo UI What must i do to overwrite a javascript function?
I bound the plotAreaClick event from the Kendo UI chart to the javascript onPlotAreaClick function. My goal is to use/display the placeholder variable in the onPlotAreaClick.
These are not working (jsfiddle line:45):
onPlotAreaClick(Placeholder)
onPlotAreaClick(this, Placeholder)
See also: http://jsfiddle.net/rule_34/gpurwayr/1/
var seriesData = [{
    productname: "Product One",
    volume: 65.50
}];

function onPlotAreaClick(e) {
    alert(kendo.format("Plot area click :: {0} : {1:N0}", e.category, e.value));
}

$(document).ready(function() {
// -----------------------------------------------------------------------
function createChart(ChartType, Placeholder, MaxValue) {

    $("#" + Placeholder).kendoChart({
        theme: "metro",
        title: {
            font: "12px Arial,Helvetica,sans-serif",
            color: "#29952D",
            text: "Name: " + Placeholder
        },
        dataSource: {
            data: seriesData
        },
        seriesDefaults: {
            labels: {
                template: "#=kendo.format('{0:n2}', (Math.abs(value)))# ltr",
                position: "outsideEnd",
                visible: true,
                background: "transparent"
            }
        },
        series: [{
            type: ChartType,
            field: "volume",
            categoryField: "productname",
        }],
        valueAxis: [{
            min: 0,
            max: MaxValue
        }],
        chartArea: {
            width: 125,
            height: 175
        },
        plotAreaClick: onPlotAreaClick, /* HERE */
    }) // kendoChart
} // function
// -------------------------------------------------------------------
createChart("column", "example_1", 200);
// -----------------------------------------------------------------------
}); // $(document).ready(function()

A: Placeholder is the ID of the chart DIV right? In the click event, e.sender is the chart object, e.sender.element is the DIV, so the id can be had by e.sender.element.prop("id").
function onPlotAreaClick(e) {
    alert(e.sender.element.prop("id"));
}

Updated FIDDLE

UPDATE: From OP's comment
Change plotAreaClick to an anonymous function and then pass placeholder to the onPlotAreaClick function:
        plotAreaClick: function(e) {
            onPlotAreaClick(e, Placeholder);
        },

function onPlotAreaClick(e, Placeholder) {
    alert(Placeholder);
}

FIDDLE


text:
Q: FSM for long bit sequence Currently, I'm working on a mealy fsm that detects a 17 bit sequence 10100001010000001. Due to the length of the sequence, I'm having difficulty figuring out which state to return to when the input doesn't allow me to move on to the next state. Any suggestions ??

A: Think about what previous pattern is satisfied when the expected pattern is not met. The FSM for a 10100001010000001 Mealy machine is shown below, in ASCII art (not sure how it will render here...)
s0-1->s1-0->s2-1->s3-0->s4-0->s5-0->s6-0->s7-1->s8-0->s9-1->s10-0->s11-0->s12-0->s13-0->s14-0->s15-0->s16-1->s17-0->s2
 |    |     |     |     |     |     |     |     |     |     |      |      |      |      |      |      |      |
 0    1     0     1     1     1     1     0     1     0     1      1      1      1      1      1      0      1
 |    |     |     |     |     |     |     |     |     |     |      |      |      |      |      |      |      |
s0    s1    s0    s1    s3    s1    s1    s0    s1    s0    s1     s3     s1     s1     s8     s1     s0     s1


text:
Q: How can I get windows EventLog with python? How  can get log from this path : Application and service -> microsoft ->windows -> ...
like This Eventlog path
I wrote this code but it did not work for this path
I also get the logtype ... from  in eventlog
    server = 'localhost' # name of the target computer to get event logs
    logtype = "Microsoft-Windows-Dhcp-Client/Admin" # 'Application' # 'Security' #'System'
    hand = we.OpenEventLog(None,logtype)
    flags = we.EVENTLOG_FORWARDS_READ|we.EVENTLOG_SEQUENTIAL_READ
    while True:
            events = we.ReadEventLog(hand, flags,0)
            if events:
                for event in events:
                   Source_Name  = event.SourceName


text:
Q: Curly brackets in regexps with Perl just trying to get my head around regexps. The following is part of the code. It read a file line by line and it has the following expression to trip the line of white spaces at either end.
\A match the start of the line
\s+ one or more white spaces
\z match the end of the line
while (<$fh>)
{
  s{\A\s+}{};
  s{\s+\z}{};
}

The part I am struggling with is the curly brackets. The only documentation I can find on them states they act as a multiplier.
I read s{\A\s+}{}; if start of line AND white spaces replace with nothing, but that's my guess. I am looking to confirm that and what the curly brackets means in this regexps

A: devnull has already given the correct answer, but I felt there was more to add than fits in a comment.
s{}{} is simply the s/// substitution operator, but used with a different delimiter. You can use just about any character as delimiter, including balanced parentheses of different types, e.g. s#foo#bar#, s[foo][bar].
You use this to avoid escaping delimiters in the matching string. Such as when matching paths:
s#/foo/bar/baz#/foo/baz/bax#

Looks better than the equivalent, using the default slash delimiter /:
s/\/foo\/bar\/baz/\/foo\/baz\/bax/

Which honestly is quite confusing.
In your case, there is no real reason to use a different delimiter, so the substitutions are in my opinion best written with the original delimiter:
s/\A\s+//
s/\s+\z//

A: The {} refer to a pair of delimiters.
You might want to refer to Quote and Quote-like Operators.
 Customary Generic Meaning  Interpolates
            s{}{}  Substitution yes*

As an example:
$ echo foo 42 bar | perl -pe 's{42}{84}'
foo 84 bar


text:
Q: What will happen if I remove lxqt for lubuntu Hey guys I was curious on what will happen if I remove lxqt from lubuntu ? What apps will go away and how will my default desktop look . I am not planning on doing it but just curious . Sorry if this feels stupid

A: LXQt is the desktop environment for Lubuntu so if you remove it, you will lose your desktop environment and most of your software.


text:
Q: 2 ProxyPass SSL wildcard on HTTPD2 So basically I am trying to setup 3 different SSL virtualhosts. I have the following setup
beta.website.com
api-beta.website.com
app-beta.website.com
beta is our old platform, api and app our part of our new platform and they live on port 8000 (node api) and 3000 (node app). So if I go to go to the sites via http with the port numbers everything works fine. However I am trying to setup proxy pass and I am so close to having it all work.
<VirtualHost *:443>
    ServerName api-beta.website.com
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/website.com.crt
    SSLCertificateKeyFile /etc/pki/tls/private/website.com.key
    SSLCACertificateFile /etc/pki/tls/certs/intermediate.crt
    ProxyPass / http://0.0.0.0:8000/
    ProxyPassReverse / http://0.0.0.0:8000/
    ErrorLog logs/ssl_error_api_log
    TransferLog logs/ssl_access_api_log
    LogLevel warn
  </VirtualHost>

  <VirtualHost *:443>
    ServerName app-beta.website.com
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/website.com.crt
    SSLCertificateKeyFile /etc/pki/tls/private/website.com.key
    SSLCACertificateFile /etc/pki/tls/certs/intermediate.crt
    ProxyPass / http://0.0.0.0:3000/
    ProxyPassReverse / http://0.0.0.0:3000/
    ErrorLog logs/ssl_error_app_log
    TransferLog logs/ssl_access_app_log
    LogLevel warn
  </VirtualHost>

Beyond that I have the virtualhost for the main beta.website.com but it is a little long to post here and I don't think it is the problem. So currently here is what happens
https://beta.website.com Works, directs to the correct spot and has SSL
https://api-beta.website.com Works, directs to the correct spot and has SSL
https://app-beta.website.com Almost works, directs to api-beta.website.com content, but has the correct URL and SSL.
Basically I am trying to proxy pass content from :3000 to app-beta.website.com but it is showing me the content from :8000. I have tried manually going to :3000 and :8000 and they both work as expected and show the correct content under http. Any ideas on what I need to change?

A: For anyone else who needs to deal with this. The issue (as far as I can tell) was that my higher port number (8000) came before my lower port number (3000). Switching the virtual hosts order in my ssl config and restarting apache fixed the issue. Someone with more knowledge please let me know WHY.


text:
Q: Visualising a region involving the $1$-norm I'm a long-time lurker but first-time poster so I apologise if this post isn't formatted correctly. I'm having trouble visualising the region $\mathcal{R}$ defined as:
$$\mathcal{R}=\{\textbf{x}\in\mathbb{R}^2:\Vert{\textbf{x}}\Vert_1\leq\lambda, \lambda>0\}$$
I know that the unit ball for the $1$-norm is a diamond shape, so I thought that $\mathcal{R}$ would be the diamond in the first quadrant (i.e. a triangle with the vertices $(0,0),\ (1,0),\ (0,1)).$ But my lecturer said that $\mathcal{R}$ is a square with the vertices $(0,0),\ (0,1),\ (1,0),\ (1,1).$
I know this problem is trivial but there is obviously a hole in my understanding which I'm hoping you can help me fix.
Thanks in advance.

A: You're both wrong!
It's actually the square whose corners are $(1,0)$, $(0,1)$, $(-1,0)$, and $(0,-1)$.

A: It is a square. Let inspect the unit norm ball.
$$\mathcal{R}=\{\textbf{x}\in\mathbb{R}^2:\Vert{\textbf{x}}\Vert_1\leq 1\}$$
Let say, $\Vert{\textbf{x}}\Vert_1= 1.$ So,
$$|x_1|+|x_2|=1.$$
Case-1 When, $x_1,\ x_2 \geq 0,$
$$x_2=1-x_1.$$
Case-2 When, $x_1 > 0,\ x_2 < 0,$
$$x_2=x_1-1.$$
Case-3 When, $x_2 > 0,\ x_1 < 0,$
$$x_2=x_1+1.$$
Case-4 When, $x_1, \ x_2 < 0,$
$$x_2=-(x_1+1).$$
So, now you can draw the region, and you will find that it is a square having vertices $(-1,0),\ (1,0), \ (0,1),\ (0,-1).$


text:
Q: ConvertTo-SecureString gives different experience on different servers I am running into an issue creating a Credential Object from an XML File on a remote server. Here is the code I am using to test
XML File
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
     <TN RefId="0">
        <T>Selected.System.Management.Automation.PSCredential</T>
        <T>System.Management.Automation.PSCustomObject</T>
        <T>System.Object</T>
     </TN>
     <MS>
        <S N="UserName">domain\username</S>
        <S N="Password">01000000d08c9ddf0115d1118c7a00c04fc297eb010000001f19c6a42b9b0d48af2c531892e737ce000000000200000000001066000000010000200000006fb8862fbaea7b83cd2bcab35d7a8c8b4d71b7764c2a91d68eb3873864bc9d83000000000e8000000002000020000000fcbcc5552c3eb40ec337594f8286b08780709c1ac583d4679dcd7a3f5a92441b20000000c8e274811ed7a411b6741b2c65a67363f6aef380e684d13218d1ecc1281dfdb940000000c7279e81e21a1e57eed7da61e969f34fe2adf3d7e534bb5e10b89902adf4fdf20a69ec7e9b9e56dab512c789043a3b2cf0611e3b4893658b7c20f7892ce0ddfd</S>
</MS>

PowerShell Code
    $cred = Import-Clixml "Payload\DeploymentCredential.xml"
    write-host $cred
    $cred.Password = ConvertTo-SecureString $cred.Password
    write-host $cred.Password
    $Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
    write-host $Credential.GetNetworkCredential().password

On one server (my local machine) it works completely fine, but on the remote server, I get this error
Key not valid for use in specified state.
+ CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicException
+ FullyQualifiedErrorId : ImportSecureString_InvalidArgument_CryptographicError,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

Both have the same version of PowerShell (3.0 Build -1 Revision -1), so I am not sure what the issue is.

A: The issue is how the original credential is created before being exported to xml.
When you use the command ConvertTo-SecureString it encrypts the plaintext password with the encryption key on the local machine, under your user account. This means that if you export it to xml, you can only use it on that same local machine.
The minute you copy the xml file to another machine and try to import the credential object, it won't work because it will be trying to decrypt it with it's local keys which don't match. (hence the error message). This is an important security measure as it prevents me from copying the file and using it on another computer.
If you need to have the user account on another computer to run something, then there is two options:

*

*(Most secure) Create the credential object on each remote computer that you need it. This way it will use the local encryption keys and will prevent people from being able to steal the account.

*(Least secure) When you create the credential with ConvertTo-SecureString you can specify the -Key or -SecureKey parameter. This way instead of using the local encryption keys, it will use the one you specify. Then in your script, you provide the same key to decrypt it. This is less secure because all I have to do is steal the credential file, and take a look inside your script (to see the key) and then I have stolen the account.

--Edit--
Here is an example of how to use a shared key. It is literally only one step up from writing in a plaintext password in your script, and is only used to obfuscate the password. There are many other -better- ways of running scripts on remote machines like PowerShell Remoting (See: Learn to Use Remoting in PowerShell). Or using Task Scheduler with saved credentials.
$PlainPassword = "P@ssw0rd"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force

$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)

$SecurePasswordKey = ConvertFrom-SecureString $SecurePassword -Key $key

#Output the hash
$SecurePasswordKey

#Output
76492d1116743f0423413b16050a5345MgB8ADIAKwBZAEkALwB0ADUAZwBQAHoAbwBNAEEAUwA0AFQAagB0AGsANwBmAHcAPQA9AHwAYgA3ADgAMwBjAGIANAAzADIAZAAwADEAYQA1AGUAMwBjAGUAYgA2AGMAMQBkADcAYQA3ADMAZAA1ADQAYwA0ADMAYgBlAGEANQAyAGQANQA0AGUAYgA5AGEAMgA0AGIANwBhAGIAMQAzADAAMwAzAGEANAA4ADEANQA0AGEAMAA=

On remote machine:
$SecurePasswordKey = '76492d1116743f0423413b16050a5345MgB8ADIAKwBZAEkALwB0ADUAZwBQAHoAbwBNAEEAUwA0AFQAagB0AGsANwBmAHcAPQA9AHwAYgA3ADgAMwBjAGIANAAzADIAZAAwADEAYQA1AGUAMwBjAGUAYgA2AGMAMQBkADcAYQA3ADMAZAA1ADQAYwA0ADMAYgBlAGEANQAyAGQANQA0AGUAYgA5AGEAMgA0AGIANwBhAGIAMQAzADAAMwAzAGEANAA4ADEANQA0AGEAMAA='

$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)

$SecurePassword = ConvertTo-SecureString -String $SecurePasswordKey -Key $key

A: Here's one method for some randomness in creating the key if you choose to use the answer from HAL9256.
[byte[]]$Rand = for($var=1;$var -le 24){
    Get-Random -min 1 -max 255
    $var++
}

We create an array of bytes which is filled with 24 random numbers from 1 to 255.  These numbers are not displayed and exist only when the script is run.
Then we have a key which can be used in the above answer.  The value of $Rand will disappear once the script executes, or you use Remove-Variable Rand
Just be sure to save the data from $Rand to some place secure or the key used to encrypt the data is lost.