text:
Q: magento 2 system configuration with a custom .phtml template? in system.xml:
<field id="custom_field" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
      Custom Field
      <source_model>Vendor\Module\Block\Adminhtml\System\Config\Custom</source_model>
</field>

Custom.php:
 namespace Vendor\Module\Block\Adminhtml\System\Config;
 use Magento\Framework\App\Config\ScopeConfigInterface;

class Custom extends \Magento\Config\Block\System\Config\Form\Field
{
protected $_template = 'Vendor_Module::system/config/custom.phtml';

const TEMPLATE = 'Vendor_Module::system/config/custom.phtml';

protected $_moduleManager;

/**
 *
 * @param \Magento\Backend\Block\Template\Context $context
 * @param ScopeConfigInterface $scopeConfig
 * @param \Magento\Framework\Module\Manager $moduleManager
 * @param \Magento\Framework\ObjectManagerInterface $objectmanager
 * @param array $data
 */
public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Framework\Module\Manager $moduleManager,
    array $data = []
)
{
    $this->_scopeConfig     = $scopeConfig;
    $this->_moduleManager   = $moduleManager;
    parent::__construct($context, $data);
}

/**
 *
 * @return $this
 */
protected function _prepareLayout()
{
    parent::_prepareLayout();
    if (!$this->getTemplate()) {
        $this->setTemplate(static::TEMPLATE);
    }
    return $this;
}
/**
 * Retrieve element HTML markup.
 *
 * @param \Magento\Framework\Data\Form\Element\AbstractElement $element
 *
 * @return string
 */
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
    $this->setNamePrefix($element->getName())
        ->setHtmlId($element->getHtmlId());

    return $this->_toHtml();
}

}

custom.phtml: As an example but more then that basically any html element

        Click here

<select name="custom" class="select admin__control-select"
        data-ui-id="select-groups-third-fields-custom-value">
    <option value="no">No</option>
    <option value="yes">Yes</option>
</select>
<input type="checkbox" name="test" />

END

A: I've manage to add by using frontend_model:
<field id="my_field" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0">
       <frontend_model>Vendor\Module\Block\System\Config\Custom</frontend_model>
       Custom
 </field>

Using this example:How to create a button in Magento 2 configuration section?


text:
Q: Activate venv and run python script from shell script I am testing a (python) bot script before using it with crontab. I was advised to run a shell script that runs the python script in the crontab. In order for the shell script to run, I need to activate the venv. This is where the problem is. When I try to run run_socialbot.py, I get:
Traceback (most recent call last):
  File "/home/gsb/socialbot.py", line 3, in <module>
    from instapy import InstaPy
ModuleNotFoundError: No module named 'instapy'

Even though instapy is installed in the venv. And when I open up the interpreter with "python3" and try to import instapy while the venv is activated, it works fine. Here is the shell script code:
#! /bin/bash

source /home/gsb/venv/bin/activate

/usr/bin/python3 /home/gsb/socialbot.py

Can anyone help out? thanks in advance
I'm running this at a digitalocean server. Ubuntu 20.04

A: Your shell script activates the venv but then it explicitly calls an absolute path /usr/bin/python3. That's not the venv Python executable. The whole point of activating the venv is to set $PATH so that python points at the venv interpreter.
In your wrapper script, change it to:
python /home/gsb/socialbot.py

Alternatively you can remove the bash wrapper script entirely, and put a venv shebang into socialbot.py, then use this Python file in the crontab directly. Make the file executable, and add as the first line:
#!/home/gsb/venv/bin/python

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSF and Facebook Is it possible to integrate facebook on a jsf page? Facebook only shows examples with php, but I already have an application written in jsf. I would like the single sign-on feature and be able to get my users pictures from facebook.
Maybe you have a little example on how you would do it :)
Thank you

A: Yes, it is possible. It does not matter whether it's JSF or any other view technology. You can take a look at RestFB - a Java API for using the Facebook Graph API. Or you can use the brand-new Spring Social, but it is not quite feature-rich yet.


text:
Q: Smooth PostScript animations I would like to run animations in PostScript smoothly. To see what I want, let me switch to PostScript directly. Call ghostscript, and
200 dup scale .5 setgray 0 0 3 3 rectfill

We have now a gray square.
0 setgray 0 1 3 1 rectfill

With a black stripe in it.  We will now fill that stripe, one time white
and black in succession:
{1 setgray 0 1 3 1 rectfill 0 setgray 0 1 3 1 rectfill} loop

You will see now some flickering of black and white rectangles that
are smaller than the original black stripe.  Ideally, we would see
the original grey square. Or almost.  Where can I get such functionality today?
To see a more interesting animation sequence searching for magic
squares of size 5:
wget http://www.complang.tuwien.ac.at/ulrich/gupu/l5.eps.gz
zcat l5.eps.gz | ghostscript -

A couple of years ago I did try to address these issues.  But it never went into ghostscript or Xfree. See
this page.  Maybe there are some better ideas now?
Edit: After reading the responses so far, let me clarify one issue here. Essentially, there are two independent issues in this question:

*

*How should an animation be viewed from the language level? I believe, the best way is to view each frame as a single page. With copypage incremental changes can be realized with low effort. Sadly, that semantics of copypage is only present in Level 1 and 2.  In Level 3, the meaning of copypage changed to showpage. I did - many years ago - a little modification to ghostscript to delay all visible changes up to copypage or showpage. In this manner, a single XCopyArea containing the changed area is performed locally on the server (that is, the display).

*How should actual changes on the visual display be synchronized to avoid artefacts that where not present in the graphics described? The irregular flicker you see is not a privilege of PostScript, it seems to be present in any double-buffered system I have seen so far. Just try to program this in whatever system you see fit.
Further edit:
To get the right language level, that is level 1 or 2 do (for ghostscript):
systemdict /.setlanguagelevel known {2 .setlanguagelevel} if

Edit: I am adding this comment to may attract some new postscript contributors.

A: We explored some of these issues in this thread on comp.lang.postscript.
Since the release of the Level 2 standard, Postscript is a garbage-collected language. You can disable collection of user objects with the fragment -2 vmreclaim, but it doesn't accomplish much. You can disable ALL ghostscript garbage collection by invoking with the -dNOGC option. This should help prevent stalling and spitting with parts of the image.
Ghostscript has a non-standard operator called flushpage, which synchronizes the rendering with the execution. This helps make sure that everything is seen before it's gone.

- flushpage -
On displays, flushes any buffered output, so that it is guaranteed to
show up on the screen; on printers, has no effect

And for timing control, there doesn't seem to be a better way than simple busy-waiting.

/smallpause {
    /flushpage where{pop flushpage}if
    50 sleep } def
/pagepause {
    /flushpage where{pop flushpage}if
    1000 sleep } def

/sleep {
    usertime add {
        10 {
            1 100000 div pop %busy
            .1 sin 257 cos atan pop %busy busy
        } repeat
        dup usertime le {exit}if
    } loop pop
} def

The where guards around flushpage allow you to send the same code to interpreters other than ghostscript (like a printer).
If you had an actual Display Postscript server, you could use the wait operator instead of busy-waiting.

A: Although I like (and upvoted) @luserdroog's answer, I don't believe Postscript should be used for animations on this way - I'd rather use some language that can run widgets or display elements that are designed for real time display and user interation - that is not the case of postscript or ghostscript.
I think it would be nice, though, use postscript for aimations for rendering purposes - just rendering a page after each modification on the image, and using an external program to assemble the different pages as animation frames.
Maybe even using postscript as a rendering engine, with the process in another language calling ghostscript to render each frame in realtime. A nice and easy to use multimedia framework to do that could be for example, the Python language with the Pygame module.
Here is a short example using "pure python + pygame".
#! /usr/bin/env python
# coding: utf-8

import pygame

size = 640,480 #(in pixels)

# multiplying factor so that the whole image is 5 units across
factor = size[0] / 5.0

# Inits pygame drawing window
screen = pygame.display.set_mode(size)

# Rectangle drawing function that scales drawing using the factor above
def draw_rect(color, rect):
    new_rect = [int (r * factor) for r in rect]
    return pygame.draw.rect(screen, color, new_rect)

def main():
    draw_rect((128,128,128), (0, 0, 3, 3))
    colors = ((255,255,255), (0,0,0))
    color_index = 0
    while True:
        draw_rect(colors[color_index], (0, 1, 3, 1))
        pygame.display.flip()
        color_index = 1 - color_index
        pygame.time.delay(50) # in miliseconds

try:
    main()
finally:
    pygame.quit()

To execute this, you have to have Python and Pygame (from http://pygame.org - there are ready packages on most linux systems for that)
Pygame's drawing API is much poorer than postscript - if you need more than rectangles
(like bezies, scaling, rotating and  shearing the coordinate system, and so on), the way to go is to use Cairo + python + some display library (which might be pygame, GTK+ or qt) . Cairo is a 2D drawing library that inherits from the postscript way. - or, as I said above, to drive a ghostscript external process using Python, having it generating a rle compressed image file to stdout or a ramdrive, and that image read and displayed frame by frame using python + pygame.
Another option is to use HTML5's Canvas, and do everything in Javascript, viewable on a browser. HTML5's Canvas also inherits the Postscript way of drawing.


text:
Q: Spring Boot project naming convention While creating a Spring Boot app, I thought some points regarding project name and package name in Spring Initializr. The issues:

*

*When creating an app that is used to save and manipulate data, should I use api or app in the name. For example, while creating an app for saving Book data with CRUD operations, should I use book-api or book-app for a better naming convention. As the app does not serve data to public, and will be used individually, I think it seems to be better using book-app. But not sure (also it has endpoints and it may also be considered as API).

*In Spring Initializr, when I use book-app in the name field, the package name field would be com.example.book-app. But if there is not multiple modules, I think there is no need to use book-app again in this field. For this reason I use just com.example (of course I update the domain properly, it is just for example) in the Package name field without name. Is that ok? Or should I always use Group + Name (com.example.book-app) as in default format?

A: *

*API (application programming interface) is a name which refers that the program you are writing provides some kind of functionality others can use, such as a library.

*You should always include the program name, as to minimize clashes of class names in the class-path.

You should use the book-app name as it describes an application, but it's not something mandated.


text:
Q: Encoding issues when spooling files from Oracle Database with UTF-8 encoding Issue description:
I have a script which runs on Oracle Databases (Windows, or Unix OS). It extracts data and then spools it to .txt files.
To ensure the file is unchanged, the data is hashed while running the script and this hash is later recalculated in a webapplication. This works 9/10 times, but sometimes it provides a mismatch, even though the files are identical and I isolated this to be an encoding issue.
In order to determine the encoding used for the files, the script writes 3 NONASCII characters to a file, which are encoded differently in different encoding schemes. These are later mapped on the backend.
--Encoding related information
SPOOL &&file_desc/Encoding.txt
SELECT ('€'||';'||'ƒ'||';'||'‰') FROM sys.dual;
SPOOL off

Expected result
On a database with UTF-8 encoding, data with NONASCII chars should be spooled correctly and the 3 NONASCII characters should also be spooled correctly.
Actual result
When using .AL32UTF8 system charset (same as DB), the data is spooled correctly, but the 3 characters for encoding are not. This makes it impossible for me to determine which encoding scheme was used.
Database has the following charactersets (obtained from database_properties):
NLS_CHARACTESET:  AL32UTF8
NLS_NCHAR_CHARACTERSET:  AL16UTF16
SQL-Developer works
When using SQL-Developer (after setting the encoding to UTF8)), I have no issues. Both the Japanese and Greek characters show up correctly and the characters used for encoding correctly show up, leading to a successful hashing match when later recalculated.
SQL*Plus doesn't work
I need it to work in SQL*Plus as well though and I've been running into issues. I've tried a range of different variations. DB is Oracle 18c express edition:
Variations tried on SQL*Plus

*

