问:
Compute fields quantities from one model to another - Odoo v8
Consider these four models:

```<code>class bsi_production_order(models.Model):
    _name = 'bsi.production.order'

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    date = fields.Date(string="Production Date")
    production_type = fields.Selection([
        ('budgeted','Budgeted'),
        ('nonbudgeted','Non Budgeted'),
        ('direct','Direct Order'),
    ], string='Type of Order', index=True,
    track_visibility='onchange', copy=False,
    help=" ")
    notes = fields.Text(string="Notes")
    order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True)
    print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders")

class bsi_production_order_lines(models.Model):
    _name = 'bsi.production.order.lines'

    production_order = fields.Many2one('bsi.production.order', string="Production Orders")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Float(string="Quantity")
    consumed_qty = fields.Float(string="Consumed quantity")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func")

    @api.onchange('qty', 'consumed_qty')
    def _remaining_func(self):
        if self.qty or self.consumed_qty:
            self.remaining_qty = self.qty +(-self.consumed_qty)

class bsi_print_order(models.Model):
    _name = 'bsi.print.order'

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    date = fields.Date(string="Print Date")
    origin = fields.Char(string="Origin")
    production_orders = fields.Many2one('bsi.production.order', ondelete='cascade', string="Production Order")
    order_lines = fields.One2many('bsi.print.order.lines', 'print_order', string="Order lines")

class bsi_print_order_lines(models.Model):
    _name = 'bsi.print.order.lines'

    print_order = fields.Many2one('bsi.print.order', string="Print Order")
    production_orders = fields.Many2one('bsi.production.order', ondelete='cascade', string="Production Order")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Integer(string="Quantity")
    consumed_qty = fields.Integer(string="Quantity consumed")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func")

    @api.onchange('qty', 'consumed_qty')
    def _remaining_func(self):
        if self.consumed_qty or self.qty:
            self.remaining_qty = self.qty +(-self.consumed_qty)
</code>```

So, production order has production order lines, and print order has it's order lines too (One2many order_lines fields)

There is a method on both of them, which are both called _remaining_func_.

These are OK for remaining_qty fields, but consumed_qty should be inter-related between production.order and print.order.

So, for example, if qty on bsi.production.order.lines is 10, (There are other methods which create a bsi.print.order from production order), and on bsi.print.order I put on qty the value 5, the original 10 should be 5 on bsi.production.order.line, I think with a similar method like _remaining_func_ I can achieve this, but I'm kind of confused on how to do this between the two models.

Any ideas?

If further explanation is needed, please let me know.

答:
What you want is impossible to manage unless the relationship between bsi.production.order and bsi.print.order is 1:1, but in your case it seems that a production order can have many print orders. I give you the example:

You could create a Many2one field in bsi.print.order.line pointing to bsi.production.order.line:

```<code>class bsi_print_order_lines(models.Model):
    _name = 'bsi.print.order.lines'

    po_line_related = fields.Many2one('bsi.production.order.lines', ondelete='cascade', string="Production Order Line Related")
</code>```

And each time a print line is created, you can easily create the related production line (you have all data you need):

```<code>@api.model
def create(self, vals):
    print_line = super(bsi_print_order_lines, self).create(vals)
    po_line_vals = {
        'production_order': print_line.print_order.production_orders.id,
        'isbn': print_line.isbn,
        'qty': print_line.qty,
        'consumed_qty': print_line.consumed_qty,
        'remaining_qty': print_line.remaining_qty,
    }
    po_line = self.env['bsi.production.order.lines'].create(po_line_vals)
    return print_line
</code>```

But you have to do the same the other way round (this time overwriting bsi.production.order.lines ORM create method), and here you find the problem:

```<code>@api.model
def create(self, vals):
    po_line = super(bsi_production_order_lines, self).create(vals)
    print_line_vals = {
        'production_orders': po_line.production_order.id,
        'po_line_related': po_line.id,
        'isbn': po_line.isbn,
        'qty': po_line.qty,
        'consumed_qty': po_line.consumed_qty,
        'remaining_qty': po_line.remaining_qty,
        'print_order': '???????'  # You cannot know which print order you have to write here since a production order can have several ones...
    }
    print_line = self.env['bsi.print.order.lines'].create(print_line_vals)
    return po_line
</code>```

If the relationship between bsi.production.order and bsi.print.order was 1:1, you could get the print order with search (because you would be sure that is going to return only one record):

```<code>@api.model
def create(self, vals):
    po_line = super(bsi_production_order_lines, self).create(vals)
    print_order = self.env['bsi.print.order'].search([
        ('production_orders', '=', po_line.production_order.id)
    ]).ensure_one()
    print_line_vals = {
        'production_orders': po_line.production_order.id,
        'po_line_related': po_line.id,
        'isbn': po_line.isbn,
        'qty': po_line.qty,
        'consumed_qty': po_line.consumed_qty,
        'remaining_qty': po_line.remaining_qty,
        'print_order': print_order.id,
    }
    print_line = self.env['bsi.print.order.lines'].create(print_line_vals)
    return po_line
</code>```

And this way you would have your production lines and print lines related, and you would have to overwrite write and unlink methods too to control when a line is modified or removed, do the same for its "twin" (it would be easy to find it thanks to the new Many2one field named po_line_related).

Of course it would not be a beautiful solution but I think it is the only one (using Odoo API) for your Entity-Relationship Diagram.

Body:
Consider these four models:

class bsi_production_order(models.Model):
    _name = 'bsi.production.order'

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    date = fields.Date(string="Production Date")
    production_type = fields.Selection([
        ('budgeted','Budgeted'),
        ('nonbudgeted','Non Budgeted'),
        ('direct','Direct Order'),
    ], string='Type of Order', index=True,
    track_visibility='onchange', copy=False,
    help=" ")
    notes = fields.Text(string="Notes")
    order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True)
    print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders")

class bsi_production_order_lines(models.Model):
    _name = 'bsi.production.order.lines'

    production_order = fields.Many2one('bsi.production.order', string="Production Orders")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Float(string="Quantity")
    consumed_qty = fields.Float(string="Consumed quantity")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func")

    @api.onchange('qty', 'consumed_qty')
    def _remaining_func(self):
        if self.qty or self.consumed_qty:
            self.remaining_qty = self.qty +(-self.consumed_qty)

class bsi_print_order(models.Model):
    _name = 'bsi.print.order'

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    date = fields.Date(string="Print Date")
    origin = fields.Char(string="Origin")
    production_orders = fields.Many2one('bsi.production.order', ondelete='cascade', string="Production Order")
    order_lines = fields.One2many('bsi.print.order.lines', 'print_order', string="Order lines")

class bsi_print_order_lines(models.Model):
    _name = 'bsi.print.order.lines'

    print_order = fields.Many2one('bsi.print.order', string="Print Order")
    production_orders = fields.Many2one('bsi.production.order', ondelete='cascade', string="Production Order")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Integer(string="Quantity")
    consumed_qty = fields.Integer(string="Quantity consumed")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func")

    @api.onchange('qty', 'consumed_qty')
    def _remaining_func(self):
        if self.consumed_qty or self.qty:
            self.remaining_qty = self.qty +(-self.consumed_qty)

So, production order has production order lines, and print order has it's order lines too (One2many order_lines fields)

There is a method on both of them, which are both called _remaining_func_.

These are OK for remaining_qty fields, but consumed_qty should be inter-related between production.order and print.order.

So, for example, if qty on bsi.production.order.lines is 10, (There are other methods which create a bsi.print.order from production order), and on bsi.print.order I put on qty the value 5, the original 10 should be 5 on bsi.production.order.line, I think with a similar method like _remaining_func_ I can achieve this, but I'm kind of confused on how to do this between the two models.

Any ideas?

If further explanation is needed, please let me know.

Body:
What you want is impossible to manage unless the relationship between bsi.production.order and bsi.print.order is 1:1, but in your case it seems that a production order can have many print orders. I give you the example:

You could create a Many2one field in bsi.print.order.line pointing to bsi.production.order.line:

class bsi_print_order_lines(models.Model):
    _name = 'bsi.print.order.lines'

    po_line_related = fields.Many2one('bsi.production.order.lines', ondelete='cascade', string="Production Order Line Related")

And each time a print line is created, you can easily create the related production line (you have all data you need):

@api.model
def create(self, vals):
    print_line = super(bsi_print_order_lines, self).create(vals)
    po_line_vals = {
        'production_order': print_line.print_order.production_orders.id,
        'isbn': print_line.isbn,
        'qty': print_line.qty,
        'consumed_qty': print_line.consumed_qty,
        'remaining_qty': print_line.remaining_qty,
    }
    po_line = self.env['bsi.production.order.lines'].create(po_line_vals)
    return print_line

But you have to do the same the other way round (this time overwriting bsi.production.order.lines ORM create method), and here you find the problem:

@api.model
def create(self, vals):
    po_line = super(bsi_production_order_lines, self).create(vals)
    print_line_vals = {
        'production_orders': po_line.production_order.id,
        'po_line_related': po_line.id,
        'isbn': po_line.isbn,
        'qty': po_line.qty,
        'consumed_qty': po_line.consumed_qty,
        'remaining_qty': po_line.remaining_qty,
        'print_order': '???????'  # You cannot know which print order you have to write here since a production order can have several ones...
    }
    print_line = self.env['bsi.print.order.lines'].create(print_line_vals)
    return po_line

If the relationship between bsi.production.order and bsi.print.order was 1:1, you could get the print order with search (because you would be sure that is going to return only one record):

@api.model
def create(self, vals):
    po_line = super(bsi_production_order_lines, self).create(vals)
    print_order = self.env['bsi.print.order'].search([
        ('production_orders', '=', po_line.production_order.id)
    ]).ensure_one()
    print_line_vals = {
        'production_orders': po_line.production_order.id,
        'po_line_related': po_line.id,
        'isbn': po_line.isbn,
        'qty': po_line.qty,
        'consumed_qty': po_line.consumed_qty,
        'remaining_qty': po_line.remaining_qty,
        'print_order': print_order.id,
    }
    print_line = self.env['bsi.print.order.lines'].create(print_line_vals)
    return po_line

And this way you would have your production lines and print lines related, and you would have to overwrite write and unlink methods too to control when a line is modified or removed, do the same for its "twin" (it would be easy to find it thanks to the new Many2one field named po_line_related).

Of course it would not be a beautiful solution but I think it is the only one (using Odoo API) for your Entity-Relationship Diagram.


来源: stackexchange

问:
How to change Preference icon color globally Android
I have set flat icon for all my Preference, I would like to change the color of that icon globally.

