text:
Q: Can Macbook be serviced by Apple Care with FileVault enabled? A few years back I had to send a Powerbook to Apple for hardware repairs (the optical disc stopped working and had to be replaced.)
I had FileVault enabled, and the tech at the time told me I'd have to disable that encryption in order for them to implement the repairs. So for privacy I just re-formatted the entire OS (having a backup, of course) before handing it off.
Is it still the case that Apple requires FileVault(2) to be turned off before they will repair a Macbook?

A: Firstly, I think this would be better handled by calling Apple Support directly. I do not see mention of this in any of the repair terms and conditions documents on apple.com.
Secondly, regardless of whether Apple requires FileVault 2 to be disabled or not, I would recommend that you follow the same process you did before - backup all the data, reformat it and install OS X afresh before giving it for repair. This would protect your privacy and also reduce (or prevent) wasting time with support if/when they inform you that they would have to format the drive and install OS X because it's encrypted with File Vault 2.

A: The response I got from Apple Support:

For many repairs, as well as quality checks after a completed repair, it is necessary that our technicians can boot the Mac. If FileVault is enabled, that means that we do need to note the password for the time of the repair.
A viable alternative is to wipe the Mac's hard drive or flash storage prior to the repair and restore from a backup afterwards.

So either prepare to hand off your password to them, or empty your hard drive before giving the macbook for repair.


text:
Q: MVC 4 adding sub-items to navigation menu I'm starting working with MVC4 (Responsive), HTML5 and CSS3.
I've created a new MVC4 Project, now i want to add sub items do the navigation menu, I want to keep the current structure to preserve responsiveness, I just want to add the sub items.
The HTML is like that:

@Html.ActionLink("Menu 1", "Index", "Home")

Sub 1.1

Sub 1.2

Sub 1.3

The CSS looks like:
/* menu */
nav {
    margin-bottom: 5px;
}

ul#menu {
    margin: 0;
    padding: 0;
    text-align: center;
}

ul#menu li {
    margin: 0;
    padding: 0;
}

What changes do I have to do to make the drop down menu?

A: You nest another
 inside of an

Menu1

Menu2

Menu3

    Menu4

SubMenu1

SubMenu2

SubMenu3

Then you'll want some styling on the nested ul to hide it until the users performs a mousehover over the parent
.
#nav ul{
    display : none;
}
#nav li:hover > ul{
    display : block;
}

Here is a fiddle for you to have a look: http://jsfiddle.net/8QtaL/6/
This is a pure html / css solution. No jQuery or javascript.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Working with MultipartFile in Spring MVC 5 always return null I can not upload an Image to a specific directory in my server. the multipartfile variable always is empty, here my code
Config Bean
 @Bean
public CommonsMultipartResolver multipartResolver()
{
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setDefaultEncoding("utf-8");
    return resolver;
}

Domain Class
private MultipartFile producImage;

public MultipartFile getProductImage() {
    return producImage;
}

public void setProducImage(MultipartFile producImage) {
    this.producImage = producImage;
}

Controller Class
   @RequestMapping(value = "/products/add", method = RequestMethod.POST)
public String processAddNewProductForm(@ModelAttribute("newProduct") Product newProduct, BindingResult result, HttpServletRequest request)
{
    String[] suppressedFields = result.getSuppressedFields();
    if(suppressedFields.length > 0)
    {
        throw new RuntimeException("Attempting to bind disallowed fields " + StringUtils.arrayToCommaDelimitedString(suppressedFields));
    }
    // productImage always receive null value !!!!!!
    MultipartFile productImage = newProduct.getProductImage();
    String rootDirectory = request.getSession().getServletContext().getRealPath("/");
    if(productImage != null && !productImage.isEmpty())
    {
        try
        {
            productImage.transferTo(new File(rootDirectory + "resources\\images\\" + newProduct.getProductId() + ".png"));
        }
        catch(Exception ex)
        {
            throw new RuntimeException("Product Image Saving failed", ex);
        }
    }

    productService.addProduct(newProduct);
    return "redirect:/market/products";
}

FrontEnd: addproduct.jsp
  <form:form method="POST" modelAttribute="newProduct" class="form-horizontal" enctype="multipart/form-data">
            <fieldset>
                <legend>Add New Product</legend>

                        <spring:message code="addProduct.form.productImage.label" />

                        <form:input id="productImage" path="productImage" type="file" class="form:input-large" />

                        <input type="submit" id="btnAdd" class="btn btn-primary" value ="Add"/>

            </fieldset>
        </form:form>

I dont know why is not working. Thanks for your help in advance

A: You have to initialize a bean of type MultipartFilter and set the multipart resolver, giving Spring the ability to handle requests containing files:
@Bean
public MultipartFilter multipartFilter(){

    MultipartFilter multipartFilter = new MultipartFilter();
    multipartFilter.setMultipartResolverBeanName("multipartResolver");
    return multipartFilter;
}


text:
Q: Django - ForeignKey : Is it possible get multiple kind of objects referencing itself? models.py
class BaseModel(TimeStampedModel):
    is_active = models.BooleanField(default=True)

    class Meta:
        abstract = True
        ordering = ('-created',)

    def deactivate(self):
        # Make all child objects is_active=False

class ModelA(BaseModel)
    name = models.CharField(max_length=10)

class ModelB(BaseModel):
    model_a = models.ForeignKey(ModelA)
    name = models.CharField(max_length=20)

class ModelC(BaseModel):
    model_a = models.ForeignKey(ModelA)
    name = models.CharField(max_length=20)

As you can see above, I want to make deactivate method for setting all childeren's is_active field as False.
Someone might think of this way:
def deactivate(self):
    # Make all child objects is_active=False
    b = ModelB.objects.filter(parent=self)
    c = ModelC.objects.filter(parent=self)

    for obj in b:
        obj.is_active = False
        obj.save()

    for obj in c:
        obj.is_active = False
        obj.save()

But it only works for ModelA which ModelB, ModelC are referencing, not available for all models.(e.g I I called modelB.delete(), it won't deactivate its child model(if ModelB had child model)
I want to make it general method so that I can use it in any models:
all_model_objects = ModelsReferencingMe.objects.filter(parent=self)

Is there any way to implement this?

A: I think you can make use of Model._meta API here.
class BaseModel(object):
    deactivation_field = None  # don't forget to override in subclasses

    is_active = models.BooleanField(default=True)

    class Meta:
        abstract = True
        ordering = ('-created',)

    def deactivate(self):
        related_models = [
            f.related_model for f in self.__class__._meta.get_fields()
            if (f.one_to_many or f.one_to_one)
            and f.auto_created and not f.concrete
        ]
        filter_clause = {self.deactivation_field: self}
        for model in related_models:
            items = model.objects.filter(**filter_clause)
            items.update(is_active=False)
            for item in items:
                item.deactivate()

And use it as follows:
class ModelA(BaseModel)
     deactivation_field = 'model_a'

     name = models.CharField(max_length=10)

class ModelB(BaseModel):
     deactivation_field = 'model_b'

     model_a = models.ForeignKey(ModelA)
     name = models.CharField(max_length=20)

Explanation: each time you call .deactivate() on some model instance, it will loop through models, set is_active to False in a single SQL UPDATE (a single update for each table, of course) and then loop through all given instances, calling .deactivate() for each instance. The purpose of deactivation_field I added is to let the deactivate method know how to filter items of child models. For instance, in case of ModelA filter_clause will yield .filter(model_a=self), in case of ModelB - .filter(model_b=self), and so on.
There are, of course, some caveats:

*

*QuerySet.update does not call .save or any signals, so if that's an issue to you, replace a single update query with individual .save calls.

*The code above does not expect any other related models except for BaseModel subclasses. If there are other models, make sure to check for that yourself.

*Maintaining deactivation_field is up to you, if you forget about it in subclasses - do expect errors.

*Do note that this idea of yours requires a deep recursion with nested loops and is a performance nightmare.


text:
Q: Search for specific words in mysql select * from data WHERE name LIKE  '%Hi There%';

returns this:
Hi There John
Hi There
Man Hi There
Hi There Mate
Hi Theres Alice
Hi Theree Man

I only want Hi There John, Hi There Mate, Hi There and Man Hi There to be returned because they contain Hi There specifically. Hi Theres Alice and Hi Theree Man should not appear.
How can this be done, simply?

A: If I understand correctly, this should work:
SELECT * FROM data WHERE
    name LIKE 'Hi There %' OR
    name LIKE '% Hi There %' OR
    name LIKE '%Hi There';

A: Use a regular expression instead of LIKE. Then you can use [:<:] and [:>:] to match word boundaries.
select * from data WHERE name RLIKE  '[:<:]Hi There[:>:]';

A: You can use regular expressions to get exactly the rows with the values you want. A query that gives you what you need would look something like this:
select * from data WHERE name REGEXP '{^\bHi There\b\s*.*$}';


text:
Q: How I can stack elements above each other? So, i have this simple footer element within which i nested 4 svg images and a Paragraph.

© 2017 Chirca Razvan

And these are the styles applied to it:
.svg {
       width: 50px;
       height: 50px;
    }

    .copyright {
        display: block;
        flex-basis: auto;
        margin-left: 15px;
        margin-right: 15px;
    }

    footer {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        background: rgb(9, 28, 41);
        padding: 30px 0;
        text-align: center;
    }

an visual example
I want to make that paragraph to appear below the images with some space between them.

A:

© 2017 Chirca Razvan

A: Add width: 100% to the paragraph, or change the flex-basis from auto to 100%.

.svg {
  width: 50px;
  height: 50px;
}

.copyright {
  display: block;
  flex-basis: auto;/*change to 100%*/
  margin-left: 15px;
  margin-right: 15px;
  color: #fff;
width: 100%;/*or add this*/
}

footer {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  background: rgb(9, 28, 41);
  padding: 30px 0;
  text-align: center;
}

© 2017 Chirca Razvan


text:
Q: Set Gmail as default mail handler for Mail PDF print option for Snow Leopard I handle most of my email through Gmail's web interface either in Firefox or Chrome.
Often I would like to print -> PDf -> mail pdf to a customer.  However the Mail PDF option in the print panel opens up a Mail.app compose window.
Instead I would like this to open a compose panel in whatever browser currently has a copy of Gmail running.
At present I can print directly to PDF, then in Gmail compose, attach, comment, send, then delete the PDF.
An alternative not quite as good solution from my perspective would be for Mail to track the contacts from Gmail so that a few characters would auto complete.  But that solution also eludes me.

A: The only way that I know how to accomplish this is to use Mailplane which is a commercial Mac app for using Gmail's web interface.
It has its own "Mail PDF with Mailplane" service which comes as part of the app:

There's no way that I know of to automate the process of attaching a PDF (or any other file) to Gmail through a web browser. You're going to need a Mac app for that. That either means setting up an email client such as Mail.app (which means duplicating contacts, etc) or Mailplane (which will let you use your existing contacts).


text:
Q: Horizontal menu CSS not working in IE7 I am trying to create a horizontal drop down menu with 3 levels of sub menus. I have almost created all menu items. I am trying to make it cross browser compatible. While I was testing in IE7 menu is not diaplaying properly. float is not working.  Please suggest me what to do?
here is my code:

Home

Applications

Agency

NVE South

NVE North

Manual Crawl

Crawl Interval

Archive List

 Visual Analytics

Settings

Manage Subject

Add Subject

Edit Subject

Delete Subject

Export Subject

Manual Crawl

Crawl Interval

Archive List

Fiddle Link
Result in IE8:

Result in IE7:

A: #menu_new > li{
display:inline-block;
position:relative;
line-height:35px;
height:35px;
*display:inline;/*Add this code of line*/
zoom:1; /*and Add this code of line*/
}