*Set just char code page to utf-8 corresponding to DB
chcp 65001    (code for utf-8)  NLS_LANG charset:    .WE8MSWIN1252
The file with the tablename including the japanese characters gives
an encoding 'error': JAPANESE¿  The file with the 3 chars used to
determine encoding does work well: €;ƒ;‰

*No changes to code page, but updated NLS_LANG charset
NLS_LANG charset:   .AL32UTF8 The file with the tablename including
the japanese character shows fine now: JAPANESE世 The file with the 3
chars used to determine encoding is now suddenly 'empty' however: ;;

*Set NLS_LANG to same as DB and updated code pages chcp
65001  (code for utf-8) NLS_LANG charset:   .AL32UTF8 The file with
the tablename including the japanese character shows fine now:
JAPANESE世 The file with the 3 chars used to determine encoding is
now suddenly 'empty' however: ;;

*Set NLS_LANG to NLS_NCHAR_Characterset. Just in case I also
tried to set the system charset to AL16UTF16 which is equal to the
NLS_NCHAR_Characterset, thinking that might help solve the issue,
but then I get the following error: Error 19 initializing SQL*PLUS
Invalid NLS character set for this OS environment
Conclusion / question
The code page doesn't really matter as it just concerns itself with outputting to the command window.
As could be expected, when using the WE8MSWIN1252 the spooling of NONASCII characters doesn't work, because it doesn't know the characters.
Yet when using AL32UTF8, the spooling of the 3 NONASCII characters form sys.dual no longer works, even though it does know the characters.
I've spent several days isolating this issue, I'm at a loss why the latter is the case, can anyone help me?

*Edit, kfinity offerd the solution, although not 100% certain yet why this is the case. So if anyone knows?
If we replace the select statement to the following, it does work:
select unistr('\20AC;\0192;\2030') from dual;

A: sqlplus inherits the code page/encoding from parent cmd window. NLS_LANG tells the database which characterset/encoding is used by the client. So, when you run
chcp 65001
set NLS_LANG=.AL32UTF8
sqlplus ....

or
chcp 1252 (the default)
set NLS_LANG=.WE8MSWIN1252
sqlplus ....

then in principle you do it correctly. However, the windows cmd does not fully support UTF-8, see How to use unicode characters in Windows command line? and/or https://community.oracle.com/tech/developers/discussion/600575/how-to-use-sqlplus-with-utf8-on-windows-command-line
You may have to use another tool than sqlplus to create your file.
See also OdbcConnection returning Chinese Characters as "?"

A: I'm not really sure what the issue is, but if you try doing:
select unistr('\20AC;\0192;\2030') from dual;

I think it would bypass the issue of getting SQL*Plus to read the correct character values from the .sql file.


text:
Q: Custom Loss Function Leads to High MSE and an offset in the output Keras I am training a neural network for time series regression. The model is
####################################################################################################################
# Define ANN Model
# define two sets of inputs
acc   =  layers.Input(shape=(3,1,))
gyro  =  layers.Input(shape=(3,1,))

# the first branch operates on the first input
x = Conv1D(256, 1, activation='relu')(acc)
x = Conv1D(128, 1, activation='relu')(x)
x = Conv1D(128, 1, activation='relu')(x)
x = MaxPooling1D(pool_size=3)(x)
x = Model(inputs=acc, outputs=x)

# the second branch opreates on the second input
y = Conv1D(256, 1, activation='relu')(gyro)
y = Conv1D(128, 1, activation='relu')(y)
y = Conv1D(128, 1, activation='relu')(y)
y = MaxPooling1D(pool_size=3)(y)
y = Model(inputs=gyro, outputs=y)

# combine the output of the three branches
combined =  layers.concatenate([x.output,  y.output])

# combined outputs
z = Bidirectional(LSTM(128, dropout=0.25, return_sequences=False,activation='tanh'))(combined)
z = Reshape((256,1),input_shape=(128,))
z = Bidirectional(LSTM(128, dropout=0.25, return_sequences=False,activation='tanh'))(combined)

#z = Dense(10, activation="relu")(z)
z = Flatten()(z)
z = Dense(4, activation="linear")(z)
model = Model(inputs=[x.input, y.input], outputs=z)
model.compile(loss=loss, optimizer = tf.keras.optimizers.Adam(),metrics=['mse'],run_eagerly=True)

I have tried to implement a custom loss function (based on different papers).
Math
The error will calculated as follows:
y_pred = [w x y z]
y_true = [w1 x1 y1 z1]
error = 2 * acos(w*w1 + x*x1 + y*y1 + z*z1)

Based on this formula I wrote the custom loss function:
def loss(y_true, y_pred):
    z = y_true * (y_pred )
    wtot = tf.reduce_sum(z,axis=1)
    error = 2*tf.math.acos(K.clip(tf.math.sqrt(wtot*wtot), -1.,1.))
    return error

But while the loss value is decreasing the MSE increased and I can see an offset in the output which will grow by the number of epochs. I understand that we do not optimize this Network for MSE but based on mathematics the MSE must be reduced or converge to some value near 1.
Orange is the Target/Reference
Blue is the Network ouptut
for 1 epoch

for 10 epochs

for 50 epochs

A: To solve this problem, I used geometric distance equation to find the loss value
def QQuat_mult(y_true, y_pred):
    """
    The function takes in two quaternions, normalizes the first one, and then multiplies the two
    quaternions together.

    The function returns the absolute value of the vector part of the resulting quaternion.

    The reason for this is that the vector part of the quaternion is the axis of rotation, and the
    absolute value of the vector part is the angle of rotation.

    The reason for normalizing the first quaternion is that the first quaternion is the predicted
    quaternion, and the predicted quaternion is not always normalized.

    The reason for returning the absolute value of the vector part of the resulting quaternion is that
    the angle of rotation is always positive.

    The reason for returning the vector part of the resulting quaternion is that the axis of rotation is
    always a vector.

    :param y_true: the ground truth quaternion
    :param y_pred: the predicted quaternion
    :return: The absolute value of the quaternion multiplication of the predicted and true quaternions.
    """

    y_pred = tf.linalg.normalize(y_pred, ord='euclidean', axis=1)[0]
    w0, x0, y0, z0 = tf.split(
        (tf.multiply(y_pred, [1., -1, -1, -1]),), num_or_size_splits=4, axis=-1)
    w1, x1, y1, z1 = tf.split(y_true, num_or_size_splits=4, axis=-1)
    w = w0*w1 - x0*x1 - y0*y1 - z0*z1
    w = tf.subtract(w, 1)
    x = w0*x1 + x0*w1 + y0*z1 - z0*y1
    y = w0*y1 - x0*z1 + y0*w1 + z0*x1
    z = w0*z1 + x0*y1 - y0*x1 + z0*w1

    loss = tf.abs(tf.concat(values=[w, x, y, z], axis=-1))
    return tf.reduce_mean(loss)


text:
Q: How do I convert stored hexa number array to decimal with MIPS? I need a string array stored as an Hexa number and i need to convert it to a base 10 number (decimal).
.data
    inputNumberArray:   .space  32

This array was read using
la   $a0, inputNumberArray  # load inputBase address to a0
li  $v0, 8          # read_string syscall code = 8
li  $a1, 32         # space allocated for inputBase
syscall

So I have an array like
inputNumberArray = 3E8
And I need the output to be
outputArray = 1000
Thanks :D

A: Finally I got it working!
I have an input array like [7b] store in inputNumberArray
### HEXA -> DECIMAL
fromHexaStringToDecimal:
    # start counter
    la   $t2, inputNumberArray       # load inputNumber address to t2
    li   $t8, 1                      # start our counter
    li   $a0, 0                      # output number
    j    hexaStringToDecimalLoop

hexaStringToDecimalLoop:
    lb   $t7, 0($t2)
    ble  $t7, '9', inputSub48       # if t7 less than or equal to char '9' inputSub48
    addi $t7, $t7, -55              # convert from string (ABCDEF) to int
    j    inputHexaNormalized
inputHexaNormalized:
    blt  $t7, $zero, convertFinish  # print int if t7 < 0
    li   $t6, 16                    # load 16 to t6
    mul  $a0, $a0, $t6              # t8 = t8 * t6
    add  $a0, $a0, $t7              # add t7 to a0
    addi $t2, $t2, 1                # increment array position
    j    hexaStringToDecimalLoop

inputSub48:
    addi $t7, $t7, -48              # convert from string (ABCDEF) to int
    j    inputHexaNormalized

So in the end I will have the decimal number stored in $a0.
The trick was to check if the number has ABCEDF chars and sum -55 in this case, otherwise -48.
Example:
'9' -48 = 9     #  '9' char to 9 int
'A' -55 = 10    #  'A' char to 10 int

Thanks to @wallyk. I started to write it again in python then converted to MIPS.


text:
Q: Android facebook auto status update I have the facebook sample app posting test and picture updates separately to my wall. I want to combine these so that i can say something like 'Hey everybody, here is a picture of my dog! followed by the picture (dont care about layout really).
Any ideas if/how i do this?

A: Make a bundle that and put all the information over there:
Bundle postParams = new Bundle();
        postParams.putString("name", "example");
        postParams.putString("caption", "caption of the image.");
        postParams.putString("description", "Put your status here.");
        postParams.putString("picture", "www.example.com/image.jpg");

Now use this bundle in the request object you make to post on timeline.
Hope this helps :)


text:
Q: How to place texts under an image in SwiftUI? I'm trying to create some tiles in my swiftUI project.
The tiles will need to look like this:

Basically, I need to place the caption on the left and the texts under the image.
I can create the image and I can overlay the texts on the image but I cannot place them under  the image and I cannot place the caption to the left.
This is my current code:
Image("flower")
               .resizable()
               //.aspectRatio(contentMode: .fill)
               .frame(width: 160, height: 200)
               // Overlay is a very simple way to add content on top of your view !

               .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
               .shadow(color: Color.black.opacity(0.3), radius: 6, x: 0, y: 3)

        VStack(alignment: .trailing, spacing: 6) {

          Text("sit amet")
            .background(Color.gray.opacity(0.2))
            .font(.caption)
        }.onTapGesture {
                   // Handle the action when the card is touched

                }

can someone please advice on this?

A: Put the Image and text both under VStack as follows:
VStack(alignment: .leading, spacing: 6) {
      Image("flower")
                   .resizable()
                   //.aspectRatio(contentMode: .fill)
                   .frame(width: 160, height: 200)
                   // Overlay is a very simple way to add content on top of your view !
                   .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
                   .shadow(color: Color.black.opacity(0.3), radius: 6, x: 0, y: 3)

    Text("sit amet")
                .background(Color.gray.opacity(0.2))
                .font(.caption)
            }.onTapGesture {
                       // Handle the action when the card is touched

                    }

    Text("Some Info goes here")
    }


text:
Q: Multi Step Form using fieldset I have my code in HTML and JavaScript that using fieldset to change step form. I want in every fieldset has own form tag, so when i submitted in 1st fieldset it changing to 2nd fieldset
Here's my HTML code

<fieldset>
    1

    <form>
        <input type="text">
        <?php
            echo form_button('previous', 'Kembali', array('class'=>'previous action-button'));
            echo form_submit('submit', 'Next', array('class'=>'next action-button'));
        ?>
    </form>
</fieldset>

<fieldset>
    2

    <form>
        <input type="text">
        <?php
            echo form_button('previous', 'Kembali', array('class'=>'previous action-button'));
            echo form_submit('submit', 'Next', array('class'=>'next action-button'));
        ?>
    </form>
</fieldset>

please help me solve this

A:

Account Setup

Social Profiles

    <form id="msform1" class="msform">

        <fieldset>

Create your account

This is step 1

            <input type="text" name="email" id="emailAccount" placeholder="Email" />
            <input type="password" name="pass" placeholder="Password" />
            <input type="password" name="cpass" placeholder="Confirm Password" />
            <input type="button" name="submit1" class="submit next action-button" value="Register" />
        </fieldset>
    </form>
    <form id="msform2" class="msform">
        <fieldset>

Welcome