When I try the below code it even changes the back button color in the toolbar.

I want only Preference icon tint to be changed globally. Thank in advance.

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <SwitchPreference
        android:id="@+id/pref_toggle_alarm"
        android:icon="@drawable/ic_pref_notifications"
        android:key="key_toggle_alarm"
        android:summaryOff="Alarm OFF"
        android:summaryOn="Alarm ON"
        android:title="Alarm" />

    <web.prefs.TimePrefs
        android:id="@+id/pref_select_time"
        android:icon="@drawable/ic_pref_time"
        android:key="key_time"
        android:summary="Set some time"
        android:title="Select Time" />

    <MultiSelectListPreference
        android:id="@+id/pref_select_week"
        android:defaultValue="@array/week_array_values"
        android:entries="@array/array_week_selection"
        android:entryValues="@array/week_array_values"
        android:icon="@drawable/ic_pref_time"
        android:key="key_week"
        android:title="Select Days" />

    <ListPreference
        android:id="@+id/pref_track"
        android:defaultValue="0"
        android:entries="@array/tracks_arrays"
        android:entryValues="@array/tracks_arrays_values"
        android:icon="@drawable/ic_music_note"
        android:key="key_track"
        android:summary="%s"
        android:title="Select Track" />

</PreferenceScreen>
</code>```

style.xml

```<code><style name="PreferencesTheme" parent="@style/AppTheme.NoActionBar">
    <item name="android:textColorPrimary">@color/primary_text</item>
    <item name="android:textColorSecondary">@color/secondary_text</item>
    <item name="android:colorAccent">@color/accent</item>
    <item name="android:tint">@color/accent</item>
</style>
</code>```

答:
Here are the solutions that I found after many tests. This implies that you use at least API 21. If you are below, I recommend using a values-v21 folder and a neutral gray color which adapts to black and white backgrounds for default file.

Solution A

One solution, if you use vector icons is to make an attribute to integrate into the XML of each image.

In values/attrs.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="iconPreferenceColor" format="reference|color" />
</resources>
</code>```

In each icon add android:fillColor="?attr/iconPreferenceColor", sample :

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="?attr/iconPreferenceColor"
        android:pathData="M13,2.05v3.03c3.39,0.49 6,3.39 6,6.92 0,0.9 -0.18,1.75 -0.48,2.54l2.6,1.53c0.56,-1.24 0.88,-2.62 0.88,-4.07 0,-5.18 -3.95,-9.45 -9,-9.95zM12,19c-3.87,0 -7,-3.13 -7,-7 0,-3.53 2.61,-6.43 6,-6.92V2.05c-5.06,0.5 -9,4.76 -9,9.95 0,5.52 4.47,10 9.99,10 3.31,0 6.24,-1.61 8.06,-4.09l-2.6,-1.53C16.17,17.98 14.21,19 12,19z"/>
</vector>
</code>```

and in style :

```<code><item name="iconPreferenceColor">@color/green</item>
</code>```

Solution B (better)

It is possible to tint the icons directly from a style file with PreferenceThemeOverlay.v14.Material.

In values/styles.xml:

```<code><style name="MyStyle.Night" parent="Theme.AppCompat" >
    <item name="preferenceTheme">@style/MyStyle.Preference.v21</item>
    ...
</style>

<!-- Preference Theme -->
<style name="MyStyle.Preference.v21" parent="@style/PreferenceThemeOverlay.v14.Material">
    <item name="android:tint">@color/green</item>
</style>
</code>```

Please note, you must also use the android:tint parameter in the style of your toolbar, otherwise you may have bugs when changing themes dynamically.

I hope it's helpful

ContentLicense: CC BY-SA 3.0

Body:
I have set flat icon for all my Preference, I would like to change the color of that icon globally.

When I try the below code it even changes the back button color in the toolbar.

I want only Preference icon tint to be changed globally. Thank in advance.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <SwitchPreference
        android:id="@+id/pref_toggle_alarm"
        android:icon="@drawable/ic_pref_notifications"
        android:key="key_toggle_alarm"
        android:summaryOff="Alarm OFF"
        android:summaryOn="Alarm ON"
        android:title="Alarm" />

    <web.prefs.TimePrefs
        android:id="@+id/pref_select_time"
        android:icon="@drawable/ic_pref_time"
        android:key="key_time"
        android:summary="Set some time"
        android:title="Select Time" />

    <MultiSelectListPreference
        android:id="@+id/pref_select_week"
        android:defaultValue="@array/week_array_values"
        android:entries="@array/array_week_selection"
        android:entryValues="@array/week_array_values"
        android:icon="@drawable/ic_pref_time"
        android:key="key_week"
        android:title="Select Days" />

    <ListPreference
        android:id="@+id/pref_track"
        android:defaultValue="0"
        android:entries="@array/tracks_arrays"
        android:entryValues="@array/tracks_arrays_values"
        android:icon="@drawable/ic_music_note"
        android:key="key_track"
        android:summary="%s"
        android:title="Select Track" />

</PreferenceScreen>

style.xml

Body:
Here are the solutions that I found after many tests. This implies that you use at least API 21. If you are below, I recommend using a values-v21 folder and a neutral gray color which adapts to black and white backgrounds for default file.

Solution A

One solution, if you use vector icons is to make an attribute to integrate into the XML of each image.

In values/attrs.xml :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="iconPreferenceColor" format="reference|color" />
</resources>

In each icon add android:fillColor="?attr/iconPreferenceColor", sample :

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="?attr/iconPreferenceColor"
        android:pathData="M13,2.05v3.03c3.39,0.49 6,3.39 6,6.92 0,0.9 -0.18,1.75 -0.48,2.54l2.6,1.53c0.56,-1.24 0.88,-2.62 0.88,-4.07 0,-5.18 -3.95,-9.45 -9,-9.95zM12,19c-3.87,0 -7,-3.13 -7,-7 0,-3.53 2.61,-6.43 6,-6.92V2.05c-5.06,0.5 -9,4.76 -9,9.95 0,5.52 4.47,10 9.99,10 3.31,0 6.24,-1.61 8.06,-4.09l-2.6,-1.53C16.17,17.98 14.21,19 12,19z"/>
</vector>

and in style :

<item name="iconPreferenceColor">@color/green</item>

Solution B (better)

It is possible to tint the icons directly from a style file with PreferenceThemeOverlay.v14.Material.

In values/styles.xml:

<style name="MyStyle.Night" parent="Theme.AppCompat" >
    <item name="preferenceTheme">@style/MyStyle.Preference.v21</item>
    ...
</style>

<!-- Preference Theme -->
<style name="MyStyle.Preference.v21" parent="@style/PreferenceThemeOverlay.v14.Material">
    <item name="android:tint">@color/green</item>
</style>

Please note, you must also use the android:tint parameter in the style of your toolbar, otherwise you may have bugs when changing themes dynamically.

I hope it's helpful

ContentLicense: CC BY-SA 4.0


问:
pressesEnded in tvOS not being called
I am developing a game for tvOS in swift spritekit.
There is a viewcontroller A which presents a SKScene B. I am forwarding the pressesBegan and pressesEnded from A to B.

pressesBegan is being called in A and forwarded to B but pressedEnded is not even called in A. Iam not getting why?

Below are the function implemented in A.

```<code>override func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
    if ((self.view as! SKView).scene?.isMemberOfClass(GameScene) == true){
        let gameScene = (self.view as! SKView).scene as! GameScene
        gameScene.pressesEnded(presses, withEvent: event)
    }
</code>```

}

```<code>override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {

    if ((self.view as! SKView).scene?.isMemberOfClass(GameScene) == true){
        let gameScene = (self.view as! SKView).scene as! GameScene
        gameScene.pressesBegan(presses, withEvent: event)
    }
}
</code>```

答:
I have also ran into this situation.

After some testing it seems that when the 'select' button is released tvOS calls either pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) OR pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?).

As to why this is, I don't know. There isn't anything that I am doing differently between each button press. Could be a bug in tvOS.

I found this solution by jumping to the definition of pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) and finding this comment:

Your responder will receive either pressesEnded:withEvent or
  pressesCancelled:withEvent: for each press it is handling (those
  presses it received in pressesBegan:withEvent:).

Here is a link to the question I asked about the same issue.

Title: pressesEnded in tvOS not being called

Body:
I am developing a game for tvOS in swift spritekit.
There is a viewcontroller A which presents a SKScene B. I am forwarding the pressesBegan and pressesEnded from A to B.

pressesBegan is being called in A and forwarded to B but pressedEnded is not even called in A. Iam not getting why?

Below are the function implemented in A.

override func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
    if ((self.view as! SKView).scene?.isMemberOfClass(GameScene) == true){
        let gameScene = (self.view as! SKView).scene as! GameScene
        gameScene.pressesEnded(presses, withEvent: event)
    }

}

override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {

    if ((self.view as! SKView).scene?.isMemberOfClass(GameScene) == true){
        let gameScene = (self.view as! SKView).scene as! GameScene
        gameScene.pressesBegan(presses, withEvent: event)
    }
}


问:
Possible to start up Jenkins again via ..war file even though the machine where Jenkins is deployed restarts?
Is it possible to start up Jenkins again via .war even though the machine where Jenkins is deployed restarts?

I have jenkins deployed on a Virtual machine using a .war file with the following command: java -jar jenkins.war

If the machine gets restarted, the command prompt which is using the above command closes and therefore stops my instance of Jenkins from running.

Is there a way to automatically start up Jenkins again even if the machine gets restarted?

VM is using windows 2008 server.

Thanks

答: Creating a batch file and pasting in the following location has resolved the issue: C:\Users\zzzzzz\Roaming\Microsoft\Windows\Start Menu\Programs\Startup </p>


问:
Morse code program i just need a little bit of guide with neatness
this is my code for making typing out Morse code

```<code>def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    print("your word or sentence translated to morse code is : ")
    for key in phrase:
        if not key.isdigit():
            print(morse_code[key], end = " ")

retry()

def retry ():
    main ()
</code>```

When the program restarts it starts on the same line the type Morse code is at, and i don't know where to put a error print, so that if someone types a number it says try again or error before restarting

答:
You should probably refactor to and use functions to get input from the user, then to translate the message to morse:  </p>

```<code>def get_message():
    while True:
        message = input("please enter your word or words: ")
        message = message.lower()
        for c in message:
            if c not in alphabet:
                print("please enter a message using the correct alphabet")
                break
        else:
            return message

def translate(message):
    code = []
    for c in message:
        code.append(morse[c])
    return ' '.join(code)