text:
Q: How can i rotate gridview on page? I want to rotate gridview in Web Form to print it clear because it doesn't fit in portrait orientation of the page. Gridview is going after page-break-before:always;
But when I rotate it, it cuts 50% of the grid for some strange reasons.
How can I rotate grid and make it fit 100% on the page ?
I want to have something like this :

But i have this situation

My CSS to rotate :
.gridCss {
    width: 100%;
    -ms-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -webkit-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    font-size:8px;
    word-wrap: break-word;
    height:100%;
}

My code:

     <asp:Label ID="MainLbl" runat="server"  />   и

    <asp:Label ID="Lab1" runat="server" Text=""></asp:Label>

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="DSI" Width="100%"   >
        <Columns>
            <asp:BoundField DataField="one" HeaderText=""  SortExpression="1" HtmlEncode="True" />
            <asp:BoundField DataField="fio" HeaderText="two" SortExpression="2" />
            <asp:BoundField DataField="3" HeaderText="" SortExpression="3" />
            <asp:BoundField DataField="4" HeaderText="К4" SortExpression="4" />
            <asp:BoundField DataField="Date" HeaderText="5" SortExpression="Date" />
          ...
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="DSI" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectSta %>" SelectCommand="Command" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:SessionParameter Name="Sess" SessionField="Sess" Type="String" />

            <asp:Parameter DefaultValue="1" Name="st" Type="Int32" />
            <asp:Parameter DefaultValue="1" Name="nr" Type="String" />

        </SelectParameters>
    </asp:SqlDataSource>

            	_______
            <asp:Label ID="Label_gv_2"        runat="server" Text="_____"></asp:Label>
            _______    __________________ 	Дата:___
            <asp:Label ID="Label_dt_2" runat="server" Text="_____"></asp:Label>
            ________ 		(ФИО)				(подпись)

A: I used DevExpress Data Grid that supports export and printing with extended options, including document page orientation. If you do not need the grid, you can use their reporting tool to print tabled data.


text:
Q: Google App Script export CSV to a customer Delimiter I have this script to export my google sheets to CSV file. I would like to export has a CSV with a customer delimited tab "|".
var pasteDataRequest = Sheets.newPasteDataRequest();
  pasteDataRequest.coordinate = {
    sheetId: SpreadsheetApp.getActiveSheet().getSheetId(),
    rowIndex: 0,
    columnIndex: 0
  };
  pasteDataRequest.data = data;
  pasteDataRequest.type = SpreadsheetApp.CopyPasteType.PASTE_VALUES;
  pasteDataRequest.delimiter = '|';

I have the full script here.
If i do export in the current way, its still split by seperated comma ",".
How u I can export my data demilited in csv with "|"?

A: How to ouput a text file similar to a CSV but with a custom delimiter
Here is a very simple method to ouput your file as a type of CSV-like file but instead of being separated with , is separated with | or any delimiter you want.
function createCsvContent(values, delimiter) {

  // This converts the values 2D array into a simple array of strings delimited by the delimiter
  const stringArray = values.map(row => row.join(delimiter))
  // Then it joins all the strings with newlines
  const output = stringArray.join("\n")

  return output
}

function createCsv() {
  // Get all the values from the sheet as a 2D array
  const file = SpreadsheetApp.getActive();
  const sheet = file.getSheetByName("Sheet1");
  const range = sheet.getDataRange();
  const values = range.getValues();

  // call the function to create the csv-like content
  const csvContent = createCsvContent(values, "|")

  // create the file in drive
  DriveApp.createFile('csvFile', csvContent, MimeType.PLAIN_TEXT)
}

Note that the last line creates the file as a plain text file. I was going to make this CSV but since its no longer comma-separated, it can no longer be classified as a CSV file. Though if you change this, it will work all the same.
The main creation happens in the createCsvContent function. It uses the map method of arrays to transform the 2D array that is obtained from the spreadsheet  into a simple array of strings.
From:
[
    [1,2,3],
    [4,5,6],
    [7,8,9],
]

To:
[
    "1|2|3",
    "4|5|6",
    "7|8|9",
]

Then finally using another join on the main array to transform it to:
"1|2|3\n4|5|6\n7|8|9"

The \n means "newline", in the end it will be rendered like this:
1|2|3
4|5|6
7|8|9

Then its a case of calling DriveApp.createFile with the name of the file you want, the content as generated by the createCsvContent function, and the mime type.
Edit
To replace the same file each time, instead of:
// create the file in drive
DriveApp.createFile('csvFile', csvContent, MimeType.PLAIN_TEXT)

You would need to get the file id of the "csv" and use getFileById and setContent:
DriveApp.getFileById("[FILE_ID]").setContent(csvContent)

setContent()
EDIT 2
To get the ID of any file in Drive you first go to drive and right click on the file you want. Click on "Get Link", then here you will find the ID:

References

*

*createFile(name, content, mimeType)

*getValues()

*map

*join


text:
Q: can't find css, images and js static files in spring my servlet-context.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing
        infrastructure -->

    <context:component-scan base-package="com.aitrich.learnware.web" />

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Maps '/' requests to the 'home' view -->
    <mvc:view-controller path="/" view-name="home" />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources directory -->

    <mvc:resources mapping="/resources/css/**" location="/resources/css/" />
    <mvc:resources mapping="/resources/js/libs/**" location="/resources/js/libs/" />
    <mvc:resources mapping="/resources/img/**" location="/resources/img/" />

    <!-- Internationalization support -->

    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="en_US" />
    </bean>

    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>

    <bean
        class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="localeChangeInterceptor" />
            </list>
        </property>
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="locale/messages" />
    </bean>

    <!-- **************************************************************** -->
    <!-- THYMELEAF-SPECIFIC ARTIFACTS -->
    <!-- TemplateResolver <- TemplateEngine <- ViewResolver -->
    <!-- **************************************************************** -->

    <bean id="templateResolver"
        class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML5" />
    </bean>

    <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
        <!-- These lines configure the dialects to use with Thymeleaf -->
        <property name="dialects">
            <set>
                <bean class="org.thymeleaf.spring3.dialect.SpringStandardDialect" />
                <bean class="nz.net.ultraq.web.thymeleaf.LayoutDialect" />
            </set>
        </property>
    </bean>

    <bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
    </bean>

</beans>

And i access the image using thymeleaf like
<img src="../../resources/img/cancel.png" th:attr="src=@{resources/img/cancel.png}, title=#{background}, alt=#{background}" />

But nothing is showing..!

