text:
Q: An automatic regex learner? I have strings with recurrent pattern. Like that:
/socket.io/1/xhr-polling/993bcoZK7UkiqsNYpbja?t=1407502307019
/socket.io/1/xhr-polling/993bcoZK7UkiqsNYpbja?t=2222222222222
/socket.io/1/xhr-polling/993bco56465456465465a?t=333333333333

And also thing like that:
/api/bucket/53e4ce6584df65130e7ead66/data/metadata
/api/bucket/465456456456465456445456/data/metadata
/api/bucket/898989898989898989898989/data/metadata

And much more like that.
How would be the best way to find patterns in these strings and to aggregate them ?
Like getting some sort of json:
{
   pattern : "/api/bucket/*/data/metadata"
   routes : ["/api/bucket/53e4ce6584df65130e7ead66/data/metadata",
             "/api/bucket/465456456456465456445456/data/metadata",
             "/api/bucket/898989898989898989898989/data/metadata"]
}

A: Ok found the solution, the Aho-Corasick matching algorithm referenced in the answer is not adapted. Levenshtein distance algorithm is. If found this module for Node.JS to do that: https://github.com/jefarmstrong/sortzzy


text:
Q: How to replace sting with punctuation and convert? I need to replace a phone string with punctuation inside and then convert it to int value.
I try to perform this query but i get all null because of the use of 'try_convert'.
Select replace(replace(replace(replace(replace(replace(phone, '-', ''), '(', ''), ')', ''), ' ',''), '0',''), '.', '') as phone, TRY_CONVERT (int, phone)
From sales. Customers

A: You can use a function to strip all non-numeric characters from your input string.
Here's a variation I use.
CREATE FUNCTION usf_StripNonNumeric
(
    @Input varchar(100)
)
RETURNS varchar(MAX)
AS
BEGIN
    DECLARE @r    VARCHAR(MAX) = ''
            ,@len INT
            ,@c   CHAR(1)
            ,@x   INT          = 0;

    SELECT @len  = LEN(@Input);

    WHILE @x <= @len
    BEGIN
        SELECT @c  = SUBSTRING(@Input, @x, 1);

        IF ISNUMERIC(@c) = 1 AND @c <> '-' SELECT @r   = @r + @c;

        SELECT @x  = @x + 1;
    END;

    RETURN @r;
END;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle SQL decimal precision on Select Hello i have a database column called price and the data in it is .1
I want to select this column using a select query and return it back to the application with 0.10. Is this possible to do this when selecting the column?
Thanks

A: Do you want to return a number to the application?  Or a string?
If you want to return a number, you don't care about the formatting.
If you want to return a string, you can use the TO_CHAR function with the format mask 'fm0.00'
  1* select to_char( .1, 'fm0.00' ) from dual
SQL> /

TO_CH
-----
0.10

A: SELECT TO_CHAR(column, '0.99')
FROM   table


text:
Q: Search Attached Sources in Eclipse Is there any way that Eclipse will let me search within attached sources of referenced libraries?
I'm trying to find all the places where a public static final String constant is used.

A: Select needed text and press CTRL + ALT + G. It performs search on whole workspace.


text:
Q: How to get deleted object information from association relation in ruby on rails I have 3 tables, Teacher/Int_Teacher_Student/Student, here is the schema:
class Teacher < ActiveRecord::Base
   self.table_name = 'teacher_table'
   has_many :teacher_students, primary_key: :teacher_id, foreigh_key: :int_teacher_id, dependent: destroy
   has_many :students, through :teacher_students

class TeacherStudent <ActiveRecord::Base
   self.table_name= 'int_teacher_student'
   belongs_to :teacher, primary_key: :teacher_id, foreign_key: :int_teacher_id, touch: true
   belongs_to :student, primary_key: :student_id, foreign_key: :int_student_id, touch: true

 class Student < ActiveRecord::Base
   self.table_name = 'int_student'
   has_many :teacher_students, primary_key: :student_id, foreigh_key: :int_student_id, dependent: destroy
   has_many :teachers, through :teacher_students

I have a task to show teacher name after either teacher or student record changed.
I have some code in Teacher class:
   def print_teacher_name
       puts "teacher name #{self.name}"
   end

And in Student class:
 after_commit :print_teacher_name
  def  print_teacher_name
       self.teachers.each do |teacher|
          teacher.print_teacher_name
       end
  end

And in TeacherStudent class:
  after_commit :print_teacher_name
  def  print_teacher_name
       self.teacher.print_teacher_name
  end

When a student or teacher deleted, or when a teacher added to a student, this works fine. But when a teacher removed from a student, the call doesn't fire. Looks to me that the print_teacher_name in TeacherStudent class didn't get fired for such situation, but I do see that the record removed from that table. Anyone can give me some idea what I can try to resolve this? Thanks.


text:
Q: Error- local variable referenced before assignment What I'm sure is another simple error, but I'm going around in circles. I'm trying to get it to show the first 10 lines in a csv using a function. I can get 1 line to show before it throws an error. Maybe my rows=0 needs to be moved down further, but I'm not sure and my attempts at moving it hasn't worked?

rows = 0

def lines():
    with open('iamacsvfile.csv') as file:
        dictreader = csv.DictReader(file)
        for row in dictreader:
            print(row)
            rows=rows+1
            if(rows>=10):
                break

lines()

UnboundLocalError                         Traceback (most recent call last)
Input In [57], in <cell line: 14>()
     11             if(rows>=5):
     12                 break
---> 14 lines()

Input In [57], in lines()
      8 for row in dictreader:
      9     print(row)
---> 10     rows=rows+1
     11     if(rows>=5):
     12         break

UnboundLocalError: local variable 'rows' referenced before assignment

A: This should work:
def lines():
    rows = 0
    with open('iamacsvfile.csv') as file:
        dictreader = csv.DictReader(file)
        for row in dictreader:
            print(row)
            rows=rows+1
            if(rows>=10):
                break

lines()

A: Your rows is outside the function so the lines function cannot access the variable. Try moving rows inside the lines function like this.
def lines():
    rows = 0

    with open('iamacsvfile.csv') as file:
        dictreader = csv.DictReader(file)
        for row in dictreader:
            print(row)
            rows=rows+1
            if(rows>=10):
                break

lines()

A: You haven't defined rows.
But you don't need that, since csv.DictReader has line_num property, which increases with each iteration. It's better to use:
for row in dictreader:
    print(row)
    if dictreader.line_num >= 10:
        break


text:
Q: Keep a thread running even when hitting a breakpoint I wish to develop a debugging service that needs to run constantly in the background, even when I hit a breakpoint -- especially during those moments. Is there any way I could do that, other than having to manually unfreeze the specific thread in the thread window ? I'd like it to be something I don't have to take care of manually. I thought about creating a thread that run inside another appDomain, but I bet that thread will also end up frozen when I hit a breakpoint. I have not tested it though.

A: I found a solution. I will make a visual studio extension. I did some tests and it's possible to have a thread running in the background all the time within an extension
Here's a simple proof of concept that keeps emiting the result of an evaluation, even when the debugger hits a breakpoint:
private Command1(AsyncPackage package, OleMenuCommandService commandService)
{
    Task.Run(() => {
        DTE dte = (DTE)ServiceProvider.GetServiceAsync(typeof(DTE)).Result;
        while (true)
        {
            Expression ex2 = dte.Debugger.GetExpression("WinFormsApp1.Test.RunStatic(str);");
            Debug.WriteLine("### " + ex2.Value);
            Thread.Sleep(1000);
        }
    }
}

The logic starts when Command1 is initialized, which won't be appropriate for the real thing, but good enough for the POC.


text:
Q: Magento 2: How to reduce column width in admin grid? I want to change column width. I don't want any scroller due to a large column width in admin grid.
Here is the code. I am using:
<block class="Magento\Backend\Block\Widget\Grid\Column" as="api_params">
    <arguments>
        <argument name="header" xsi:type="string" translate="true">API Parameters</argument>
        <argument name="index" xsi:type="string">api_params</argument>
        <argument name="type" xsi:type="string">text</argument>
        <argument name="width" xsi:type="string">60</argument>
        <argument name="column_css_class" xsi:type="string">col-id</argument>
        <argument name="header_css_class" xsi:type="string">col-id</argument>
    </arguments>
</block>

Screenshot:


text:
Q: Convert Microsoft WGL4 charmap to wxString? I have some mutibyte data that are specified as "Microsoft WGL4 charmap, matching Unicode" which are returned from an external library.
These bultibyte data e.g. are some stuff like
}0fšÔ

(continues after that, the total length of this string is 16 bytes).
Now I want to convert them to a wxString showing the correct Unicode representation of them. But when I use these data as UTF8 and generate the wxString via wxString::FromUTF8(), the result is an empty string. When I use the data as UTF16 BE and convert via wxMBConvUTF16BE, the result is a hige string containing some crap only.
So...any idea how to correctly convert these "Microsoft WGL4 charmap" data to a wxString?
Thanks!


text:
Q: How to Wrap a JS Encapsulating Function Around a Directive I have seen this done before, I am trying to implement an encapsulating function, but it breaks my directive. Without the encapsulation it works. Has anyone done this before or does anyone know why it breaks the directive?
https://jsfiddle.net/ciderman/a0n9h0ar/1/
(function () {
  myApp.directive('myPerfectDirective', function(){
    return{
      restrict: 'E',
      scope: {
        data: '='
      },
      template: '
my perrrrrrfeccct directivve
',
      templateUrl: 'book-widget.html'
    }
  });
});

A: What you're talking about is called an IIFE (Immediately-invoked function expression).
You've got part of it right, the problem as Alejandro has pointed out you're missing the () which will invoke the function.
So change your code to look like this:
(function () {
  myApp.directive('myPerfectDirective', function(){
    return{
      restrict: 'E',
      scope: {
        data: '='
      },
      template: '
my perrrrrrfeccct directivve
',
      templateUrl: 'book-widget.html'
    }
  });
})();

For more information on IIFE(pronounced IIFY) look here What is the (function() { } )() construct in JavaScript?


text:
Q: JSF Chrome Save Password on Login form How do I get my JSF login page to prompt Chrome to save password?
    <h:form id="login-form" class="form login-form">

                <h:outputLabel for="j_username" value="Email:" />
                <p:inputText value="#{loginBean.j_username}" id="j_username"
                    required="true">
                </p:inputText>

                <h:outputLabel for="j_password" value="Password:" />
                <h:inputSecret value="#{loginBean.j_password}" id="j_password"
                    required="true">

            <p:commandButton id="loginButton"
                value="Login"  action="#{loginBean.login}" />

        </h:form>

A: Turn off ajax by ajax="false" on the <p:commandButton>. For security reasons, Chrome won't save passwords of ajax login forms.
If that also doesn't help, then go to Settings > Show advanced settings > Manage  saved passwords (or go to chrome://settings/passwords in Chrome) and scroll to the very bottom of the list to see if the site in question isn't accidently covered by "Never saved" list.