alphabet = 'abcdefghijklmnopqrtsuvwxyz '
morse = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
              "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

print(translate(get_message()))
</code>```

Body:
this is my code for making typing out Morse code

def main ():

    morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
                  "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

    phrase = input("please enter your word or words: ")
    print("your word or sentence translated to morse code is : ")
    for key in phrase:
        if not key.isdigit():
            print(morse_code[key], end = " ")

retry()

def retry ():
    main ()

When the program restarts it starts on the same line the type Morse code is at, and i don't know where to put a error print, so that if someone types a number it says try again or error before restarting

Body:
You should probably refactor to and use functions to get input from the user, then to translate the message to morse:

def get_message():
    while True:
        message = input("please enter your word or words: ")
        message = message.lower()
        for c in message:
            if c not in alphabet:
                print("please enter a message using the correct alphabet")
                break
        else:
            return message

def translate(message):
    code = []
    for c in message:
        code.append(morse[c])
    return ' '.join(code)

alphabet = 'abcdefghijklmnopqrtsuvwxyz '
morse = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
              "m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}

print(translate(get_message()))


问:
jQuery Hover question
here:

http://www.jsfiddle.net/JEXru/1/

i don't know how to make it so if you hover over the slide it stays active ... help?

答:
Change your javascript to this:

```<code>$(function() {
$('.slide').hide();
$('.title:first').css({
    'margin-left': '1px #333 solid'
});
$('ul#horzAccordion ul').hover(
    function() {
         var slideLink = $(this).children('a').attr('name');
         $(slideLink).animate({
             'width': '320px'
         }).show();
    }, function() {
         var slideLink = $(this).children('a').attr('name');
         $(slideLink).animate({
             'width': '0px'
    }, 300).hide();
});
});
</code>```

What you were doing is setting the hover event on just the link which only encompasses the first LI (the link surrounding the list item is invalid html by the way you will want to move that to inside the LI).  So when your mouse moved away from the link it closed.  The updated javascript sets the hover on the interior UL so that you can interact with the shown contents.

Let me know if you have any questions on the above.

edit: code formatting.

ContentLicense: CC BY-SA 2.5

Title: jQuery Hover question

Body:
Change your javascript to this:

$(function() {
$('.slide').hide();
$('.title:first').css({
    'margin-left': '1px #333 solid'
});
$('ul#horzAccordion ul').hover(
    function() {
         var slideLink = $(this).children('a').attr('name');
         $(slideLink).animate({
             'width': '320px'
         }).show();
    }, function() {
         var slideLink = $(this).children('a').attr('name');
         $(slideLink).animate({
             'width': '0px'
    }, 300).hide();
});
});

What you were doing is setting the hover event on just the link which only encompasses the first LI (the link surrounding the list item is invalid html by the way you will want to move that to inside the LI).  So when your mouse moved away from the link it closed.  The updated javascript sets the hover on the interior UL so that you can interact with the shown contents.

Let me know if you have any questions on the above.

edit: code formatting.


问:
chrome extension dynamically change icon (without clicking)
how can I make my chrome extension change icon (without clicking on it). I've got script that's checking if page has certain string and if it has I want my extension icon change from grey to colored one. </p>

答:
In background you can do stuff like :

```<code>const updateIcon = tabId => {
  const icon = isDisabled() ? icons.disabled : icons.enabled;
  chrome.pageAction.setIcon({ tabId, path: icon });
};
chrome.tabs.onUpdated.addListener(updateIcon);
</code>```

ref : https://github.com/gbleu/opteamissed/blob/master/background.js#L38

Body:
In background you can do stuff like :

const updateIcon = tabId => {
  const icon = isDisabled() ? icons.disabled : icons.enabled;
  chrome.pageAction.setIcon({ tabId, path: icon });
};
chrome.tabs.onUpdated.addListener(updateIcon);

ref : https://github.com/gbleu/opteamissed/blob/master/background.js#L38


问:
How to include single row multiple column subquery (PIPELINED function) results in the result set
I am using Oracle 11g.

So, lets say that I have a test data table like this one

```<code>with test_data as (
    select 1 as id, 'John' as name from dual
        union all
    select 2 as id, 'Jack' as name from dual
        union all
    select 3 as id, 'Peter' as name from dual
)
</code>```

Also I have a piplined function that returns one row per call, with multiple columns like the following:

```<code>CREATE OR REPLACE PACKAGE MY_PACK AS
  TYPE result_record is RECORD(
   surname           varchar2(27),
   telephone          varchar2(50),
   place_of_birth     varchar2(50)
       );

  TYPE result_table IS TABLE OF result_record;
  function runPipe(id number) RETURN result_table PIPELINED;
END ERC_PACK;
/

CREATE OR REPLACE PACKAGE BODY MY_PACK AS
    function runPipe(id number) RETURN result_table PIPELINED IS
    rec           result_record:=null;
    begin
       if  (id=1) then
         select 'Smih','139289289','Paris' into rec from dual;
       end if;
       if  (id=2) then
         select 'Lock','1888888888','London' into rec from dual;
       end if;
       if  (id=3) then
         select 'May','99999999999','Berlin' into rec from dual;
       end if;
       pipe row (rec);
       return;
  end;
END ERC_PACK;
/
</code>```

And of course the

```<code>select * from table(MY_PACK.runPipe(1))
</code>```

returns

```<code>Smih    139289289   Paris
</code>```

Now I would like a select statement that will return all the rows of the test_data  along with the corresponding values from pipeline function

e.g. something like

```<code>select test_data.*, (select * from table(MY_PACK.runPipe(id))) from test_data
</code>```

which of course doses not work
but the expected results would be something like:

```<code>1 John  Smih    139289289   Paris
2 Jack  Lock    1888888888  London
3 Peter May     99999999999 Berlin
</code>```

So how to achieve the above expected result, given the test_data table and the pipelined function?

答:
Kindly Try the below with alias </p>

```<code>with test_data as (
select 1 as id, 'John' as name from dual
    union all
select 2 as id, 'Jack' as name from dual
    union all
select 3 as id, 'Peter' as name from dual
)
select * from table(MY_PACK.runPipe(test_data.id))) from test_data
</code>```

Body:
I am using Oracle 11g.

So, lets say that I have a test data table like this one

with test_data as (
    select 1 as id, 'John' as name from dual
        union all
    select 2 as id, 'Jack' as name from dual
        union all
    select 3 as id, 'Peter' as name from dual
)

Also I have a piplined function that returns one row per call, with multiple columns like the following:

CREATE OR REPLACE PACKAGE MY_PACK AS
  TYPE result_record is RECORD(
   surname           varchar2(27),
   telephone          varchar2(50),
   place_of_birth     varchar2(50)
       );

  TYPE result_table IS TABLE OF result_record;
  function runPipe(id number) RETURN result_table PIPELINED;
END ERC_PACK;
/

CREATE OR REPLACE PACKAGE BODY MY_PACK AS
    function runPipe(id number) RETURN result_table PIPELINED IS
    rec           result_record:=null;
    begin
       if  (id=1) then
         select 'Smih','139289289','Paris' into rec from dual;
       end if;
       if  (id=2) then
         select 'Lock','1888888888','London' into rec from dual;
       end if;
       if  (id=3) then
         select 'May','99999999999','Berlin' into rec from dual;
       end if;
       pipe row (rec);
       return;
  end;
END ERC_PACK;
/

And of course the

select * from table(MY_PACK.runPipe(1))

returns

Smih    139289289   Paris

Now I would like a select statement that will return all the rows of the test_data  along with the corresponding values from pipeline function

e.g. something like

select test_data.*, (select * from table(MY_PACK.runPipe(id))) from test_data

which of course doses not work
but the expected results would be something like:

1 John  Smih    139289289   Paris
2 Jack  Lock    1888888888  London
3 Peter May     99999999999 Berlin

So how to achieve the above expected result, given the test_data table and the pipelined function?

Body:
Kindly Try the below with alias

with test_data as (
select 1 as id, 'John' as name from dual
    union all
select 2 as id, 'Jack' as name from dual
    union all
select 3 as id, 'Peter' as name from dual
)
select * from table(MY_PACK.runPipe(test_data.id))) from test_data


问:
How do I specify a generic in Type.GetType()?
I am working on a VS extension that will generate documentation comments for a file. Roslyn provides classes that allow processing of source code and adding the comments. The specific problem I am having is determining the fully qualified name for a base class or interface in a class declaration. For example:

```<code>using System;
using System.Collections;
using System.Linq;

public class MyClass: IEnumerable
{ ... }
</code>```

for which I want to generate:

```<code><summary></summary>
<seealso cref="System.Collections.IEnumerable"/>
</code>```

I determine that IEnumerable is defined in System.Collections by looping through each of the using directives to pick up the IdentifierName or QualifiedName and appending the interface name to generate a potential fully qualified name. I then call Type.GetType(potentialFullyQualifiedName), which returns the type if the name is valid, and null otherwise. If the returned value is not null, then I know I have the valid fully qualified name. For the example above, I first try
"System.IEnumerable" which returns null. Then "System.Collections.IEnumerable" which returns a type, so I know I have the correct fully qualified name. Everything is good so far.

But if I change the code being processed to this:

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public class MyClass : IEnumerable<int>
{ ... }
</code>```

everything I have tried returns null. IEnumerable is in System.Collections.Generic, so I will limit further discussion to that.

None of:

```<code>System.Collections.Generic.IEnumerable
System.Collections.Generic.IEnumerable<>
System.Collections.Generic.IEnumerable<T>
System.Collections.Generic.IEnumerable<int>
System.Collections.Generic.IEnumerable<out T>
System.Collections.Generic.IEnumberable`1
</code>```

return a type from Type.GetType(). How do I specify the interface name to get Type.GetType() to return a type rather than null?

After looking at the first comment and first answer below, neither of which provide a "solution", it appears I need to add a bit more information.

The source code that I included above is just that, source code, or in other words, text, that is parsed to create a syntactic model which I then go through. I can't instantiate a Class1 object because the source code has not been compiled and is not part of the assembly that is processing the syntactic model. I could compile the source code to produce a semantic model of the source code, but that is potentially an expensive operation that I would much rather avoid. So it comes down to how do I determine that IEnumerable is actually System.Collections.Generic.IEnumerable, given that I only have IEnumerable as text?

答:
This is because the format of the full name for generic classes is a little bit different. It additionally includes the generic type's namespace and full assembly identifying string enclosed into [].

I wrote a short example to illustrate it. Consider we have the following 2 types:

```<code>class NonGeneric : IEnumerable
</code>```

and

```<code>class Generic : IEnumerable<string>
</code>```

...and the following code which prints interface names into console:

```<code>var nonGeneric = new NonGeneric();
var generic = new Generic();
string nonGenericName = nonGeneric.GetType().GetInterfaces().First().FullName;
string genericName = generic.GetType().GetInterfaces().First().FullName;