A: If you have java project and your resources/img/** or resources/css/**  folder comes under WebContent  you can access the your resources like this
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/styleV.css"
 type="text/css" />

and similar way for images and js file.
Or second approach is you can add following mapping in web.xml for your servlet.
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
  </servlet-mapping>

 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
 </servlet-mapping>

and access the css as
<link rel="stylesheet" type="text/css" href="resources/css/jquery-ui-1.8.22.custom.css">

A: Try add to web.xml
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.ico</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
</servlet-mapping>

and my css/js/img located - webapp/js/, webapp/img/, webapp/css/

A: I just found on Linux that I have to remove the starting "/" in my resource mapping!
see here
<!--    NOTE the location does not have a starting /!!!! -->
<resources mapping="/resources/**" location="resources/" />

boy did this cause me a lot of frustration.  All the examples have the / prefix for location.  It works great now by calling c:url pattern example below:
<link rel="stylesheet"
 href="<c:url value="/resources/css/coreStyle.css" />" type="text/css">


text:
Q: Entity Framework Code First with an existing database view My team is starting a new project using Entity Framework Code First.  We have a new, empty database for the project; the schema will be managed through Code First migrations.
However, there is one piece of data that we will need to access that lives in an external database (managed by a different project).  We were given access to this data through a view in our own database that maps to a table in the external database.
Because of this setup, we have two competing requirements:

*

*When creating migrations, Entity Framework should not try to create or edit the view.

*At runtime, we should still be able to query/insert/update/delete data through the view using Entity Framework as if it is a regular table.

We've looked at both the [NotMapped] attribute and the .Ignore() method, but both seems to only satisfy one of the two requirements above.
Is this configuration possible using Entity Framework Code First, or will we need to switch to Database First?
We're using Entity Framework Core version 2.1.1.

A: There is no configuration which satisfies both requirements, and I don't see how Database First (or Code Second) would help, since the problem is with migration, not mapping.
The requirement #2 can easily be satisfied by mapping the view as table (either conventionally, [Table] data annotation or ToTable fluent API). For EF CRUD operations it really doesn't matter if the actual db object with that name is a table or view, as soon as it supports the corresponding SQL commands.
The requirement #1 cannot be satisfied by the above solution, but can easily be workaround. Since EF Core requires pre created code migrations (no automatic migrations like EF6), you can manually edit the migrations which contains CreateTable in Up / DropTable in Down and simply remove them.
Actually there is also a solution based on custom MigrationSqlGenerator, but it's more complicated and doesn't worth the effort just for a single view.


text:
Q: How to overwrite a method of a dynamically created class instance A class I cannot change the code of has a method from_lowercase that returns an instance of itself. Now I would like to inherit a class. However, when calling the inherited class over from_lowercase an instance of the original class is returned.
class Animal:
    """I CANNOT change the code in this class"""
    def __init__(self, uppercase_name: str):
        self.uppercase_name = uppercase_name

    def say(self) -> str:
        return f"I am {self.uppercase_name}"

    @staticmethod
    def from_lowercase(lowercase_name: str) -> "Animal":
        return Animal(lowercase_name.upper())

class PoliteAnimal(Animal):
    def say(self) -> str:
        return f"Hello dear sir, {super().say()}!"
    # insert magic here

calling some examples:
animal = Animal("JOHN")
animal_from_lowercase = Animal.from_lowercase("john")
nice_animal = PoliteAnimal("MARIA")
nice_animal_from_lowercase = PoliteAnimal.from_lowercase("maria")

print(animal.say())
print(animal_from_lowercase.say())
print(nice_animal.say())
print(nice_animal_from_lowercase.say())

leads to the following:
I am JOHN
I am JOHN
Hello dear sir, I am MARIA!
I am MARIA

However, the desired output is the following:
I am JOHN
I am JOHN
Hello dear sir, I am MARIA!
Hello dear sir, I am MARIA!

Obviously nice_animal_from_lowercase is an instance of Animal and not PoliteAnimal. How can this be fixed?

A: You need to implement the same method on your subclass so it will be overridden
class PoliteAnimal(Animal):
    def say(self) -> str:
        return f"Hello dear sir, {super().say()}!"
    # insert magic here
    @staticmethod
    def from_lowercase(lowercase_name: str) -> "Animal":
        return PoliteAnimal(lowercase_name.upper())

Ouput:
I am JOHN
I am JOHN
Hello dear sir, I am MARIA!
Hello dear sir, I am MARIA!

A: I would patch Animal to fix from_lowercase, which should be a class method, not a static method.
def from_lowercase(cls, lc: str):
    return cls(lc.upper())

Animal.from_lowercase = classmethod(from_lowercase)

This works even if you do it after PoliteAnimal is defined.
When you call PoliteAnimal.from_lowercase(...), the method lookup will result in a call to Animal.from_lowercase, but as a class method it will receive PoliteAnimal as its first argument, leading to the correct class being instantiated.


text:
Q: sub query in sql server I have two tables :
create table sales (
    unitcode int ,
    categorycode smallint ,
    ddate varchar(10) ,
    price float
)

and
create table timetable (
    year varchar(4) ,
    month varchar(11) ,
    ddate varchar(10)
)

I want to write a subquery to find :
 in each month in each year which 2 products(unitcode , categorycode) have a top of price ?

A: Try this
;WITH cte AS (
SELECT  unitcode,categorycode,t.ddate,price,ROW_NUMBER() OVER (PARTITION BY t.[year],t.[month] ORDER BY price desc) AS price_order,t.[year],t.[month]
FROM  sales s
INNER JOIN timetable t
    ON t.ddate = s.ddate
)
SELECT  *
FROM    cte
WHERE price_order <= 2
ORDER BY [year] ASC,[month] ASC,price DESC


text: Q: MySQL curious duplicates issue I have a MySQL members table with names and addresses, and need to find those rows with duplicate addresses. I do this successfully with a query using GROUP BY.  The curiosity is that it produces an output of 300+ rows of duplicate addresses, as expected, but includes just one record as being a duplicate when it isn't. If I add a GROUP_CONCAT to the query it lists the same unique id number twice for this row.  Any ideas why this should happen?


text:
Q: Data between two dates using where condition I'am Using a stored procedure to retrieve values between data using Where condition(related to particular Person not the one related to Date).
E.g I have table with cols
User Name  User ID  date_used  Book Name
xxxx       UID001   12-03-2012 zzzzz
yyyy       UID002   14-03-2015 ccccc
xxxx       UID001   14-03-2015 rrrrr

Desired Out put
User Name  User ID  date_used  Book Name
xxxx       UID001   12-03-2012 zzzzz
xxxx       UID001   14-03-2015 rrrrr

For this I tried below way, please help me where i'm wrong
SELECT     UserID,Issue_Date,Book_Name FROM dbo.Books
where UserID = @userID and Issue_Date >= @From and Issue_Date <= @To
order by Issue_Date Desc

@From(datetime) and @to(datetime) are datepickers value(startDate and EndDate)
@userID varchar
When i remove UserID clause I was able to retrive all the books issued for all the users. but when i add a where clause of user id no rows are reflected.
Please advice me on this with other methods to get this done.


text:
Q: Form Processing Ajax I have a very simple form.I want to insert the form data in mysql database.using ajax.
I need to pick data from form and send them as xml to the server.
the form is  as :
              <form>
                     Name:<input type="text" id=name/>
                     Contact<input type="text" id=contact/>
              </form>

And i am picking the data from my form using js as :
              function GetData(form)
                     {
                             var name=document.getelementbyid('name');
                             vat contact=document.getelementbyid('contact');
                     }

               function Ajax
                        {
                            " Here i want to send the form datas as an xml to the server"
                        }

Can any one help me how to do this .And also how to receive the the request from server as xml and insert to database.
Just give me the proper way.Not Query string or json or jquery.I want to use xml using ajax
Thanks,

A:  function GetData(form)
{
var name=document.getelementbyid('name');
var contact=document.getelementbyid('contact');
Ajax(name,contact);
                     }

function Ajax(name,contact)
{
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    var response=xmlhttp.responseText;
    }
  }
//var datas='?name='+name+'&contact='+contact;
var xmlval='<name>'+name+'</name><contact>'+contact+'</contact>';
 var datas='?xmlvalue='+xmlval;
xmlhttp.open("GET",'phpfile.php'+datas,true);
xmlhttp.send();
}

Important question: Why do you need XML to submit?
Also, to use XML, look up SimpleXML, and to save to database, there are a lot tutorials.
Update: if you meant the response as XML? That's just like the same as in JS. And to use it in JS, look at this. However, in that case, uncomment the commented line and comment the next 2.


text:
Q: Proving system of bilinear equations does not have a solution using convex optimization Consider a collection of $m$ matrices $A_i$ of size $n\times n$, and a vector $b$ of size $m$. Collecting variables into two vectors $x,y$ of size $n$, I have the bilinear system of equations:
$$\left\{ x^T A_i y = b_i : i = 1,\dots,m \right\}.$$
I would like to consider the domain of the variables to be the complex numbers.
What techniques are available to prove such a system has no solution?

In case it helps, the particular problem I am interested in has $A_i$ and $b$ real valued.
Furthermore, the $A_i$ are such for any pair of values of $j$, $k$ the term $x_j y_k$ will only be used by at most one $A_i$ constraint. (The latter sounds quite constraining, but I couldn't figure out how to use it effectively.

Here is an interesting approach suggested on mathoverflow for solving such systems:
https://mathoverflow.net/questions/308163/solving-system-of-bilinear-equations
The suggestion is to linearize it into a system of equations on the elements of the matrix $Z = x y^T$. Such a matrix (as long as zero is not a solution) must have rank 1. Then we may use convex optimization: the constraints are now linear, and optimize the solution with the objective to minimize $||Z||_{*}$ the nuclear norm which is a proxy for the rank.
I do not understand this method well enough to understand if it is guaranteed to work if there is a solution. In particular, I'd like to invert the argument: if I optimize and get a matrix with rank>1, can I therefore conclude that there is no solution to the original problem?


text:
Q: "Ten bucks says…" or "Ten bucks say…"? Which is correct? In the movie Avengers I, when the Cap said,"At this point, I doubt anything would surprise me." Then the director Fury answered,"Ten bucks says you're wrong."
I understand that Fury was betting ten bucks that the cap was wrong. My questions are:
1) 'Ten bucks' is a plural, why use 'says' instead of 'say'?
2) It's not the first time I heard this expression and it seems most time people use 'says'; so is it a fixed phrase ? Or some kind of abbreviation for some sentence? If so, could anyone help to show me the complete version? Thanks a lot.


text:
Q: Get last logout for every user for every day (MAX(), GROUP BY) [postgresql] I have multiple logouts for many users. I want to get the last logout for every user for every day.
SELECT t_logouts.log_id,
t_users.last_name || ' ' || t_users.first_name,
t_logouts.log_date,
MAX(t_logouts.log_time),
(DATE_PART('hour', '18:00:00'::time - t_logouts.log_time ) * 60 +
 DATE_PART('minute', '18:00:00'::time - t_logouts.log_time )) / 60
FROM t_logouts
LEFT JOIN t_users
ON t_users.user_id = t_logouts.user_id
GROUP BY DATE(t_logouts.log_date), t_users.user_id
ORDER BY t_logouts.log_date  DESC, t_logouts.log_time  ASC ;

Throws error:
LINE 1: SELECT t_logouts.log_id,
               ^
SQL state: 42803
Character: 8

There are some problem with multiple aggregation as far as I understand.
I've tried to use this manual:
https://www.postgresqltutorial.com/postgresql-group-by/
https://www.postgresqltutorial.com/postgresql-max-function/
Tables I am trying to work with.
CREATE TABLE t_users (
    user_id SERIAL PRIMARY KEY,
    nickname name UNIQUE not null check (length(nickname) < 64),
    first_name VARCHAR NOT NULL check (length(first_name) < 64),
    last_name VARCHAR NOT NULL check (length(last_name) < 64),
    email VARCHAR DEFAULT NULL check (email ~* '^.+@.+\..+$' )
);
CREATE TABLE t_logins (
    log_id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL,
        FOREIGN KEY (user_id)
        REFERENCES t_users (user_id)
        ON UPDATE CASCADE ON DELETE RESTRICT,
    log_date DATE NOT NULL,
    log_time TIME NOT NULL
);
CREATE TABLE t_logouts (
    log_id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL,
        FOREIGN KEY (user_id)
        REFERENCES t_users (user_id)
        ON UPDATE CASCADE ON DELETE RESTRICT,
    log_date DATE NOT NULL,
    log_time TIME NOT NULL
);

A: This is typically done using distinct on () in Postgres:
SELECT distinct on (t_users.user_id)
         t_logouts.log_id,
         t_users.last_name || ' ' || t_users.first_name,
         t_logouts.log_date,
         t_logouts.log_time,
         extract(epoch from '18:00:00'::time - t_logouts.log_time) / 3600
FROM t_logouts
  LEFT JOIN t_users ON t_users.user_id = t_logouts.user_id
ORDER BY t_users.user_id, t_logouts.log_date DESC;


text:
Q: Creating a file with a list so for my code, I am trying to create a program that creates a file, and enters this into the file.
0 1
1 2
2 3
3 4
4 5

I was trying to get a for loop to obtain this, but I am getting an error with using an int in a string. How would you tell the program to also print the first number in the row plus one without using the +1 in the write?
f = open("data.txt","w")
for int in range(0,4):
    f.write(int)
    f.write(int+1)
    f.write("\n")

A: f = open("data.txt","w")
for i in range (0,5):
    f.write(str(i))
    f.write(str(i+1))
    f.write("\n")
f.close()

A: Use str(i) or:
with open('data.txt','w') as fout:
    for i in range(0,5):
        fout.write(f'{i} {i+1}\n')


text:
Q: Open .vym files with View Your Mind How can I open .vym files with View Your Mind? It is not listening in the open with dialog.

A: View Your Mind accepts .vym files as command line arguments and is able to open them properly. But the problem resides in the default .desktop file shipped with the package.
You should edit /usr/share/applications/vym.desktop. To do so;

*

*open a terminal and type:
sudo gedit /usr/share/applications/vym.desktop

*Find the line containing:
Exec=vym

*Add %f at the end of that line. It should look like:
Exec=vym %f

*Save and close the file.
Now Nautilus knows that View Your Mind is able to open files. Just right click on a .vym file, and go to "Open With" context menu. If you don't see View Your Mind in the list, click on "Other Application..." and "Show other applications" respectively and choose View Your Mind from the list.


text:
Q: Почему usingElementComparatorIgnoringFields() используется для сравнения списков? Разбираюсь с чужим кодом. Для тестирования используется JUnit 5. Для сравнения используется две таких функции:
(a, e) -> assertThat(a).usingRecursiveComparison().ignoringFields(fieldsToIgnore).isEqualTo(e);
(a, e) -> assertThat(a).usingElementComparatorIgnoringFields(fieldsToIgnore).isEqualTo(e);

Первая функция используется для сравнения единичных объектов, а вторая для сравнения Iterable, то есть для сравнения списков объектов. Я понимаю первую функцию. Вот тут: usingRecursiveComparison() мы задаём рекурсивное сравнение (то есть сравнение по внутренним полям в том числе), а вот тут: ignoringFields(fieldsToIgnore) задаём игнорируемые в сравнении поля. Это мне понятно.
Я не понимаю вторую функцию. К сожалению, моего знания английского недостаточно для того, чтобы уловить разницу между usingElementComparatorIgnoringFields(fieldsToIgnore) и usingRecursiveComparison().ignoringFields(fieldsToIgnore).
Вопрос в следующем: какая разница между двумя этими функциями и почему первая предназначена для сравнения одиночных объектов, а вторая для сравнения списков?

A: *

*В первом случае usingRecursiveComparison() используется рекурсивное сравнение объектов, то есть если в объекте есть вложенные объекты то компаратор будет рекурсивно спускаться по ним, игнорируя заданные в ignoringFields() поля

*В случае usingElementComparatorIgnoringFields сравниваются только сами объекты, включая поля, но без рекурсивного спуска по полям объекта, игнорируя заданные поля


text:
Q: R cannot be resolved into a variable after declaration I have already declared the R into a variable. However, the error still remains there. I cleaned the project and restarted it but nothing changed. Im a beginner to eclipse android coding. Can someone help me out with the R variable?
Main.java
package com.example.smsmessaging;
import com.example.smsmessaging.R;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.telephony.gsm.SmsManager;

public class SMS extends Activity
{

 Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
    txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
    txtMessage = (EditText) findViewById(R.id.txtMessage);

    btnSendSMS.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            String phoneNo = txtPhoneNo.getText().toString();
            String message = txtMessage.getText().toString();
            if (phoneNo.length()>0 && message.length()>0)
                sendSMS(phoneNo, message);
            else
                Toast.makeText(getBaseContext(),
                    "Please enter both phone number and message.",
                    Toast.LENGTH_SHORT).show();
        }
    });
}
public class SMS extends Activity
{
    //...

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        //...
    }

    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);
    }
  }
  //---sends an SMS message to another device---
  private void sendSMS(String phoneNumber, String message)
  {
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";

    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
        new Intent(SENT), 0);

    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
        new Intent(DELIVERED), 0);

    //---when the SMS has been sent---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }, new IntentFilter(SENT));

    //---when the SMS has been delivered---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }, new IntentFilter(DELIVERED));

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
   }

xml:

    <receiver android:name=".SmsReceiver">
        <intent-filter>
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

</application>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>

A: Remove line import com.example.smsmessaging.R; We should not import it in our .java.

A: Once check your imports and remove unused import in your code:
This line: import com.example.smsmessaging.R;
Then organize imports -> Ctrl+Shift+OThats it...

A: First Remove tour R.java file form gen folder. Now clean your project and import android.R;
Alternate import can be done by pressing  Ctrl+Shift+O

A: You shouldn't import R or define it as a variable.
Quoting from http://source.android.com/source/using-eclipse.html:

Note: Eclipse sometimes likes to add an import android.R statement at the top of your files > that use resources, especially when you ask eclipse to sort or otherwise manage imports. > This will cause your make to break. Look out for these erroneous import statements and delete them.

If there is no error in your resource xml files, then R should automatically be available. XML issues are usually reported in Eclipse. If you're not able to figure out the error, post your xml files here.


text:
Q: "Parsing error identifier expected" on v-on:change I had an issue where importing a class to be used only as a typescript type annotation caused a no-unused vars error. This thread said to add "plugin:@typescript-eslint/recommended" to the eslint config, which solved the issue but caused more parsing errors:

*

*ESLint: Parsing error: Identifier expected which occurred on v-on:change

*ESLint: Parsing error: '}' expected. which occurred on components: {} in @Component(...)
/App.vue:
<template>
    <div id="app" style="height: 100%">
        <input v-on:change="onChange"/> <!--This is the "Identifier expected" error -->
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import Foo from "@/path/to/Foo";
import Bar from "@/path/to/Bar";

@Component({
    components: {  //This is where the `'}' expected.` error occurs

    }
})
export default class App extends Vue {
    onChange(e : any) : void {
        let f : Foo = Bar.baz();  //This is what caused the "no-unused-vars" problem before
        f.someFunc();
    }
}
</script>

Here is my Eslint config from package.json:
"eslintConfig": {
    "root": true,
    "env": {
        "node": true
    },
    "extends": [
        "plugin:vue/essential",
        "eslint:recommended",
        "@vue/typescript",
        "plugin:@typescript-eslint/recommended"
    ],
    "parserOptions": {
        "parser": "@typescript-eslint/parser"
    },
    "rules": {}
}

I've tried enabling vue/valid-v-on in the rules, as well as each of the other exports used in the GitHub thread above.
What should I do to fix this?
Thanks in advance.
Edit: I've removed plugin:@typescript-eslint/recommended" from the eslint config, and put the line // eslint-disable-next-line no-unused-vars above each "unused" import in the code. This is not an optimum solution, so I'll leave the question open.

A: Update (a year on): I've had this error a few times now, and I found that jsut restarting the TypeScript service usually fixes it.
At the bottom right of the IntelliJ Idea window, click on "Vue TypeScript ", then click "Restart TypeScript Service". After a second or two all the "errors" will have been reevaluated and anything incorrectly marked as an error should be cleared.
This can also be used to "fix" lots of other issues with the TypeScript error checker.

A: I just had the same thing. I suspected that it's just a 'bad mood' of the computer... so I've put the line in comment and just wrote by myself the same thing underneath. The compiler stayed silent so I deleted the previous line.
Probably just a bug.

A: skip @typescript-eslint/parser the vue file
add .eslintignore file
# @typescript-eslint/parser can not parse vue v-on
src/view/example/index.vue


text:
Q: Connect with a TCP Server running into VMWare where network type is NAT I have C# TCP Server program which is running into VMWare and network type is NAT. There TCP server works as a http server, so that I can connect it using browser. Now when I am connecting it using this url http://localhost:33333/OrderDetails, it works without any problem. But when I am trying to connect it from outside of VMWare using this link http://1.39.37.243:33333/OrderDetails (1.39.37.243 is my PC's public ip), then its not working. I can't change the network type NAT, because my customer's office Network system is also NAT system. Where am I doing it wrong ? Any thoughts or suggestion will be highly appreciated.

A: This isn't working because the machine receiving the TCP packets has no reason to forward them to the VM. In other words, this isn't working because you haven't done anything to make it work.
You need to configure VMWare's NAT to forward these incoming TCP connections to the VM.
You could also have other problems:

*

*The server might not be listening on the right IP address. For example, if the listening socket is bound to localhost, only localhost connections will work.

*There might be something else in the path keeping the TCP packets from getting to the host. For example, if the host itself is behind NAT, port forwarding may need to be configured in the router.

*Port forwarding won't work from inside the LAN unless the router supports hairpinning. If the host itself is behind NAT, test from outside the LAN after setting up port forwarding in the router.


text:
Q: Multi Select fields in Woocommerce backend I am trying to create 4 multi-select options at Woocommerce product variations.
For example: I am selling trees and want to display the season the tree is available. So we have 4 seasons (spring, summer, autumn, winter), Some trees are available in two or tree seasons.
I added this code to my functions.php, but it won't save the selected options. When i save the option and reload the page the options are blank again.
And I was also wondering how to show the selected options on the single product page (frontend) as icon.
For now the function with the options works at the product variations. Please see this screenshot (product variation with multi select options):

My code:
// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );

/**
 * Create custom field type
 *
*/
function woocommerce_wp_select_multiple( $field ) {
    global $thepostid, $post, $woocommerce;

    $thepostid              = empty( $thepostid ) ? $post->ID : $thepostid;
    $field['class']         = isset( $field['class'] ) ? $field['class'] : 'select short';
    $field['wrapper_class'] = isset( $field['wrapper_class'] ) ? $field['wrapper_class'] : '';
    $field['name']          = isset( $field['name'] ) ? $field['name'] : $field['id'];
    $field['value']         = isset( $field['value'] ) ? $field['value'] : ( get_post_meta( $thepostid, $field['id'], true ) ? get_post_meta( $thepostid, $field['id'], true ) : array() );

    echo '
' . wp_kses_post( $field['label'] ) . '<select id="' . esc_attr( $field['id'] ) . '" name="' . esc_attr( $field['name'] ) . '" class="' . esc_attr( $field['class'] ) . '" multiple="multiple">';

    foreach ( $field['options'] as $key => $value ) {

        echo '<option value="' . esc_attr( $key ) . '" ' . ( in_array( $key, $field['value'] ) ? 'selected="selected"' : '' ) . '>' . esc_html( $value ) . '</option>';

    }

    echo '</select> ';

    if ( ! empty( $field['description'] ) ) {

        if ( isset( $field['desc_tip'] ) && false !== $field['desc_tip'] ) {
            echo 'plugin_url() ) . '/assets/images/help.png" height="16" width="16" />';
        } else {
            echo '' . wp_kses_post( $field['description'] ) . '';
        }

    }
    echo '
';
}