text:
Q: jQuery UI Datepicker and bassistance.de validation plugin problem I have the jQuery UI Datepicker and the bassistance.de validation plugin working except for one problem.  When a date is selected with the date picker, it causes a validation error even though the date is correct.  I have tried it on different sites and I get the same problem.  It doesn't cause a validation error when you click submit.

A: I think I found the answer. The problem is that the jQuery validation plugin is validating on the click, keyup, or onfocusout event. Not sure which one. I just disable these so it would only do it on submit which looks cleaner for my implementation anyway.
These are the values I set to false:
onfocusout: false,
onkeyup: false,
onclick: false

A: I had this problem when I used the datepicker with default settings.
When I stepped through, it looked like the issue is validation gets called when you select a new date on the picker, but gets passed the existing value, not the one you've just selected.
After the picker closes, you're no longer in the input, so the validation doesn't fire again, meaning it never gets called with the correct value.
Using a button and the fix at JQuery UI Datepicker loses focus when selecting date with mouse I was able to get the two playing nicely together.  That is, after selecting a new date, the focus is still on the date input, and tabbing/clicking out causes validation to fire correctly.


text:
Q: ERROR StatusLogger Error processing element BatchDelivery ([appenders: null]): CLASS_NOT_FOUND I was trying to send logs to elastic search but my log4j2 file shows this error. Can anyone help me out of this. Thanks in advance.
TestLogger.java
public class TestLogger {
 private static final Logger logger = LogManager.getLogger(TestLogger.class);

    public static void main(String[] args) {

        logger.info("Hello World !");

        logger.info("Hello ElasticSearch !");
    }
}

log4j2.xml

<Appenders>

    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="[%d{ABSOLUTE}][%-5p][%-25c][%t] %m%n" />
    </Console>

        <BatchDelivery batchSize="10000" deliveryInterval="1000">
        <NoSql name="elasticsearchAppender">
        <Elasticsearch url="http://10.162.205.175:9200/_bulk" index="data_upload_assignment" type="log4j2">
        </Elasticsearch>
        </NoSql>
        </BatchDelivery>

</Appenders>

<loggers>
    <!-- <logger name="com.ait.TestLogger">
        <appender-ref ref="elasticsearchAppender" />
    </logger>-->

    <root level="ALL">
        <appender-ref ref="Console" />
        <appender-ref ref="elasticsearchAppender" />
    </root>
</loggers>


text:
Q: Display element just once only on scrolling up or down when in viewport (waypoints) I'm using jquery waypoints (http://imakewebthings.com/jquery-waypoints/#docs) to check if an element is the view of the browser
I want to display element just once only on scrolling up or down when in viewport ...here the js
var inview = new Waypoint.Inview({
element: $('#waypoint')[0],
enter: function(direction) {
if (direction === 'down') {

    setTimeout(function() {
 $('#first').hide('fast');
 }, 500); // <-- time in milliseconds

 setTimeout(function() {
  $('#second').fadeIn("fast");;
  }, 500); // <-- time in milliseconds

   }
if (direction === 'up') {

    setTimeout(function() {
 $('#first').hide('fast');
 }, 500); // <-- time in milliseconds

 setTimeout(function() {
  $('#second').fadeIn("fast");;
  }, 500); // <-- time in milliseconds

   }

    }
  })

This code is working perfectly when scrolling is down but not working when scrolling is up.
I want when detect position is down run only the down function and when detect the position is up run only the function up