Console.WriteLine($"Non generic: {nonGenericName}");
Console.WriteLine($"Generic: {genericName}");
</code>```

The output:

```<code>Non generic: System.Collections.IEnumerable
Generic: System.Collections.Generic.IEnumerable`1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]]
</code>```

I hope it helps you!

Body:
I am working on a VS extension that will generate documentation comments for a file. Roslyn provides classes that allow processing of source code and adding the comments. The specific problem I am having is determining the fully qualified name for a base class or interface in a class declaration. For example:

using System;
using System.Collections;
using System.Linq;

public class MyClass: IEnumerable
{ ... }

for which I want to generate:

<seealso cref="System.Collections.IEnumerable"/>

I determine that IEnumerable is defined in System.Collections by looping through each of the using directives to pick up the IdentifierName or QualifiedName and appending the interface name to generate a potential fully qualified name. I then call Type.GetType(potentialFullyQualifiedName), which returns the type if the name is valid, and null otherwise. If the returned value is not null, then I know I have the valid fully qualified name. For the example above, I first try
"System.IEnumerable" which returns null. Then "System.Collections.IEnumerable" which returns a type, so I know I have the correct fully qualified name. Everything is good so far.

But if I change the code being processed to this:

using System;
using System.Collections.Generic;
using System.Linq;

public class MyClass : IEnumerable<int>
{ ... }

everything I have tried returns null. IEnumerable is in System.Collections.Generic, so I will limit further discussion to that.

None of:

System.Collections.Generic.IEnumerable
System.Collections.Generic.IEnumerable<>
System.Collections.Generic.IEnumerable<T>
System.Collections.Generic.IEnumerable<int>
System.Collections.Generic.IEnumerable<out T>
System.Collections.Generic.IEnumberable`1

return a type from Type.GetType(). How do I specify the interface name to get Type.GetType() to return a type rather than null?

After looking at the first comment and first answer below, neither of which provide a "solution", it appears I need to add a bit more information.

The source code that I included above is just that, source code, or in other words, text, that is parsed to create a syntactic model which I then go through. I can't instantiate a Class1 object because the source code has not been compiled and is not part of the assembly that is processing the syntactic model. I could compile the source code to produce a semantic model of the source code, but that is potentially an expensive operation that I would much rather avoid. So it comes down to how do I determine that IEnumerable is actually System.Collections.Generic.IEnumerable, given that I only have IEnumerable as text?

Body:
This is because the format of the full name for generic classes is a little bit different. It additionally includes the generic type's namespace and full assembly identifying string enclosed into [].

I wrote a short example to illustrate it. Consider we have the following 2 types:

class NonGeneric : IEnumerable

and

class Generic : IEnumerable<string>

...and the following code which prints interface names into console:

var nonGeneric = new NonGeneric();
var generic = new Generic();
string nonGenericName = nonGeneric.GetType().GetInterfaces().First().FullName;
string genericName = generic.GetType().GetInterfaces().First().FullName;

Console.WriteLine($"Non generic: {nonGenericName}");
Console.WriteLine($"Generic: {genericName}");

The output:

Non generic: System.Collections.IEnumerable
Generic: System.Collections.Generic.IEnumerable`1[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]]

I hope it helps you!


问:
Fastest way to negate a std::vector
Assume I have a std::vector of double, namely

```<code>std::vector<double> MyVec(N);
</code>```

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

```<code>std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());
</code>```

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

答:
Fortunately the data in std::vector is contiguous so you can multiply by -1 using vector intrinsics (using unaligned load/stores and special handing of the possible overflow). Or use ippsMulC_64f/ippsMulC_64f_I from intel's IPP library (you'll struggle to write something faster) which will use the largest vector registers available to your platform: https://software.intel.com/en-us/ipp-dev-reference-mulc

Update: to clear up some confusion in the comments, the full version of Intel IPP is free (although you can pay for support) and comes on Linux, Windows and macOS.

Title: Fastest way to negate a std::vector

Body:
Assume I have a std::vector of double, namely

std::vector<double> MyVec(N);

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.


问:
Exercise: Implement an abstract class
So i'm following a C# beginner tutorial at dotnetcademy.net and one of the exercises is to Implement an abstract class.

and the goals are:
1. Create a class named SpaceStation that is abstract
2. On that abstract class, add a abstract method called FireLaser
3. Create a derived class called DeathStar that implements the FireLaser method to write "Pew pew" to the Console followed by a new line.

the code that you start with is:

```<code>using System;

// Implement your classes here

public class Program
{
    public static void Main()
    {
    }
}
</code>```

so i wrote this but it says on return that "Since 'DeathStar.FireLaser()' returns void, a return keyword must not be followed by an object expression"
but i don't know what else to write, i've tried multiple other things

```<code>using System;

// Implement your classes here
public abstract class SpaceStation
{
    public abstract void FireLaser();
}

public class DeathStar : SpaceStation
{
    public override void FireLaser()
    {
        return  Console.WriteLine("Pew pew");
    }
}

public class Program
{
    public static void Main()
    {
    }
}
</code>```

So if anybody has a solution so i can reflect it on what i wrote that would be nice or if anybody can say what it should be instead.

答:
A method marked as void does not return anything. The return keyword is usually used to return a result from a method. Therefore it usually does not make sense in a void method. Removing the return keyword from your statement will resolve your compiler error.

```<code>public class DeathStar : SpaceStation
{
    public override void FireLaser()
    {
        Console.WriteLine("Pew pew");
    }
}
</code>```

Note that the return keyword can be used in a void method to end the method. However, its usage is generally discouraged because it can result code that returns from multiple places and this can be confusing. When used in this manner, you still do not return an actual value. return would be the only part of the statement. Consider the following code:

```<code>public void ProcessSomeWork(SomeWork work)
{
    if(work.IsCompleted)
    {
        return;
    }

    work.DoSomething();
    DoSomethingElseToWork(work);
}
</code>```

Title: Exercise: Implement an abstract class

Body:
So i'm following a C# beginner tutorial at dotnetcademy.net and one of the exercises is to Implement an abstract class.

and the goals are:
1. Create a class named SpaceStation that is abstract
2. On that abstract class, add a abstract method called FireLaser
3. Create a derived class called DeathStar that implements the FireLaser method to write "Pew pew" to the Console followed by a new line.

the code that you start with is:

using System;

// Implement your classes here

public class Program
{
    public static void Main()
    {
    }
}

so i wrote this but it says on return that "Since 'DeathStar.FireLaser()' returns void, a return keyword must not be followed by an object expression"
but i don't know what else to write, i've tried multiple other things

using System;

// Implement your classes here
public abstract class SpaceStation
{
    public abstract void FireLaser();
}

public class DeathStar : SpaceStation
{
    public override void FireLaser()
    {
        return  Console.WriteLine("Pew pew");
    }
}

public class Program
{
    public static void Main()
    {
    }
}

So if anybody has a solution so i can reflect it on what i wrote that would be nice or if anybody can say what it should be instead.

Body:
A method marked as void does not return anything. The return keyword is usually used to return a result from a method. Therefore it usually does not make sense in a void method. Removing the return keyword from your statement will resolve your compiler error.

public class DeathStar : SpaceStation
{
    public override void FireLaser()
    {
        Console.WriteLine("Pew pew");
    }
}

Note that the return keyword can be used in a void method to end the method. However, its usage is generally discouraged because it can result code that returns from multiple places and this can be confusing. When used in this manner, you still do not return an actual value. return would be the only part of the statement. Consider the following code:

public void ProcessSomeWork(SomeWork work)
{
    if(work.IsCompleted)
    {
        return;
    }

    work.DoSomething();
    DoSomethingElseToWork(work);
}


问:
What is the advantage of using composite primary key instead of single primary key in this context?
Cakephp v3 is now able to support composite primary key.
http://book.cakephp.org/3.0/en/quickstart.html

One example given at the quick start guide;

```<code>CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL,
    created DATETIME,
    modified DATETIME
);

CREATE TABLE bookmarks (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    title VARCHAR(50),
    description TEXT,
    url TEXT,
    created DATETIME,
    modified DATETIME,
    FOREIGN KEY user_key (user_id) REFERENCES users(id)
);

CREATE TABLE tags (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255),
    created DATETIME,
    modified DATETIME,
    UNIQUE KEY (title)
);

CREATE TABLE bookmarks_tags (
    bookmark_id INT NOT NULL,
    tag_id INT NOT NULL,
    PRIMARY KEY (bookmark_id, tag_id),
    INDEX tag_idx (tag_id, bookmark_id),
    FOREIGN KEY tag_key(tag_id) REFERENCES tags(id),
    FOREIGN KEY bookmark_key(bookmark_id) REFERENCES bookmarks(id)
);
</code>```

The Quick start guide mentions "You may have noticed that the bookmarks_tags table used a composite primary key. CakePHP supports composite primary keys almost everywhere, **making it easier to build multi-tenanted applications**."

What is meant by multi-tenanted applications? In this context, why is it better to use composite primary key versus single primary key?

答: if we do select * from bookmarks_tags then Sorting will be done on the basis of column bookmarks_id(first field) of table bookmarks_tags.

Body:
Cakephp v3 is now able to support composite primary key.
http://book.cakephp.org/3.0/en/quickstart.html

One example given at the quick start guide;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL,
    created DATETIME,
    modified DATETIME
);

CREATE TABLE bookmarks (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    title VARCHAR(50),
    description TEXT,
    url TEXT,
    created DATETIME,
    modified DATETIME,
    FOREIGN KEY user_key (user_id) REFERENCES users(id)
);

CREATE TABLE tags (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255),
    created DATETIME,
    modified DATETIME,
    UNIQUE KEY (title)
);

CREATE TABLE bookmarks_tags (
    bookmark_id INT NOT NULL,
    tag_id INT NOT NULL,
    PRIMARY KEY (bookmark_id, tag_id),
    INDEX tag_idx (tag_id, bookmark_id),
    FOREIGN KEY tag_key(tag_id) REFERENCES tags(id),
    FOREIGN KEY bookmark_key(bookmark_id) REFERENCES bookmarks(id)
);

The Quick start guide mentions "You may have noticed that the bookmarks_tags table used a composite primary key. CakePHP supports composite primary keys almost everywhere, **making it easier to build multi-tenanted applications**."