/**
 * Create new fields for variations
 *
*/
function variation_settings_fields( $loop, $variation_data, $variation ) {

    woocommerce_wp_select_multiple( array(
        'id' => 'season_' . $variation->ID,
        'class' => 'season',
        'label' => __('Season', 'woocommerce'),
        'value' => get_post_meta( $variation->ID, '_season', true ),
        'options' => array(
            'spring' => 'Spring',
            'summer' => 'Summer',
            'autumn' => 'Autumn',
            'winter' => 'Winter',
        ))
    );
}

add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
function save_variation_settings_fields( $post_id ) {

    $select = $_POST["season_$post_id"];
    if( ! empty( $select ) ) {
        update_post_meta( $post_id, '_season', esc_attr( $select ) );
    }
}

A: To handle variable products for multi select fields is another thing and some changes need to be done to make it work. I have made 2 answers after below:

*

*The first one for product variations (for you)

*The other one for all other product types

So the main function that enable multi-select fields in WooCommerce backend will be:
function woocommerce_wp_multi_select( $field, $variation_id = 0 ) {
    global $thepostid, $post;

    if( $variation_id == 0 )
        $the_id = empty( $thepostid ) ? $post->ID : $thepostid;
    else
        $the_id = $variation_id;

    $field['class']         = isset( $field['class'] ) ? $field['class'] : 'select short';
    $field['wrapper_class'] = isset( $field['wrapper_class'] ) ? $field['wrapper_class'] : '';
    $field['name']          = isset( $field['name'] ) ? $field['name'] : $field['id'];

    $meta_data              = maybe_unserialize( get_post_meta( $the_id, $field['id'], true ) );
    $meta_data              = $meta_data ? $meta_data : array() ;

    $field['value'] = isset( $field['value'] ) ? $field['value'] : $meta_data;

    echo '
' . wp_kses_post( $field['label'] ) . '<select id="' . esc_attr( $field['id'] ) . '" name="' . esc_attr( $field['name'] ) . '" class="' . esc_attr( $field['class'] ) . '" multiple="multiple">';

    foreach ( $field['options'] as $key => $value ) {
        echo '<option value="' . esc_attr( $key ) . '" ' . ( in_array( $key, $field['value'] ) ? 'selected="selected"' : '' ) . '>' . esc_html( $value ) . '</option>';
    }
    echo '</select> ';
    if ( ! empty( $field['description'] ) ) {
        if ( isset( $field['desc_tip'] ) && false !== $field['desc_tip'] ) {
            echo 'plugin_url() ) . '/assets/images/help.png" height="16" width="16" />';
        } else {
            echo '' . wp_kses_post( $field['description'] ) . '';
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). This function, will handle now any type of products, including product variations.
Related: Multi checkbox fields in Woocommerce backend

1). For product variations (for you):
// Add custom multi-select fields in variation setting tab
add_action( 'woocommerce_product_after_variable_attributes', 'add_variation_settings_fields', 20, 3 );
function add_variation_settings_fields( $loop, $variation_data, $variation_post ) {

    woocommerce_wp_multi_select( array(
        'id' => '_season',
        'name' => '_season['.$loop.'][]',
        'class' => '',
        'label' => __('Season', 'woocommerce'),
        'options' => array(
            'spring' => __("Spring", "woocommerce"),
            'summer' => __("Summer", "woocommerce"),
            'autumn' => __("Autumn", "woocommerce"),
            'winter' => __("Winter", "woocommerce"),
        )
    ), $variation_post->ID );
}

// Save custom multi-select fields for variations
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
function save_variation_settings_fields( $variation_id, $i ) {
    if( isset( $_POST['_season'][$i] ) ){
        $post_data = $_POST['_season'][$i];
        // Multi data sanitization
        $sanitize_data = array();
        if( is_array($post_data) && sizeof($post_data) > 0 ){
            foreach( $post_data as $value ){
                $sanitize_data[] = esc_attr( $value );
            }
        }
        update_post_meta( $variation_id, '_season', $sanitize_data );
    }

}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

2). For all other product types (except product variations, where we hide that custom field):
// Add custom fields for product general option settings (hidding it for variable products)
add_action( 'woocommerce_product_options_general_product_data', 'add_custom_settings_fields', 20 );
function add_custom_settings_fields() {
    global $post;

    echo '
'; // Hidding in variable products

    woocommerce_wp_multi_select( array(
        'id' => '_season',
        'name' => '_season[]',
        'class' => '',
        'label' => __('Season', 'woocommerce'),
        'options' => array(
            'spring' => __("Spring", "woocommerce"),
            'summer' => __("Summer", "woocommerce"),
            'autumn' => __("Autumn", "woocommerce"),
            'winter' => __("Winter", "woocommerce"),
        )
    ) );

    echo '
';
}