For complete account, link with social network

            <input type="text" name="twitter" placeholder="Twitter" />
            <input type="text" name="facebook" placeholder="Facebook" />
            <input type="text" name="gplus" placeholder="Google Plus" />
            <input type="button" name="previous" class="previous action-button" value="Previous" />
            <input type="button" name="submit2" class="submit action-button" value="Complete" />
        </fieldset>
    </form>

A: You can do for each fieldsets call custom ajax request by javascript depending on step, validating this fields on client-side.
Because if you not use ajax, the page will be refresh and you will lose the step.


text:
Q: How to remove leading spaces in multiple lines based on indent in first line? Processing a text line-by-line removing leading spaces on each line is easy:
$ LC_ALL=C git ls-files | sed -nE 's:^.*(\.[^./]+)$:\1:p' \
    | sort | uniq -c | sort -snr > lines # create example "lines" file
$ cat lines # "lines" example file
     30 .md
      8 .png
      4 .yml
      1 .css
      1 .gitignore
      1 .ico
      1 .sh
      1 .txt
$ sed -Ee 's/^ +//' lines # removing leading spaces (U+0020)
30 .md
8 .png
4 .yml
1 .css
1 .gitignore
1 .ico
1 .sh
1 .txt

However if only the first line should set the number of spaces to remove of all subsequent lines, how to achieve this? The output would look like:
30 .md
 8 .png
 4 .yml
 1 .css
 1 .gitignore
 1 .ico
 1 .sh
 1 .txt

What I'm trying to achieve is to pipe it to column(1) and make the output more dense but keeping the horizontal spacing across all lines. Simulation:
$ column -x lines | expand -t 8
     30 .md                   8 .png                  4 .yml
      1 .css                  1 .gitignore            1 .ico
      1 .sh                   1 .txt

Right now w/o trimming on the left a lot of space is in use as uniq(1) with the -c option adds them as it does right-justify the numbers (at position 8).
As long as I assume the maximum count is fixed, e.g. at maximum two digits long, I could hard-code it:
sed -Ee 's/^ {5}//' lines | column -x | expand -t 8
30 .md           8 .png          4 .yml          1 .css          1 .gitignore
 1 .ico          1 .sh           1 .txt

A: Gnu sed: store the leading whitespace in the hold and then strip away this much amount of leading whitespace from every line. Assuming the lines are sorted as shown.
sed -Ee '
  1{h;s/\S.*//;x;}
  G;s/^(\s*)(.*)\n\1$/\2/
' file

awk '
NR==1 {
  l0=length()
  $1=$1
  re = "^\\s{" l0-length() "}"
}
sub(re, "")+1
' file

perl -lpe '
  $x //= do{/^\s*/g;+pos;};
  $_ = substr($_,$x);
' file

A: I should have been looking into awk(1) earlier. At least I could write a small program that stores the number of leading spaces of the first line and formats every line:
$ awk '
    NR==1 && match($0, /^ */) {p=RLENGTH+1};
    {print(substr($0,p))}
' lines | column -x | expand -t 8
30 .md           8 .png          4 .yml          1 .css          1 .gitignore
 1 .ico          1 .sh           1 .txt

A: Why limit to the first line? As long as you don't need to process gigabytes of data where storing it all in memory would be an issue, you can just save the longest first field, and then use that to format the rest:
$ cat lines
      4 .yml
      1 .sh
      1 .ico
      1 .gitignore
      1 .css
     30 .md
      1 .txt
      8 .png

And:
$ awk -v l=0 '{
                if(length($1)>l){
                    l=length($1)
                }
                a[$2]=$1
              }
              END{
                for(line in a){
                    printf "%"l"s %s\n",a[line],line
                }
             }' lines
 8 .png
 1 .ico
 1 .txt
 1 .css
 1 .sh
30 .md
 1 .gitignore
 4 .yml

So:
$ awk -v l=0 '{ if(length($1)>l){l=length($1)} a[$2]=$1}END{for(line in a){printf "%"l"s %s\n",a[line],line}}' lines |
    column -x | expand -t 8
 8 .png          1 .ico          1 .txt          1 .css          1 .sh
30 .md           1 .gitignore    4 .yml

If you don't need this, and only care about the first line, you could simplify to:
$ perl -pe '/^(\s+)/; $l//=$1; s/^$l//' lines | column -x | expand -t 8
30 .md           4 .yml          1 .sh           1 .ico          1 .gitignore
 1 .css          1 .txt          8 .png

A: I hope I understand and I'm on the right path:
$ sed 's/^[[:blank:]]//' file | cut -d' ' -f3- | column -x | expand -t 8 | cut -d' ' -f3-
30 .md           8 .png          4 .yml          1 .css          1 .gitignore
 1 .ico          1 .sh           1 .txt

For a scenario like this, for example:
     30 .md
      8 .png
      4 .yml
      1 .css
      1 .gitignore
   4000 .ico
      1 .sh
      1 .txt
    300 .foo

$ sed 's/^[[:blank:]]//' file | cut -d' ' -f3- | column -x | expand -t 8 | cut -d' ' -f3-
30 .md           8 .png          4 .yml          1 .css       4000 .ico
 1 .gitignore    1 .sh           1 .txt        300 .foo


text:
Q: Tcolorbox and lost floats I use tcolorbox to write exercises with solutions for a book of probability. When I use some floats, like tables or figures, it refuses it, and I have error messages like ! LaTeX Error: Not in outer par mode. or Float(s) lost.. so I'm obliged to undo the float command begin{figure}.. \end{figure} and use instead the caption package, and it's command
\captionof{figure}{The caption}...
Now, I want to use floats in such cases. 1/ How can I use it ?
2/ Moreover, is it possible to use with \NewTColorBox some rotated tables, given by the package ctable, like this one, for example: ?
\ctable[
caption={Mycaption},
label={tab:Mytable},
botcap, % caption below table
sideways % This rotates the table
]
{ccc}
{
% Table footnotes here
}
{
Column 1 & Column 2 & Column 3 \\
Row 2, 1 & 2, 2     & 2, 3 \\
}

3/ More and moreover, can I write some things outside the box of solution, for writing some comments for example, or some floats !, between two successive solutions ?
I give an example of an exercise, where one can note that the commands \begin{figure} \end{figure} are commented, (there is the error Not in outer par mode when it is uncomented)
\documentclass{book}

\usepackage[most]{tcolorbox}
\tcbuselibrary{skins,breakable,xparse}

\usepackage{caption}

\usepackage[most]{tcolorbox}
\tcbuselibrary{skins,breakable,xparse}

\usepackage{tikz}
\usetikzlibrary{arrows,backgrounds,plotmarks,calc,positioning,shadings,patterns,tikzmark}
\usepackage{pgfplots}

%\usepackage{ctable}% Uncomment If one wants to compile the ctable given as example
\usepackage{polyglossia}
\setmainlanguage{english}