text:
Q: IBM JSF Date Picker hx:inputHelperDatePicker Accessibility Issue I'm using the IBM JSF to build the application, and I found that there's a bug with the little calendar date picker component hx:inputHelperDatePicker, which is that the Date picker icons can only be accessible and opened once with a keyboard or mouse. The little calendar will only popup for the first time I click on the date picker icon, after that it would not be accessible any more. And here's the code:
import com.ibm.faces.component.html.HtmlInputHelperDatePicker;
protected HtmlInputHelperDatePicker datePicker;
protected HtmlInputHelperDatePicker getDatePicker() {
        if (datePicker == null) {
            datePicker = (HtmlInputHelperDatePicker) findComponentInRoot("datePicker");
        }
        return datePicker;

JSP part:
<h:inputText
    styleClass="inputText" id="actualDate"
    value="#{announcementInfoBean.announcementDetail.actual_announcement_date}">
    <hx:inputHelperDatePicker />
    <hx:validateDateTimeRange
        minimum="1978/03/01" maximum="#{sessionScope.userSession.systemDate}" />
    <f:convertDateTime  pattern="MMM-dd-yyyy" />
    </h:inputText>

    <h:message styleClass="message" id="message_actualDate"
        for="actualDate"></h:message>

Does anyone how to fix this?


text:
Q: Fade in/out on scroll divs are invisible Basically, what I want to happen is a class of divs to fade in/out on scroll. It seems to work perfectly on this jsfiddle page.
The only change I made to the code was adding this plug-in, but it still doesn't seem to work, and the posts are just invisible:

Am I perhaps using the wrong plug-in?

A: *

*Did you include the JavasScript?

$(window).on("load",function() {
    function fade() {
        $('.fade').each(function() {
            /* Check the location of each desired element */
            var objectBottom = $(this).offset().top + $(this).outerHeight();
            var windowBottom = $(window).scrollTop() + $(window).innerHeight();

            /* If the object is completely visible in the window, fade it in */
            if (objectBottom < windowBottom) { //object comes into view (scrolling down)
                if ($(this).css('opacity')==0) {$(this).fadeTo(500,1);}
            } else { //object goes out of view (scrolling up)
                if ($(this).css('opacity')==1) {$(this).fadeTo(500,0);}
            }
        });
    }
    fade(); //Fade in completely visible elements during page-load
    $(window).scroll(function() {fade();}); //Fade in elements during scroll
});

*Did you call the script after jQuery loaded?

*Did you include the CSS?

.fade {
    margin: 50px;
    padding: 50px;
    background-color: lightgreen;
    opacity: 0;
}

*Did you include the HTML?

Fade In 01

Fade In 02

Fade In 03

Fade In 04

Fade In 05

Fade In 06

Fade In 07

Fade In 08

Fade In 09

Fade In 10

*Did you make it HTML5?

Here is the complete code to make it work.

$(window).on("load",function() {
    function fade() {
        $('.fade').each(function() {
            /* Check the location of each desired element */
            var objectBottom = $(this).offset().top + $(this).outerHeight();
            var windowBottom = $(window).scrollTop() + $(window).innerHeight();

            /* If the object is completely visible in the window, fade it in */
            if (objectBottom < windowBottom) { //object comes into view (scrolling down)
                if ($(this).css('opacity')==0) {$(this).fadeTo(500,1);}
            } else { //object goes out of view (scrolling up)
                if ($(this).css('opacity')==1) {$(this).fadeTo(500,0);}
            }
        });
    }
    fade(); //Fade in completely visible elements during page-load
    $(window).scroll(function() {fade();}); //Fade in elements during scroll
});
.fade {
    margin: 50px;
    padding: 50px;
    background-color: lightgreen;
    opacity: 0;
}

Fade In 01

Fade In 02

Fade In 03

Fade In 04

Fade In 05

Fade In 06

Fade In 07

Fade In 08

Fade In 09

Fade In 10

A: Include jquery sourcefile in head portion, You have to load jquery file first.

You have to load jquery before running the snippet of code
$(window).on("load",function() {
    function fade() {
        $('.fade').each(function() {
            /* Check the location of each desired element */
            var objectBottom = $(this).offset().top + $(this).outerHeight();
            var windowBottom = $(window).scrollTop() + $(window).innerHeight();

            /* If the object is completely visible in the window, fade it in */
            if (objectBottom < windowBottom) { //object comes into view (scrolling down)
                if ($(this).css('opacity')==0) {$(this).fadeTo(500,1);}
            } else { //object goes out of view (scrolling up)
                if ($(this).css('opacity')==1) {$(this).fadeTo(500,0);}
            }
        });
    }
    fade(); //Fade in completely visible elements during page-load
    $(window).scroll(function() {fade();}); //Fade in elements during scroll
});


text:
Q: Unable to target xlink:href using attribute selectors I am trying to avoid having to <use class="myicon" xlink:href="myicon" /> by simply targeting the value of the xlink:href attribute when styling my SVGs. None of the following selectors seem to work:
[xlink|href*=myicon], // I also set the namespace at the top of the file
[xlink:href*=myicon],
[xlink\:href*=myicon] {
    color: yellow !important;
}

A few other questions on the site seem to imply that styling using the attribute selectors on namespaced attributes should be possible, even though plain html has no support for namespaced attributes, as it should just regard them as one word. But I cannot get it to work, so I am losing faith in just that.

A: As Blake Mann says, if you're listing all your selectors together like that, it won't work because [xlink:href*=myicon] is invalid, which causes your entire ruleset to be dropped. If you're trying different selectors, you need to try them one at a time.
[xlink|href*=myicon] works just fine, but make sure you've specified the XLink namespace and not the SVG namespace:

@namespace xlink 'http://www.w3.org/1999/xlink';

html {
    background-color: black;
}

[xlink|href*=myicon] {
    fill: yellow;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <text id="myicon" y="16">Icon</text>
  </defs>
  <use xlink:href="#myicon" />
</svg>

A: You were definitely on the right track with what you were doing.. in fact, you have the right answer:
[xlink\:href*=myicon] {
    color: yellow !important;
}

The reason it isn't working is because the first two selectors you tried were invalid (both the | and : characters need to be escaped), and if a CSS selector contains invalid characters, the whole selector group gets thrown out.
Check this example as proof... the div (just using a div for simplicity, even though that's not quite right) should get set to be red, as that rule comes after the blue one, but because the selector group gets thrown out, that rule won't get applied. The other selector that does not have the invalid characters will apply though!

[xlink\:href*=myicon] {
    color: blue;
}

[xlink|href*=myicon],
[xlink:href*=myicon],
[xlink\:href*=myicon] {
    color: red;
}
<div xlink:href="myicon">Lorem Ipsum</div>


text:
Q: Obtener URL de un Objeto de S3 [ Symfony & EasyAdmin ] Estoy realizando un CRUD a una entidad Usuarios, y estoy cargando archivos de esos usuarios a un Bucket en S3...
La carga de los archivos es satisfactoria, pero deseo recuperar el link que me genera AWS S3 de ese objeto cargado, para almacenarlo en otra tabla inmediatamente es cargado allá en mi Bucket...
La pregunta es, ¿De qué manera puedo obtener la URL que se genera de mi objeto cargado en S3?
Bundles:
    Vich\UploaderBundle\VichUploaderBundle
    Oneup\FlysystemBundle\OneupFlysystemBundle
    League\FlysystemBundle\FlysystemBundle

EasyAdmin Controller:
    namespace App\Controller\Admin;

    use App\Entity\Users;
    use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
    use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
    use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
    use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
    use EasyCorp\Bundle\EasyAdminBundle\Field\Field;
    use Vich\UploaderBundle\Form\Type\VichImageType;
    use App\Form\VichImageField;
    use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;

    class UserCrudController extends AbstractCrudController
    {
        public static function getEntityFqcn(): string
        {
            return User::class;
        }

        public function configureFields(string $pageName): iterable
        {
            return [
                VichImageField::new('imageFile')->setFormType(VichImageType::class)->onlyOnForms()
            ];
        }

    }

*

*Configuración VichUploader Bundle
    vich_uploader:
        db_driver: orm
        storage: flysystem

        mappings:
            asset_images:
                inject_on_load: true
                uri_prefix: '%assets_uri%'
                upload_destination: oneup_flysystem.default_filesystem_filesystem
                delete_on_update:   false
                delete_on_remove:   false
                namer: vich_uploader.namer_uniqid

*

*oneup_flysystem configuración:
    oneup_flysystem:
        adapters:
            acme.flysystem_adapter:
                awss3v3:
                    client: acme.s3_client
                    bucket: '%env(TEST_AWS_S3_NAME_BUCKET)%'
        filesystems:
            default_filesystem:
                adapter: acme.flysystem_adapter
                mount: default_filesystem

Necesito registrar la url generada por S3 a éste entity:
Entidad Documentos:
namespace App\Entity;

use App\Repository\DocumentosRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Entity(repositoryClass=DocumentosRepository::class)
 * @Vich\Uploadable
 */
class Documento
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     *
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=500, nullable=true)
     */
    private $descripcion;

    /**
     * @ORM\Column(type="string", length=500)
     */
    private $path;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @var string|null
     */
    private $nombre;

    /**
     * @Vich\UploadableField(mapping="asset_images", fileNameProperty="nombre")
     * @var File
     */
    private $archivoDocumento;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     * @var \DateTime|null
     */
    private $updatedAt;

    /**
     * @ORM\ManyToOne(targetEntity=Usuario::class)
     * @ORM\JoinColumn(nullable=false)
     */
    private $usuario;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getDescripcion(): ?string
    {
        return $this->descripcion;
    }

    public function setDescripcion(?string $descripcion): self
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    public function getPath(): ?string
    {
        return $this->path;
    }

    public function setPath(string $path): self
    {
        $this->path = $path;

        return $this;
    }

    public function getNombre(): ?string
    {
        return $this->nombre;
    }

    public function setNombre(string $nombre): self
    {
        $this->nombre = $nombre;

        return $this;
    }

    public function setArchivoDocumento(File $nombre = null)
    {
        $this->archivoDocumento = $nombre;

        // VERY IMPORTANT:
        // It is required that at least one field changes if you are using Doctrine,
        // otherwise the event listeners won't be called and the file is lost
        if ($nombre) {
            // if 'updatedAt' is not defined in your entity, use another property
            $this->updatedAt = new \DateTime('now');
        }
    }

    public function getArchivoDocumento()
    {
        return $this->archivoDocumento;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(?\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    public function getUsuario(): ?Usuario
    {
        return $this->usuario;
    }

    public function setUsuario(?Usuario $usuario): self
    {
        $this->usuario = $usuario;

        return $this;
    }
}

Cualquier sugerencia o comentario lo aprecio realmente.


text:
Q: Using defaultdict to handle dynamic insertion to key if not present From another thread i came to know that to generate a custom dictionary where the keys are assigned dynamically, we can use collections's defaultdict instead of setdefault.
I;m trying to use that where in i have a list of node and each node will have a handle and cfg_str.
I wrote the code as below:
import re
from collections import defaultdict

custom_dict = defaultdict(list)

node = ['TERM1','TERM2','L2','S1','S2','TERM3']

for node in node:
    if re.search(r'TERM', node, re.I):
        custom_dict[node] = 'test'      --> this works.
        custom_dict[node]['handle'] = 'handle value'  --> this doesn;t work
        custom_dict[node]['cfg_str'] = {}     ---> This does not work

print(custom_dict)

am I missing anything here?

A: Looks like you need defaultdict(dict).
Ex:
import re
from collections import defaultdict

custom_dict = defaultdict(dict)

node = ['TERM1','TERM2','L2','S1','S2','TERM3']

for node in node:
    if re.search(r'TERM', node, re.I):
        custom_dict[node] = {'handle': 'handle value', 'cfg_str': {}}

print(custom_dict)

Output:
defaultdict(<type 'dict'>, {'TERM3': {'cfg_str': {}, 'handle': 'handle value'}, 'TERM2': {'cfg_str': {}, 'handle': 'handle value'}, 'TERM1': {'cfg_str': {}, 'handle': 'handle value'}})

A: Not sure what your expected output is. But you can build dicts dynamically using the get method too look for keys and set defaults if absent.
foo = {}
nodes = ['TERM1','TERM2','L2','S1','S2','TERM3']
for node in nodes:
    if 'TERM' in node:
        foo[node] = foo.get(node, dict(handle = 'handle value',\
                                       cfg_str = {}))

foo is now:
{'TERM1': {'handle': 'handle value', 'cfg_str': {}},
 'TERM2': {'handle': 'handle value', 'cfg_str': {}},
 'TERM3': {'handle': 'handle value', 'cfg_str': {}}}


text:
Q: Django DecimalField inconsistent rounding Django 2.2, PostgreSQL database. I have a Line object with a positions property. This is an ArrayField of a DecimalField with a max_digits of 12 and decimal_places of 3.
I store some floats as Decimals and get them back out of the Database:
pos = [6586.87849502, 2.04190477e-01, 7.14666669e-01]
line = Line(positions=pos)
line.save()
line.refresh_from_db()  # send it through Django's ORM piping
print(line.positions)

Output:

[Decimal('6586.879'), Decimal('0.204'), Decimal('0.715')]

Interestingly, the first position was rounded up despite its next more significant digit being below 5. The other float is rounded down as expected.
I thought it might be PostgreSQL messing around, but no:
INSERT INTO line(positions) VALUES (array[6586.87849502, 2.04190477e-01, 7.14666669e-01]) RETURNING positions;

positions (numeric[])
{6586.878,0.204,0.715}

The real issue is that I'm trying to predict what will come out of the database, down to the required precision of three decimal places:
[Decimal(x).quantize(Decimal("0.001")) for x in pos]

might yield

[Decimal('6586.878'), Decimal('0.204'), Decimal('0.715')]

or

[Decimal('6586.879'), Decimal('0.205'), Decimal('0.714')]

depending on the decimal.ROUND_* flag I pass in quantize(), but I never get consistent rounding throughout the array. What kind of pre-processing does Django do to my numbers before inserting them?


text:
Q: Problem with Simulation Results VS Tested Results for a signal For the circuit shown i am having some trouble wondering why my tested signal looks like this (i understand that it could be clipping) but when i measure my circuit in the simulation it is correct? What could be causing these issues. I have to make a signal play through a speaker and just dont get what the issue could be? The amps are 2 x lm6484 and 1 x lm386. The circuit works perfectly and plays the sound as it should (with the 50k resistor being the potentiometer) but i just dont get what coiuld cause this change to the signal?

Could it potentially be a faulty breadboard. Also on another note i have a problem that when a different recording is played, the gain of the amp isnt 20, why is this?


text:
Q: FindFit: Fit that is always lower - Change of Norm? I am trying to find a fitting function for a multidimensional set of data. I will have to find a fitting function that is always lower (conservative) than the data fitted.
The easiest way is to look for the largest underestimation and add this value to the fit function. But this does not lead to very good fits.
I have illustrated this in the following using some random data:
test = {{0.0, 120.0}, {1, 115}, {2, 50}, {3, 50}, {4, 30}, {5, 25}};
function[x_] := a + b x + c x^2;
rep = FindFit[test, function[x], {a, b, c}, {x}]
delta = (test -
    Table[{x, function[x]} /. rep, {x, 0, 5, 1}])[[All, 2]];
Show[
 ListLinePlot[test, PlotMarkers -> Automatic, AxesOrigin -> {0, 0}],
 Plot[function[x] /. rep, {x, 0, 5}, PlotStyle -> Red],
 Plot[(function[x] /. rep) + Min[delta], {x, 0, 5},
  PlotStyle -> Green]
 ]

Red is best fit, Green is shifted fit (no longer a good fit).
If I understood correctly I will have to change the norm. But I do not how such a norm could look like and how to implement it. To me it seems like some kind of penalty method could be implemented in the norm.
Thank you very much for your answers and hints!

A: You can use constraints together with the definition of your model function :
rep2 = NonlinearModelFit[test,
        Join[{function[x]}, function[#[[1]]] <= #[[2]] & /@ test], {a, b, c}, x];

rep2 // Normal
(* 120. - 45.6667 x + 5.33333 x^2 *)

Show[ListLinePlot[test, PlotMarkers -> Automatic, AxesOrigin -> {0, 0}],
     Plot[rep2[x], {x, 0, 5}, PlotStyle -> Red]]

A: A simple penalty method is just to multiply the norm by some factor when the error is positive, e.g:
rep = FindFit[test, function[x], {a, b, c}, {x},
  NormFunction -> (Total[(20 Sign[#] + 21) #^2] &)]


text: Q: Is there any way to separate py and pyc files while building Django project using pybuilder I was trying to build a Django project using pybuilder where I need to separate the pyc files and resource files. This is regarding protecting the source code, I know we can achieve this by the licencing mechanism. Our requirement is distributed the pyc file to the client instead of actual py file.


text:
Q: AWS Lambda not calling third party api in loop i am using aws lambda and i am calling third party server using request library. this library on outside the loop but on loop its not hitting even i am not getting any error or result. and i also checked on server there is no hitting
below is my code with console

exports.handler = async (event) => {
    try {
        let transactionList = [];
        // event.body is json form object with keys and values that we send
        userBrokers.forEach(async (brokers) => {
            const userStocks = 50;
            const qty = (qtyPercentage * userStocks) / 100;
            console.log("function before api call")
            request.post({
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    "Apca-Api-Key-Id": brokers.api_key,
                    "Apca-Api-Secret-Key": brokers.secret_key
                },
                url: 'https://paper-api.alpaca.markets/v2/orders',
                json: {
                    symbol,
                    qty,
                    side: orderType,
                    type: marketType,
                    time_in_force
                }
            }, function (error, response, body) {
                if (error) {
                    console.log("api call error")
                    transactionList.push({
                        transactionSuccess: false,
                        reason: error,
                        userId: brokers.user_id,
                        documentId: brokers._id
                    })
                }
                else {
                    console.log("api response")
                    if (response.statusCode == 200) {
                        transactionList.push({
                            brokerOrderId: body.id,
                            symbol: body.symbol,
                            orderType: body.order_type,
                            marketType: body.side,
                            transactionSuccess: true,
                            userId: brokers.user_id,
                            documentId: brokers._id
                        })
                    }
                    else {
                        transactionList.push({
                            transactionSuccess: false,
                            reason: body.message,
                            userId: brokers.user_id,
                            documentId: brokers._id
                        })
                    }
                }
            });
        })
    console.log("function before response")
    return {
        statusCode: 200,
        body: JSON.stringify(transactionList),
    };
} catch (error) {
    console.log("function catch block")
    return {
        statusCode: 200,
        body: JSON.stringify(error.message),
    };
}};

and i get below console.
function before api call
function before response

and response from lambda
status: 200 and message: []

A: The problem is that you're trying to execute an async method in a forEach but you have no way of enforcing Lambda to wait for the loop to finish. You should switch your forEach to a map and await all the promises:
Bad:
arr.forEach(async (val) => {})

Good:
const arrOfResults = await Promise.all(arr.map(async (val) => {}))


text:
Q: Buildroot generic package does not install in init.d directory I'm trying to build an embedded Linux image for the embedded system I'm working on.
It uses Buildroot and we are trying to install generic packages in it.
This works well up to the point where I install a script in the /etc/init.d/ directory on the target image.
To build in my software inside the image, I created the following makefile that is picked up by Buildroot.
It aims to copy a JAR file to the filesystem, with some additional scripts.
I found that scripts that start with the letter S are run automatically.
See: https://buildroot.org/downloads/manual/manual.html#_init_system
define MY_GATEWAY_INSTALL_TARGET_CMDS

  $(INSTALL) -d $(TARGET_DIR)/$(DST_FOLDER); \
  $(INSTALL) -D -m 0644 $(@D)/*.jar $(TARGET_DIR)/$(DST_FOLDER); \
  \
  $(INSTALL) -D -m 0700 /work/package/mycompany/my-gateway/artifacts/start_heimdall $(TARGET_DIR)/$(DST_FOLDER); \
  ln -snrf $(TARGET_DIR)/$(DST_FOLDER)/start_heimdall $(TARGET_DIR)/usr/bin/start_heimdall; \
  \
  $(INSTALL) -D -m 0755 /work/package/mycompany/my-gateway/artifacts/S99gateway $(TARGET_DIR)/$(DST_FOLDER); \
  $(INSTALL) -D -m 0755 /work/package/mycompany/my-gateway/artifacts/S99gateway $(TARGET_DIR)/etc/init.d/S99gateway; \
  \
  if [[ "$(BR2_HSDP_GATEWAY_INCLUDE_VERSION_FILE)" == "y" ]]; then \
      echo $(HEIMDALL_VERSION) > $(TARGET_DIR)/my_gw_version; \
  fi

endef

After building my image, I found that the JAR file and the start_heimdall script are correctly placed in the expected directory.
This is not the case for the S99gateway script, which does not appear in the /etc/init.d/ directory.
My application is therefor not started.
The target directory of the built image looks as follows:
ls -al $(TARGET)/usr/heimdall
total 19476
drwxr-xr-x 2 rick rick     4096 feb 28 08:43 .
drwxr-xr-x 8 rick rick     4096 feb 28 08:43 ..
-rw-r--r-- 1 rick rick 19924893 feb 28 08:40 heimdall-squidlink-1.0.0-1582809178-release.jar
-rwxr-xr-x 1 rick rick      362 feb 28 08:40 S99gateway
-rwx------ 1 rick rick      230 feb 28 08:40 start_heimdall

ls -al /etc/init.d
total 68
drwxr-xr-x  2 rick rick 4096 feb 28 08:43 .
drwxr-xr-x 14 rick rick 4096 feb 28 08:43 ..
-rwxr-xr-x  1 rick rick  423 dec  4 14:50 rcK
-rwxr-xr-x  1 rick rick  408 dec  4 14:50 rcS
-rwxr-x---  1 rick rick 1295 aug 13  2014 S01logging
-rwxr-xr-x  1 rick rick  241 feb 28 08:19 S10mdev
-rwxr-x---  1 rick rick 1708 nov  4  2016 S10modules
-rwxr-x---  1 rick rick  396 mei 30  2016 S11led
-rwxr-x---  1 rick rick  968 mrt 17  2015 S12automount
-rwxr-x---  1 rick rick  397 apr 27  2015 S15hostname
-rwxr-xr-x  1 rick rick 1365 dec  4 14:50 S20urandom
-rwxr-x---  1 rick rick   48 apr 22  2015 S40network
-rwxr-xr-x  1 rick rick  936 feb 28 08:40 S49ntp
-rwxr-xr-x  1 rick rick 4066 feb 28 08:31 S50dropbear
-rwxr-xr-x  1 rick rick  435 feb 28 08:41 S50stunnel
-rwxr-xr-x  1 rick rick  462 feb 28 08:31 S80dnsmasq
-rwxr-xr-x  1 rick rick  362 feb 28 08:40 S99gateway

The last line shows that my script is successfully copied to the desired directory.
When I flash the image onto my embedded device and SSH into it, I see the following:
ls -al /usr/heimdall
total 19468
drwxr-xr-x    2 root     root           408 Feb 28  2020 .
drwxr-xr-x    8 root     root           616 Feb 28  2020 ..
-rwxr-xr-x    1 root     root           362 Feb 28  2020 S99gateway
-rw-r--r--    1 root     root      19924893 Feb 28  2020 heimdall-squidlink-1.0.0-1582809178-release.jar
-rwx------    1 root     root           230 Feb 28  2020 start_heimdall

ls -al /etc/init.d
total 56
drwxr-xr-x    2 root     root          1128 Jan 17 22:12 .
drwx--x--x   14 root     root          3088 Jan 17 22:12 ..
-rwxr-x---    1 root     root          1295 Aug 13  2014 S01logging
-rwxr-xr-x    1 root     root           241 Feb  7  2020 S10mdev
-rwxr-x---    1 root     root          1708 Nov  4  2016 S10modules
-rwxr-x---    1 root     root           396 May 30  2016 S11led
-rwxr-x---    1 root     root           968 Mar 17  2015 S12automount
-rwxr-x---    1 root     root           397 Apr 27  2015 S15hostname
-rwxrwxr-x    1 root     root          1365 Dec  4  2019 S20urandom
-rwxr-x---    1 root     root            48 Apr 22  2015 S40network
-rwxr-xr-x    1 root     root           936 Jan 17 22:12 S49ntp
-rwxr-xr-x    1 root     root          4066 Feb  7  2020 S50dropbear
-rwxr-xr-x    1 root     root           435 Feb  7  2020 S50stunnel
-rwxr-xr-x    1 root     root           462 Feb  7  2020 S80dnsmasq
-rwxrwxr-x    1 root     root           423 Dec  4  2019 rcK
-rwxrwxr-x    1 root     root           408 Dec  4  2019 rcS

In this case, after flashing, the S99 script is no longer there.
Is the /etc/init.d/ directory protected in some way?
I'm trying to understand why the script is not there anymore.
Is the correctness of the inner workings of the script important for the installation process?

A: There is nothing special about /etc/init.d/. However, we cannot really understand what happened here: what is your DST_FOLDER variable ?
If your S99 script is in output/target, then it should definitely be part of the final filesystem image. Are you sure you ran make to regenerate the filesystem image, and reflashed your image properly ?
Generally speaking, what you wrote has a number of problems:

*

*You don't need ; or \ at the end of each line

*The init script should rather be installed in the _INIT_SYSV variable instead of in _INSTALL_TARGET_CMDS variable, even though that's not your issue

*The check on BR2_HSDP_GATEWAY_INCLUDE_VERSION_FILE should be done using a make condition and not a shell condition

*It's not clear why you install each file several times.


text:
Q: Getting the value of the second selectbox to fetch result I'm trying to fetch city,county,area in a nested select for my project.
So I have 3 levels of nested selects. But when I try to fetch the data with 2 variables, I cannot pass the value of "first selected select" to the fetch url.
How can I pass the value of firstly selected select value to the fetch url?
I need to replace this.MUSTBEVALUEOFTHESECONDSELECTEDSELECT with the value
Here is a demo
http://jsfiddle.net/krsj3ecy/

  İl Seçiniz
  <select class="form-control col-md-3" v-model="selected" v-on:change="ilceleriGetir()">

                                    <option v-for="list in iller"
                                            v-bind:value="list.cityid">
                                        {{list.cityname}}
                                    </option>
                                </select>

     İlçe Seçiniz
    <select class="form-control col-md-3" v-on:change="mahalleleriGetir()">
                                        <option v-for="list in ilceler"
                                                v-bind:value="list.countyid">
                                            {{list.countyname}}
                                        </option>
                                    </select>

     Mahalle Seçiniz
    <select class="form-control col-md-3">
                                        <option v-for="list in mahalleler"
                                                v-bind:value="list.areaid">
                                            {{list.areaname}}
                                        </option>
                                    </select>

A: Make a new object that has properties for each select box to mutate:
selections: {
    iller: null,
    ilceler: null,
    mahalleler: null
}

Update all your v-model bindings:
v-model="selections.iller"
v-model="selections.ilceler"
v-model="selections.mhalleler"

Now you can get them correctly.


text:
Q: Facebook on Android — Debug popup Hashkey keep appear I'm trying to add the Facebook API in my application. I build it in ActionScript3-AIR to proceed an export on iOS/Android and use the GoViral API to apply the connection with Facebook.
After the creation of the application on Facebook Developer, it works on iOS, but not on Android.
When this line is read GoViral.goViral.initFacebook( XXXXXXX ), on Android, the application show a popup which display the Key Hashes Here, the screenshot:

Then, nothing happen. The connexion don't seem to be done and, if I try an authentication with GoViral.goViral.authenticateWithFacebook( "user_likes,user_photos,publish_actions" ) it does nothing. And by that, I really mean nothing in the way that it don't even return the GVFacebookEvent.FB_LOGIN_FAILED event.
I used the "Mail It" button on this popup. Took the hash key and pasted it in the Android section of my application in the Facebook Developer Here, the screenshot:

But, nothing changes and the popup always appears.
After that and by the results of some google research, I've try to make my own Hash Key, helped by some tutorials. The Key has been generated but didn't correct anything about the popup.
So, actually, I'm a little confuse about this issue.
Especially as I've try to put another fake App ID in the initFacebook method : the popup continues to appear. So I wonder if it can really see it.
For information, I created the application project on the Google Developers Console.
The manifest I use to apply the Facebook API is this one :
    <uses-sdk android:targetSdkVersion="12"/>
    <uses-sdk android:minSdkVersion="8"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application>
    <activity android:name="com.facebook.LoginActivity"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    android:label="Login"/>
    </application>

Thanks a lot to help me to fix this issue.
------ EDIT ------
I found the problem about the Debug Pop-up with the Hash Key. It was relative to the GoViral API which ( I didn't know this ) has two version : One normal and one for the debug which always makes appear the hash key in a pop-up at connection.
The Facebook connection still not working, but it's sound to be another problem so I can say this problem is solved.

A: I've found the solution which is way simple than I imagined. In the sources of GoViral, there was two ANE, I used the one which was makes for debug. It makes appear the popup to give us the hashkey. After what, we have to put the other ane to make it work.


text:
Q: Sort Method for Doubly Linked List Trying to figure out how to sort my doubly linked list.
I get a null pointer exception here:
while (temp.getNext()!=null){

Is there a better approach or any advice to get this going the right way?
public void sort() {
    //bubble sort!
    boolean swapped = (head != null);
    while (swapped) {
        swapped = false;

        EntryNode temp = head;

        //can't swap something with nothing
        while (temp.getNext()!=null){
            if (temp.getLastName().compareTo(temp.getNext().getLastName()) > 0) {
                swapped = true;

                //special case for two nodes
                if (size == 2) {
                    //reassign head and tail
                    tail = temp;
                    head = temp.getNext();
                    tail.setPrev(head);
                    head.setNext(tail);
                    tail.setNext(null);
                    head.setNext(null);
                }
                //if swapping is at head
                else {

                    if (temp == head) {
                        head = temp.getNext();
                        temp.setNext(head.getNext());
                        head.getNext().setPrev(temp);
                        head.setPrev(null);
                        head.setNext(temp);
                        temp.setPrev(head);
                    }

                    else {
                        temp.setNext(temp.getNext().getNext());
                        temp.setPrev(temp.getNext());
                        temp.getNext().setNext(temp);
                        temp.getNext().setPrev(temp.getPrev());
                    }
                }
            }
            //loop through list
            temp = temp.getNext();
        }
    }
}

A: Use the merge sort algorithm, is often the best choice for sorting a (single or doubly) linked list. There's already a post discussing the relevant implementation issues.

A: I think you should check for:
while(temp != null)

because you are already assigning
temp = temp.getNext()

at the end of the while loop.

A: The simple approach is to put the list contents into an array, use Arrays.sort to sort the array, and finally rebuild the list from the sorted array.


text:
Q: Comparing data from different sources using QGIS? I have two files in QGIS about restaurants in the same area.
How can I get elements that are only in the first source and not in the second and viceversa, connected to the same activity?
I also need to get the elements in common, associated to the same restaurant. The problem is that the attribute tables of the two sources are organised in different ways, there's not an univocal ID to join the sources, also the attribute "names" are slightly different between them and same cells are empty in the second source.


text:
Q: Remove video from youtube watch later by python gdata library How can I remove video from youtube watch later by python gdata library?
I check API: https://developers.google.com/youtube/2.0/developers_guide_protocol?hl=en#Retrieving_watch_later_playlist,
and try its method:
Deleting a video from the playlist:
https://gdata.youtube.com/feeds/api/users/default/watch_later/VIDEO_ID.
via python gdata library
playlist_uri = u"https://gdata.youtube.com/feeds/api/users/default/watch_later"
playlist_entry_id = videoID .............(Does watch later have playlist_entry_id??)
response = yt_service.DeletePlaylistVideoEntry(playlist_uri,
                                               playlist_entry_id)
=>Error: Bad request

or
playlist_uri = u"https://gdata.youtube.com/feeds/api/users/default/watch_later/%s" % videoID
response = yt_service.Delete("playlist_uri)
=>Error: Bad request

Both Failed!
Is there any other way to get it? Thanks a lot.

A: After testing & trying again and again, the code which can successfully perform in my develop environment is very different form Youtube document: https://developers.google.com/youtube/2.0/developers_guide_protocol?hl=en#Retrieving_watch_later_playlist.
For Reference Purposes Only.
1. Use playlist_entry_id instead of VIDEO_ID:
   - How to get playlist_entry_id for each video in watch later?
     . General playlist: entry.id.text.split('/')[-1]
     . Watch later playlist: entry.id.text.split('watch_later:')[-1]
2. API URL need to add '?v=2'
My Ans:
   playlist_uri = https://gdata.youtube.com/feeds/api/users/default/watch_later/playlist_entry_id?v=2
   self.__ytService.Delete(playlist_uri)


text:
Q: Colocar a data no formato americano com substring Como colocar a string 22012018 que é uma data no formato americano pra salvar no banco de dados?
O código abaixo me retornar o valor:

2018-22-01

Ou seja, ANO-DIA-MÊS
O certo seria ANO-MÊS-DIA
 EstFData = Path.GetFileName(arquivo).Substring(4, 8).Trim();
 EstFData = EstFData.Substring(4, 4) + "-" + EstFData.Substring(3, 2) + "-" + EstFData.Substring(0, 2);

A: Se preferir usar um código menos verboso, você pode tentar desta forma:
EstData = DateTime.ParseExact(
        EstData,
        "ddMMyyyy",
        System.Globalization.CultureInfo.CurrentCulture)
    .ToString("yyyy-MM-dd");

A: Creio que da forma que digitou está correto, apenas o posição está incorreta, tente desta forma:
EstFData = EstFData.Substring(3, 4) + "-" + EstFData.Substring(2, 2) + "-" + EstFData.Substring(0, 2);

A: Utilize o método DateTime.ParseExact para converter em datetime.
Segue exemplo:
DateTime dataConvertida = DateTime.ParseExact("22012018", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);

Para conseguir esta data no seu código, entendo que seria assim:
string EstFData = Path.GetFileName(arquivo).Substring(4, 8).Trim();
DateTime dataConvertida = DateTime.ParseExact(EstFData, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);


text:
Q: Disable up and down arrow I have this data field for input

And it does show a data selector plugin wich works fine with the keyboard.
But I want to disable the up and down arrows. Could you guide me how?
Also need when date filed is clicked that it open date picker or when the user clicks on calendar icon
Thanks.
Code:

                                <input type="date"ng-model="date" class="form-control"  placeholder="date" style="width:180px" id="date" ng-required="true">

                            <input type="date"ng-model="client.dateofbirth" class="form-control"  placeholder="Data de nascimento" style="width:180px" id="dateofbirth" ng-required="true">

the calendar icon also shows me down not in the correct place...
i want when i click on the textbox it opens the calendar.

        // not working
    $('#date').datepicker(
        {
            allowInputToggle: true

        });

A: From the look of it, it looks like the input has type="number", but I am not sure why there is a dropdown arrow there. You can remove the up and down arrows using CSS. I always add this snippet in my main CSS/SASS file.

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type="number"] {
    -moz-appearance: test-field;
}
<input type="number"/>

Source: Turn Off Number Input Spinners | CSS-Tricks


text:
Q: How to install networkx on activepython community edition? I am attempting to run the command easy_install networkx to install the NetworkX package. When I do it generates this error message:
        SyntaxError: invalid syntax.
Is it because I am using the free community edition of activepython or am I making a stupid mistake?


text:
Q: Apache Nifi Failed to write to HDFS I'm getting this following error when I try to put files on HDFS using the PutHDFS processor :

I work with the HortonWorks sandbox HDP and HDF (docker containers on Windows). It seem to be an Nifi's problem, HDFS is ok, I can put/write/read on it.
I'm trying to fix this but no result, I have deleted the docker's HDP image and got a new one, but no result too.

A: Usually that error means that whatever is writing to HDFS was able to reach the namenode but wasn't able to reach the datanode. In your case it is most likely a networking config issue between the two containers.
You could test this by eliminating NiFi from the scenario and install the Hadoop client on the container where NiFi is running, and try to use the Hadoop command line to write a file to HDFS. I would expect you get the same error.
If so make sure that you can ping the datanode hostname from the HDF container, make sure correct port is open, and make sure the datanode is accepting connections from all hosts and not just from localhost.


text:
Q: How to add disclaimer if there is an attachment? - Exchange 2010 Currently we have an extremely long disclaimer with two paragraphs. The first paragraph deals with the email content itself. The second paragraph deals with attachments that go out (typically AutoCAD drawings) and how they are to be used/modified and are property of my company, etc., etc.
I'd like to split the disclaimer into two parts - one that is always appended and one that is only appended if there is an attachment on the message.
Is this possible? I've searched on Google, Technet, and here on ServerFault but was unable to find an answer.

A: You'll need two Transport Rules with a disclaimer each:
# Our disclaimer, with HTML and fancy predicates:
$DisclaimerText = @"

We, here at %%Company%% hate the environment, and want YOU to invest in additional storage!
Please take these extra bytes of HTML as a sign of our gratitude towards your continued support of natural resource depletion
*Patent forms*, *legal threats*, *copyright voodo* Trademark pending

"@

# Create a new transport rule for mails sent from inside the organization and out
New-TransportRule -Name "LegalDisclaimer" -ApplyHtmlDisclaimerText $DisclaimerText -FromScope InOrganization -SentToScope NotInOrganization

The above will apply to all emails sent from your employees to external recipients.
To apply a second disclaimer only in the event that an attachment exists, test if the attachment size exceeds 0 bytes:
# Another disclaimer, with HTML and fancy predicates:
$AttachmentText = @"

We, here at %%Company%% still hate the environment, and want YOU to invest in even MORE additional storage!
Please accept this huge attachment in our course of world domination. Thanks in Advance
*Patent forms*, *legal threats*, *copyright voodo* Trademark pending

"@

# Create a new transport rule with the same scopes, but for only emails with attachments
New-TransportRule -Name "AttachmentDisclaimer" -AttachmentSizeOver 0 -ApplyHtmlDisclaimerText $AttachmentText -FromScope InOrganization -SentToScope NotInOrganization

But... don't use it, disclaimers are lame


text:
Q: Cannot use normal array functions Why is it that i cannot use the normal array functions in C# like:
string[] k = {"Hello" , "There"};
k.RemoveAt(index); //Not possible

Code completion comes with suggestions like All<>, Any<>, Cast<> or Average<>, but no function to remove strings from the array. This happens with all kind of arrays. Is this because my build target is set to .NET 4.5.1?

A: You cannot "Add" or "Remove" items from an array, nor should you, as arrays are defined to be a fixed size. The functions you mention (All, Any) are there because Array<T> implements IEnumerable<T> and so you get access to the LINQ extensions.
While it does implement IList<T>, the methods will throw a NotSupportedException. In your case, to "remove" the string, just do:
k[index] = String.Empty; //Or null, whichever you prefer

A: The length of an array is fixed when it's created and doesn't change, it represents a block of memory. Arrays do actually implement IList/IList<T>, but only partially - any method that tries to change the array is only available after casting and will throw an exception. Arrays are used internally in most collections.
If you need to add and remove arbitrarily and have fast acces by index you should use a List<T> which uses a resizing array internally.


text:
Q: How to make a 4 level progress circle in Flutter? How to obtain something similar to this ? I was thinking I could use Stack, but I don't know how to get started

A: A simple example:
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatelessWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Stack(
          children: const [
            CircularProgressIndicator(
              color: Colors.blue,
              value: 0.8,
            ),
            CircularProgressIndicator(
              color: Colors.red,
              value: 0.7,
            ),
            CircularProgressIndicator(
              color: Colors.green,
              value: 0.6,
            ),
            CircularProgressIndicator(
              color: Colors.yellow,
              value: 0.5,
            )
          ],
        ),
      ),
    );
  }
}

Output:


text:
Q: QGIS print composer exported as PDF is not the same as I expected I'm trying to export a finished map to pdf. The layout view is correct but when I open the pdf file there is something missing in the legend. I'm using QGIS 3.16.
In the legend, I added an expression to pull the data from the attribute's layer and display this in the legend.
In the view, I can see the layer name and the specific field from the attribute table next to. However, when I export as a pdf., even exported as an image, the data from the attributes has disappeared from the legend and only the layer's name is exported.
Example:  Roads- 50m
Is there any solution, apart from adding it manually instead of using an expression? or am I missing something?


text:
Q: In which version of openssl is the pkcs8 v2 option introduced? In which version of openssl is the pkcs8 v2 option introduced?
Ex: openssl pkcs8 -in key.pem -topk8 -v2 des3 -out enckey.pem
From which version of openssl does v2 of pkcs8 work by default?(Which uses the pkcs#5 v2.0)


text:
Q: Setting a variable from an executable I am running an executable in a batch file with two parameters;
cmd /k ""executable" "param1" "param2""
This returns a string that I want to launch. I can't figure out how to set this return in a variable and subsequently launch it in IE.
Any ideas?

A: If the returned string contains a single line you may use FOR /F to set the value of an environment variable. For example:
s1.cmd
echo this is a one line string

s2.cmd
@SETLOCAL
@ECHO OFF
for /f "tokens=*" %%a in ('cmd /c s1.cmd') do set MY_VAR=%%a
echo got: %MY_VAR%
ENDLOCAL

Result
C:\> s2.cmd
got: this is a one line string

C:\>

A: You can use the following syntax to capture the output of your executable into a variable:
FOR /F "tokens=*" %%i in ('%~dp0YOUR_APP.exe') do SET TOOLOUTPUT=%%i

Source
then you can pass the value on to IE like so:
START "YOUR_WINDOW_NAME" /MAX /D"C:\Program Files\Internet Explorer\" iexplore %TOOLOUTPUT%

I take it that the application code that determines the url is too complicated to be reproduced in a batch file directly, or the source to the executable has been lost.  If not I personally would prefer to have the logic visible in the batch file itself.

A: start %1 %2

A: Edit: Romulo A. Ceccon posted a much better solution which doesn't involve any file system access and dirty tricks. Left this here for reference (it works with command.com as well if you need 9x compatibility), but please prefer Romulo's solution.

Go through an environment variable you set by using an intermediate helper script you dynamically generate from a template. You will need write permissions somewhere, otherwise it cannot be done (the Windows command shell language is very, very limited.)
Let's call your helper script template helper.tpl with the following contents:
set INTERMEDVAR=

Make sure that helper.tpl has only a single line (no trailing CRLF!) and make sure you don't have any spaces after the equals sign there.
Now, in your main script, capture the output from your command into a temporary file (let's call it my_output_file.tmp):
cmd /k ""executable" "param1" "param2"" > my_output_file.tmp

Then copy the contents of the helper template and the output together into your helper script, let's call it my_helper_script.cmd:
copy /b helper.tpl + my_output_file.tmp my_helper_script.cmd

Then evaluate the helper script in the current context:
call my_helper_script.cmd

Now the INTERMEDVAR variable is set to the first line of the output from "executable" (if it outputs more than one line, you're on your own...) You can now invoke IE:
start iexplore.exe "%INTERMEDVAR%"

And don't forget to clean up the created files:
del /q /f my_output_file.tmp my_helper_script.cmd

This will obviously not work when invoked multiple times in parallel - you'll have to parametrize the temporary file and helper script names using the current cmd.exe's PID (for example) so that they won't overwrite each other's output, but the principle is the same.
However, if you can get a real shell, use that. cmd.exe is extremely cumbersome.


text:
Q: Is loop 'for element in list_[a:b]' using unused copy optimized by interpreters? Is this :
for element in list_[a:b]:

translated during interpretation (CPython) to be equivalent to :
for i in range(a, b):
    element = list_[i]

or is the copy
list_[a:b]

really performed ?

A: The copy is really performed. The interpreter has no way of knowing what kind of object list_ is at runtime and what you will do with it (maybe you'll start editing the original list_).
If you want to not produce the copy, use itertools.islice:
import itertools

def f(list_, a, b):
    for element in itertools.islice(list_, a, b):
        element

You can look at the islice documentation I linked for the full (python translated) implementation but this is a simplified version:
def islice(itr, start, stop):
    for index, element in enumerate(itr):
         if index == stop:
              break
         if start <= index:
              yield element


text:
Q: c++: Matplotlib pyplot show() giving SegFault I want to create a log-log plot using pyplot, but have trouble when calling plt.show():
import matplotlib.pyplot as plt

xVec = [...]
yVec = [...]

plt.figure()
plt.loglog(xVec,yVec,'.',label='This is my test plot')
plt.xlabel('x axis')
plt.ylabel('y axis')

plt.show()

I am running this code from C++ via:
Py_Initialize();
Py_SimpleString(pythonCode.str().c_str());
Py_Exit(0);

where pythonCode is a stringstream containing the Python code above. The code runs if I don't include the plt.show() line, but of course no plot shows up.
The matplotlibrc config file shows that the backend is TkAgg, which shouldn't give problems as indicated here or here. I've tried adding plt.close() after the last line in the code above, but the error persists.
Perhaps the most surprising thing is this: I've also tried running the code in a separate Python script (with plt.show()), and the plot appears correctly! Does anyone have any idea about what's going on? Thanks in advance!
EDIT: I have also tried pylab instead of pyplot, with the same results. Do I need to compile the program with a certain python module to link the libraries properly?


text:
Q: No envía datos ingresados en POST Tengo un problema con el envio de datos por POST, estoy realizando una aplicacion php con mvc puro y JavaScript (jQuery), ahora bien, estoy tratando de realizar un formulario el cual se encuentra en un DIV de una pagina principal, al momento de enviar el formulario deseo, que envie a un controlador ejemplo: Empresa y un metodo ejemplo guardarEmpresa, y ahí recoger los valores: en este momento solo tengo un campo empresa.

<!DOCTYPE html>

                    <form id="formulario" action="Empresa/guardarEmpresa" method="POST" >
                        <input type="text" name="empresa" id="empresa" placeholder="ingrese empresa">
                        <input type="submit" class="btn btn-primary mb-2"  value="Guardar">
                    </form>

Y tengo este Jquery:

jQuery(function($){

    var formulario = $('#formulario');

    formulario.submit(function(event) {
        event.preventDefault();
        var $target = $(event.currentTarget);

        var destinationLocation = $target.attr('action');
        if (destinationLocation !== '#') {
            $('#objeto').load(
                destinationLocation
            );
        }
    });

});

que actualmente funciona, osea, va al controlador se ubica en el metodo y si escribo dentro del mismo:

class empresa{
  public function guardarEmpresa(){
    echo "Llegas hasta acá y sin cargar me muestras este mensaje en el      div";
  }
}

redirige cargando el echo del mensaje, y lo coloca en el div

Pero cuando envío datos no los agarra en el metodo, osea no llegan los datos.
$empresa = $_POST['empresa'];
Resultado Nada
Le hago un var_dump a $_POST
Resultado Array()
Agradezco me puedan ayudar, ya lo hice sin el jquery (de la forma natural), me redirige la pagina y ahí si agarra los post. pero eso no lo necesito, necesito que todo lo maneje dentro del div.
Muchas gracias al que me pueda ayudar.

A: Es muy raro tu código, no estas usando AJAX, estás usando el comportamiento natural de un <form>
Te voy a dejar unas recomendaciones sin necesidad de utilizar el <form> a menos que utlices CSS con selectores directos a tag o acciones complejas con JS.
TU HTML

    <input type="text" id="empresa" placeholder="ingrese empresa">
    <input type="button" id="enviar" class="btn btn-primary mb-2" value="Cargar Excel">

Como el DOM ya sabe que tiene que recoger sólo un valor, entonces no necesitamos el formulario, sólo tener en memoria la empresa y la ruta donde se procesará. Quité el formulario, y le puse un ID al botón de enviar
TU JAVASCRIPT
//Cuando cargue el DOM ( función ready que tu tenías )
$( () => {

    /*Creamos una función que esté escuchando el evento
    click del botón enviar y pasamos unas instrucciones*/
    $( document ).on( 'click', '#enviar', function(){

        //Recogemos el valor de la empresa
        let empresa = $('#empresa').val();

        //Validamos que hayan escrito algo
        if( empresa.trim() != '' ){

            //Lanzamos una petición AJAX

            $.ajax({
                method: 'POST',
                url: 'Empresa/guardarEmpresa',
                data: { empresa },
                success: function( respuesta ){

                    /*Cuando el backend procese la solicitud regresará algo,
                    lo almacenamos en respuesta*/

                    //Ahora esa respuesta la ponemos en el div
                    $('#objeto').html( respuesta )
                }
            });
        }
    });
});

TU PHP
<?php
class Empresa{

    public function guardarEmpresa( $valor ){
      //Todo lo que tengas que hace con ese valor
      return "La información para el DIV";
    }
}

//Recuperas el valor que llegó por POST, en realidad
//El superarreglo $_REQUEST engloba $_POST y $_GET
$valor = $_REQUEST['empresa'];

//Instanciamos un objeto de empresa
$empresa = new Empresa();

//regresamos al front lo que procesó la función
echo $empresa->guardarEmpresa( $valor );
?>

No entiendo que haga tu código de PHP, de hecho no se por qué estas recibiendo los valores en la misma clase ( o lo estoy imaginando, quizá tenga otra esctructura ) si lo tienes todo junto te recomendaría lo separaras para una mejor mantenibilidad a largo plazo.
Si no te sirve mucho el código de PHP, solo puedes usar $_REQUEST['empresa'] o $_POST['empresa'] para recuperar lo enviado
Espero te puedas guiar


text:
Q: ThreadPool and Threading.Timer? I have a question about timer in thread?
My code :
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
       Testing testing = new Testing();
       Thread thread = new Thread(new ThreadStart(delegate
        {
            testing.Start();
        }));
        thread.IsBackground = true;
        thread.Start();
    }

}

public class Testing
{
    System.Threading.Timer timer = null;

    public void Start()
    {
        if (timer == null)
            timer = new System.Threading.Timer(timerTick, null, 500, 500);
        List<ManualResetEvent> amanual = new List<ManualResetEvent>();
        for (int index = 0; index < 10; index++)
        {
            ManualResetEvent manual = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object context)
                {
                    this.RunningThreadPool(context);
                    manual.Set();
                }
                ));
            amanual.Add(manual);
        }

        WaitHandle.WaitAll(amanual.ToArray());
        Console.WriteLine("Task complete");
    }
    void timerTick(object sender)
    {
        Console.WriteLine("Timer running");
    }

    public void RunningThreadPool(object context)
    {
        Console.WriteLine("Thread in Threadpool is running...");
    }
}

}
And this is result
Thread in Threadpool is running...
Thread in Threadpool is running...
Thread in Threadpool is running...
Thread in Threadpool is running...
Thread in Threadpool is running...
Thread in Threadpool is running...
Thread in Threadpool is running...
Thread in Threadpool is running...
Thread in Threadpool is running...
Thread in Threadpool is running...
Task complete
Timer running
Timer running
Timer running
Timer running
I have a question that how do timer run before threadpool executed. Except set timer on threadpool. Because i need timer check threads on threadpool.

A: I'd say that 500ms is quite enough time to complete your work queue, before the Timer even fires once. 10 Console.WriteLine calls doesn't amount to much work.
Assuming that you're running a somewhat heavier workload:
The Timer runs its callback in the ThreadPool, so it's queued after the other work has been queued... i.e. It's last in the queue. Because you are queueing more items than there are threads in the ThreadPool, and the ThreadPool only spins up new threads under prolonged load, the ThreadPool can't execute the Timer's callback in a timely fashion.


text:
Q: Discord js doesn't plays audio anymore I had a base discordjs code that could play 2 audio files, leave and join voice channels, but I did created a new file with this code followed from a youtube video:
const ytSearch = require('yt-search');

module.exports = {
    name: 'play',
    descreption: 'Play',
    async execute(message, args) {
        const voiceChannel = message.member.voice.channel;

        if (!voiceChannel) return message.send('PALI! Egy voice channelben bent kéne lenne, már nemazé!');
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if (!permissions.has('Player')) return message.reply('Kéne rang is nem gondolnád?, hogy a bánat egyeki a lelked!');
        if (!args.length) return message.channel.reply('KÖZÖLDNÉDHOGYMIAKUKITAKARSZ?? (Need more argumets)');

        const connection = await voiceChannel.join();

        const videoFinder = async (query) => {
            const videoResult = await ytSearch(query);
            return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
        }
        const video = await videoFinder(args.join(' '));
        if (video) {
            const stream = ytdl(video.url, { filter: 'audioonly' });
            connection.play(stream, { seek: 0, volume: 100 })
            on('finish', () => {
                voiceChannel.leave();
            });

            await message.reply(`Most játszom: ***${video.title}$***`)
        }
        else {
            message.channel.send('Nem találtam videót.')
        }
    }
}

Then I tried to imploment it into my other js file, but after I did it it gave me errors so I gave it up and deleted all that stuff, but now the original code just doesn't wants to play audio, it doesn't gives me errors or anything, I tried everthing I could but I couldn't solve it. Any solutions?
Here's the code:
const Discord = require('discord.js');
const client = new Discord.Client();
//const ytdl = require('ytdl-core');
//const ytSearch = require('yt-search');
var prefix = ';';
client.login('CENSORED');

client.on('ready', () =>{
    console.log('\n ----------WELCOME TO ADY STUDIOS AUTOMATIC------------')
})

client.on('message', async message => {

  if (message.content === ';join') {

    if (message.member.voice.channel) {
        const connection = await message.member.voice.channel.join();

    } else {
      message.reply('You need to join a voice channel first!');
    }
  }
  if(message.content === ';leave'){
    message.guild.me.voice.channel.leave();
    }

   if (message.content === ';coconut') {
        const connection = await message.member.voice.channel.join();
        const dispatcher = connection.play('./coconut.m4a');
   }
   if (message.content === ';roll'){
        const connection = await message.member.voice.channel.join();
       const dispatcher = connection.play('./rickroll.m4a');
   }

});

A: {   "dependencies": {     "@discordjs/opus": "^0.3.2",     "discord.js": "^12.3.1",     "ffmpeg-static": "^4.2.7",     "mysql": "^2.18.1",     "opusscript": "0.0.7",     "request": "^2.88.2",     "ytdl-core": "^4.2.1"   } } install disc should be work


text:
Q: Логика работы CMS Требуется создать CMS.
Админка

*

*Создание категорий

*Создание постов

*Создание под-доменов

С первыми двумя ясно, а вот как быть с под-доменами ? как они должны создаваться на хостинге ? или перенаправлятся через .htaccess ?
Нужно сделать так, чтобы меньше было тело-движений, ввел имя под-домена, нажал создать и он создался.
Но вот логика работы создания не ясна.
Подобная реализация есть в Wordpress (Multisite), нужно создать мини аналог, но без всех наворотов.


text:
Q: Meteor app works locally but will not load when deployed to meteor.com I have no idea what to do here. Everything was working fine but all of a sudden when I deploy now I get cryptic errors
Uncaught TypeError: Cannot read property 'helpers' of undefined
bf828391c4c2197419ba1631eee96dfda64d3e0a.js:111 Uncaught TypeError: Cannot read property 'ServiceConfiguration' of undefined
memrey.meteor.com/:1 Document was loaded from Application Cache with manifest http://memrey.meteor.com/app.manifest
memrey.meteor.com/:1 Application Cache Checking event
bf828391c4c2197419ba1631eee96dfda64d3e0a.js:3 Exception in callback of async function: TypeError: Cannot read property 'form' of undefined
    at x.setState (http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:135:16160)
    at a.contains.o.route.a.extend.onBeforeAction (http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:142:3525)
    at p (http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:72:4036)
    at http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:3:6711
    at C (http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:82:4631)
    at p (http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:72:4036)
    at http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:3:6711
    at b (http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:82:4559)
    at p (http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:72:4036)
    at http://memrey.meteor.com/bf828391c4c2197419ba1631eee96dfda64d3e0a.js:3:6711
memrey.meteor.com/:1 Application Cache NoUpdate event
bf828391c4c2197419ba1631eee96dfda64d3e0a.js:64 Route dispatch never rendered. Did you forget to call this.next() in an onBeforeAction?

The code is working just fine locally. So I am lost. I don't even know where to begin debugging.
I am using iron router with useraccounts template package. I am not sure if it is related to that.

A: Ok I found out what the issue is.
When I defined a template helper like:
Template.notification.helpers
I misspelled notification
Which caused all the errors. But what is strange is that it worked locally but not when deployed.

A: Exceptions may be tolerated because they are in seperate files when working in development mode, however when deployed in production they're minified and join so the execution of the js file is stopped.
Source


text:
Q: How to hide tabs in ionic2 Is it possible to remove tabs in ionic 2, My main component is as follows
<ion-tabs>
    <ion-tab [root]="tab1Root" tabTitle="Dash"> </ion-tab>
</ion-tab>

if I give   It gives error saying
Can't bind to 'show' since it isn't a known property of 'ion-tabs'

A: I was able to successfully hide tab bar on a specific page.
First give an id to the  component:
Then handle showing/hiding like this:
{
    templateUrl: '...',
})
export class PageWithoutTabBar
{

    constructor()
    {

        this.tabBarElement = document.querySelector('#tabs ion-tabbar-section');

    }

    ionViewDidEnter()
    {

this.tabBarElement.style.display = 'none';

    }

    ionViewWillLeave()
    {

        this.tabBarElement.style.display = 'block';

    }

}

A: In ionic 3, try
<ion-tab [root]="tab2Root" tabTitle="Tab 2" tabIcon="contacts" show=false></ion-tab >


text:
Q: Почему это приложение выдаёт мне Exception: Invalid instance in App.root? Мне нужно включить несколько лэйаутов в один в будущем, по-этому вариант из уже решенного вопроса мне не подходит:
from kivy.app import App
from calculate import *
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.config import Config
Config.set("graphics", "resizable", "0")

class MyRootWidget():
    pass

class uiApp(App):
    def build(self):
        app = MyRootWidget()
        return app

uiApp().run()

  BoxLayout:
    orientation: 'vertical'
    Button:
      text: "1"
    Button:
      text: "2"
    Button:
      text: '3'
    Button:
      text: '*'
    Button:
      text: '4'
    Button:
      text: '5'
    Button:
      text: '6'
    Button:
      text: '/'
    Button:
      text: '7'
    Button:
      text: '8'
    Button:
      text: '9'
    Button:
      text: '-'
    Button:
      text: '='
    Button:
      text: '0'
    Button:
      text: '+'
    Button:
      text: 'C'


text:
Q: Regex matching not working in jquery-highlighttextarea library I'm using jquery-highlighttextarea library and jquery-1.7.2.js for a sample application which is targeting to match and highlight a valid IPv4 address in an input tag.
There is a facility to match and highlight a text based on a regex
<script>
  $(document).ready(function() {
    $( "#demo1" ).keypress(function() {
        $('#demo1').highlightTextarea({
          words: {
            color: '#ADF0FF',
            words: ['[0-9]{1,3}'] // regex goes here
          }
        });
    });
  });

HTML :
<body>
  <article>
   <input id="demo1" class="inputBox"></input>
  </article>
</body>

I used (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) as the regex to catch the IP address.It was in here.
<script>
  $(document).ready(function() {
    $( "#demo1" ).keypress(function() {
        $('#demo1').highlightTextarea({
          words: {
            color: '#ADF0FF',
            words: ['(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)']
          }
        });
    });
  });
</script>

But the problem is now it's not matching the text correctly. i.e. it will take this (256.2.3) and this (23 123.123.123) as valid IPs.
I think someone familiar with regex or this particular library can help me with this.

A: The words value is a string that requires double slashes to escape regex metacharacters. Right now, the \. inside it is treated as a special regex subpattern matching any character but a newline, that is why you get matches where you do not want to.
It is always safer to use character classes to "wrap" such characters so as they are treated as literal symbols.
Use
words: ['(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)']

If you need to validate the string that is exactly the IPv4 address (i.e. it should only contain the IPv4 address), you will be safer using ^ (=string start) and $ (=string end) anchors:
words: ['^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$']


text:
Q: celery and long running tasks I just watch a youtube video where the presenter mentioned that one should design his/her celery to be short. Tasks running several minutes are bad.
Is this correct? What I do see is that I have some long running task, which takes say 10 minutes to finish. When these kind of task is scheduled frequently, the queue is swamped and no other tasks get scheduled. Is this the reason?
If so, what should be used for long running tasks?

A: Long running tasks aren't great but It's by no means appropriate to say they are bad.  The best way to handle long running tasks is to create a queue for just those tasks and have them run on a separate worker then the short tasks.

A: The problem with long running tasks is that you have to wait for them when you're pushing a new software version on your server. If you don't wait, your task may run possibly incompatible code, especially if you pickled some complex object as a parameter (which is strongly discouraged).

A: As @user2097159 said its a good practice to keep the long running tasks in a dedicate queue. You should do that by routing using "settings.CELERY_ROUTES" more info here
If you could estimate how long a task can be running, I recommend to use soft_time_limit per task, you will be able to handle it.
There is a gist from a talk I gave here

A: Augment the basic Task definition to optionally treat the task instantiation as a generator, and check for TERM or soft timeout on every iteration through the generator.  Generically inject a "state" dict kwarg into tasks that support it.  If it's the first time the task is run, allocate a new one in results cache, otherwise look up the existing one from results cache.
In your task, figure out a good place to yield which results in short execution times.  Update the state parameter as necessary.
When control returns to the master task class, check for TERM or soft timeout, and if there is one, save off the state object and respond to the signal.


text:
Q: Build a requirements.txt for streamlit app that directs to python script, which in turn determine the proper version of package to be installed I am preparing a streamlit app for object detection that can do both training and inference.
I want to prepare a single requirements.txt file that can work whether when the app is run locally or if the app is deployed to streamlit cloud.
On streamlit cloud obviously, I won't be doing training because of the need to have a GPU and in this case the user should clone the github repo for running locally.
Now, I come to the dependencies and requirements.txt. If I am running locally, I want to include say opencv-python but if I am running on streamlit cloud, I would want to include opencv-python-headless instead. PS: I have couple of cases like this; e.g pytorch+cuXX for local (GPU enabled) and pytorch for streamlit cloud (CPU only).
My question is how to reflect this in the requirements.txt file. I came across pip environment markers for conditional installation of pip packages, but the available environment markers cannot tell if the app is local or deployed. I wonder if there is a solution to this.
I came across this response which can help a lot, but as far as I understand it, I can make a setup.py and use subprocess.run to pip install the package. As I said, I would be doing previous work in this setup.py to determine the correct version for installation.
Given this (if this is a correct approach), then I call this setup.py from requirements.txt where each line represents something like a pip install <package_name>. I don't know yet how to do such a thing. If the total approach is not suitable for my case, I would appreciate your help.


text:
Q: Fellow oak dicom C-Find response i have a question regarding the c-find Operation in the fellow oak dicom. I have developed a Service wich implements a c-find operation and should send the found patients back tot he ultrasound machine. I'm testing currently with the 4d view "emulator" from GE.
I've implemented the code like I found on this forum and its receiving the request. I send back a dataset but everytime I get on the ultrasound machine the message that no items could be found. L
May anyone of you can help me?
Thanks in advance
Andreas
    Public Function OnCFindRequest(request As Global.Dicom.Network.DicomCFindRequest) As IEnumerable(Of Global.Dicom.Network.DicomCFindResponse) Implements Global.Dicom.Network.IDicomCFindProvider.OnCFindRequest
        Logging.Trace(CurrentLogger, "C-Find request")
        Dim familyname As String = ""
        Dim patientId As Integer?

        If request.Dataset.Contains(PatientNumberTag) Then
            Dim dicomLongStringItem As DicomLongString = request.Dataset.Get(Of DicomLongString)(PatientNumberTag)
            If IsNumeric(dicomLongStringItem.Value) Then patientId = dicomLongStringItem.Value
        End If
        If request.Dataset.Contains(PatientNameTag) Then
            Dim dicomPersonNameItem As DicomPersonName = request.Dataset.Get(Of DicomPersonName)(PatientNameTag)
            If Not String.IsNullOrEmpty(dicomPersonNameItem.Last) AndAlso dicomPersonNameItem.Last <> "*" Then familyname = dicomPersonNameItem.Last
        End If

        Dim responses As New List(Of DicomCFindResponse)()
        If request.Level = DicomQueryRetrieveLevel.Patient Then
            For Each result As DicomDataset In getworklistresults(request)
                Dim response As New DicomCFindResponse(request, DicomStatus.Pending)
                response.Dataset = result
                responses.Add(response)

            Next
        End If

        responses.Add(New DicomCFindResponse(request, DicomStatus.Success))

        Return responses
    End Function

    Private Function getworklistresults(request As Global.Dicom.Network.DicomCFindRequest) As List(Of DicomDataset)
        Dim dicomdatasets As New DicomDataset()

        dicomdatasets.Add(DicomTag.SpecificCharacterSet, "ISO_IR 100")
        dicomdatasets.Add(DicomTag.AccessionNumber, "")
        dicomdatasets.Add(DicomTag.ReferringPhysicianName, "")

        Dim sequenceDatase0 = New DicomDataset
        Dim sq0 As New DicomSequence(DicomTag.ReferencedStudySequence, sequenceDatase0)
        dicomdatasets.Add(DicomTag.ReferencedStudySequence, sq0)

        Dim sequenceDataset1 = New DicomDataset
        Dim sq1 As New DicomSequence(DicomTag.ReferencedPatientSequence, sequenceDataset1)
        dicomdatasets.Add(DicomTag.ReferencedPatientSequence, sq1)

        dicomdatasets.Add(New DicomPersonName(DicomTag.PatientName, DicomEncoding.GetEncoding("ISO 2022 IR 100"), "name^surname"))
        dicomdatasets.Add(DicomTag.PatientID, "12345")
        dicomdatasets.Add(DicomTag.IssuerOfPatientID, "")
        dicomdatasets.Add(DicomTag.PatientBirthDate, "")

        dicomdatasets.Add(DicomTag.PatientSex, "F")
        dicomdatasets.Add(DicomTag.PatientSize, "170")
        dicomdatasets.Add(DicomTag.PatientWeight, "170")
        dicomdatasets.Add(DicomTag.LastMenstrualDate, "")

        dicomdatasets.Add(DicomTag.StudyInstanceUID, "")
        dicomdatasets.Add(DicomTag.RequestingPhysician, "")
        dicomdatasets.Add(DicomTag.RequestedProcedureDescription, "")

        Dim sequenceDataset2 = New DicomDataset
        Dim sq2 As New DicomSequence(DicomTag.RequestedProcedureCodeSequence, sequenceDataset2)

        dicomdatasets.Add(DicomTag.RequestedProcedureCodeSequence, sq2)
        dicomdatasets.Add(DicomTag.AdmissionID, "")

        Dim sequenceDataset3 = New DicomDataset
        Dim sq3 As New DicomSequence(DicomTag.ScheduledProcedureStepSequence, sequenceDataset3)
        dicomdatasets.Add(DicomTag.ScheduledProcedureStepSequence, sq3)

        dicomdatasets.Add(DicomTag.RequestedProcedureID, "")
        dicomdatasets.Add(DicomTag.ReasonForTheRequestedProcedure, "")

        Dim a As New List(Of DicomDataset)
        a.Add(dicomdatasets)
        Return a
    End Function

A: You are missing many of the required return key attributes in your C-FIND Response. Please, review the "Table K.6-1 - Attributes for the Modality Worklist Information Model" in PS 3.4 of the DICOM standard.
If the value in the "Return Key Type" column is "1", you must include the attribute with a valid value in your C-Find response. As for example, Scheduled Station AE Title (0040,0001), Scheduled Procedure Step Start Date (0040,0002), Scheduled Procedure Step Start Time (0040,0003), Modality (0008,0060) etc are type 1 return key under Scheduled Procedure Step Sequence (0040,0100).
If the value for "Return Key Type" column is "2", you must include the attribute in C-Find response but it can be empty (if not know). Example of such attributes is Scheduled Performing Physician's Name, Scheduled Station Name, and Scheduled Procedure Step Location etc.
The value "1C" is like type "1" when condition is satisfied. Such example is Scheduled Procedure Step Description and Scheduled Protocol Code Sequence. Also, "2C" is type "2" conditional. Type "3" is optional and you do not need to include them in your response, if the attribute is not in the request dataset.


text:
Q: How do I tell awk not to make any changes to an empty row I have a dataset with three columns that look like this:
    0.1 0.2 0.3
    0.4 0.5 0.6

    0.7 0.8 0.9
    1.0 1.0 1.2

I want to subtract a certain number from each entry in the second column and I know how to do that. But with how the data looks, I end up getting an output that looks like this:
    0.1 0.1 0.3
    0.4 0.4 0.6
       -0.1
    0.7 0.7 0.9
    1.0 0.9 1.2

How do I prevent awk from adding that extra "-0.1" in the empty space?
I tried to use the sed command to remove that specific entry but since somewhere in the data, I have "-0.1" which must be in the data, it removes some important aspect of that data.

A: awk 'NF>0 {$2-=0.1}1' file

NF: The number of fields in the current input record.

Output:

0.1 0.1 0.3
0.4 0.4 0.6

0.7 0.7 0.9
1.0 0.9 1.2

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR


text:
Q: How to read another Text element value while customising element? What I Did:
Step 1: I have made two text element (let say name of elements are userName and UserId) in "Test" authoring Template.
Step 2: I have customized the first element( userName) by using jsp.
But while customising first element(userName) I need to fetch the second text element( UserId) value into userName.
I am able to get the value of first Text element(UserName) by using below Code but How I will get the second element value?
<%@ taglib uri="/WEB-INF/tld/portlet.tld" prefix="portletAPI" %>
<%@ page import="com.ibm.workplace.wcm.api.authoring.CustomItemBean" %>

<portletAPI:init />

<%
CustomItemBean customItem =
(CustomItemBean) request.getAttribute("CustomItemBean");
customItem.setSubmitFunctionName("myoptionsubmit");
String fvalue = (String)customItem.getFieldValue();

%>

<INPUT id='<%=customItem.getFieldName()%>_mycustomoption' value="<%=fvalue%>">

A: <%@ page import="com.ibm.workplace.wcm.api.*"%>
<%@ page import="com.ibm.workplace.wcm.api.exceptions.*"%>
<%@ page import="java.util.*,javax.servlet.jsp.JspWriter,java.io.*"%>
<%
Workspace myworkspace=null;
try {
DocumentId docId=null;
DocumentIdIterator itemsIterator=null;
myworkspace = WCM_API.getRepository().getSystemWorkspace();
DocumentLibrary MyLibrary = myworkspace.getDocumentLibrary("LIB_FOR_DEVICE");
DocumentIdIterator docIdIterator = myworkspace.findByName(DocumentTypes.Content,    "RENDER_TEST_CONTENT");
DocumentId docId1;
Content currentContent;
LibraryRichTextComponent currentContent1;
Object object=null;
TextComponent textComponent=null;
RichTextComponent richTextComponent=null;
ImageComponent imageComponent=null;
while(docIdIterator.hasNext())
{
docId1 = (DocumentId)docIdIterator.next();
currentContent = (Content)myworkspace.getById(docId1);

ContentComponentIterator contentComponentIterator=currentContent.componentIterator();
     while(contentComponentIterator.hasNext())
     {
     object=contentComponentIterator.next();
     if(object instanceof TextComponent)
     {
     textComponent=(TextComponent)object;
      out.println("
TC:
"+ textComponent.getText());
     }
      if(object instanceof RichTextComponent)
     {
     richTextComponent=(RichTextComponent)object;
      out.println("
RTC:
"+ richTextComponent.getRichText());
     }
     }

 }

myworkspace.logout();
}
   catch (Exception e)
   {}
   %>