// Save custom multi-select fields to database when submitted in Backend (for all other product types)
add_action( 'woocommerce_process_product_meta', 'save_product_options_custom_fields', 30, 1 );
function save_product_options_custom_fields( $post_id ){
    if( isset( $_POST['_season'] ) ){
        $post_data = $_POST['_season'];
        // Multi data sanitization
        $sanitize_data = array();
        if( is_array($post_data) && sizeof($post_data) > 0 ){
            foreach( $post_data as $value ){
                $sanitize_data[] = esc_attr( $value );
            }
        }
        update_post_meta( $post_id, '_season', $sanitize_data );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


text:
Q: Parse SDK Flutter- Database query to get pointer/ relation field data I am developing a Task Management app in flutter and I am using Parse SDK for the backend.
How to fetch data of pointer/ relation columns in a query?
My setup:
I have 4 Classes

*

*User: this is parse user with the username, email, and password

*Categories:  columns--> cat_name ( name of this category)

*Task: below are the columns-
task_name ( name of this task ) and
task_cat (this is a pointer to Category class)

*Activities: Below are the columns:
userID ( a pointer to User class )
taskId: ( a pointer to Task Class )
startTime ( DateTime )
endTime ( DateTime)
activityNotes ( String )
activityDuration( Number)
I am running the following code:
await ParseObject('Activities').getAll();

And I am getting the following response:

[{"className":"Activities","objectId":"F7TviWDd1H","createdAt":"2021-02-17T07:21:33.723Z","updatedAt":"2021-02-18T08:59:51.649Z","startTime":{"__type":"Date","iso":"2021-02-17T06:21:00.000Z"},"endTime":{"__type":"Date","iso":"2021-02-17T07:21:00.000Z"},"userID":{"__type":"Pointer","className":"_User","objectId":"1tHoCAv1QW"},"taskID":{"__type":"Pointer","className":"Tasks","objectId":"MFC2oMP2wL"},"activityNotes":"This
is a Test
Activity","activityDuration":11234000,"ACL":{"":{"read":true}}},
{"className":"Activities","objectId":"5dNxryEGdi","createdAt":"2021-02-17T08:50:58.480Z","updatedAt":"2021-02-18T08:59:58.736Z","startTime":{"__type":"Date","iso":"2021-02-17T04:50:00.000Z"},"endTime":{"__type":"Date","iso":"2021-02-17T06:50:00.000Z"},"userID":{"__type":"Pointer","className":"_User","objectId":"1tHoCAv1QW"},"taskID":{"__type":"Pointer","className":"Tasks","objectId":"rghVxYA6BX"},"activityNotes":"This
is another test
activity","activityDuration":33456000,"ACL":{"":{"read":true}}} ]

My query:
How can I get the username, task_name, and cat_name associated with an activity in a single query??


text:
Q: Why does Windows Media Player no longer start up? In Windows Vista, Windows Media Player was working but now suddenly it is not. If I start it from the task bar or from a desktop shortcut to a specific MP4 video, nothing happens.
In Windows Task Manager I saw wmplayer.exe was present. When I killed this task and restarted WMP, it started no problem.
Does anyone know if there is a permanent fix?

A: I've had this problem in the past with the Opera browser. and maybe with other programs too. It's rare. You just kill the funny process, and start it.  I'm sure it has happened to many people and  doesn't bother them. It's like asking why a program crashes.. it crashed.. dealing with it is what one can do about it.
One of the instances crashed. So it comes under the category of just a crash. But this has the added thing that a new instance won't start unless the old one is killed.
Sometimes i've thought it RAM related..  'cos I think I may have had situations where a program won't start until I end task a different one. But this is probably not the case here, especially since wmplayer is probably small relative to the available ram you probably have.
I'd be interested to know the cause of that.  Maybe a windows programmer might know what is going on. So could be made into more of a stackoverflow question.
Usually with crashes though, you don't know unless you are can see the code and what's happening in it. Not something anybody other than microsoft can do with windows media player. But since the not being able to start another instance is a  problem i've seen in other programs , maybe this is a type of crash that programmers may know a little about. though I doubt it'll be much use to you.  You've figured out how to deal with the crash.

A: Check if Windows Media Player is running on startup. Maybe it tries to load on Windowsstart and hangs while loading. The moment you want to open it, the failed process is blocking your instance.
Update
You can check if its running on startup by opening typing msconfig into the comandline. At the  tab startup you can activat or deactivate programms running on startup.
Also, like Ivo Flipse allready mentioned, reinstallign and/or updating the player also may fix this problem.


text:
Q: Can't create a project from an archetype-catalog.xml I'm trying to use my own project template, but when I perform the command:
mvn archetype:generate -DarchetypeCatalog=local

I got the following message:
 [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.
archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
   Your filter doesn't match any archetype (hint: enter to return to initial list)
Choose a number or apply filter (format: [groupId:]artifactId, case-sensitive contains): :

I tried many possible solutions that I found here, but I did not succeed ...
My steps:  - I created a project in eclipse  -Then I went to root directory of this project and performed the following command in prompt:
mvn archetype:create-from-project

and had BUILD SUCCESS.

Then I performed the following command on project's folder
mvn install

and had BUILD SUCCESS

I checked the .m2 folder, and the archetpe-catalog.xml was there:
<?xml version="1.0" encoding="UTF-8"?>
<archetype-catalog xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-catalog/1.0.0 http://maven.apache.org/xsd/archetype-catalog-1.0.0.xsd"
    xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-catalog/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <archetypes>
    <archetype>
      <groupId>io.openbdt</groupId>
      <artifactId>framework-openbdt</artifactId>
      <version>1.0</version>
      <description>framework-openbdt</description>
    </archetype>
  </archetypes>
</archetype-catalog>

In maven's documentation explains that default path of archetypeCatalog=local is  path/.m2/archetype-catalog.xml but on debug (mvn archetype:generate -DarchetypeCatalog=local -X), maven search the xml file in path/.m2/repository/archetype-catalog.xml
Note: These steps were typically performed in my notebook, but on my desktop I was unsuccessful. Then I created a new user on the notebook and it also didn't work anymore.
Can anyone help me, please?

A: Maven 3.5.2 is inconsistent location between read and write.
When set localRepository in settings.xml, mvn archetype:generate -DarchetypeCatalog=local command reads ${localRepository}/archetype-catalog.xml .
When without localRepository setting, that command reads ~/.m2/archetype-catalog.xml .

mvn archetype:update-local-catalog command creates ~/.m2/archetype-catalog.xml with maven-archetype-plugin v2.4.
That command creates ${localRepository}/archetype-catalog.xml with v3.0.1 .

refs:
[ARCHETYPE-529] Maven archetype:generate does not find local archetypes in interactive mode - ASF JIRA

A: I have the exact same problem and reproduced it with Maven versions 3.3.9 and 3.5.2. Probably something is inconsistent in how mvn install and mvn archetype:generate handle processing archetype-catalog.xml.
Because nothing helped for me as well, I created a soft-link:
ln -s PATH/TO/.m2/archetype-catalog.xml PATH/TO/.m2/repository/archetype-catalog.xml

This made the trick for me. Unfortunately, this works only for unix-like systems.


text:
Q: What does "status=10/n/a" mean in systemd output? I am developing a .service file so that systemd can manage an app as a service on Amazon Linux 2.  But when I type systemctl start my-new-service, the following error is reported in the logs:
Mar 24 hh:mm:ss the.host.name systemd[1]: my-new-service.service: main process exited, code=exited, status=10/n/a

What does status=10/n/a refer to in this error message?
Please explain how to interpret the various possible status codes, perhaps with a link to a thorough explanation if the summary would be too long for this forum.

A: The message means that the app your .service file started with ExecStart= exited and set the return code to 10 when it did so.
There is no single uniform standard (although there are several partial standards and conventions) on result codes, so the only way to find out what the code 10 means is reading the documentation of that specific app... or its source code, if the documentation does not specify it.
So systemd does not know what code 10 means, so it adds n/a to indicate that no verbal description is available from systemd. You've not told us what the app in question is, so we cannot look up result code 10 for you any further than this.
In the documentation of systemd, there are several tables of result code conventions. To summarize:

*

*the C library basically defines just 0 for OK and 1 (or any non-zero value) for failure

*the Linux Standards Base (LSB) has definitions for codes 2...7, for things designed to be used as services (or originally for SysVinit-style service startup scripts)

*the LSB specification suggests that codes 200 and above would be implementation-specific, and so systemd defines a set of codes in that range for errors generated by systemd itself.

*the BSD operating systems define a group of generically useable exit codes in range 64..78. The definition for these codes is typically available on Linux systems too, in file /usr/include/sysexits.h, if the C development packages have been installed on the system.
But none of these are saying anything about code 10, so no guesses can be made without knowing the application in question.

A: 10 is the return value of the main process. By convention every non-zero exit code is considered a failure, where the number should ideally indicate what went wrong.
n/a stands for not applicable or available (Cf. https://en.wikipedia.org/wiki/N/a) and it means there is no symbolic name for the exit code 10 defined, so it does not indicate what went wrong.
In short, something went wrong (or your script/program returns 10 erroneously).


text:
Q: What is an alternative in AWS for sending message from SNS to SQS FIFO? I have this situation where I am using Amazon SNS + SQS in order to handle domain events.
Basically on domain event I publish a message to SNS and two SQS queues are subscribed to SNS. Since i noticed SQS supports FIFO, but SNS doesn't support FIFO, I am trying to find a resolution on how to simultaneously deliver message A to multiple SQS FIFO queues?
What I had so far

*

*Publish Message A to SNS

*Distribute Message A to SQS 1 and SQS 2

All I can think of now is

*

*Publish message A to SQS A

*Use code to pull message A from SQS and publish it to SQS 1 and SQS 2

Not really an atomic process I was looking for...
Is there an alternative to this approach?

A: Today, we launched Amazon SNS FIFO topics, which can fan out messages to multiple Amazon SQS FIFO queues!
https://aws.amazon.com/about-aws/whats-new/2020/10/amazon-sns-introduces-fifo-topics-with-strict-ordering-and-deduplication-of-messages/

A: You can think about using the AWS Kinesis Data stream. One feature of it is an ordering.
From faq: https://aws.amazon.com/kinesis/data-streams/faqs/

When should I use Amazon Kinesis Data Streams, and when should I use Amazon SQS?

Ordering of records. For example, you want to transfer log data from the application host to the processing/archival host while maintaining the order of log statements.

You can process events from Kinesis to SQSs.

A: If your goal is to have a message be pushed to two Amazon SQS FIFO queues, I'd recommend:

*

*Have Amazon SNS trigger an AWS Lambda function

*The Lambda function can send the same message to both Amazon SQS queues
It is effectively doing the fan-out via Lambda rather than SNS.
The Lambda function might also be able to extract a Message Group ID that it can provide with the SQS message, which will enable parallel processing of messages while maintaining FIFO within the message group. For example, all messages coming from a particular source will be FIFO, but can be processed in parallel with messages from other sources. It's a very powerful capability that would not be available just by having Amazon SNS forward the message.


text:
Q: PHP Shortcode - 500 error I have been working on a shortcode with help from this article: http://code.tutsplus.com/tutorials/create-a-shortcode-to-list-posts-with-multiple-parameters--wp-32199.
I have tried to do what the article says, however I have tried to include a while loop. The problem is that when I paste it into the functions.php in the theme editor, the page crashes and returns internal server error 500.
My code looks like this:
add_shortcode('lande_galleri', 'lande_galleri_parameter');

function lande_galleri_parameter($atts) {
ob_start();

//Definer attributter
extract( shortcode_atts( array (
    'post_type' => 'embm_beer',
    'order' =>'date',
    'orderby' => 'title',
    'posts' => -1,
    'land' => '',
), $atts));

//Definer parametre
$options = array(
    'post_type' => $type,
    'order' => $order,
    'orderby' => $orderby,
    'posts_per_page' => $posts,
    'land' => $land,
);
$query = new WP_Query($options);

if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();{ ?>

 <?php
        echo 'ID) . '" title="' . esc_attr($post->post_title) . '">';
        echo get_the_post_thumbnail($post->ID, 'medium');
        echo '';?>

<?php endwhile;
wp_reset_query();
wp_reset_postdata();

$myvariable = ob_get_clean();
return $myvariable;
}
}

Can anyone see the problem?
The point of the shortcode: I have a custom post type with a taxanomy. I would like to have the shortcode attribute "land", and then if the input is for example "germany", I would like the file to get all of the posts within the category, and they display the post thumbnails.

A: Like @s_ha_dum said, those nightmarish "template tag" style conditionals made it hard to find those errors. Please use define( 'WP_DEBUG', true ); in your wp-config file to print those PHP errors while you are developing.
function lande_galleri_parameter($atts) {
    extract( shortcode_atts( array (
        'post_type' => 'embm_beer',
        'order' =>'date',
        'orderby' => 'title',
        'posts' => -1,
        'land' => '',
    ), $atts));

    $options = array(
        'post_type' => $post_type,
        'order' => $order,
        'orderby' => $orderby,
        'posts_per_page' => $posts,
        'land' => $land,
    );

    $out = '';

    $query = new WP_Query($options);

    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            $out .= '
';
            $out .= get_the_post_thumbnail( get_the_ID(), 'medium');
            $out .= '
';
        }
    }
    wp_reset_postdata();
    return $$out;
}
add_shortcode('lande_galleri', 'lande_galleri_parameter');


text:
Q: Strange behavior in Scala Parallel View According to Scaladoc,

A view is a lazy version of some collection. Collection transformers such as map or filter or ++ do not traverse any elements when applied on a view. Instead they create a new view which simply records that fact that the operation needs to be applied.

That means the operations won't be applied until the elements is accessed. But how about Parallel ?
Take a look at this example:
def tn = Thread.currentThread.getName
val strList = List("I", "am", "a" , "student", ".", "I", "come", "from", "China", ".","I","love","peace")
val pvs = strList.par.view.filter{ s => println("f "+ tn); s == "I"}.map{s => println("m " + tn); s.toLowerCase}

The second will print out like the following :

When you apply foreach on pvs , it outputs :

I can't understand why the performance of  Parallel style is not the same as the normal one :
val strList = List("I", "am", "a" , "student", ".", "I", "come", "from", "China", ".","I","love","peace")  // or read from a text file , e.g. article.txt
strList.view.filter{s => println("f");  s == "I"}.map{s => println("m"); s.toLowerCase}.foreach(s => println("p"))

A: Because the interpreter evaluates the expression by forcing it if the expression is a parallel collection view, so that it could print it (in essence, forces the view). Try either running this as a standalone Scala program, or do this:
scala> object foo { var bar: AnyRef = null }

scala> foo.bar = strList.par.view.filter{ s => println("f "+ tn); s == "I"}.map{s => println("m " + tn); s.toLowerCase}

EDIT:
Another issue above is the filter method on parallel views - unlike regular views, it is implemented by forcing the collection. This means that the moment you call filter on the parallel view, the entire filtered collection will be forced into an array and the predicate associated with the filter will have to be called. Methods like groupBy do the same thing on regular views.


text:
Q: Как сделать передачу аргументов? Как правильно сделать, чтобы проходил тест?
Задание: Cоздайте класс EventEmitter для управления событиями. У этого класса должны быть следующие методы:
.on(event, callback) - добавить обработчик события
.off(event, callback) - удалить обработчик события
.once(event, callback) - добавить обработчик события, который сработает единожды
.emit(event, [...arg]) - вызвать все обработчики события event, можно передать аргументы
Расширьте EventEmitter классом BroadcastEventEmitter так, чтобы была возможность вызвать все обработчики всех событий:
emit("*", [...arg]) - вызвать все обработчики событий, можно передать аргументы
class EventEmitter {
 constructor() {
       this.events = {};
 }

 on(eventName, callback) {
     !this.events[eventName] && (this.events[eventName] = []);
     this.events[eventName].push(callback);
 }

 off(eventName, callback) {
     this.events[eventName] = this.events[eventName].filter(eventCallback => callback !== eventCallback);}

once(eventName, callback) {
   this.events[eventName] = this.events[eventName] || [];
     const onceEvent = () => {
         callback();
         this.off(eventName, onceEvent);
     }
     this.events[eventName].push(onceEvent);
     return this;
 }

 emit(eventName, args) {
    const event = this.events[eventName];
    event && event.forEach(callback => callback.call(null, args));
 }
}

class BroadcastEventEmitter extends EventEmitter {
 emit(event, ...args) {
     if (event === '*') {
         Object.keys(this.events).forEach((e) => super.emit(e, ...args));
     } else {
         super.emit(event, ...args);
     }
 }}

Не проходит тест:
тестирование класса BroadcastEventEmitter
✓ проверка наследования от EventEmitter (1ms)
✓ вызов всех событий
✕ передача аргументов (4ms)
  ● тестирование класса BroadcastEventEmitter › передача аргументов

expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: 1, 2
Received: 1

Number of calls: 1

  163 |     emitter.emit('*', ...args);
  164 |
> 165 |     expect(mockFirstListener).toHaveBeenCalledWith(...args);
      |                               ^
  166 |     expect(mockSecondListener).toHaveBeenCalledWith(...args);
  167 |   });
  168 | });

  at Object.toHaveBeenCalledWith test.js:165:31)