What is meant by multi-tenanted applications? In this context, why is it better to use composite primary key versus single primary key?


问:
Upload file from local machine (Windows) to HDFS via cURL: Protocol mismatch
What I want to achieve
I want to move a file from my local Windows machine to HDFS using cURL. In my case HDFS is running on a virtual machine

What's not working
I'm using following command

```<code>curl -i -X PUT "http://ip:port/webhdfs/v1/...?op=CREATE"
</code>```

I'm executing the above from Windows Command Prompt which I cd'ed to the folder containing the testfile.txt. The command returns the following

```<code>SSH-2.0-OpenSSH_5.3
Protocol mismatch.
</code>```

Edit: According to this this I should be getting a response as

```<code>HTTP/1.1 307 TEMPORARY_REDIRECT
Location: http://<DATANODE>:<PORT>/webhdfs/v1/<PATH>?op=CREATE...
Content-Length: 0
</code>```

Then I should be able to run the second step as follows

```<code>curl -i -X PUT -T testfile.txt "http://ip:port/webhdfs/v1/data?op=CREATE..."
</code>```

Question
How can I successfully upload a file on hdfs using curl?

答:
The reason for the Protocol Mismatch is given by cricket_007 in the comments

Based on your response, you've curled to an SSH server, not the namenode.

This was due to a wrong port in the curl -i -X PUT "http://ip:port/webhdfs/v1/...?op=CREATE" statement.

The default port is 50070 on the hortonworks sandboxs HDP distribution.

Body:
What I want to achieve
I want to move a file from my local Windows machine to HDFS using cURL. In my case HDFS is running on a virtual machine

What's not working
I'm using following command

curl -i -X PUT "http://ip:port/webhdfs/v1/...?op=CREATE"

I'm executing the above from Windows Command Prompt which I cd'ed to the folder containing the testfile.txt. The command returns the following

SSH-2.0-OpenSSH_5.3
Protocol mismatch.

Edit: According to this this I should be getting a response as

HTTP/1.1 307 TEMPORARY_REDIRECT
Location: http://<DATANODE>:<PORT>/webhdfs/v1/<PATH>?op=CREATE...
Content-Length: 0

Then I should be able to run the second step as follows

curl -i -X PUT -T testfile.txt "http://ip:port/webhdfs/v1/data?op=CREATE..."

Question
How can I successfully upload a file on hdfs using curl?


问:
get the sum of related items that contained in one group the returned on condition
this is related to another question get first record in group by result base on condition
to make it clear, I'll start from the beginning
this is my database structure create database testGroupfirst; go

```<code>use testGroupfirst;
go

create table testTbl (

id int primary key identity,name nvarchar(50) ,year int ,degree int , place  nvarchar(50)

)

insert into testTbl values ('jack',2015,50,'giza')
insert into testTbl values ('jack',2016,500,'cai')
insert into testTbl values ('jack',2017,660,'alex')
insert into testTbl values ('jack',2018,666,'giza')
insert into testTbl values ('jack',2011,50,'alex')
insert into testTbl values ('rami',2015,5054,'giza')
insert into testTbl values ('rami',2016,1500,'cai')
insert into testTbl values ('rami',2017,66220,'giza')
insert into testTbl values ('rami',2018,6656,'alex')
insert into testTbl values ('rami',2011,540,'cai')
insert into testTbl values ('jack',2010,50,'cai')
select * from testTbl
</code>```

this is the result till now

to get the latest 2 orders, etc  from a group by this could be solved by this code

```<code>SELECT name, year, degree, place
FROM
(SELECT name,degree, year,  place,
    ROW_NUMBER() OVER (PARTITION BY name ORDER BY degree desc) rn
     FROM testTbl
) t
WHERE rn in(1,2,3);

--another way
select t.*
from testTbl t
    cross apply (select top 2 id from testTbl t2 where t2.name = t.name order by degree desc) r
where t.id = r.id
</code>```

i need to get aggregate function like sum to get the sum of all related items in one group
i make a code like this

```<code>select t.*, sum (t.degree) as sumtest
from testTbl t
    cross apply (select top 2 id ,degree  , sum (degree) as sumtest from testTbl t2 where t2.place = t.place group by id,degree order by degree  ) r
where t.id = r.id group by t.id,t.name,t.place,t.year,t.degree
</code>```

but it didn't work like I thought as I need to make aggregate value not scalar for every item itself , i need to get the sum of all items in one group
what i need to get is what shown in this pic

答:
Use another window function:</p>

```<code>    SELECT name, year, degree, place, sum(degree) over (partition by name) as [sum]
    FROM
    (SELECT name,degree, year,  place,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY degree desc) rn
         FROM #testTbl
    ) t
    WHERE rn in(1,2,3);
</code>```

Body:
this is related to another question get first record in group by result base on condition
to make it clear, I'll start from the beginning
this is my database structure create database testGroupfirst; go

use testGroupfirst;
go

create table testTbl (

id int primary key identity,name nvarchar(50) ,year int ,degree int , place  nvarchar(50)

)

insert into testTbl values ('jack',2015,50,'giza')
insert into testTbl values ('jack',2016,500,'cai')
insert into testTbl values ('jack',2017,660,'alex')
insert into testTbl values ('jack',2018,666,'giza')
insert into testTbl values ('jack',2011,50,'alex')
insert into testTbl values ('rami',2015,5054,'giza')
insert into testTbl values ('rami',2016,1500,'cai')
insert into testTbl values ('rami',2017,66220,'giza')
insert into testTbl values ('rami',2018,6656,'alex')
insert into testTbl values ('rami',2011,540,'cai')
insert into testTbl values ('jack',2010,50,'cai')
select * from testTbl

this is the result till now

to get the latest 2 orders, etc  from a group by this could be solved by this code

SELECT name, year, degree, place
FROM
(SELECT name,degree, year,  place,
    ROW_NUMBER() OVER (PARTITION BY name ORDER BY degree desc) rn
     FROM testTbl
) t
WHERE rn in(1,2,3);

--another way
select t.*
from testTbl t
    cross apply (select top 2 id from testTbl t2 where t2.name = t.name order by degree desc) r
where t.id = r.id

i need to get aggregate function like sum to get the sum of all related items in one group
i make a code like this

select t.*, sum (t.degree) as sumtest
from testTbl t
    cross apply (select top 2 id ,degree  , sum (degree) as sumtest from testTbl t2 where t2.place = t.place group by id,degree order by degree  ) r
where t.id = r.id group by t.id,t.name,t.place,t.year,t.degree

but it didn't work like I thought as I need to make aggregate value not scalar for every item itself , i need to get the sum of all items in one group
what i need to get is what shown in this pic

Body:
Use another window function:

    SELECT name, year, degree, place, sum(degree) over (partition by name) as [sum]
    FROM
    (SELECT name,degree, year,  place,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY degree desc) rn
         FROM #testTbl
    ) t
    WHERE rn in(1,2,3);


问:
Loaded ubuntu + ROS kinetic (on dual booted W8.1 box)
Following YouTube ROS Course #1. All apps work,etc. Almost half way through ROS #1 tutorial, while in my catkin_ws$ directory (Per ROS Tutorial) I typed "catkin build [whatever]. Reply from ROS: "catkin: command not found" Any help appreciated. John.</p>

答: The command you want to write is catkin_build.


问:
How can I extract page numbers and id numbers from a URI?
I am trying to load my whole site through a single point of entry, index.php?uri

My goal is to have nice clean urls though, so far I have come up with...

domain.com/section-name/page-of-that-section

so the first part will load the class/file for the section (mail, users, account, etc.)

The 2nd part will load the class/page for the page of that section

This is pretty straight forward and easy so far.  The part that is tricky  for me is that some pages will have an ID number (user ID, message ID, blog ID, forum ID, forum post ID, forum topic ID, etc.) this will be used to look up that record in the database by id number.

Next, some pages will also have a page number used for paging.

So sometimes a page number will be present and sometime it will not, same with the id numbers depending on the section it is in.

I am looking for examples, advice, help on getting the page numbers and id numbers part working, I need to be able to get them and assign them to a variable $page_number  and
$id_number

Below is my code I have so far along with some example url's that I will need to access.  I do not want to use an existing framework for this, please help if you can I think I am getting close to getting this to work.

right now I have added id/ in front of id numbers and page/ in front of a paging number, this could be changed to anything (ie; id-423423 page-23 page/23  page23 p/23) as long as I can get the numbers to store to a variable in the PHP

```<code><?php
//get uri
$uri = isset( $_GET['uri'] ) ? $_GET['uri'] : null;

//put uri into array, everything in between '/' will be an array value
$uri1 = explode('/', $uri);

//the first array value will be the SECTION name/class
$section_name = $uri['0'];

//the second array value will always be the PAGE name/class
$page_name = $uri['1'];

//Now some pages will have numbers in the uri
// some are id numbers for things such as a message ID, users ID, comment ID, photo ID, blog ID
// then to complicate it even more sometimes, pages will need paging so will also have a page number in the uri
// I am looking for a way to detect if there is a ID number or page number in uri's for example like listed below.
// right now I have added id/ in front of id numbers and page/ in front of a paging number, this could be changed to anything **(ie; id-423423 page-23 page/23  page23 p/23)**

mail/inbox/
mail/inbox/page/12
mail/message/id/3432435

users/online/
users/online/page/234
users/profile/id/42234
users/comments/id/42234
users/comments/id/42234/page/3

blogs/list/id/42234
blogs/list/id/42234/page/25
blogs/viewpost/id/1323/
blogs/create/
blogs/edit/id/34453353

?>
</code>```

答:
The easiest way is to create a routing system, using regular expressions it's quite an easy task. You can also use some opensource stuff:

http://robap.github.com/php-router/

And here is mine for example (simple as a bottle of vodka, but working):

```<code>// for urls like http://mysite.com/1 or http://mysite.com/29 (any digit)
$ROUTE['(\d*)'] = 'pages/showPage/$1' ;
// for url http://mysite.com/admin/new-page
$ROUTE['admin\/new-page'] = 'pages/addPage' ;

function get_route($uri) {
    global $ROUTE ;
    $routes = $ROUTE ;

    foreach ($routes as $rUri => $rRoute) {
        if (preg_match("#^{$rUri}$#Ui", $uri)) {
            $route = preg_replace("#^{$rUri}$#Ui", $rRoute, $uri) ;
            break ;
        }
    }

    $route = explode('/', $route) ;
    $return['controller'] = array_shift($route) ;
    $return['action'] = array_shift($route) ;
    $return['params'] = empty($route) ? array() : $route ;

    return $return ;
}

//testing for http://mysite.com/2
$route = get_route( $_GET[ 'uri' ] ) ;
var_dump( $route ) ;
</code>```