\NewTColorBox[auto counter,number within=chapter]{exercise}{m+O{}}{%
    enhanced,
    colframe=green!20!black,
    colback=yellow!10!white,
    coltitle=green!40!black,
    fonttitle=\bfseries,
    underlay={\begin{tcbclipinterior}
        \shade[inner color=green!80!yellow,outer color=yellow!10!white]
            (interior.north west) circle (2cm);
        \draw[help lines,step=5mm,yellow!80!black,shift={(interior.north west)}]
            (interior.south west) grid (interior.north east);
        \end{tcbclipinterior}},
    title={Exercise~ \thetcbcounter:},
    label={exercise:#1},
    attach title to upper=\quad,
    after upper={\par\hfill\textcolor{green!40!black}%
        {\itshape Solution on page~\pageref{solution:#1}}},
    lowerbox=ignored,
    savelowerto=solutions/exercise-\thetcbcounter.tex,
    record={\string\solution{#1}{solutions/exercise-\thetcbcounter.tex}},
    #2
}

\NewTotalTColorBox{\solution}{mm}{%
    enhanced,
    colframe=red!20!black,
    colback=yellow!10!white,
    coltitle=red!40!black,
    fonttitle=\bfseries,
    underlay={\begin{tcbclipinterior}
        \shade[inner color=red!50!yellow,outer color=yellow!10!white]
            (interior.north west) circle (2cm);
        \draw[help lines,step=5mm,yellow!80!black,shift={(interior.north west)}]
            (interior.south west) grid (interior.north east);
        \end{tcbclipinterior}},
    title={Solution of Exercise~\ref{exercise:#1} on page~\pageref{exercise:#1}:},
    phantomlabel={solution:#1},
    attach title to upper=\par,
}{\input{#2}}

\tcbset{no solution/.style={no recording,after upper=}}

\begin{document}
%% Uncomment If one wants to compile this ctable
%%  \ctable[
%%  caption={Your table caption},
%%  label={tab:mytable},
%%  botcap, % caption below table
%%  sideways % This rotates the table
%%  ]
%%  {ccc}
%%  {
%%  % Table footnotes here
%%  }
%%  {
%%  Column 1 & Column 2 & Column 3 \\
%%  Row 2, 1 & 2, 2     & 2, 3 \\
%%  }
\chapter{The first chapter}
\tcbstartrecording
\begin{exercise}{BanachMatch}
The bar graph of the distribution of Banach matches..
\tcblower
%   \begin{figure}[h]
    {\centering
\begin{tikzpicture}[
    declare function={
    comb(\n,\k)=\n!/(\k!*(\n-\k)!);
    albanach(\k,\n,\p)=comb(2*\n-\k,\n)*(\p^(\n+1)*(1-\p)^(\n-\k)+\p^(\n-\k)*(1-\p)^(\n+1));
    }
]
\begin{axis}[
    xlabel={$x$}, ylabel={$P(X=x)$},
    yticklabel style={
        /pgf/number format/fixed,
        /pgf/number format/fixed zerofill,
        /pgf/number format/precision=2
    },
    legend style={
cells={anchor=east},
legend pos=outer north east,
    xlabel={$x$}, ylabel={$P(X=x)$},samples at={0,...,50},
    yticklabel style={
        /pgf/number format/fixed,
        /pgf/number format/fixed zerofill,
        /pgf/number format/precision=2
                     }
              },
    ybar=0pt, bar width=2
]
\addplot [fill=orange, fill opacity=0.5] {albanach(x,50,0.5)}; \addlegendentry{$p=0.5$}
\addplot [fill=cyan, fill opacity=0.5] {albanach(x,50,0.4)}; \addlegendentry{$p=0.4$}
\addplot [fill=blue, fill opacity=0.5] {albanach(x,50,0.3)}; \addlegendentry{$p=0.3$}
\end{axis}
\end{tikzpicture}
\par}
\captionof{figure}{Banach matches}
%\end{figure}
\end{exercise}
\tcbstoprecording
\tcbinputrecords
\end{document}

and its compilation, using xelatex:

A: You have the nesting in the wrong order, you want your coloured boxes to float, so they should be inside figure you do not want figure to be inside the box.
this works without error
\begin{figure}[htp]
\begin{exercise}{BanachMatch}

....
\end{exercise}
\end{figure}

with no other changes needed to your document.

\documentclass{book}

\usepackage[most]{tcolorbox}
\tcbuselibrary{skins,breakable,xparse}

\usepackage{caption}

\usepackage[most]{tcolorbox}
\tcbuselibrary{skins,breakable,xparse}

\usepackage{tikz}
\usetikzlibrary{arrows,backgrounds,plotmarks,calc,positioning,shadings,patterns,tikzmark}
\usepackage{pgfplots}

%\usepackage{ctable}% Uncomment If one wants to compile the ctable given as example
\usepackage{polyglossia}
\setmainlanguage{english}

\NewTColorBox[auto counter,number within=chapter]{exercise}{m+O{}}{%
    enhanced,
    colframe=green!20!black,
    colback=yellow!10!white,
    coltitle=green!40!black,
    fonttitle=\bfseries,
    underlay={\begin{tcbclipinterior}
        \shade[inner color=green!80!yellow,outer color=yellow!10!white]
            (interior.north west) circle (2cm);
        \draw[help lines,step=5mm,yellow!80!black,shift={(interior.north west)}]
            (interior.south west) grid (interior.north east);
        \end{tcbclipinterior}},
    title={Exercise~ \thetcbcounter:},
    label={exercise:#1},
    attach title to upper=\quad,
    after upper={\par\hfill\textcolor{green!40!black}%
        {\itshape Solution on page~\pageref{solution:#1}}},
    lowerbox=ignored,
    savelowerto=solutions/exercise-\thetcbcounter.tex,
    record={\string\solution{#1}{solutions/exercise-\thetcbcounter.tex}},
    #2
}

\NewTotalTColorBox{\solution}{mm}{%
    enhanced,
    colframe=red!20!black,
    colback=yellow!10!white,
    coltitle=red!40!black,
    fonttitle=\bfseries,
    underlay={\begin{tcbclipinterior}
        \shade[inner color=red!50!yellow,outer color=yellow!10!white]
            (interior.north west) circle (2cm);
        \draw[help lines,step=5mm,yellow!80!black,shift={(interior.north west)}]
            (interior.south west) grid (interior.north east);
        \end{tcbclipinterior}},
    title={Solution of Exercise~\ref{exercise:#1} on page~\pageref{exercise:#1}:},
    phantomlabel={solution:#1},
    attach title to upper=\par,
}{\input{#2}}

\tcbset{no solution/.style={no recording,after upper=}}

\begin{document}
%% Uncomment If one wants to compile this ctable
%%  \ctable[
%%  caption={Your table caption},
%%  label={tab:mytable},
%%  botcap, % caption below table
%%  sideways % This rotates the table
%%  ]
%%  {ccc}
%%  {
%%  % Table footnotes here
%%  }
%%  {
%%  Column 1 & Column 2 & Column 3 \\
%%  Row 2, 1 & 2, 2     & 2, 3 \\
%%  }
\chapter{The first chapter}
\tcbstartrecording
\begin{figure}[htp]
\begin{exercise}{BanachMatch}
The bar graph of the distribution of Banach matches..
\tcblower
    {\centering
\begin{tikzpicture}[
    declare function={
    comb(\n,\k)=\n!/(\k!*(\n-\k)!);
    albanach(\k,\n,\p)=comb(2*\n-\k,\n)*(\p^(\n+1)*(1-\p)^(\n-\k)+\p^(\n-\k)*(1-\p)^(\n+1));
    }
]
\begin{axis}[
    xlabel={$x$}, ylabel={$P(X=x)$},
    yticklabel style={
        /pgf/number format/fixed,
        /pgf/number format/fixed zerofill,
        /pgf/number format/precision=2
    },
    legend style={
cells={anchor=east},
legend pos=outer north east,
    xlabel={$x$}, ylabel={$P(X=x)$},samples at={0,...,50},
    yticklabel style={
        /pgf/number format/fixed,
        /pgf/number format/fixed zerofill,
        /pgf/number format/precision=2
                     }
              },
    ybar=0pt, bar width=2
]
\addplot [fill=orange, fill opacity=0.5] {albanach(x,50,0.5)}; \addlegendentry{$p=0.5$}
\addplot [fill=cyan, fill opacity=0.5] {albanach(x,50,0.4)}; \addlegendentry{$p=0.4$}
\addplot [fill=blue, fill opacity=0.5] {albanach(x,50,0.3)}; \addlegendentry{$p=0.3$}
\end{axis}
\end{tikzpicture}
\par}
\captionof{figure}{Banach matches}
\end{exercise}
\end{figure}
\tcbstoprecording
\tcbinputrecords
\end{document}


text:
Q: Create Sql Server Reporting Service using subreport to repeat records i am creating a Sql Server Reporting. I want pick one row from one dataset and all details regarding this row under it.
Like Department name Dot-Net is on header and its employee details under it.Then Department PHP and all PHP employee below it.
Here is the sample :-
Department
DotNet
       Employee Name                    Age

    Bharat                              25
    Arvind                              28
    Deepak                              30

SQL
     Employee Name                       AGE
        Aman                               30
        Umesh                              25

It is just sample . I want to create same hierarchy for five tables, which linked each other.
I don't know how to show data like it.
I have used subreports and list also for reporting.
Thanks in advance!!

A: I would join the tables together in one dataset using a SQL query.  Then I would define one Table with a Row Group on the Department.
http://msdn.microsoft.com/en-us/library/ms170712.aspx


text:
Q: Why is the twisted cubic given as maximal minors of a matrix? Today I began reading Hartshorne, and was doing an exercise about the twisted cubic, parametrically given by $t \mapsto (t,t^2,t^3)$. According to Wikipedia, its (non-homogeneous) ideal is $(xz-y^2,y-z^2,x-yz)$. Toying a bit with these equations, I noticed that they are precisely the maximal minors of the matrix
$\begin{pmatrix}x &y &z \\ y& z& 1\end{pmatrix}$
Is there a reason for this? I tend to think of determinants as having to do only with linear equations of some sort, but the twisted cubic does not seem very "linear".


text:
Q: Node-Local Map reduce job I am currently attempting to write a map-reduce job where the input data is not in HDFS and cannot be loaded into HDFS basically because the programs using the data cannot use data from HDFS and there is too much to copy it into HDFS, at least 1TB per node.
So I have 4 directories on each of the 4 nodes in my cluster. Ideally I would like my mappers to just receive the paths for these 4 local directories and read them, using something like file:///var/mydata/... and then 1 mapper can work with each directory. i.e. 16 Mappers in total.
However to be able to do this I need to ensure that I get exactly 4 mappers per node and exactly the 4 mappers which have been assigned the paths local to that machine. These paths are static and so can be hard coded into my fileinputformat and recordreader, but how do I guarantee that given splits end up on a given node with a known hostname. If it were in HDFS I could use a varient on FileInputFormat setting isSplittable to false and hadoop would take care of it but as all the data is local this causes issues.
Basically all I want is to be able to crawl local directory structures on every node in my cluster exactly once, process a collection of SSTables in these directories and emit rows (on the mapper), and reduce the results (in the reduce step) into HDFS for further bulk processing.
I noticed that the inputSplits provide a getLocations function but I believe that this does not guarantee locality of execution, only optimises it and clearly if I try and use file:///some_path in each mapper I need to ensure exact locality otherwise I may end up reading some directories repeatedly and other not at all.
Any help would be greatly appreciated.

A: I see there are three ways you can do it.
1.) Simply load the data into HDFS, which you do not it want to do. But it is worth trying as it will be useful for future processing
2.) You can make use of NLineInputFormat. Create four different files with the URLs of the input files in each of your node.
file://192.168.2.3/usr/rags/data/DFile1.xyz
.......

You load these files into HDFS and write your program on these files to access the data data using these URLs and process your data. If you use NLineInputFormat with 1 line. You will process 16 mappers, each map processing an exclusive file. The only issue here, there is a high possibility that the data on one node may be processed on another node, however there will not be any duplicate processing
3.) You can further optimize the above method by loading the above four files with URLs separately. While loading any of these files you can remove the other three nodes to ensure that the file exactly goes to the node where the data files are locally present. While loading choose the replication as 1 so that the blocks are not replicated. This process will increase the probability of the maps launched processing the local files to a very high degree.
Cheers
Rags


text:
Q: How to run Qthread one after another without freezing UI? How to run Qthread one after another?
For the following code:
import sys
from PyQt5 import QtCore, QtWidgets

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('MyWindow')
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        self.button = QtWidgets.QPushButton('Run')
        self.button.clicked.connect(self.my_method)
        layout = QtWidgets.QGridLayout(self._main)
        layout.addWidget(self.button)
        layout.addWidget(self.button)

    def my_method(self):
        for i in range(0,3):
            self.n = 5
            self.loadthread = MyThread(self.n, self)
            self.loadthread.start()

class MyThread(QtCore.QThread):
    def __init__(self, n, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.n = n

    def run(self):
        for i in range(self.n):
            print(i)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    screen = MyWindow()
    screen.show()
    sys.exit(app.exec_())

I am getting the output as:
0
1
0
2
3
1
2
3
4
4
0
1
2
3
4

The threads are running concurrently. I want it to run one after another.
Desired output:
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4

How can I run the threads only after one is finished?
I tried using thread.wait(). It works. But the UI freezes during that.

A: I saw your task like this:
import sys
from PyQt5 import QtCore, QtWidgets

class MyThread(QtCore.QThread):
    def __init__(self, n, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.n = n

    def run(self):
        for i in range(self.n):
            print(i)
            self.msleep(50)

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('MyWindow')
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)

        self.button = QtWidgets.QPushButton('Run')
        self.button.clicked.connect(self.my_method)

        layout = QtWidgets.QGridLayout(self._main)
        layout.addWidget(self.button)
        layout.addWidget(self.button)

        self.n = 5
        self.loadthread = MyThread(self.n, self)
        self.loadthread.finished.connect(self.task_finished)

    def my_method(self):
        self.button.setEnabled(False)
        self.number_of_tasks = 3
        self.list_tasks = [i for i in range(self.number_of_tasks, 0, -1)]
        self.load_task()

    def load_task(self):
        self.number_of_tasks -= 1
        self.task = self.list_tasks[self.number_of_tasks]
        print(f'\n Start task: {self.task}')
        self.loadthread.start()

    def task_finished(self):
        print(f'--- Finish task: {self.task}')
        if self.number_of_tasks:
            self.load_task()
        else:
            self.button.setEnabled(True)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    screen = MyWindow()
    screen.show()
    sys.exit(app.exec_())


text:
Q: sql select min, return value from different column in same row with grouping I want the OrderType for the min(Date) for each Name.
So, I want this:
Name    Date        OrderType
Alex    1/1/2014    Direct
Alex    9/15/2014   Distributor
Cindy   6/4/2014    Distributor
John    5/8/2014    Direct
John    2/14/2014   Distributor

to return this:
Name    Date        OrderType
Alex    1/1/2014    Direct
Cindy   6/4/2014    Distributor
John    2/14/2014   Distributor

A: We can get row number based on the date  for each [Name] and pick the least date record.
SELECT [T].*
FROM (
    SELECT [Name]
         , [DATE]
         , [OrderType]
         , ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [Date]) AS [seq]
    FROM [TableA]
) AS [T]
WHERE [T].[seq] = 1

A: I think you need select the min date per person then join back to the original table to get the type for that row.
Assuming your table is called tab and each person only had one order per date (otherwise the question is impossible) then something like:
Select t.name, t.date, t.ordertype
From tab t,
     ( select min (i.date) date, i.name from tab i group by i.name) t2
Where t.date = t2.date
  And t.name = t2.name

Sorry I work mainly with mysql and Oracle not tsql so it is generic sql syntax.

A: CREATE TABLE #tmp
( Name VARCHAR(50), orderdate DATE, OrderType VARCHAR(50) )
INSERT #tmp ( Name, orderdate, OrderType )
VALUES  ( 'Alex', '01/01/2014','Direct')
INSERT #tmp
VALUES  ( 'Alex', '9/15/2014','Distributor')
INSERT #tmp
VALUES  ( 'Cindy', '6/4/2014','Distributor')
INSERT #tmp
VALUES  ( 'John', '5/8/2014','Direct')
INSERT #tmp
VALUES  ( 'John', '2/14/2014','Distributor')

; WITH CTE_RESULT AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY ORDERDATE ASC) ROW_NO , Name, orderdate, OrderType
    FROM #tmp
)

SELECT  * FROM CTE_RESULT T WHERE T.ROW_NO=1

A: try this
select
a.name,
MIN(a.date)as date,

from dbname a i
inner join (select name, min(date), ordertype from dbname) b on b.name=a.name and a.date=b.date

group by a.name, b.ordertype


text:
Q: best tutorial for using the entity framework, POCO, and MySQL I am looking for a solid tutorial on using the Entity Framework with POCO (ie. not using the designer) using MySQL as the back-end.  I am looking for something that is semi-in-depth covering stuff like attributes (like how to map a database table/field name to a class/field name that is different).  Also I am looking for C#, not VB.  Does anyone know of any such tutorials?

A: For EF with MySQL, check this other question:
Using MySQL with Entity Framework
Basically you need to get a connector from MySQL and work normally from there.
For POCOs, either you do code the mappings, and then I assume you use EF 4 Futures CTP 5 recently releaed, or you use the designer, and this is what is normally in EF 4.
If the meant is default EF 4 POCO support, or POCO template in EF CTP5, those should be helpful reads:
http://thedatafarm.com/blog/data-access/agile-entity-framework-4-repository-part-1-model-and-poco-classes/ (the entire series)
Generally http://thedatafarm.com/blog/search?q=poco or if page is too slow http://www.google.com.au/#q=poco+site:thedatafarm.com
http://blogs.msdn.com/b/adonet/archive/2009/05/28/poco-in-the-entity-framework-part-2-complex-types-deferred-loading-and-explicit-loading.aspx
http://blogs.msdn.com/b/adonet/archive/2009/06/10/poco-in-the-entity-framework-part-3-change-tracking-with-poco.aspx
If you are using the code only way, you need to realize it's pre-release and has some issues when working with.


text:
Q: How flutter parses ArrayBuffer flutter 2.0.0 uses the long connection websocket protocol, the returned data is ArrayBuffer, how to convert it into json data
[31, 139, 8, 0, 0, 0, 0, 0, 0, 0, 37, 144, 49, 79, 195, 48, 16, 70, 255, 10, 186, 217, 61, 249, 206, 103, 59, 241, 214, 38, 65, 68, 13, 36, 212, 41, 66, 221, 2, 237, 192, 208, 5, 194, 84, 229, 191, 115, 41, 147, 101, 125, 239, 61, 75, 190, 193, 231, 245, 12, 9, 126, 126, 63, 240, 123, 154, 47, 96, 224, 60, 205, 19, 164, 27, 28, 115, 61, 174, 231, 208, 119, 25, 146, 160, 48, 137, 129, 93, 126, 131, 196, 145, 48, 82, 136, 6, 218, 62, 43, 100, 209, 122, 239, 165, 208, 185, 122, 130, 20, 98, 68, 9, 6, 170, 237, 190, 81, 216, 161, 13, 106, 62, 182, 29, 36, 138, 1, 197, 137, 154, 117, 175, 162, 88, 100, 17, 29, 235, 109, 86, 145, 11, 198, 82, 43, 221, 160, 155, 35, 36, 13, 254, 231, 169, 8, 108, 160, 25, 43, 133, 244, 42, 209, 25, 120, 63, 12, 26, 68, 231, 136, 244, 177, 174, 125, 217, 171, 196, 120, 175, 159, 154, 149, 36, 143, 190, 92, 27, 207, 107, 132, 138, 184, 114, 247, 134, 148, 24, 189, 129, 215, 241, 168, 19, 9, 150, 236, 138, 101, 49, 48, 127, 93, 47, 250, 29, 108, 153, 54, 86, 54, 68, 15, 76, 73, 202, 100, 9, 150, 63, 238, 197, 136, 230, 44, 1, 0, 0]


text:
Q: How to send data from Raspberry pi to Remote SQL DB without installing mysql or mysql Client I would like send some port checking data and a timestamp ( both saved as a variable) to my remote Mysql DB running on a linux Node machine . I don't want install sql or sql client in Pi because the device having  enough load already

A: If you can ssh to the database server, you can run mysql directly on the server via ssh:
ssh user@dbserver \
  mysql -u USER -p PASSWORD \
    -e "insert into table (data, timestamp) VALUES ('${data}','${timestamp}') " \
    database-name


text:
Q: How & Why to use SUPER in code? I work with some advanced JavaScript people and they have used the SUPER keyword in their code. I admit, I don't have a good grasp of how and why one can and would use this.
Can someone direct me or show me how to become well versed in its usage and reasoning thereof?
Here are some examples:
openup: function( $super ) {
    $super();
    this.shop.enable_access();
}

addLeft: function( data ) {
    var cell = Element('td');
    if ( data.item_data ) {
        var item = new SRIL(data.item_data);
        item.attach(cell);
        item.show();
    }

    return cell;

}
var SRIL = Class.create(Module, {
initialize: function( $super, data ) {
    $super({ dom: 'show_line' });
    this.data = data;
    if ( data.Type[0] == 'Car' ) {
        //some code
    }
    else {
        // some code
    }
}

});

A: JavaScript does not have such a thing.
Update: You should have a look at the documentation of the library that is in use here. This is a library feature, not a language one.

A: Since Javascript doesn't have classical inheritance, structured instead according to a prototypal/functional model, developers have made various attempts at re-creating the classical model. super is part of one such strategy. The particular problem it solves is in the case of a child object that has the same method – even if it's just the constructor – as the parent object. Without creating super as an alias to the parent's methods, accessing such methods becomes somewhat cumbersome (and, in some cases, impossible).
John Resig has a wrapper that shows this off fairly well. Note his use of _super() in the first example to call the parent object's dance method.


text:
Q: What is the best way to iterate over multiple lists at once? Let's say I have two or more lists of same length. What's a good way to iterate through them?
a, b are the lists.
 for i, ele in enumerate(a):
    print ele, b[i]

or
for i in range(len(a)):
   print a[i], b[i]

or is there any variant I am missing?
Is there any particular advantages of using one over other?

A: You can use zip:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
...
1 a
2 b
3 c

A: The usual way is to use zip():
for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted.  Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).


text:
Q: What is a container app in iPhone? Our client wants us to make a container app, but I am not exactly sure what he means by this. I have to extend the functionality of his existing app but he does not wish to share his code with me.. so he says I should make a container app... I know it something similar to making in app purchases but can any one elaborate ?

A: Note: you should definitely clarify this with your client instead of this community.
I guess your client wants to have an App-in-App structure that you find in various iOS applications in the AppStore. E.g. the three20 framework offers a launcher that is similar to the Springboard of the iPhone/iPad/iPod where you can put multiple apps (which aren't necessarily independent apps).


text:
Q: Ffmpeg avs to avi lossless conversion How to convert avs (Avisynth file) to avi without loss of quality?
Firstly, I'm changing avs to 264:
ffmpeg -i "Source.avs" -c:v libx264 -preset veryslow -crf 24 "Output.264"
Secondly, I'm trying to convert 264 to avi:
ffmpeg -i "input.264" "output.avi"
Final avi should have almost 200MB, but has only 2MB. 264 file has almost 150MB, so it should be good. I think that I should use some codec in second command, but I don't know which. I'm trying to change this for a few days, but without effect.
Or maybe there is a way to lossless conversion without 264, only avs to avi?
Thank you for your help.
Edit:
Thank you for answers. Unfortunatelly, both methods fail.
First gives me a video, which is blurry and I can't see anything on it.
Output:
C:\Users\Piotr>"C:\Users\Piotr\Documents\Visual Studio 2010\Projects\SoRecorder\
SoRecorder\bin\Release\Ffmpeg\ffmpeg.exe" -i "C:\Users\Piotr\Documents\Visual St
udio 2010\Projects\SoRecorder\SoRecorder\bin\Release\Scripts\-2016-02-20.avs" -c
 copy "E:\-2016-02-20.avi"
ffmpeg version N-78559-g2e8ad2d Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 5.3.0 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-av
isynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enab
le-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --
enable-libdcadec --enable-libfreetype --enable-libgme --enable-libgsm --enable-l
ibilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enab
le-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --en
able-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --ena
ble-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --
enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-lib
x265 --enable-libxavs --enable-libxvid --enable-libzimg --enable-lzma --enable-d
ecklink --enable-zlib
  libavutil      55. 17.103 / 55. 17.103
  libavcodec     57. 24.103 / 57. 24.103
  libavformat    57. 25.100 / 57. 25.100
  libavdevice    57.  0.101 / 57.  0.101
  libavfilter     6. 32.100 /  6. 32.100
  libswscale      4.  0.100 /  4.  0.100
  libswresample   2.  0.101 /  2.  0.101
  libpostproc    54.  0.100 / 54.  0.100
Input #0, avisynth, from 'C:\Users\Piotr\Documents\Visual Studio 2010\Projects\S
oRecorder\SoRecorder\bin\Release\Scripts\-2016-02-20.avs':
  Duration: 00:00:21.80, start: 0.000000, bitrate: 0 kb/s
    Stream #0:0: Video: rawvideo (BGRA / 0x41524742), bgra, 1280x720, 15 fps, 15
 tbr, 15 tbn, 15 tbc
[avi @ 048d8cc0] bgra rawvideo cannot be written to avi, output file will be unr
eadable
Output #0, avi, to 'E:\-2016-02-20.avi':
  Metadata:
    ISFT            : Lavf57.25.100
    Stream #0:0: Video: rawvideo, bgra, 1280x720, q=2-31, 15 fps, 15 tbr, 15 tbn
, 15 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
Press [q] to stop, [?] for help
frame=   41 fps=0.0 q=-1.0 size=  147606kB time=00:00:02.73 bitrate=442385.6kbit
frame=   65 fps= 63 q=-1.0 size=  234006kB time=00:00:04.33 bitrate=442379.5kbit
frame=   93 fps= 60 q=-1.0 size=  334806kB time=00:00:06.20 bitrate=442376.3kbit
frame=  110 fps= 51 q=-1.0 size=  396006kB time=00:00:07.33 bitrate=442375.2kbit
frame=  116 fps= 42 q=-1.0 size=  417606kB time=00:00:07.73 bitrate=442374.9kbit
frame=  122 fps= 37 q=-1.0 size=  439206kB time=00:00:08.13 bitrate=442374.6kbit
frame=  128 fps= 33 q=-1.0 size=  460807kB time=00:00:08.53 bitrate=442374.3kbit
frame=  133 fps= 31 q=-1.0 size=  478807kB time=00:00:08.86 bitrate=442374.1kbit
frame=  139 fps= 29 q=-1.0 size=  500407kB time=00:00:09.26 bitrate=442373.8kbit
frame=  145 fps= 27 q=-1.0 size=  522007kB time=00:00:09.66 bitrate=442373.6kbit
frame=  151 fps= 25 q=-1.0 size=  543607kB time=00:00:10.06 bitrate=442373.5kbit
frame=  157 fps= 24 q=-1.0 size=  565207kB time=00:00:10.46 bitrate=442373.3kbit
frame=  163 fps= 23 q=-1.0 size=  586807kB time=00:00:10.86 bitrate=442373.1kbit
frame=  169 fps= 22 q=-1.0 size=  608407kB time=00:00:11.26 bitrate=442373.0kbit
frame=  175 fps= 21 q=-1.0 size=  630007kB time=00:00:11.66 bitrate=442372.8kbit
frame=  181 fps= 21 q=-1.0 size=  651607kB time=00:00:12.06 bitrate=442372.7kbit
frame=  187 fps= 20 q=-1.0 size=  673207kB time=00:00:12.46 bitrate=442372.6kbit
frame=  193 fps= 19 q=-1.0 size=  694807kB time=00:00:12.86 bitrate=442372.5kbit
frame=  199 fps= 19 q=-1.0 size=  716407kB time=00:00:13.26 bitrate=442372.4kbit
frame=  204 fps= 19 q=-1.0 size=  734407kB time=00:00:13.60 bitrate=442372.3kbit
frame=  210 fps= 18 q=-1.0 size=  756007kB time=00:00:14.00 bitrate=442372.2kbit
frame=  215 fps= 18 q=-1.0 size=  774007kB time=00:00:14.33 bitrate=442372.1kbit
frame=  221 fps= 18 q=-1.0 size=  795607kB time=00:00:14.73 bitrate=442372.1kbit
frame=  226 fps= 17 q=-1.0 size=  813607kB time=00:00:15.06 bitrate=442372.0kbit
frame=  232 fps= 17 q=-1.0 size=  835207kB time=00:00:15.46 bitrate=442371.9kbit
frame=  238 fps= 17 q=-1.0 size=  856807kB time=00:00:15.86 bitrate=442371.8kbit
frame=  244 fps= 17 q=-1.0 size=  878407kB time=00:00:16.26 bitrate=442371.7kbit
frame=  250 fps= 16 q=-1.0 size=  900007kB time=00:00:16.66 bitrate=442371.7kbit
frame=  256 fps= 16 q=-1.0 size=  921608kB time=00:00:17.06 bitrate=442371.6kbit
frame=  261 fps= 16 q=-1.0 size=  939608kB time=00:00:17.40 bitrate=442371.6kbit
frame=  267 fps= 16 q=-1.0 size=  961208kB time=00:00:17.80 bitrate=442371.5kbit
frame=  273 fps= 16 q=-1.0 size=  982808kB time=00:00:18.20 bitrate=442371.5kbit
frame=  278 fps= 16 q=-1.0 size= 1000808kB time=00:00:18.53 bitrate=442371.4kbit
frame=  284 fps= 15 q=-1.0 size= 1022408kB time=00:00:18.93 bitrate=442371.4kbit
frame=  290 fps= 15 q=-1.0 size= 1044008kB time=00:00:19.33 bitrate=442371.3kbit
frame=  296 fps= 15 q=-1.0 size= 1065615kB time=00:00:19.73 bitrate=442374.1kbit
frame=  302 fps= 15 q=-1.0 size= 1087215kB time=00:00:20.13 bitrate=442374.0kbit
frame=  308 fps= 15 q=-1.0 size= 1108815kB time=00:00:20.53 bitrate=442373.9kbit
frame=  314 fps= 15 q=-1.0 size= 1130415kB time=00:00:20.93 bitrate=442373.8kbit
frame=  320 fps= 15 q=-1.0 size= 1152015kB time=00:00:21.33 bitrate=442373.7kbit
frame=  326 fps= 15 q=-1.0 size= 1173615kB time=00:00:21.73 bitrate=442373.7kbit
frame=  327 fps= 15 q=-1.0 Lsize= 1177215kB time=00:00:21.80 bitrate=442373.8kbi
ts/s speed=0.967x
video:1177200kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxi
ng overhead: 0.001301%

EDIT: Output after PNG command:
C:\Users\Piotr>"C:\Users\Piotr\Documents\Visual Studio 2010\Projects\SoRecorder\
SoRecorder\bin\Release\Ffmpeg\ffmpeg.exe" -i "C:\Users\Piotr\Documents\Visual St
udio 2010\Projects\SoRecorder\SoRecorder\bin\Release\Scripts\-2016-02-21--1.avs"
 -c:v png -pix_fmt bgra "E:\-2016-02-21.avi"
ffmpeg version N-78559-g2e8ad2d Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 5.3.0 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-av
isynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enab
le-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --
enable-libdcadec --enable-libfreetype --enable-libgme --enable-libgsm --enable-l
ibilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enab
le-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --en
able-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --ena
ble-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --
enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-lib
x265 --enable-libxavs --enable-libxvid --enable-libzimg --enable-lzma --enable-d
ecklink --enable-zlib
  libavutil      55. 17.103 / 55. 17.103
  libavcodec     57. 24.103 / 57. 24.103
  libavformat    57. 25.100 / 57. 25.100
  libavdevice    57.  0.101 / 57.  0.101
  libavfilter     6. 32.100 /  6. 32.100
  libswscale      4.  0.100 /  4.  0.100
  libswresample   2.  0.101 /  2.  0.101
  libpostproc    54.  0.100 / 54.  0.100
Input #0, avisynth, from 'C:\Users\Piotr\Documents\Visual Studio 2010\Projects\S
oRecorder\SoRecorder\bin\Release\Scripts\-2016-02-21--1.avs':
  Duration: 00:00:25.07, start: 0.000000, bitrate: 0 kb/s
    Stream #0:0: Video: rawvideo (BGRA / 0x41524742), bgra, 640x480, 30 fps, 30
tbr, 30 tbn, 30 tbc
Incompatible pixel format 'bgra' for codec 'png', auto-selecting format 'rgba'
Output #0, avi, to 'E:\-2016-02-21.avi':
  Metadata:
    ISFT            : Lavf57.25.100
    Stream #0:0: Video: png (MPNG / 0x474E504D), rgba, 640x480, q=2-31, 200 kb/s
, 30 fps, 30 tbn, 30 tbc
    Metadata:
      encoder         : Lavc57.24.103 png
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> png (native))
Press [q] to stop, [?] for help
frame=   18 fps=0.0 q=-0.0 size=   10716kB time=00:00:00.46 bitrate=188119.0kbit
frame=   35 fps= 34 q=-0.0 size=   23722kB time=00:00:01.03 bitrate=188065.8kbit
frame=   48 fps= 27 q=-0.0 size=   33668kB time=00:00:01.46 bitrate=188052.7kbit
frame=   61 fps= 26 q=-0.0 size=   43614kB time=00:00:01.90 bitrate=188045.7kbit
frame=   74 fps= 26 q=-0.0 size=   53560kB time=00:00:02.33 bitrate=188041.3kbit
frame=   89 fps= 26 q=-0.0 size=   65036kB time=00:00:02.83 bitrate=188037.8kbit
frame=  106 fps= 27 q=-0.0 size=   78042kB time=00:00:03.40 bitrate=188035.1kbit
frame=  123 fps= 28 q=-0.0 size=   91048kB time=00:00:03.96 bitrate=188033.2kbit
frame=  137 fps= 28 q=-0.0 size=  101759kB time=00:00:04.43 bitrate=188032.0kbit
frame=  155 fps= 28 q=-0.0 size=  115530kB time=00:00:05.03 bitrate=188030.8kbit
frame=  186 fps= 31 q=-0.0 size=  125735kB time=00:00:06.06 bitrate=169783.8kbit
frame=  224 fps= 35 q=-0.0 size=  133831kB time=00:00:07.33 bitrate=149501.7kbit
frame=  261 fps= 37 q=-0.0 size=  142679kB time=00:00:08.56 bitrate=136438.4kbit
frame=  300 fps= 40 q=-0.0 size=  151249kB time=00:00:09.86 bitrate=125577.5kbit
frame=  338 fps= 42 q=-0.0 size=  159452kB time=00:00:11.13 bitrate=117326.2kbit
frame=  371 fps= 44 q=-0.0 size=  169169kB time=00:00:12.23 bitrate=113283.3kbit
frame=  407 fps= 45 q=-0.0 size=  178924kB time=00:00:13.43 bitrate=109112.3kbit
frame=  444 fps= 47 q=-0.0 size=  187571kB time=00:00:14.66 bitrate=104767.1kbit
frame=  488 fps= 49 q=-0.0 size=  194672kB time=00:00:16.13 bitrate=98848.5kbits
frame=  535 fps= 51 q=-0.0 size=  199781kB time=00:00:17.70 bitrate=92463.5kbits
frame=  569 fps= 52 q=-0.0 size=  208530kB time=00:00:18.83 bitrate=90705.2kbits
frame=  604 fps= 52 q=-0.0 size=  216658kB time=00:00:20.00 bitrate=88743.0kbits
frame=  622 fps= 52 q=-0.0 size=  229851kB time=00:00:20.60 bitrate=91404.7kbits
frame=  639 fps= 51 q=-0.0 size=  242857kB time=00:00:21.16 bitrate=93991.3kbits
frame=  656 fps= 50 q=-0.0 size=  255863kB time=00:00:21.73 bitrate=96443.0kbits
frame=  673 fps= 49 q=-0.0 size=  268869kB time=00:00:22.30 bitrate=98770.1kbits
frame=  690 fps= 49 q=-0.0 size=  281875kB time=00:00:22.86 bitrate=100981.9kbit
frame=  707 fps= 48 q=-0.0 size=  294881kB time=00:00:23.43 bitrate=103086.7kbit
frame=  724 fps= 48 q=-0.0 size=  307887kB time=00:00:24.00 bitrate=105092.1kbit
frame=  741 fps= 47 q=-0.0 size=  320893kB time=00:00:24.56 bitrate=107005.0kbit
frame=  752 fps= 46 q=-0.0 Lsize=  332381kB time=00:00:25.06 bitrate=108624.9kbi
ts/s speed=1.54x
video:332357kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxin
g overhead: 0.007042%

A: Your Avisynth input is uncompressed, so you can wrap it in AVI like so:
ffmpeg -i source.avs -c:v rawvideo -pix_fmt bgra source.avi

The intermediation via H.264 is not needed. In any case, your commands don't produce lossless H.264. For that, you would need
ffmpeg -i "Source.avs" -c:v libx264rgb -crf 0 "Output.avi"

(This will be unacceptable if the source contains an alpha channel, since H.264 doesn't support alpha)


text:
Q: Generating power set recursively without any loops How do you write a recursive method PowerSet(String input) that prints out all possible combinations of a string that is passed to it?
For example: PowerSet("abc") will print out abc, ab, ac, bc, a, b, c
I have seen some recursive solutions with loops, but in this case no loops are allowed.
Any ideas?
Edit: The required method has only one parameter, i.e. String input.

A: This will also do the trick:
var powerset = function(arr, prefix, subsets) {
  subsets = subsets || [];
  prefix = prefix || [];
  if (arr.length) {
    powerset(arr.slice(1), prefix.concat(arr[0]), subsets);
    powerset(arr.slice(1), prefix, subsets);
  } else {
    subsets.push(prefix);
  }
  return subsets;
};

powerset('abc');

A: Well if you don't have loops, emulate one with recursion, using iterators this is acutally quite simple.
    public final Set<Set<Integer>> powerSet(Set<Integer> set) {
        Set<Set<Integer>> powerSet = new HashSet<>();
        powerSet(set, powerSet, set.iterator());
        return powerSet;
    }
    public final void powerSet(Set<Integer> set, Set<Set<Integer>> powerSet, Iterator<Integer> iterator) {
        if(iterator.hasNext()) {
            Integer exlude = iterator.next();
            Set<Integer> powThis = new HashSet<Integer>();
            powThis.addAll(set);
            powThis.remove(exlude);
            powerSet.add(powThis);
            powerSet(powThis, powerSet, powThis.iterator());
            powerSet(set, powerSet, iterator);
        }
    }
//usage
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(4);
        log.error(powerSet(set).toString());

A: The powerset of abcd is the union of the power-sets of abc, abd, acd (plus the set abcd itself*).
 P(`abcd`) = {`abcd`} + P(`abc`) + P(`abd`) + P(`acd`) + P(`bcd`)

* Note that the empty set, which is a member of P(abcd) is also a member of P(abc), P(abd), ... so the equivalence stated above holds.
Recursively, P(abc) = {abc} + P(ab) + P(ac), and so on
A first approach, in pseudocode, could be:
powerset(string) {
  add string to set;
  for each char in string {
   let substring = string excluding char,
   add powerset(substring) to set
  }
  return set;
}

The recursion ends when the string is empty (because it never enters the loop).
If your really want no loops, you will have to convert that loop to another recursion.
Now we want to generate ab, ac and cb from abc
powerset(string) {
  add string to set;
  add powerset2(string,0) to set;
  return set
}

powerset2(string,pos) {
  if pos<length(string) then
    let substring = (string excluding the char at pos)
    add powerset(substring) to set
    add powerset2(string,pos+1) to set
  else
    add "" to set
  endif
  return set
}

Another approach implement a recursive function P that either removes the first character from its argument, or does not. (Here + means set union, . means concatenation and λ is the empty string)
P(abcd) = P(bcd) + a.P(bcd)
P(bcd)  = P(cd)  + b.P(cd)
P(cd)   = P(d)   + c.P(d)
P(d)    = λ+d //particular case

Then
P(d)    = λ+d
R(cd)   = P(d)  + c.P(d)  = λ + d + c.(λ+d) = λ + d + c + cd
R(bcd)  = P(cd) + b.P(cd) = λ + d + c + cd + b.(λ + d + c + cd)
                          = λ + d + c + cd + b + bd + bc + bcd
P(abcd) =  λ +  d +  c +  cd +  b +  bd +  bc +  bcd
        + aλ + ad + ac + acd + ab + abd + abc + abcd

If loops were allowed, then P is out power-set function. Otherwise, we would need a one-parameter loopless function for concatenating a given character to a given set of strings (which obviously are two things).
Some tweak could be possible by playing with String.replace (if a String result is desired, or by replacing Set with List (so that the "additional" parameter is actually the first element in the list).

A: A recursive version of the generic solution proposed by João Silva :
public static <T> Set<Set<T>> powerSet2(Set<T> originalSet) {
    Set<Set<T>> sets = new HashSet<Set<T>>();
    if (originalSet.isEmpty()) {
        sets.add(new HashSet<T>());
        return sets;
    }
    List<T> list = new ArrayList<T>(originalSet);
    T head = list.get(0);
    Set<T> rest = new HashSet<T>(list.subList(1, list.size()));
    addSets(sets, powerSet(rest), head);
    return  sets;
}

private static <T> void addSets(Set<Set<T>> sets, Set<Set<T>> setsToAdd, T head) {
    Iterator<Set<T>> iterator = setsToAdd.iterator();
    if (iterator.hasNext()) {
        Set<T> set = iterator.next();
        iterator.remove();
        Set<T> newSet = new HashSet<T>();
        newSet.add(head);
        newSet.addAll(set);
        sets.add(newSet);
        sets.add(set);
        addSets(sets, setsToAdd, head);
    }
}

I extract the recursive addSets method to transform the original for loop:
for (Set<T> set : powerSet(rest)) {
    Set<T> newSet = new HashSet<T>();
    newSet.add(head);
    newSet.addAll(set);
    sets.add(newSet);
    sets.add(set);
}

A: void powerSet(int * ar, int *temp, int n, int level,int index)
{
    if(index==n) return;

    int i,j;
    for(i=index;i<n;i++)
    {
    temp[level]=ar[i];

    for(j=0;j<=level;j++)
    printf("%d ",temp[j]);
    printf("   - - -  t\n");

    powerSet(ar, temp, n, level+1,i+1);
    }
}

int main()
{
    int price[] = {1,2,3,7};
    int temp[4] ={0};

    int n = sizeof(price)/sizeof(price[0]);

    powerSet(price, temp, n, 0,0);

    return 0;
}

A: Simple solution but with poor time complexity(2^n) is as following(just keep one thing in mind once we have to avoid(i.e. 0) and once we have to take it(i.e. 1):
public HashSet<int[]> powerSet(int n) {
    return calcPowerSet(n-1, new HashSet<int[]>(), new int[n]);
}

private HashSet<int[]> calcPowerSet(int n, HashSet<int[]> result, int []set) {
    if(n < 0) {
        result.add(set.clone());
        return null;
    }
    else {
        set[n] = 0;
        calcPowerSet(n-1, result, set);
        set[n] = 1;
        calcPowerSet(n-1, result, set);
        return result;
    }
}

A: Just for fun, a version that does powersets of any set stored in a LinkedList (to make it easy to remove the head element). Java 8 streams do the functional part:
static <T> LinkedList<LinkedList<T>> powerset(LinkedList<T> elements) {
  if (elements.isEmpty())
    return copyWithAddedElement(new LinkedList<>(), new LinkedList<>());
  T first = elements.pop();
  LinkedList<LinkedList<T>> powersetOfRest = powerset(elements);
  return Stream.concat(
      powersetOfRest.stream(),
      powersetOfRest.stream().map(list -> copyWithAddedElement(list, first)))
          .collect(Collectors.toCollection(LinkedList::new));
}

static <T> LinkedList<T> copyWithAddedElement(LinkedList<T> list, T elt) {
  list = new LinkedList<>(list);
  list.push(elt);
  return list;
}

This is inspired by the following Common Lisp, which shows that the right language can make things simpler:
(defun powerset (set)
  (cond ((null set) '(()))
        (t (let ((powerset-of-rest (powerset (cdr set))))
          (append powerset-of-rest
                  (mapcar #'(lambda (x) (cons (car set) x))
                          powerset-of-rest))))))

A: Based on the info here, here is solution in C#.
NOTE: the loop in the main function is just to print the result into the console value. No loops used  in the PowerSet method.
    public static void Main(string[] args)
    {

        string input = "abbcdd";

        Dictionary < string, string> resultSet = new Dictionary<string, string>();

        PowerSet(input, "", 0, resultSet);

        //apply sorting
        var resultSorted = resultSet.OrderBy(l => l.Key.Length).ThenBy(l=>l.Key);

        //print values
        foreach(var keyValue in resultSorted)
        {
            Console.Write("{{{0}}}, ",keyValue.Key);
        }

    }

    /// <summary>
    /// Computes the powerset of a string recursively
    /// based on the Algorithm http://www.ideserve.co.in/learn/generate-all-subsets-of-a-set-recursion
    /// </summary>
    /// <param name="input">Original input string</param>
    /// <param name="temp">Temporary variable to store the current char for the curr call</param>
    /// <param name="depth">The character position we are evaluating to add to the set</param>
    /// <param name="resultSet">A hash list to store the result</param>
    public static void PowerSet(string input, string temp, int depth, Dictionary<string, string> resultSet)
    {

        //base case
        if(input.Length == depth)
        {
            //remove duplicate characters
            string key = new string(temp.ToCharArray().Distinct().ToArray());

            //if the character/combination is already in the result, skip it
            if (!resultSet.ContainsKey(key))
                resultSet.Add(key, key);

            return;//exit
        }

        //left
        PowerSet(input, temp, depth + 1, resultSet);

        //right
        PowerSet(input, temp + input[depth], depth + 1, resultSet);

    }

A: PowerSet will print all combinations of elements
for example [123] will forms 123,12,13,23,1,2,3
We can find the powerset values easily by using the concept of tree
let add an element or remove an element every time
                    abc
           a                   " "
       ab     a             b       " "
  abc   ab  ac  a         bc   b   c   " "

here first have added a and not added a so tree form "a" and " " subelements
now take a constant and add 'b' to it and don't add 'b' then it will create another sub tree for 'a' in the same way the we add and remove element utill we reach the end .
here the method to add element and to remove element
powerset(str,i+1,cur+str.charAt(i));
powerset(str,i+1,cur);
import java.io.*;
import java.util.*;
import java.lang.Math;

class Demo{

    public static void main(String args[]) {
        String str="123";
        String str1="";
        int r=0;
        powerset(str,r,str1);

    }

    public static void powerset(String str,int i,String cur){

        if(i==str.length()){

            System.out.println(cur);
            return;

        }

        powerset(str,i+1,cur+str.charAt(i));
        powerset(str,i+1,cur);

    }

}

A: Power set (P) of string "abc" contains 2 types of elements: character 'a' itself and its combination with elements of P('bc').
Similarly P('bc') contains character 'b' and its combination with elements of P('c').
And also P('c') contains character 'c' and its combination with null string.
Now make function powerSet(string input, string substring="") This will print the substring and it denotes the combination of first element of input string with substring.
Base Condition: When length of input string is 0 then prints the substring.
Recursive condition:
1). Call powerSet( input[1: input.length()], substring ) #this is for elements of power set of string exluding 0th index character
2). Call powerSet( input[1: input.length()], substring+input[0]) # this is for combination.
#include<iostream>
#include<string>
using namespace std;

void powerSet(string input,string substring){

    if(input.length()==0){
        cout<<substring<<", ";
        return;
    }
    string op1=substring;
    string op2=substring + input[0];
    powerSet(input.substr(1),op1);
    powerSet(input.substr(1),op2);
    return;
}
int main(){
    string input="abc";
    powerSet(input);
}


text:
Q: StringJoin in Thread not working Here is what I have tried first.
Thread[f["x", {"1", "2"}]]

{f["x", "1"], f["x", "2"]}
But the weirdest thing happened when I substituted StringJoin for f
Thread[StringJoin["x", {"1", "2"}]]

"x12"
I thought it would be like this below
{"x1","x2"}

Is there anyone who can explain this?

A: Thread >> Possible Issues:

*

*"Thread evaluates the whole expression before threading"
Wrap StringJoin with Unevaluated to prevent evaluation of StringJoin before Thread gets to work:
Thread[Unevaluated @ StringJoin["x", {"1", "2"}]]

{"x1", "x2"}

Alternatively, you can use
Thread[foo["x", {"1", "2"}]] /. foo -> StringJoin

{"x1", "x2"}


text:
Q: Shuffle two Strings recursively to make another String I'm trying to create a method shuffle (String stri, String str2, String str3) that returns a boolean and take two Strings and "shuffles" them to make a third String, but I'm trying to do it recursively, which is kind of tough for me to think about. I want to return true if str1 and str2can be shuffled and return false if they can't be shuffled.
For example, if str1 = "tv" and str2 = "aol", the method might return taovl.
I also plan to test the method out as well as create another helper method to make it more efficient, but that's easy.

A: import java.util.Scanner;
public class lab3{
public static void main(String[] args) {
    String str;
    System.out.print("Enter String: ");
    Scanner sc = new Scanner(System.in);
    str = sc.nextLine();
    String res = revRec3(str);
    System.out.println(res);
}

public static String revRec3(String str)
{
    if (str.length() <= 1)
       return str;
   else{
       String first = str.substring(0, str.length() / 3);
       String second = str.substring(str.length() / 3, ((2 * str.length()) / 3));
       String third = str.substring((2 * str.length()) / 3, str.length());

       return revRec3(third)+revRec3(second)+revRec3(first);
   }
}
}

try doing something like this. This Program splits a String into 3 pieces and then reverses them using recursion.

A: I solved this by simply creating three integer variables to go through the indices of all three strings and checking to see if a a letter at any index matches the same order of s3


text:
Q: How could i get the name of a role in discord.py I created an add role command. It works fine but my problem is that it works only with the id of the role. I was wondering how could I somehow convert the id of the role to the name of the role.
This is the code.
    @commands.has_permissions(manage_messages=True)
    async def addrole(self, ctx, member: discord.Member,rolename):
        if member is None:
            member=ctx.author
        role = discord.utils.get(ctx.guild.roles, id=rolename)
        await member.add_roles(role)
        await ctx.send(f"{member.mention}was added {rolename}")

Any help is appreciated.edit
solution
I made use of the 2 comments and created this command which works perfectly.
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def addrole(self, ctx, role: discord.Role, member: discord.Member=None):
        if member is None:
            member=ctx.author
        await member.add_roles(role)
        await ctx.send(f"{member.mention} was added {role}")```

A: You could declare your rolename variable as a discord.Role and make use of the implicit role converter that will be applied, just like what happens to your member object. Your function would look something like this:
@commands.has_permissions(manage_messages=True)
async def addrole(self, ctx, member: discord.Member, role: discord.Role):
    await member.add_roles(role)
    await ctx.send(f"{member.mention} was added {rolename}")

A: You can use role converter just like you used member converter. You can pass role: discord.Role in arguments. Then, you just have to mention the role.
Also, you have to assign a default value None to the member argument in order to check if it's None.
@commands.has_permissions(manage_messages=True)
async def addrole(self, ctx, role: discord.Role, member: discord.Member=None):
    if not member:
        member=ctx.author
    await member.add_roles(role)
    await ctx.send(f"{member.mention}was added {role.name}")

References

*

*RoleConverter

*discord.Role.name


text:
Q: Using variadic template as parameter for both class and method My question is about the following piece of code:
    template <class...T>
    class A
    {
    public:
        template <class...S>
        static void a() { }
    };

    template <class...T>
    class B
    {
    public:
        template <class...S>
        void b()
        {
            A<T...>::a<S...>();
        }
    };

    int main(int argc, char** argv)
    {
        return 0;
    }

I have a class A that has a variadic template and contains a static method a that has another variadic template. From somewhere else (class B in this case) I have two different sets of variadic templates I want to pass to A::a.
The compiler (GCC 4.8.1) gives the following error message:
    main.cpp: In static member function 'static void B<T>::b()':
    main.cpp:16:22: error: expected primary-expression before '...' token
             A <T...>::a<S...>();
                          ^
    main.cpp:16:22: error: expected ';' before '...' token

Also notice that when I change the method b() to this:
        void b()
        {
            A<int, char, short>::a<S...>();
        }

or some other specification of A's templates then the code compiles just fine.
What is wrong with the above code?

A: add template here
A<T...>::template a<S...>();

see comment for reason. Also this compile nicely on VC++ without the keyword so I guess it is compiler dependent.


text:
Q: How do I Convert a list to dataframe in for bucle I appreciate your collaboration to convert the result code into a dataframe with the 2 columns. I was able to do the for loop to print each result and now I need to save this data to a dataframe. But I have not been able to get the result correct. Can you help me?
import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.skysports.com/premier-league-table') #get page web information
soup = BeautifulSoup(r.text, 'html.parser') # interpreter
print(soup.prettify())
print(soup.title)

league_table = soup.find('table', class_ = 'standing-table__table callfn')

for team in league_table.find_all('tbody'):
    rows = team.find_all('tr')
    for row in rows:
        pl_team = row.find('td', class_ ='standing-table__cell standing-table__cell--name')
        pl_team = pl_team['data-long-name']
        points = row.find_all('td', class_ = 'standing-table__cell')[9].text
        print(pl_team, points)

A: Use pandas. You can do it in 1 line.
import pandas as pd

df = pd.read_html('https://www.skysports.com/premier-league-table')[0]

Ouput:
print(df[['Team','Pts']])
                        Team  Pts
0            Manchester City   83
1          Manchester United   71
2                    Chelsea   67
3                  Liverpool   66
4             Leicester City   66
5            West Ham United   62
6          Tottenham Hotspur   59
7                    Everton   59
8                    Arsenal   58
9               Leeds United   56
10               Aston Villa   52
11   Wolverhampton Wanderers   45
12            Crystal Palace   44
13               Southampton   43
14          Newcastle United   42
15  Brighton and Hove Albion   41
16                   Burnley   39
17                    Fulham   28
18      West Bromwich Albion   26
19          Sheffield United   20


text:
Q: Nested .SelectMany statements in C# / LINQ I have the below code which works perfectly fine:
return from fa in [...]
where fa.Flows.Any()
from f in fa.Flows
select new Flow(f.Id, f.DealingDate, f.NetCashUsd, fa.Account);

As you can see, I need Account from fa deeper down in the second select.
However I'm required to use ".Selects" instead, and this (equivalent I thought) does not work:
return [...]
.Where(fa => fa.Flows.Any())
.SelectMany(fa => fa.Flows)
.Select(f => new Flow(f.Id, f.DealingDate, f.NetCashUsd, fa.Account));

The issue here is obvious, the second .Select doesn't "know" the fa stuff anymore so can't get to Account.
(As you can probably tell by now, an "fa" has one Account and multiple Flows, and I want to turn them into "Flow"s which all have the Account assigned to them as well.)
How can I solve this using only the "." statements? I looked into different GroupBys as well but couldn't make them work either.
Thank you!

A: An overload of SelectMany uses an extra argument (result selector) in which you can define the returned objects. In this result selector you have access to both source item and sub item:
[....]
.SelectMany(fa => fa.Flows, (fa,f)=> new Flow(f.Id, f.DealingDate, f.NetCashUsd, fa.Account));

A: The equivalent would be to create an intermediate anonymous type to hold both objects.
return [...]
    .SelectMany(fa => fa.Flows.Select(f => new { f, fa}))
    .Select(x => new Flow(x.f.Id, x.f.DealingDate, x.f.NetCashUsd, x.fa.Account));

Also you don't need the Where since an empty Flows will just result in no selected items.


text:
Q: Booting a machine using a virtual hard-disk I need to boot a physical machine using a virtual hard-disk (.vhd). The virtual hard-disk will be created in a hyper-visor like virtual box and will have the operating system installed on it. So, in simple words, i need to be able to make the PC treat the virtual hard disk as a physical hard disk at boot time.
Any pointers on this would be extremely helpful.
Thanks.

Thanks for the replies guys, but I need to be able to boot Linux. And it'll be helpful if we could use GRUB to do it instead of the windows boot loader.

A: As long as you've sysprepped the image before deployment and storage controller drivers are available, there shouldn't be any significant issues.
Windows 7 supports native VHD booting as well (Enterprise and Ultimate), so you could just copy the sysprepped image to your target PC, do some magic in BCDEdit, and be off and running.
The internet is full of guides for booting from a VHD, like this one, and this one.  There's some limitations too: like these.
Why do you want to boot the VHD, rather than capturing and deploying an image?

A: The capability to boot from properly prepared VHDs is actually built in to the Windows 7 bootloader. this article was originally written for a prerelease build of Windows 7 but still applies, and explains the step to get this working. You'll have to use some Microsoft virtualization product to create the image, the free Virtual PC will do.
For Linux, vmlite makes a product called VBoot that's essentially GRUB modified to boot VHDs just like it can currently do ISO/IMG. here are instructions to set it up from an existing Windows install on the machine. Unfortunately support and documentation for vboot seems to be sparse, and I see a lot of people complaining about it.


text:
Q: How to use a configuration file for controlling variables I'm coding a theme and i want to create a configuration file (maybe ini) to control variables in the theme
For example,
I want to have a file with simple content like this
navigation: 1;
site_name: MYSITE;

^ dunno if the syntax is right...just an example
And then i want to use that file to show the content stored in those variables.
for example :

 shows the value entered in the file

i also want to show/hide specific content based on the Boolean value entered in the value (navigation: 1 or 0)
something like

I hope i'm understandable. I'm a noob in PHP :'>

A: I moved away from .ini files when I discovered json. Makes everything so easy.
$filePath = "/var/www/config.json";

// Puts the config into an array
$config = json_decode(file_get_contents($filePath));

// Saves array back to config file
file_put_contents($filePath, json_encode($config));

A: Perhaps take a look at parse_ini_file().


text:
Q: Super simple query takes 39 seconds to execute My DB has about 150K DocumentNames records and all I am doing is a simple join with NameTypes. NameTypeID is a foreign key in DocumentNames.
This is my query:
With cte as
(
    Select ROW_NUMBER() OVER
    (Order By nm.Name asc )
    peta_rn,
    dn.DocumentNameID,
    dn.DocumentID
    From DocumentNames dn

    Left Join NameTypes nm On dn.NameTypeID = nm.NameTypeID
)
Select * from cte Where peta_rn >= 10000 And peta_rn <= 10050

This is the screenshot:

The sort takes 90% cost. I am totally confused what should I do at this point. I want to bang my head but I can't as there are other people around. Please suggest what should I do?

A: If, for some arbitrary reason (like a job interview), you need to optimize a query like this, try a UNION.
[Corrected to recognize alias column]
With cte as
(
  Select ROW_NUMBER() OVER
  (Order By nm.Name asc ) AS
  peta_rn,
  dn.DocumentNameID,
  dn.DocumentID
  From DocumentNames dn

  INNER Join NameTypes nm On dn.NameTypeID = nm.NameTypeID /* note change */
),
cte2 as
(
  Select ROW_NUMBER() OVER
  () AS /* yes, this is random */
  peta_rn,
  dn.DocumentNameID,
  dn.DocumentID
  From DocumentNames dn

  WHERE dn.NameTypeID  NOT IN SELECT (nm.NameTypeID FROM NameTypes nm)
)

Select * from cte Where peta_rn >= 10000 And peta_rn <= 10050

UNION

Select * from cte2 Where peta_rn >= 10000 And peta_rn <= 10050

I've never done a UNION with CTEs, so you may need some extra parentheses to make this legal. Also an ORDER BY for the entire result. I'll leave that as an exercise.
The point is that the INNER JOIN will be able to use the index on nm.Name, while the second clause will be able to do an indexed anti-semijoin. Two indexed queries should be much faster than one unindexed query.

A: For what it worth, here is some SQLFiddle to test any syntax.
By far the simplest approach is to enusre that the NameTypes are inserted in Name order, and therefore, that the NameTypeIDs are assigned alphabetically.
In this situation there is no need to join to the NameTypes table. You can just do,
WITH [CTE] AS
(
SELECT
            ROW_NUMBER() OVER (ORDER BY [NameTypeID] ASC) [PetaRN],
            [DocumentNameID],
            [DocumentID]
    FROM
            [DocumentNames]
)
SELECT
            [PetaRN],
            [DocumentNameID],
            [DocumentID]
    FROM
            [CTE]
    WHERE
            [PetaRN] BETWEEN 10000 AND 10050
    ORDER BY
            [PetaRN] ASC;

How about
WITH [CTE] AS
(
SELECT
            ROW_NUMBER() OVER (ORDER BY [NameTypeID] ASC) [PetaRN],
            [DocumentNameID],
            [DocumentID]
    FROM
            [DocumentNames]
)
SELECT TOP 50
            [PetaRN],
            [DocumentNameID],
            [DocumentID]
    FROM
            [CTE]
    WHERE
            [PetaRN] >= 10000
    ORDER BY
            [PetaRN] ASC;

When testing large datasets on SQL 2005 I've noticed that CTE's don't perform well for large result sets, this may be related to resource availability on the server. A counter intuitive use of temporary tables may turn out to be faster. This also allows you to index the row number allowing quick page selection however, this must be offset against the cost of insertion. Try it and see.
CREATE TABLE #Peta
(
    [PetaRN] BigInt NOT NULL CONSTRAINT [PK_Peta] PRIMARY KEY CLUSTERED,
    [DocumentNameID] Int NOT NULL,
    [DocumentID] Int NOT NULL
);

INSERT #Peta
SELECT
            ROW_NUMBER() OVER (ORDER BY [NameTypeID] ASC) [PetaRN],
            [DocumentNameID],
            [DocumentID]
    FROM
            [DocumentNames];

SELECT TOP 50
            [PetaRN],
            [DocumentNameID],
            [DocumentID]
    FROM
            #Peta
    WHERE
            [PetaRN] >= 10000
    ORDER BY
            [PetaRN] ASC;

DROP TABLE #Peta;

A: A few things you could try:

*

*Make the clustered index start with Name... not very efficient to have a wide clustered index but give it a go and see if it stops the sort occuring

*Permanently create a column which has the order number in it. This depends on how often your table is updated.
Please post your table and index definitions.


text:
Q: Sending dynamically created html content through email with PHP I'm making a simple todo list: http://jsbin.com/pemeqeni/1/edit?html,output
I want to be able to email myself the list, and I'm wondering how to do this with PHP specifically. I thought about scraping the HTML with DOMdocument, but I think that will only get the content from the static HTML page, which will never have list items. My other idea is to dynamically create a bunch of hidden input fields in the emailForm and dynamically delete them just as I do with the list items. Are there any other options? What's the standard protocol for something like this?

A: Something like this should work for getting all list elements.
<script>
function getEachListElement() {
   var testList = document.getElementsByClassName("todoBody");
   for (var i = 0; i < testList.length; i++) {
       document.writeln(testList[i].innerHTML);
   }
}
</script>

Try it out by changing your form action to this
<form name="emailForm" method="GET" action="JavaScript:getEachListElement()">

Then you can just create a string that you pass to PHP to email to yourself.

A: Have you tried the php mail function?
ie
<?
mail( $email, $subject , $text );
?>

Instead of get I would use post then set up a php script you call where you put your values(strings) into variables using $_post and use the mail function to mail those variables(strings).
just to be more clear your html would look like this
<form name="emailForm" method="POST" action="getContent.php">
                <input type="text" name="email" value="email"><input type="submit" value="send">
            </form>

Your getContent.php would then look like this
<?

$myemail = "myemail@tada.com";
$email = $_POST["email"];

mail ($myemail, 'The shiz you wanted', $email);

?>