A: В методе BroadcastEventEmitter.emit, в обращении к методу наследующего класса super.emit(event, ...args), для передачи использовался оператор rest. Из-за него передавался только 1 аргумент, самый первый.

class EventEmitter {
  constructor() {
    this.events = {};
  }

  on(eventName, callback) {
    !this.events[eventName] && (this.events[eventName] = []);
    this.events[eventName].push(callback);
  }

  off(eventName, callback) {
    this.events[eventName] = this.events[eventName].filter(eventCallback => callback !== eventCallback);
  }

  once(eventName, callback) {
    this.events[eventName] = this.events[eventName] || [];
    const onceEvent = (args) => {
      callback.call(onceEvent, args);
      this.off(eventName, onceEvent);
    };
    this.events[eventName].push(onceEvent);
    return this;
  }

  emit(eventName, ...args) {
    const event = this.events[eventName];
    event && event.forEach(callback => callback.call(null, ...args));
  }
}

class BroadcastEventEmitter extends EventEmitter {
  emit(event, ...args) {
    if (event !== '*') return void(super.emit(event, args));
    Object.keys(this.events).forEach((e) => super.emit(e, args));
  }
}

const emitter = new BroadcastEventEmitter();

emitter.on('event', (args) => console.log(args));
emitter.once('event3', (args) => console.log(args));