Body:
I am trying to load my whole site through a single point of entry, index.php?uri

My goal is to have nice clean urls though, so far I have come up with...

domain.com/section-name/page-of-that-section

so the first part will load the class/file for the section (mail, users, account, etc.)

The 2nd part will load the class/page for the page of that section

This is pretty straight forward and easy so far.  The part that is tricky  for me is that some pages will have an ID number (user ID, message ID, blog ID, forum ID, forum post ID, forum topic ID, etc.) this will be used to look up that record in the database by id number.

Next, some pages will also have a page number used for paging.

So sometimes a page number will be present and sometime it will not, same with the id numbers depending on the section it is in.

I am looking for examples, advice, help on getting the page numbers and id numbers part working, I need to be able to get them and assign them to a variable $page_number  and
$id_number

Below is my code I have so far along with some example url's that I will need to access.  I do not want to use an existing framework for this, please help if you can I think I am getting close to getting this to work.

right now I have added id/ in front of id numbers and page/ in front of a paging number, this could be changed to anything (ie; id-423423 page-23 page/23  page23 p/23) as long as I can get the numbers to store to a variable in the PHP

<?php
//get uri
$uri = isset( $_GET['uri'] ) ? $_GET['uri'] : null;

//put uri into array, everything in between '/' will be an array value
$uri1 = explode('/', $uri);

//the first array value will be the SECTION name/class
$section_name = $uri['0'];

//the second array value will always be the PAGE name/class
$page_name = $uri['1'];

//Now some pages will have numbers in the uri
// some are id numbers for things such as a message ID, users ID, comment ID, photo ID, blog ID
// then to complicate it even more sometimes, pages will need paging so will also have a page number in the uri
// I am looking for a way to detect if there is a ID number or page number in uri's for example like listed below.
// right now I have added id/ in front of id numbers and page/ in front of a paging number, this could be changed to anything **(ie; id-423423 page-23 page/23  page23 p/23)**

mail/inbox/
mail/inbox/page/12
mail/message/id/3432435

users/online/
users/online/page/234
users/profile/id/42234
users/comments/id/42234
users/comments/id/42234/page/3

blogs/list/id/42234
blogs/list/id/42234/page/25
blogs/viewpost/id/1323/
blogs/create/
blogs/edit/id/34453353

?>

Body:
The easiest way is to create a routing system, using regular expressions it's quite an easy task. You can also use some opensource stuff:

http://robap.github.com/php-router/

And here is mine for example (simple as a bottle of vodka, but working):

// for urls like http://mysite.com/1 or http://mysite.com/29 (any digit)
$ROUTE['(\d*)'] = 'pages/showPage/$1' ;
// for url http://mysite.com/admin/new-page
$ROUTE['admin\/new-page'] = 'pages/addPage' ;

function get_route($uri) {
    global $ROUTE ;
    $routes = $ROUTE ;

    foreach ($routes as $rUri => $rRoute) {
        if (preg_match("#^{$rUri}$#Ui", $uri)) {
            $route = preg_replace("#^{$rUri}$#Ui", $rRoute, $uri) ;
            break ;
        }
    }

    $route = explode('/', $route) ;
    $return['controller'] = array_shift($route) ;
    $return['action'] = array_shift($route) ;
    $return['params'] = empty($route) ? array() : $route ;

    return $return ;
}

//testing for http://mysite.com/2
$route = get_route( $_GET[ 'uri' ] ) ;
var_dump( $route ) ;


问:
Liskov substitution principle or encapsulation violation
In this post I wanna to show you a little code example with several JS classes and ask you, whether this code is okay because of LSP or it violates encapsulation principles.

The _framesMonitor variable in this example is an instance of some 3-d party library vqt that we use inside Job class. _framesMonitor.stopListen() can throw exceptions, particularly vqt.Errors.ProcessExitError.

In this example below, is it okay to expose vqt.Errors.ProcessExitError type to the JobManager class (and it's okay because of LSP) or it violates
encapsulation revealing inner implementation details.

```<code>// Job.js
class Job {
  constructor() {
     this._framesMonitor = new FramesMonitor();
  }

  async stop() {
      await this._framesMonitor.stopListen();
  }
}

// JobsManager.js
class JobsManager {
  async deleteJob() {
    try {
      await job.stop();
    } catch(err) {
      // vqt.Errors.ProcessExitError here
    }
  }
}
</code>```

答:
In this case Job is a concrete class and JobManager depends on it directly so it is allowed to know the specifics of Job as long as your intent is to have only one kind of Job.

However, if you conceptually plan to have many different Job implementations (whether the language supports explicit interfaces or not) then ideally JobManager should attempt to treat all Job generically and should do it's best not to depend on any Job details.

Therefore, JobManager may catch any error, but shouldn't ideally drive it's workflow based on arbitrary error details. If JobManager must know some level of details to issue the appropriate compensating actions then you should try to come up with a normalized JobFailureError (or even a return value) that provides the necessary information (it could as well carry the low-level error cause for logging purpose).

Finally, if somehow you need special case handling for every kind of job which cannot be normalized then it will be a question of trade-offs.

To keep error handling out of Job concerns you could allow the registration of special job handling strategies with the JobManager. Although this approach adheres to the Open-Closed Principle (OCP) it is also an implementation of the Service Locator which some sees as an anti-pattern. When adding new Job implementations you would also need to remember to add a corresponding handler.

E.g.

```<code>jobManager.registerHandler('some-job-type', function (job) {
    //Special handling code job of some-job-type
});
</code>```

If you do not mind some level of coupling between the concept of an error handler and a Job then you could do something like new SomeJob(errorHandler) or even having SomeJob couple to a specific handler.

I'd usually go for the Service Locator approach here, but I'm not sure if we can say it's an absolute best in every similar scenarios.

For instance, if you were using a static typed language perhaps using double-dispatch techniques or even pattern matching if available would be better because you could get compile-time feedback.

Body:
In this post I wanna to show you a little code example with several JS classes and ask you, whether this code is okay because of LSP or it violates encapsulation principles.

The _framesMonitor variable in this example is an instance of some 3-d party library vqt that we use inside Job class. _framesMonitor.stopListen() can throw exceptions, particularly vqt.Errors.ProcessExitError.

In this example below, is it okay to expose vqt.Errors.ProcessExitError type to the JobManager class (and it's okay because of LSP) or it violates
encapsulation revealing inner implementation details.

// Job.js
class Job {
  constructor() {
     this._framesMonitor = new FramesMonitor();
  }

  async stop() {
      await this._framesMonitor.stopListen();
  }
}

// JobsManager.js
class JobsManager {
  async deleteJob() {
    try {
      await job.stop();
    } catch(err) {
      // vqt.Errors.ProcessExitError here
    }
  }
}

Body:
In this case Job is a concrete class and JobManager depends on it directly so it is allowed to know the specifics of Job as long as your intent is to have only one kind of Job.

However, if you conceptually plan to have many different Job implementations (whether the language supports explicit interfaces or not) then ideally JobManager should attempt to treat all Job generically and should do it's best not to depend on any Job details.

Therefore, JobManager may catch any error, but shouldn't ideally drive it's workflow based on arbitrary error details. If JobManager must know some level of details to issue the appropriate compensating actions then you should try to come up with a normalized JobFailureError (or even a return value) that provides the necessary information (it could as well carry the low-level error cause for logging purpose).

Finally, if somehow you need special case handling for every kind of job which cannot be normalized then it will be a question of trade-offs.

To keep error handling out of Job concerns you could allow the registration of special job handling strategies with the JobManager. Although this approach adheres to the Open-Closed Principle (OCP) it is also an implementation of the Service Locator which some sees as an anti-pattern. When adding new Job implementations you would also need to remember to add a corresponding handler.

E.g.

jobManager.registerHandler('some-job-type', function (job) {
    //Special handling code job of some-job-type
});

If you do not mind some level of coupling between the concept of an error handler and a Job then you could do something like new SomeJob(errorHandler) or even having SomeJob couple to a specific handler.

I'd usually go for the Service Locator approach here, but I'm not sure if we can say it's an absolute best in every similar scenarios.

For instance, if you were using a static typed language perhaps using double-dispatch techniques or even pattern matching if available would be better because you could get compile-time feedback.


问:
Need sql help: For each record in table A (has more columns than table B), insert into Table B
I know my subject is a little sparse, but for the life of me I cannot figure out how to do this.  I could accomplish this in C# but I am getting confused by the SQL syntax. I searched and searched and I can't seem to find what I am looking for probably because I don't understand some of the SQL that I am looking at.

```<code>TABLE 1
-----------
| CustNo | Catalog1 | Catalog2 | Catalog3 | Catalog4 |
|    1   |    A     |    B     |    C     |   NULL   |
|    2   |    B     |    C     |   NULL   |    D     |
|    3   |    A     |    C     |    E     |    F     |

TABLE 2 (empty)
COLUMNS: CustNo|Catalog
</code>```

So Basically for each record in Table 1, I want to insert the catalogs into table 2.
So the desired output would look like the following.

```<code>TABLE 2
CustNo|Catalog
|  1  |  A
|  1  |  B
|  1  |  C
|  2  |  B
|  2  |  C
|  2  |  D
|  3  |  A
|  3  |  C
|  3  |  E
|  3  |  F
</code>```

Thank you all for any help!

答:
Just unpivot.  I like to do this using apply;

```<code>insert into table2 (CustNo, Catalog)
    select t1.CustNo, v.Catalog
    from table1 t1 cross apply
         (values (t1.Catalog1), (t1.Catalog2), (t1.Catalog3), (t1.Catalog4)
         ) v(catalog)
    where v.Catalog is not null;
</code>```

Body:
I know my subject is a little sparse, but for the life of me I cannot figure out how to do this.  I could accomplish this in C# but I am getting confused by the SQL syntax. I searched and searched and I can't seem to find what I am looking for probably because I don't understand some of the SQL that I am looking at.

TABLE 1
-----------
| CustNo | Catalog1 | Catalog2 | Catalog3 | Catalog4 |
|    1   |    A     |    B     |    C     |   NULL   |
|    2   |    B     |    C     |   NULL   |    D     |
|    3   |    A     |    C     |    E     |    F     |

TABLE 2 (empty)
COLUMNS: CustNo|Catalog

So Basically for each record in Table 1, I want to insert the catalogs into table 2.
So the desired output would look like the following.

TABLE 2
CustNo|Catalog
|  1  |  A
|  1  |  B
|  1  |  C
|  2  |  B
|  2  |  C
|  2  |  D
|  3  |  A
|  3  |  C
|  3  |  E
|  3  |  F

Thank you all for any help!

Body:
Just unpivot.  I like to do this using apply;

insert into table2 (CustNo, Catalog)
    select t1.CustNo, v.Catalog
    from table1 t1 cross apply
         (values (t1.Catalog1), (t1.Catalog2), (t1.Catalog3), (t1.Catalog4)
         ) v(catalog)
    where v.Catalog is not null;


问:
Select all anchor tags based on href and Change it
i have a question regarding changing URL of anchor tags based on HREF.

What i do to select all anchor tags is like this:

```<code>var anchortags = document.querySelectorAll("a[href*='secureloan.asim.no']");
</code>```

With this i select all anchor tags that refers to secureloan.asim.no

What i want also is to CHANGE the links when user click on it (i want to remove a parameter)

example of URL can be:

Example URL:
www.secureloan.asim.no/oasis/index.html#/no/asim?lang=nb-no&product=lev&lanekilde=&campaigncode(etc....).

i want to remove "lanekilde=" from the parameter. im using this code:

```<code>String(document.location.href).replace("&lanekilde=", "");
</code>```

This gives me right URL but how do i change it for all users on website when they click on it.

Code ive made til now:

```<code>var anchortags= document.querySelectorAll("a[href*='secureloan.remember.no']");
String(document.location.href).replace("&lanekilde=", "");
</code>```

thank you :)

PS: NO Jquery please!

PS: im using tag manager if anyone has a idea of different way

答:
You just need to iterate over the nodeset and change each one in turn:</p>

```<code>var anchortags = document.querySelectorAll("a[href*='secureloan.asim.no']");
anchortags.forEach(function(tag) {
    tag.href = tag.href.replace('&lanekilde=', '');
});
</code>```

Body:
i have a question regarding changing URL of anchor tags based on HREF.

What i do to select all anchor tags is like this:

var anchortags = document.querySelectorAll("a[href*='secureloan.asim.no']");

With this i select all anchor tags that refers to secureloan.asim.no

What i want also is to CHANGE the links when user click on it (i want to remove a parameter)

example of URL can be:

Example URL:
www.secureloan.asim.no/oasis/index.html#/no/asim?lang=nb-no&product=lev&lanekilde=&campaigncode(etc....).

i want to remove "lanekilde=" from the parameter. im using this code:

String(document.location.href).replace("&lanekilde=", "");

This gives me right URL but how do i change it for all users on website when they click on it.

Code ive made til now:

var anchortags= document.querySelectorAll("a[href*='secureloan.remember.no']");
String(document.location.href).replace("&lanekilde=", "");

thank you :)

PS: NO Jquery please!

PS: im using tag manager if anyone has a idea of different way

Body:
You just need to iterate over the nodeset and change each one in turn:

var anchortags = document.querySelectorAll("a[href*='secureloan.asim.no']");
anchortags.forEach(function(tag) {
    tag.href = tag.href.replace('&lanekilde=', '');
});


问:
Importing png Files in Visual studio C++ Resource Editor
I would like to be able to import png file inside of Visual Studio Resource Editor so as to be able to use the embedded resource in different other projects . Is there a solution for that? I know that it works for bitmaps but i am interested in the pngs because of the "transparency" that is availble even on lower format [16x16] or [32x32] (but lacks for bitmaps).
Any ideas?
Thank you.</p>

答:
With VS 2008 you can import pngs and they will be recognized as an image, ie you will able to "see" it, but you will not be able to modify with within the resource editor.

But anyway the problem is that they will no be treated as bitmaps, so you can't embedded it inside a dialog. But you can access it with the usual FindResource/LockResource.

Also as MFC relies on GDI and it doesn't support natively PNG (at least on XP, I didn't try on Vista or Win7) you will need to convert them to BMP anyway. Here Gdi+ can be helpful.

Also I didn't check on VS 2010, perhaps worth a try if it have a better C++ resource editor.

OwnerDisplayName: seylom

OwnerDisplayName: xhantt


问:
python: writing a wrapper around a third-party class
I need some functionality from a class X of a third-party module m. I could just use m.X directly, but I may need to replace m.X with another class n.Y in the future (e.g., if I discover a better implementation).

I'd like to avoid changing the rest of the code in such a situation.

For now, I want the full interface of m.X, including initialization, to pass through unchanged. I wrote a wrapper W for m.X as follows:

```<code>class W(m.X):
    def __init__(self, *args):
        super().__init__(*args)
</code>```

In the future, should the need arise, I plan to rewrite the above as:

```<code>class W(n.Y):
    def __init__(self, *args):
        super().__init__(*args)
    # override instance methods of n.Y that don't share the semantics with m.X
    # for example, in case f1 is hard to replicate in n.Y:
    # def f1(self, *args):
    #     print("this method is no longer available")
    #     raise MyDeprecatedMethod()
    # for example, in case f2 needs to be recalculated
    # def f2(self, *args):
          # do the calculations required to keep W.f2 unchanged
</code>```

Is my current wrapper for m.X acceptable? Are there are problems with it, or with the planned wrapper for n.Y?

答:
You could simply use

```<code>class W(m.X):
    pass
</code>```

which inherits m.X.__init__() by default.

Body:
I need some functionality from a class X of a third-party module m. I could just use m.X directly, but I may need to replace m.X with another class n.Y in the future (e.g., if I discover a better implementation).

I'd like to avoid changing the rest of the code in such a situation.

For now, I want the full interface of m.X, including initialization, to pass through unchanged. I wrote a wrapper W for m.X as follows:

class W(m.X):
    def __init__(self, *args):
        super().__init__(*args)

In the future, should the need arise, I plan to rewrite the above as:

class W(n.Y):
    def __init__(self, *args):
        super().__init__(*args)
    # override instance methods of n.Y that don't share the semantics with m.X
    # for example, in case f1 is hard to replicate in n.Y:
    # def f1(self, *args):
    #     print("this method is no longer available")
    #     raise MyDeprecatedMethod()
    # for example, in case f2 needs to be recalculated
    # def f2(self, *args):
          # do the calculations required to keep W.f2 unchanged

Is my current wrapper for m.X acceptable? Are there are problems with it, or with the planned wrapper for n.Y?

Body:
You could simply use

class W(m.X):
    pass

which inherits m.X.__init__() by default.


问:
Remove unmixed numbers from file
Say I have a file called input.txt that looks like this

```<code>I listened to 4 u2 albums today
meet me at 5
squad 4ever
</code>```

I want to filter out the numbers that are on their own, so "4" and "5" should go but "u2" and "4ever" should remain the same. i.e the output should be

```<code>I listened to u2 albums today
meet me at
squad 4ever
</code>```

I've been trying to use this code

```<code>for line in fileinput.input("input.txt", inplace=True):
    new_s = ""
    for word in line.split(' '):
        if not all(char.isdigit() for char in word):
            new_s += word
            new_s += ' '
    print(new_s, end='')
</code>```

Which is pretty similar to the code I found here: Removing numbers mixed with letters from string

But instead of the wanted output I get

```<code>I listened to u2 albums today
 meet me at 5
 squad 4ever
</code>```

As you can see there are two problems here, first only the first line loses the digit I want it to lose, "5" is still present in the second line. The second problem is the extra white space at the beginning of a new line.

I've been playing around with the code for a while and browsing stackoverflow, but can't find where the problem is coming from. Any insights?

答:
Just use regexp.

```<code>re.sub(r"\b\d+\b", "", input)
</code>```

match any digit between word boundaries

Or to avoid double spaces:

```<code>re.sub(r"\s\d+\s", " ", input)
</code>```

Title: Remove unmixed numbers from file

Body:
Say I have a file called input.txt that looks like this

I listened to 4 u2 albums today
meet me at 5
squad 4ever

I want to filter out the numbers that are on their own, so "4" and "5" should go but "u2" and "4ever" should remain the same. i.e the output should be

I listened to u2 albums today
meet me at
squad 4ever

I've been trying to use this code

for line in fileinput.input("input.txt", inplace=True):
    new_s = ""
    for word in line.split(' '):
        if not all(char.isdigit() for char in word):
            new_s += word
            new_s += ' '
    print(new_s, end='')

Which is pretty similar to the code I found here: Removing numbers mixed with letters from string

But instead of the wanted output I get

I listened to u2 albums today
 meet me at 5
 squad 4ever

As you can see there are two problems here, first only the first line loses the digit I want it to lose, "5" is still present in the second line. The second problem is the extra white space at the beginning of a new line.

I've been playing around with the code for a while and browsing stackoverflow, but can't find where the problem is coming from. Any insights?

Body:
Just use regexp.

re.sub(r"\b\d+\b", "", input)

match any digit between word boundaries

Or to avoid double spaces:

re.sub(r"\s\d+\s", " ", input)


问:
c# mocking IFormFile CopyToAsync() method
I am working on a unit test for an async function that converts a list of IFormFile to a list of my own arbitrary database file classes.

The method that converts the file data to a byte array is:

```<code>internal async Task<List<File>> ConvertFormFilesToFiles(ICollection<IFormFile> formFiles)
{
    var file = new File
    {
        InsertDateTime = DateTime.Now,
        LastChangeDateTime = DateTime.Now
    };
    if (formFile.Length > 0)
    {
        using (var memoryStream = new MemoryStream())
        {
            await formFile.CopyToAsync(memoryStream, CancellationToken.None);
            file.FileData = memoryStream.ToArray();
        }
    }
    // ...
}
</code>```

The function receives an ICollection of IFormFiles so it is mockable.

For now I have test code like this:

```<code>//Arrange
var fileConverter = new FilesConverter();
using (var fileStream = new FileStream("Files/uploadme.txt", FileMode.Open, FileAccess.Read))
{
    using (var memoryStream = new MemoryStream())
    {
        var newMemoryStream = new MemoryStream();
        fileStream.CopyTo(memoryStream);
        FormFileMock.Setup(f => f.CopyToAsync(newMemoryStream, CancellationToken.None)).Returns(Task.CompletedTask);
        // some other setups

        //Act
        var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { FormFileMock.Object });
        //Assert
        Assert.IsTrue(result.Any());
    }
}
</code>```