emitter.emit('event3', 1, 2, 3, 4, 5);
emitter.emit('event', 1, 2, 3, 4, 5);

Попробуйте, прогоните через тест, если что, поправлю ответ.


text:
Q: Why is Pydot not installed? I am working my way through Google's Machine Learning videos. To complete one of the modules, I had to pip install pydot, which was done successfully in the command prompt. I went back to my code, and I keep getting an error-"name 'pydot' is not defined," but I have made sure, multiple times, that I installed it. I even closed jupyter and re-opened it and I get the same error. Any help would be greatly appreciated.
import numpy as np
import pydot
from sklearn.datasets import load_iris

iris = load_iris()
test_idx = [0, 50, 100]

train_target = np.delete(iris.target, test_idx)
train_data = np.delete(iris.data, test_idx, axis=0)

test_target = iris.target[test_idx]
test_data = iris.data[test_idx]

clf = tree.DecisionTreeClassifier()
clf.fit(train_data, train_target)

print(test_target)
print(clf.predict(test_data))

from sklearn.externals.six import StringIO

dot_data = StringIO()
tree.export_graphviz(clf,
                out_file=dot_data,
                feature_names=iris.feature_names,
                class_names=iris.target_names,
                filled=True, rounded=True,
                impurity=False)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")

print(test_data[0], test_target[0])

A: Try running your code in the IDLE, it could be that your IDE doesn't recognize the package. If that works, you'll have to import the package in the Project Settings.


text:
Q: parse all value of a column I have a data table
and it contains some int type columns, some type double columns, some date  type columns
what i am trying to do is,
i want to do double.TryParse for double column, and if there is any value with it then it will store dbnull value in corresponding rows,
same thing i will do for date, int
since my data table could have 100000 records so i don't to run loop for each row
is it possible through linq or with any method
Thank You

A: LINQ is not good for batch operations. You should create a stored procedure in your DB and import it in your model (If you are using EF that is import function, if using LINQ to SQL then a simple drag and drop will do it).

A: LINQ is no silver bullet for all problems where you need to loop over a (maybe very large) set of data. So if you want to go over each data set and change the values depending on some condition, a foreach loop is your friend.
LINQ is a query language to retrieve data and not some kind of super-fast way to alter large lists or other enumerable objects. It comes in handy if you want to get data from a given object applying some conditions or doing a GroupBy without ending up in a 20-lines unreadable mash of foreach-loops and if-statements.

A: It doesn't matter if you'll do it in a loop or with linq, you'll still need to iterate over the entire data table ...
there's no silver bullet that will save you from doing the checks and inserts i'm afraid


text:
Q: what will limit the growth of cwnd(congestion window)? When i use tcp_probe module to collect cwnd for a TCP connection, the cwnd will stop to increase by around 1467(packets). Can anyone explain the reason for this ? or what is limiting the cwnd on earth ?
The TCP connection is a download a 2G file from host1 (192.168.0.2) to host2 (192.168.0.25), here is my commands for this connection.
@host1:  python -m SimpleHTTPServer
@host2:  wget http://192.168.0.2:8000/test_2G
Here is the command for using tcp_probe to collect the cwnd:
@host1: modprobe tcp_probe port=800 full=1
Here are some other info you may want to know:
@host1:
#ifconfig eth4
eth4      Link encap:Ethernet  HWaddr 90:E2:BA:14:BE:AC
      inet addr:192.168.0.2  Bcast:192.255.255.255  Mask:255.0.0.0
      inet6 addr: fe80::92e2:baff:fe14:beac/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:15263651 errors:0 dropped:0 overruns:0 frame:0
      TX packets:31145880 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:5000
      RX bytes:1008133254 (961.4 MiB)  TX bytes:47154490579 (43.9 GiB)
      Memory:fb780000-fb800000
#cat /proc/sys/net/ipv4/tcp_mem
770373  1027165 1540746
#cat /proc/sys/net/core/rmem_default
212992
#cat /proc/sys/net/core/rmem_max
12582912
#cat /proc/sys/net/core/wmem_default
425984
#cat /proc/sys/net/core/wmem_max
12582912
#cat /proc/sys/net/ipv4/tcp_wmem
10240   87380   12582912
#cat /proc/sys/net/ipv4/tcp_rmem
10240   87380   12582912

A: After digged in the kernel code, i find out the CWND wouldn't invoke the increase function if the tcp is limited by application instead of network capacity.
All the magic is caused by the function tcp_is_cwnd_limited in the file tcp_cong.c. Every congestion algorithm will return directly if tcp is NOT limited by cwnd. :)


text:
Q: Xcode 8.2 Use Legacy Swift issue When I try to run in xcode 8.2 with set "User Legacy Swift -> YES" in build setting, it give me errors for cocoapods only.
I receive the following error:

A: Toggled the "Use Legacy Swift Language Version" from "No" to "Yes" and back to "No" for each(Build Settings). The project then built again.


text:
Q: DesiredCapabilities is obsolete in Selenium Web Driver V.3.14 How to write the code for Selenium grid in C#? I have the following code. I update the selenium web driver to v3.14 and it shows the obsolete and error messages.
DesiredCapabilities capabilities; --deprecated

capabilities = DesiredCapabilities.Chrome(); --has the error for Selennium wen driver v3.14

capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));

Uri uri = new Uri(hub url);

_driver = new RemoteWebDriver(uri, capabilities, TimeSpan.FromSeconds(120));

From class RemoteWebDriver in OpenQA.Selenium.Remote, it still has the ICapabilities parameter

public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout);

I saw some posts using Chrome options. But I still cannot make it work for selenium grid. Any idea?

A: The following should work without incident:
ChromeOptions options = new ChromeOptions();
options.PlatformName = "windows";

Uri uri = new Uri(hub url);

_driver = new RemoteWebDriver(uri, options.ToCapabilities(), TimeSpan.FromSeconds(120));


text:
Q: Changing body styles in Nuxt/Vue template I am trying to add body styles to my template in Nuxt, but I am running into issues.
I am trying to use the beforeCreate call, but when I do, I run into the error: document is not defined.
I would like to maintain SSR.  How can I add styling on the body element?
<script scoped>
  export default {
    head() {
      return {
        script: [
          {
            src: '/js/vendor/jquery.min.js'
          },
          {
            src: '/js/site.js'
          }
        ]

      }
    },
    beforeCreate: function() {
        document.body.className = 'service';
    }
  }
</script>

<style scoped>
@import '~/assets/css/style.min.css';
</style>

Update
I added this:
head() {
      return {
        script: [
          {
            src: '/js/vendor/jquery.min.js'
          },
          {
            src: '/js/site.js'
          }
        ],
        bodyAttrs: {
          class: 'service',
        }

      }
    }

The tag does get added to the body:
<body class="service" data-n-head="%7B%22class%22:%7B%22ssr%22:%22service%22%7D%7D" style="zoom: 1;">

However, the styling does not?
body.service{padding-top:80px}
body.service{font-family:'Geomanist', sans-serif;color:#000}

A: I think the best way handling this is using nuxt layouts (https://nuxtjs.org/docs/2.x/directory-structure/layouts/). Basically you can define your global html or body styles inside style secion of the layout file (which is also a vue file) and then use that layout with your pages (https://nuxtjs.org/docs/2.x/components-glossary/pages-layout/)

A: It seems you can add:
bodyAttrs: {
  class: 'hidden',
},

in nuxt.config.js

According to this answer, you can create an app.html file at the root  of your application with following content. I've added the class directly to the <body>:
<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
  <head {{ HEAD_ATTRS }}>
    {{ HEAD }}
  </head>
  <body {{ BODY_ATTRS }} class="service">
    {{ APP }}
  </body>
</html>


text:
Q: Trivial question about splitting fields I'm having trouble with super basic ring theoretic concepts. Given some irreducible $f$ in $k[x]$, denote by $p$ the projection to the quotient $F$ by the ideal generated by $f$. I'm struggling to understand why $p(x)$ is now a root of $f$. The wiki page says $f(p(x))=p(f(x)) =0$, but I don't understand the left equality. What is going on?

A: It is as simple as it looks. We first have $p(0)=0$. Consider $\alpha\in k,\, \alpha\neq 0$. It is a polynomial of degree $0$. Perform the Euclidean division of $\alpha$ by $f$ to get $\alpha=0\cdot f+\alpha$. This means $\forall \alpha\in k,\,p(\alpha)=\alpha$ and therefore
$$\begin{align}p(f(x))&=p(\sum_0^n\alpha_i x^i)\\&=\sum_0^np(\alpha_i)p(x)^i\\&=\sum_0^n\alpha_ip(x)^i\\&=f(p(x))\end{align}$$

A: I also had a lot of trouble with this when I first saw it.  Here is the explanation that made sense to me with the details written out.
If $k$ is a field, and $p(X)$ is an irreducible polynomial in the ring $k[X]$, then the ideal $\mathfrak p$ generated by $p(X)$ is a maximal ideal (because, for example, $k[X]$ is a principal ideal domain).  Thus the quotient ring $F = k[X]/\mathfrak p$ is a field.
This field contains $k$.  Well, not really.  But, the mapping $a \mapsto a + \mathfrak p$ gives an injective ring homomorphism $k \rightarrow F$, and so you can regard $k$ as a subfield of $F$, by identifying any $a \in k$ with the coset $a + \mathfrak p \in F$).  But to be precise, we will say that we have an injective ring homomorphism $\phi: k \rightarrow F$ given by $\phi(a) = a + \mathfrak p$.
The fields $k, F$ are respectively subsets of the polynomial rings $k[Y], F[Y]$.  Since we have a natural inclusion of $k$ inside $F$, we also have a natural inclusion of the polynomial ring $k[Y]$ inside the polynomial $F[Y]$ (I am using a different letter to denote a polynomial ring here, because $F$ itself is defined in terms of a polynomials in the indeterminate $X$).  That is, the injective homomorphism $\phi: k \rightarrow F$ extends to an injective homomorphism (let's also call it $\phi$) $k[Y] \rightarrow F[Y]$, given by $$\phi(a_0 + a_1Y + \cdots + a_nY^n) = \phi(a_0) + \phi(a_1)Y + \cdots + \phi(a_n)Y^n$$ $$ = (a_0 + \mathfrak p) + (a_1 + \mathfrak p)Y + \cdots + (a_n + \mathfrak p)Y^n$$ The image of this homomorphism is clearly $\phi(k)[Y]$, i.e. polynomials with coefficients in $\phi(k)$.  So basically, you can regard any polynomial with coefficients in $k$, as a polynomial with coefficients in $F$, in a natural way.   So now your polynomial $p(Y) \in k[Y]$ gives a polynomial $\phi(p(Y)) \in \phi(k)[Y] \subseteq F[Y]$.
And the claim is that $\phi(p(Y))$ (a polynomial with coefficients in $\phi(k)$) has a root in $F$.  That root is the coset $X + \mathfrak p \in F$.  Write out $p(Y) = c_0 + c_1Y + \cdots + c_nY^n$ for $c_i \in k$, so that $$\phi(p(Y)) = (c_0 + \mathfrak p) + (c_1 + \mathfrak p)Y + \cdots + (c_n + \mathfrak p)Y^n$$ If you evaluate this polynomial at $X + \mathfrak p$, then from the fact that $fg + \mathfrak p = (f+ \mathfrak p)(g + \mathfrak p)$ and $(f+ \mathfrak p) + (g+ \mathfrak p) = (f + g) + \mathfrak p$ for any $f, g \in k[X]$, you get $$ (c_0 + \mathfrak p) + (c_1 + \mathfrak p)(X + \mathfrak p) + \cdots + (c_n + \mathfrak p)(X + \mathfrak p)^n $$ $$ = (c_0 + c_1X + \cdots + c_nX^n) + \mathfrak p = p(X) + \mathfrak p = 0 + \mathfrak p$$ because $p(X) \in \mathfrak p$.
In textbooks and pretty much everywhere, they are not going to say "the claim is that $\phi(p(Y))$ has a root in $F$."  Instead, they will say "the claim is that $p(Y)$ has a root in $F$," because they are not going to bother distinguish $k$ from its isomorphic copy $\phi(k)$.  And in the same way they are going to think of $k[X]$ as a subring of $F[X]$, even though it is not really.  These identifications are natural and won't lead to any contradictions.  If you are comfortable with them, the proof becomes a lot shorter.

A: Suppose $f(x) = a_0 + a_1x + \cdots + a_nx^n \in F[x]$ for some field $F$.
If $u = x + \langle f(x)\rangle$ (the coset of $x$ in $F[x]/\langle f(x)\rangle$), then:
$f(u) = a_0 + a_1(x + \langle f(x)\rangle) + \cdots + a_n(x + \langle f(x)\rangle)^n$
...now a natural question is how we can multiply an element of $F[x]/\langle f(x)\rangle$ by an element of $F$?
What we do is define for $c \in F$: $c(g(x) + \langle f(x)\rangle) = (c\cdot g(x)) + \langle f(x) \rangle$.
This "makes sense" because the image $p(F)$ of $F$ under $p$ sends $c \mapsto c + \langle f(x)\rangle$ (the latter sees "$c$" as a CONSTANT polynomial) is an isomorphism of $F$ with $p(F)$.
So $f(u) = (a_0 + \langle f(x)\rangle) +  (a_1 + \langle f(x)\rangle)(x + \langle f(x)\rangle) + \cdots + (a_n + \langle f(x)\rangle)^n$.
Recall that in a quotient ring $R/I$, we have $(a+ I)(b + I) = ab + I$, so the above becomes:
$f(u) = (a_0 + \langle f(x)\rangle) + (a_x + \langle f(x)\rangle) +\cdots + (a_nx^n + \langle f(x)\rangle)$
And in a quotient ring $R/I$, we have $(a + I) + (b + I) = (a+b) + I$,
so we have:
$f(u) = (a_0 + a_1x + \cdots + a_nx^n) + \langle f(x)\rangle = f(x) + \langle f(x)\rangle$
But $f(x) + \langle f(x)\rangle = 0 + \langle f(x) \rangle = 0_{F[x]/\langle f(x)\rangle}$, since $f(x) = f(x) - 0 \in \langle f(x)\rangle$.
Thus $p(f(x)) = f(x) + \langle f(x)\rangle = 0_{F[x]/\langle f(x)\rangle} = f(u) = f(p(x))$.

A: $p(x)$ is confusing notation because it looks like you're applying a polynomial to $x$. I will use $\underline{a}$ instead for the image of $a \in k[x]$ in $k[x]/f(x)$. Also, I don't understand why everyone's working so hard. Write $f(x) = \sum f_n x^n$. The key point is that $a \mapsto \underline{a}$ is a $k$-algebra homomorphism, and this is true more or less by definition of the $k$-algebra structure on $k[x]/f(x)$. Now it follows that
$$\underline{f(x)} = \underline{\sum f_n x^n} = \sum f_n \underline{x}^n = f(\underline{x})$$
but since by definition $\underline{f(x)} = 0$ we conclude that $f(\underline{x}) = 0$ as well.


text:
Q: XmlTextReader - XML reading old content after file update
So I am using a "Updater.exe" which is reading an XML file on my webserver. The Updater checks if a new version of the program is available who transfers the new file (replacing the old one) and runs it. (The file name is gibberish as i dont want users to run it directly, it has to go trough the updater (who runs it with the help of p.StartInfo.UseShellExecute = false;)).
I have now encountered a really weird "bug" or how should i call this.
Lets say i make a new version after 1 week. I update the assembly info of the application and the XML file version aswell. Now when i run the UPDATER.exe, he does not see the new updated XML content, telling him a new version is available. As i wanted to check the file trough my web browser it was also showing the OLD content (previous version) meaning, the application is UP to DATE which is false.
After i pressed the "refresh" button in Chrome, the content i had displayed was updated and running the Updater.exe again worked fine.
I do not have any IDEA what is actually going on. What does "refreshing" the page in the browser has to do with my application?
Checking the XMLTextReader class from MSDN it says:
Represents a reader that provides fast, non-cached, forward-only access to XML data. So yeah, searching the internet telling me i should lookup for "caching" issues, makes me even more confused when i read the class description. After refreshing in the browser after such a long period of no updates, all next updates are working just fine. Seems that the "big pause" always makes this problem.
Anyway, i would love to find a solution to this. Maybe it is just ME that has this problem. But i dont want to see this problem from the users using the application. They do not have time or knowledge to "refresh" anything. It just has to work.
The XML example is here:
<?xml version="1.0" encoding = "utf-8" standalone="yes"?>
<Application>
    <version>2.0.0.16</version>
    <url>http://server/folder/gibberish.extension</url>
</Application>

And some code I use to read the XML.
Version newVersion = null;
string xmlUrl = "http://server/folder/file.xml";

XmlTextReader reader = null;
try
{
    reader = new XmlTextReader(xmlUrl);
    reader.MoveToContent();
    string elementName = "";
    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "Application"))
    {
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                elementName = reader.Name;
            }
            else
            {
                if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue))
                {
                    switch (elementName)
                    {
                        case "version":
                            newVersion = new Version(reader.Value);
                            break;

                            case "url":
                                downloadUrl = reader.Value;
                                break;
                    }
                }
            }
        }
    }
}
catch (Exception ee)
{
    //catch error
}

I did my best to describe the problem as detailed as i can(with my simple knowledge in english language) here. And i searched the internet with no luck. I hope this will not result in a duplicate. IF you have any other questions, feel free to ask. I will definitely give you all the information you need to solve this weird puzzle.
Best Regards, MiKE

A: The first thing that comes to my mind is CDNs. Do you use any kind of CDNs such as CloudFlare? CloudFlare and similar CDNs cache your content for a short time causing this effect.