The newMemoryStream variable is created because the function calls the CopyToAsync method with a new and empty memorystream (I'm not sure if this is necessary).

The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

答:
I combined the answers of @Nkosi and @nvoigt. As @nvoigt pointed out: access to a real file should really not be in a "unit" test. So I replaced the file with a byte array like so:

```<code>using (var memoryStream = new MemoryStream(new byte[]{1,2,3,4}))
</code>```

Instead of a complete file.

And I implemented the .callback on the mocked object as suggested by @Nkosi

```<code>FormFileMock.Setup(f => f.CopyToAsync(It.IsAny<Stream>(), CancellationToken.None))
    .Callback<Stream, CancellationToken>((stream, token) =>
    {
        // with memoryStream being the stream from inside the using statement
        memoryStream.CopyTo(stream);
    }).Returns(Task.CompletedTask);
</code>```

And now it works.

Body:
I am working on a unit test for an async function that converts a list of IFormFile to a list of my own arbitrary database file classes.

The method that converts the file data to a byte array is:

internal async Task<List<File>> ConvertFormFilesToFiles(ICollection<IFormFile> formFiles)
{
    var file = new File
    {
        InsertDateTime = DateTime.Now,
        LastChangeDateTime = DateTime.Now
    };
    if (formFile.Length > 0)
    {
        using (var memoryStream = new MemoryStream())
        {
            await formFile.CopyToAsync(memoryStream, CancellationToken.None);
            file.FileData = memoryStream.ToArray();
        }
    }
    // ...
}

The function receives an ICollection of IFormFiles so it is mockable.

For now I have test code like this:

//Arrange
var fileConverter = new FilesConverter();
using (var fileStream = new FileStream("Files/uploadme.txt", FileMode.Open, FileAccess.Read))
{
    using (var memoryStream = new MemoryStream())
    {
        var newMemoryStream = new MemoryStream();
        fileStream.CopyTo(memoryStream);
        FormFileMock.Setup(f => f.CopyToAsync(newMemoryStream, CancellationToken.None)).Returns(Task.CompletedTask);
        // some other setups

        //Act
        var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { FormFileMock.Object });
        //Assert
        Assert.IsTrue(result.Any());
    }
}

The newMemoryStream variable is created because the function calls the CopyToAsync method with a new and empty memorystream (I'm not sure if this is necessary).

The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

Body:
I combined the answers of @Nkosi and @nvoigt. As @nvoigt pointed out: access to a real file should really not be in a "unit" test. So I replaced the file with a byte array like so:

using (var memoryStream = new MemoryStream(new byte[]{1,2,3,4}))

Instead of a complete file.

And I implemented the .callback on the mocked object as suggested by @Nkosi

FormFileMock.Setup(f => f.CopyToAsync(It.IsAny<Stream>(), CancellationToken.None))
    .Callback<Stream, CancellationToken>((stream, token) =>
    {
        // with memoryStream being the stream from inside the using statement
        memoryStream.CopyTo(stream);
    }).Returns(Task.CompletedTask);

And now it works.


问:
Ecto.Query joins generates far too many INNER JOIN
Not sure why Ecto is returning the incorrect result.
I might be messing things up with joins

This is my Ecto.Query

```<code>from u in User,
        join: c in assoc(u, :companies),
        join: r in assoc(c, :roles),
        join: a in assoc(r, :assets),
        where: u.id == ^2 and a.id == ^1,
        group_by: [c.id, u.id, r.id],
        select: {u.email, u.id, r.name, c.name}
</code>```

It generates:

```<code>    SELECT u0."email", u0."id", r2."name", c1."name"
FROM "users" AS u0
INNER JOIN "access_lists" AS a4 ON a4."user_id" = u0."id"
INNER JOIN "companies" AS c1 ON a4."company_id" = c1."id"
INNER JOIN "access_lists" AS a5 ON a5."company_id" = c1."id"
INNER JOIN "roles" AS r2 ON a5."role_id" = r2."id"
INNER JOIN "access_lists" AS a6 ON a6."role_id" = r2."id"
INNER JOIN "assets" AS a3 ON a6."asset_id" = a3."id"
 WHERE ((u0."id" = $1) AND (a3."id" = $2))
GROUP BY c1."id", u0."id", r2."id" [2, 1]
</code>```

The result of this query is incorrect

this is the correct query:

```<code>SELECT u0.email, u0.id, r2.name, c1.name, a6.asset_name , a6.id as asset_id
FROM users AS u0
INNER JOIN access_lists AS a4 ON a4.user_id = u0.id
INNER JOIN assets AS a6 ON a4.asset_id = a6.id
INNER JOIN companies AS c1 ON a4.company_id = c1.id
INNER JOIN roles AS r2 ON a4.role_id = r2.id
WHERE ((u0.id = 2) AND (a6.id = 1))
Group By u0.id, r2.id, c1.id, a6.id
</code>```

Here is the schemas:

AccessList:

```<code>  schema "access_lists" do
        belongs_to :user, Db.User
        belongs_to :role, Db.Role
        belongs_to :asset, Db.Asset
        belongs_to :project, Db.Project
        belongs_to :company, Db.Company

        timestamps()
    end
</code>```

User:

```<code>many_to_many :roles, Db.Role, join_through: Db.AccessList
many_to_many :assets, Db.Asset, join_through: Db.AccessList
many_to_many :projects, Db.Project, join_through: Db.AccessList
many_to_many :companies, Db.Company, join_through: Db.AccessList
</code>```

Asset:

```<code>many_to_many :users, Db.User, join_through: Db.AccessList
many_to_many :companies, Db.Company, join_through: Db.AccessList
many_to_many :roles, Db.Role, join_through: Db.AccessList
many_to_many :projects, Db.Project, join_through: Db.AccessList
</code>```

Company:

```<code>    many_to_many :users, Db.User, join_through: Db.AccessList
    many_to_many :assets, Db.Asset, join_through: Db.AccessList
    many_to_many :roles, Db.Role, join_through: Db.AccessList
    many_to_many :projects, Db.Project, join_through: Db.AccessList
</code>```

Role:

```<code>    many_to_many :users, Db.User, join_through: Db.AccessList
    many_to_many :assets, Db.Asset, join_through: Db.AccessList
    many_to_many :projects, Db.Project, join_through: Db.AccessList
    many_to_many :companies, Db.Company, join_through: Db.AccessList
</code>```

Here is a diagram:

答:
Without seeing the schemas, it's difficult to tell, but I can make some guesses. Since AccessList is the join table between the User and companies, roles, and assets, Ecto doesn't know well enough to reuse the previous AccessList query in subsequent joins.

Try explicitly mapping it out like this:

```<code>from u in User,
  join: acl in assoc(u, :access_lists),
  join: c in assoc(acl, :companies),
  join: r in assoc(acl, :roles),
  join: a in assoc(acl, :assets),
  where: u.id == ^2 and a.id == ^1,
  group_by: [c.id, u.id, r.id],
  select: {u.email, u.id, r.name, c.name}
</code>```

Body:
Not sure why Ecto is returning the incorrect result.
I might be messing things up with joins

This is my Ecto.Query

from u in User,
        join: c in assoc(u, :companies),
        join: r in assoc(c, :roles),
        join: a in assoc(r, :assets),
        where: u.id == ^2 and a.id == ^1,
        group_by: [c.id, u.id, r.id],
        select: {u.email, u.id, r.name, c.name}

It generates:

    SELECT u0."email", u0."id", r2."name", c1."name"
FROM "users" AS u0
INNER JOIN "access_lists" AS a4 ON a4."user_id" = u0."id"
INNER JOIN "companies" AS c1 ON a4."company_id" = c1."id"
INNER JOIN "access_lists" AS a5 ON a5."company_id" = c1."id"
INNER JOIN "roles" AS r2 ON a5."role_id" = r2."id"
INNER JOIN "access_lists" AS a6 ON a6."role_id" = r2."id"
INNER JOIN "assets" AS a3 ON a6."asset_id" = a3."id"
 WHERE ((u0."id" = $1) AND (a3."id" = $2))
GROUP BY c1."id", u0."id", r2."id" [2, 1]

The result of this query is incorrect

this is the correct query:

SELECT u0.email, u0.id, r2.name, c1.name, a6.asset_name , a6.id as asset_id
FROM users AS u0
INNER JOIN access_lists AS a4 ON a4.user_id = u0.id
INNER JOIN assets AS a6 ON a4.asset_id = a6.id
INNER JOIN companies AS c1 ON a4.company_id = c1.id
INNER JOIN roles AS r2 ON a4.role_id = r2.id
WHERE ((u0.id = 2) AND (a6.id = 1))
Group By u0.id, r2.id, c1.id, a6.id

Here is the schemas:

AccessList:

  schema "access_lists" do
        belongs_to :user, Db.User
        belongs_to :role, Db.Role
        belongs_to :asset, Db.Asset
        belongs_to :project, Db.Project
        belongs_to :company, Db.Company

        timestamps()
    end

User:

many_to_many :roles, Db.Role, join_through: Db.AccessList
many_to_many :assets, Db.Asset, join_through: Db.AccessList
many_to_many :projects, Db.Project, join_through: Db.AccessList
many_to_many :companies, Db.Company, join_through: Db.AccessList

Asset:

many_to_many :users, Db.User, join_through: Db.AccessList
many_to_many :companies, Db.Company, join_through: Db.AccessList
many_to_many :roles, Db.Role, join_through: Db.AccessList
many_to_many :projects, Db.Project, join_through: Db.AccessList

Company:

    many_to_many :users, Db.User, join_through: Db.AccessList
    many_to_many :assets, Db.Asset, join_through: Db.AccessList
    many_to_many :roles, Db.Role, join_through: Db.AccessList
    many_to_many :projects, Db.Project, join_through: Db.AccessList

Role:

    many_to_many :users, Db.User, join_through: Db.AccessList
    many_to_many :assets, Db.Asset, join_through: Db.AccessList
    many_to_many :projects, Db.Project, join_through: Db.AccessList
    many_to_many :companies, Db.Company, join_through: Db.AccessList

Here is a diagram:

Body:
Without seeing the schemas, it's difficult to tell, but I can make some guesses. Since AccessList is the join table between the User and companies, roles, and assets, Ecto doesn't know well enough to reuse the previous AccessList query in subsequent joins.

Try explicitly mapping it out like this:

from u in User,
  join: acl in assoc(u, :access_lists),
  join: c in assoc(acl, :companies),
  join: r in assoc(acl, :roles),
  join: a in assoc(acl, :assets),
  where: u.id == ^2 and a.id == ^1,
  group_by: [c.id, u.id, r.id],
  select: {u.email, u.id, r.name, c.name}