text:
Q: Read/Write 'Extended' file properties (C#) I'm trying to find out how to read/write to the extended file properties in C#
e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer.
Any ideas how to do this?
EDIT: I'll mainly be reading/writing to video files (AVI/DIVX/...)

A: For those of not crazy about VB, here it is in c#:
Note, you have to add a reference to Microsoft Shell Controls and Automation from the COM tab of the References dialog.
public static void Main(string[] args)
{
    List<string> arrHeaders = new List<string>();

    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;

    objFolder = shell.NameSpace(@"C:\temp\testprop");

    for( int i = 0; i < short.MaxValue; i++ )
    {
        string header = objFolder.GetDetailsOf(null, i);
        if (String.IsNullOrEmpty(header))
            break;
        arrHeaders.Add(header);
    }

    foreach(Shell32.FolderItem2 item in objFolder.Items())
    {
        for (int i = 0; i < arrHeaders.Count; i++)
        {
            Console.WriteLine(
              $"{i}\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
        }
    }
}

A: Thank you guys for this thread! It helped me when I wanted to figure out an exe's file version. However, I needed to figure out the last bit myself of what is called Extended Properties.
If you open properties of an exe (or dll) file in Windows Explorer, you get a Version tab, and a view of Extended Properties of that file. I wanted to access one of those values.
The solution to this is the property indexer FolderItem.ExtendedProperty and if you drop all spaces in the property's name, you'll get the value. E.g. File Version goes FileVersion, and there you have it.
Hope this helps anyone else, just thought I'd add this info to this thread. Cheers!

A: GetDetailsOf() Method - Retrieves details about an item in a folder. For example, its size, type, or the time of its last modification. File Properties may vary based on the Windows-OS version.
List<string> arrHeaders = new List<string>();

 Shell shell = new ShellClass();
 Folder rFolder = shell.NameSpace(_rootPath);
 FolderItem rFiles = rFolder.ParseName(filename);

 for (int i = 0; i < short.MaxValue; i++)
 {
      string value = rFolder.GetDetailsOf(rFiles, i).Trim();
      arrHeaders.Add(value);
 }

A: Jerker's answer is little simpler. Here's sample code which works from MS:
var folder = new Shell().NameSpace(folderPath);
foreach (FolderItem2 item in folder.Items())
{
    var company = item.ExtendedProperty("Company");
    var author = item.ExtendedProperty("Author");
    // Etc.
}

For those who can't reference shell32 statically, you can invoke it dynamically like this:
var shellAppType = Type.GetTypeFromProgID("Shell.Application");
dynamic shellApp = Activator.CreateInstance(shellAppType);
var folder = shellApp.NameSpace(folderPath);
foreach (var item in folder.Items())
{
    var company = item.ExtendedProperty("Company");
    var author = item.ExtendedProperty("Author");
    // Etc.
}

A: *

*After looking at a number of solutions on this thread and elsewhere
the following code was put together. This is only to read a property.

*I could not get the
Shell32.FolderItem2.ExtendedProperty function to work, it is supposed
to take a string value and return the correct value and type for that
property... this was always null for me and developer reference resources were very thin.

*The WindowsApiCodePack seems
to have been abandoned by Microsoft which brings us the code below.

Use:
string propertyValue = GetExtendedFileProperty("c:\\temp\\FileNameYouWant.ext","PropertyYouWant");

*

*Will return you the value of the extended property you want as a
string for the given file and property name.

*Only loops until it found the specified property - not until
all properties are discovered like some sample code

*Will work on Windows versions like Windows server 2008 where you will get the error "Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'" if just trying to create the Shell32 Object normally.
public static string GetExtendedFileProperty(string filePath, string propertyName)
{
    string value = string.Empty;
    string baseFolder = Path.GetDirectoryName(filePath);
    string fileName = Path.GetFileName(filePath);

    //Method to load and execute the Shell object for Windows server 8 environment otherwise you get "Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'"
    Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
    Object shell = Activator.CreateInstance(shellAppType);
    Shell32.Folder shellFolder = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { baseFolder });

    //Parsename will find the specific file I'm looking for in the Shell32.Folder object
    Shell32.FolderItem folderitem = shellFolder.ParseName(fileName);
    if (folderitem != null)
    {
        for (int i = 0; i < short.MaxValue; i++)
        {
            //Get the property name for property index i
            string property = shellFolder.GetDetailsOf(null, i);

            //Will be empty when all possible properties has been looped through, break out of loop
            if (String.IsNullOrEmpty(property)) break;

            //Skip to next property if this is not the specified property
            if (property != propertyName) continue;

            //Read value of property
            value = shellFolder.GetDetailsOf(folderitem, i);
        }
    }
    //returns string.Empty if no value was found for the specified property
    return value;
}

A: Solution 2016
Add following NuGet packages to your project:

*

*Microsoft.WindowsAPICodePack-Shell by Microsoft

*Microsoft.WindowsAPICodePack-Core by Microsoft

Read and Write Properties
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;

string filePath = @"C:\temp\example.docx";
var file = ShellFile.FromFilePath(filePath);

// Read and Write:

string[] oldAuthors = file.Properties.System.Author.Value;
string oldTitle = file.Properties.System.Title.Value;

file.Properties.System.Author.Value = new string[] { "Author #1", "Author #2" };
file.Properties.System.Title.Value = "Example Title";

// Alternate way to Write:

ShellPropertyWriter propertyWriter =  file.Properties.GetPropertyWriter();
propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });
propertyWriter.Close();

Important:
The file must be a valid one, created by the specific assigned software. Every file type has specific extended file properties and not all of them are writable.
If you right-click a file on desktop and cannot edit a property, you wont be able to edit it in code too.
Example:

*

*Create txt file on desktop, rename its extension to docx. You can't
edit its Author or Title property.

*Open it with Word, edit and save
it. Now you can.

So just make sure to use some try catch
Further Topic:
Microsoft Docs: Implementing Property Handlers

A: There's a CodeProject article for an ID3 reader.  And a thread at kixtart.org that has more information for other properties. Basically, you need to call the GetDetailsOf() method on the folder shell object for shell32.dll.

A: This sample in VB.NET reads all extended properties:
Sub Main()
        Dim arrHeaders(35)

        Dim shell As New Shell32.Shell
        Dim objFolder As Shell32.Folder

        objFolder = shell.NameSpace("C:\tmp")

        For i = 0 To 34
            arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)
        Next
        For Each strFileName In objfolder.Items
            For i = 0 To 34
                Console.WriteLine(i & vbTab & arrHeaders(i) & ": " & objfolder.GetDetailsOf(strFileName, i))
            Next
        Next

    End Sub

You have to add a reference to Microsoft Shell Controls and Automation from the COM tab of the References dialog.

A: Here is a solution for reading - not writing - the extended properties based on what I found on this page and at help with shell32 objects.
To be clear this is a hack. It looks like this code will still run on Windows 10 but will hit on some empty properties. Previous version of Windows should use:
        var i = 0;
        while (true)
        {
            ...
            if (String.IsNullOrEmpty(header)) break;
            ...
            i++;

On Windows 10 we assume that there are about 320 properties to read and simply skip the empty entries:
    private Dictionary<string, string> GetExtendedProperties(string filePath)
    {
        var directory = Path.GetDirectoryName(filePath);
        var shell = new Shell32.Shell();
        var shellFolder = shell.NameSpace(directory);
        var fileName = Path.GetFileName(filePath);
        var folderitem = shellFolder.ParseName(fileName);
        var dictionary = new Dictionary<string, string>();
        var i = -1;
        while (++i < 320)
        {
            var header = shellFolder.GetDetailsOf(null, i);
            if (String.IsNullOrEmpty(header)) continue;
            var value = shellFolder.GetDetailsOf(folderitem, i);
            if (!dictionary.ContainsKey(header)) dictionary.Add(header, value);
            Console.WriteLine(header +": " + value);
        }
        Marshal.ReleaseComObject(shell);
        Marshal.ReleaseComObject(shellFolder);
        return dictionary;
    }

As mentioned you need to reference the Com assembly Interop.Shell32.
If you get an STA related exception, you will find the solution here:
Exception when using Shell32 to get File extended properties
I have no idea what those properties names would be like on a foreign system and couldn't find information about which localizable constants to use in order to access the dictionary. I also found that not all the properties from the Properties dialog were present in the dictionary returned.
BTW this is terribly slow and - at least on Windows 10 - parsing dates in the string retrieved would be a challenge so using this seems to be a bad idea to start with.
On Windows 10 you should definitely use the Windows.Storage library which contains the SystemPhotoProperties, SystemMusicProperties etc.
https://learn.microsoft.com/en-us/windows/uwp/files/quickstart-getting-file-properties
And finally, I posted a much better solution that uses WindowsAPICodePack there

A: I'm not sure what types of files you are trying to write the properties for but taglib-sharp is an excellent open source tagging library that wraps up all this functionality nicely.  It has a lot of built in support for most of the popular media file types but also allows you to do more advanced tagging with pretty much any file.
EDIT:  I've updated the link to taglib sharp.  The old link no longer worked.
EDIT: Updated the link once again per kzu's comment.


text:
Q: Pass ion-select-option to function - Ionic 4 I have this Ionic version 4 code that is simply trying to take a the selected value and pass it to a function in it's component:
<ion-item>
<ion-label>Convert Currency</ion-label>
<ion-select [(ngModel)]="currency">
<ion-select-option *ngFor="let c of currencyData" [value] = "c" >{{c.text}}</ion-select-option>
</ion-select>

I tried onChange but that is apparently not in version 4.

A: You are looking for ionChange
  <ion-select [(ngModel)]="currency" (ionChange)="yourFunction($event)">

A: you can use ionChange to pass the selected value as follow :
     <ion-select (ionChange)="checkValue($event)"  interface="popover"
      placeholder="Select One" >
        <ion-select-option *ngFor="let c of currencyData" [value]="c">
       {{c.text}}</ion-select-option>
 </ion-select>

In your typeScript:
checkValue(event){ console.log(event.detail.value)}

redpajama_set_name: RedPajamaStackExchange


text:
Q: object "input" not found. r shiny app I have server.R and ui.R script below. It keeps me giving me "Object 'input' not found" message and I have no idea why. I made sure that selectInput is named right and such, but no solution.
SERVER.R
library(shiny)
library(data.table)
library(dplyr)
library(ggplot2)

shinyServer(function(input, output){

selected_data <- reactive({

data <- data.table::fread(input="final_master_table.csv",header = TRUE,     data.table = TRUE)
data <- data[,V1:=NULL]

 velo <- data %>% group_by(input$pitcher_name, input$pitch_type, input$year) %>% summarise(velocity = mean(data$start_speed)) %>%
  arrange(velocity)

data2 <- filter(velo,input$pitcher_name)
data2 <- data2[data2$Year %in% input$year,]
return(data2)
})

output$pitcher_bar <- renderPlot(

ggplot(selected_data(), aes(x = input$year, y = selected_data()$velocity, group = input$pitch_type, color = input$pitch_type)) +
  geom_line(aes(linetype=input$pitch_type), size=1) + geom_point(size=3, fill="white") +
  xlab("Year") + ylab("Velocity") + ggtitle("Velocity") + theme_bw()

)

})

Then here is UI.R:
UI.R

library(shiny)
library(data.table)
library(dplyr)
library(ggplot2)

shinyUI(fluidPage(

titlePanel("Boxplot of MLB Pitcher Attributes"),

sidebarLayout(

sidebarPanel(

# Slider for setting year parameter

sliderInput("year",
            "year:",
            min=2008,max=2015,value=c(2008,2015)
            ),

 selectInput("pitcher_name","Pitcher Name:", choices = unique(data$pitcher_name)),

 selectInput("pitch_type","Pitch Type:", choices = unique(data$pitch_type)),

 helpText("Please wait 30 seconds for 2008 to 2015 pitchFx data to load")

 ),

 mainPanel(plotOutput("pitcher_bar"))

 )))

A: It looks the the problem is in group_by where you want the standard evaluation version, group_by_.
Try
group_by_(.dots=c(input$pitcher_name, input$pitch_type, input$year))


text:
Q: Azure Service Fabric Multi-Tenancy I'm trying to get a little follow up to this question that's already been answered...
Service Fabric multi-tenant
If I were to setup my tenants as Azure Service Fabric Stateless Services (they'll get their state out-of-band), how can I put more than one tenant on each node in the cluster? In testing, it seems that Service Fabric gags if you try and make your instance count greater than the node count.
These tenants are very lightweight, so I should be able to run dozens of them on each node (we will have hundreds overall), and I don't want to have to do a node for each one. Specifically, the tenants are more-or-less just opening a long-polling HTTP connection to an external customer service and streaming that data back into our system - so there's no public endpoints in play here. I just need the ability to spin up a lot of these workers that'll each open up their own long-polling connection.
Can somebody point me in the right direction?
FYI, I've explained a little bit more here... https://social.msdn.microsoft.com/Forums/en-US/efd172e2-0783-489b-b3ab-ec62fb7b8ee4/multiple-instances-per-node?forum=AzureServiceFabric
Thanks in advance!

A: You'll need to somehow partition your service.
There is several options, but the two that aligns good here (and also with the SO question you linked are):
Have a SF application where each tenant gets an instance of your service. You will then need to have a shared service in front to route requests to the correct service. It should look something like this.
MyAwesomeApp
    SharedStatelessApi <- External API points here
    MyTenantService_Tenant1 <- ServiceType: MyTenantService
    MyTenantService_Tenant2 <- ServiceType: MyTenantService
    ...

The other solution is to have one (or more) service fabric application per tenant, and would look something along the lines of:
MySharedApp
    SharedStatelessApi <- External API points here
Tenant1 <- ApplicationType: MyTenantApp
    MyTenantService <- ServiceType: MyTenantService
Tenant2 <- ApplicationType: MyTenantApp
    MyTenantService <- ServiceType: MyTenantService

It's the same concept as the first example, but the partition is done on a higher lever.
Personally, I prefer the second case. It feels more right.
In both cases, you'll have to either create the services/application manually when a new customer signs up, or do it in code. If you want to do it in code, you should look at the FabricClient. If you need an example of that, let me know.
Also, as you can see, you should have a shared public endpoint, and in that endpoint route the request to the correct service based on something (header, auth token, uri, whatever is inline with your app).
Example of using FabricClient to create a service:
First you need a FabricClient. For a unsecured cluster (your local dev cluster), the following is enough:
var fabricClient = new FabricClient("localhost:19000");

When you have deployed to a secured cluster (for example in Azure), you need to authenticate the FabricClient, like so:
var creds = new X509Credentials
{
    FindType = X509FindType.FindByThumbprint,
    FindValue = clientCertThumbprint,
    RemoteCertThumbprints = {clientCertThumbprint},
    StoreLocation = StoreLocation.LocalMachine,
    StoreName = "My"
};

var clusterEndpoint = "CLUSTERNAME.LOCATION.cloudapp.azure.com:19000"
// or whatever your cluster endpoint is

var fabricClient = new FabricClient(creds, clusterEndpoint);

Then, when you have a FabricClient, you can create a stateless service like this:
var statelessDescriptor = new StatelessServiceDescription
{
    ApplicationName = new Uri("fabric:/MYAPP"),
    InstanceCount = 1, // How many instances.
    PartitionSchemeDescription = new SingletonPartitionSchemeDescription(),
    ServiceName = new Uri("fabric:/MYAPP/TenantA"),
    ServiceTypeName = "YourServiceTypeName",
    InitializationData = DATA_TO_PASS_TO_SERVICE_BYTE[] // Only if needed.
};

await _client.ServiceManager.CreateServiceAsync(statelessDescriptor)

If you passed any data in the "InitializationData" prop, it will be available in the service as ServiceInitializationParameters.InitializationData


text:
Q: .on('show_variation') WooCommerce returns empty values Can not seem to access attributes when .on('show_variation') fires if variations is set to Any option.
<?php
add_action( 'wp_footer', 'return_js_varations' );
function return_js_varations() { ?>
    <script type="text/javascript">
        (function($){
            $('form.variations_form').on('show_variation', function(event, data) {
                console.info( data.attributes );        // The variation attributes
            });
        })(jQuery);
    </script>
<?php }

I have attributes:
Color red|green|blue
Size sm|lg

Inside variations tab I have one variation ID:
Any Color, Any Size

It returns blank data values
Object { attribute_color: "", attribute_size: "" }

But when I use the generate Create variations from all attributes it returns desired values.
Inside variations tab I have 6 variation ID:
red,sm
red,lg
blue,sm
blue,lg
green,sm
green,lg

Returns
Object { attribute_color: "red", attribute_size: "sm" }

Is this by design?
How can I get the values of when Any attributed is used?
I can probably do this via vanilla javascript/jquery but I would prefer to use WooCommerce built in functions.
I do not need to create variations from all attributes, it's messy and tedious.
I have quite a bit of attributes (as this is just a simple example)


text:
Q: Core Data Migration - "Can't add source store" error In my iPhone app I'm using Core Data and I've made changes to my data model that cannot be automatically migrated over (i.e. added new relationships). I added the data model version (Design -> Data Model -> Add Model Version) and applied my new data model changes to the new version 2. I then created a mapping object model and set the Source and Destination models to their correct data models (old and new respectively).
When I run the app and call the persistentStoreCoordinator, my app barfs with the following:
2010-02-27 02:40:30.922 XXXX[73578:20b] Unresolved error Error Domain=NSCocoaErrorDomain Code=134110 UserInfo=0xfc2240 "Operation could not be completed. (Cocoa error 134110.)", {
        NSUnderlyingError = Error Domain=NSCocoaErrorDomain Code=134130 UserInfo=0xfbb3a0 "Operation could not be completed. (Cocoa error 134130.)";
        reason = "Can't add source store";
    }
FWIW (not much i think) I've also made the usual code changes in persistentStoreCoordinator to use the NSMigratePersistentStoresAutomaticallyOption and NSInferMappingModelAutomaticallyOption (for future data model changes that can be automatically migrated). More relevantly, my managedObjectModel is created by calling initWithContentsOfURL where the file/resource type is "momd".
I've tried updating both the source and destination model in the mapping model (Design -> Mapping Model -> Update XXX Model) as well as deleted the mapping model and recreated it. I've cleaned and re-built but all to no avail. I still get the above error message.
Any pointers/thoughts on how I can further debug or resolve this problem please? I haven't posted any code snippets because this feels much more like a build environment issue (and my code is very standard - just the usual core data code to handle migrations using a mapping model but I'm happy to show the code if it helps).
Appreciate any help.
Thanks

A: Ok, this is now fixed.
I (a) deleted and then recreated my managed object model classes, (b) deleted and then recreated the mapping model and then finally I (c) deleted the iphone project under the users/xxx/Library/Application Support/iPhone Simulator/User/Applications.
Given I previously tried and failed with doing just (a) and (b), I suspect it was (c) which fixed the problem.


text:
Q: Symfony2. How to save request body from 400: Invalid json message received I'm writing a web API.
I'm working with an 3rd party client that has sent a application/json request with an invalid JSON body.
My controller never get's the request because Symfony responds with Invalid json message received (400 Bad Request).
The developer of the 3rd party client will need this invalid JSON to debug their software.
Other than changing the content-type to text/plain, then testing the JSON myself, how can I save the invalid JSON for review later?
Thanks!

A: If you need to log an exception during a request handle, you just need to register an event listener on the kernel.exception. This event dispatches a GetResponseForExceptionEvent where you can find the triggered exception, the request and some others informations.
So, in this listener, check if the exception if a Symfony\Component\HttpKernel\Exception\BadRequestHttpException and then, log the request body where/as you want for further debugging.

A: Ah, ok.  This was programmer error.  The check wasn't done by Synfony, but by a leftover Friends Of Symfony Rest module.  After removing this module, the behavior disappeared.  Controller has to check the JSON body anyways.


text:
Q: The type WebMvcConfigurerAdapter is deprecated I just migrate to spring mvc version 5.0.1.RELEASE but suddenly in eclipse STS WebMvcConfigurerAdapter is marked as deprecated
public class MvcConfig extends WebMvcConfigurerAdapter {
  @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        // to serve static .html pages...
        registry.addResourceHandler("/static/**").addResourceLocations("/resources/static/");
    }
  ....
  }

How can i remove this!

A: Since Spring 5 you just need to implement the interface WebMvcConfigurer:
public class MvcConfig implements WebMvcConfigurer {

This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter class
See here:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html

A: I have been working on Swagger equivalent documentation library called Springfox nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer has been implemented by class WebMvcConfigurationSupport class which we can directly extend.
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConfig extends WebMvcConfigurationSupport { }

And this is how I have used it for setting my resource handling mechanism as follows -
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

A: In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.
Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.

*

*we have added the /js/** pattern to the ResourceHandler, lets include the foo.js resource located in the webapp/js/ directory

*we have added the /resources/static/** pattern to the ResourceHandler, lets include the foo.html resource located in the webapp/resources/ directory

@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("/resources/");

        registry
            .addResourceHandler("/js/**")
            .addResourceLocations("/js/")
            .setCachePeriod(3600)
            .resourceChain(true)
            .addResolver(new GzipResourceResolver())
            .addResolver(new PathResourceResolver());
    }
}

XML Configuration
<mvc:annotation-driven />
  <mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
                 cache-period="60"/>

Spring Boot MVC Static Content if the file is located in the WAR's webapp/resources folder.
spring.mvc.static-path-pattern=/resources/static/**

A: Use org.springframework.web.servlet.config.annotation.WebMvcConfigurer
With Spring Boot 2.1.4.RELEASE (Spring Framework 5.1.6.RELEASE), do like this
package vn.bkit;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // Deprecated.
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}


text:
Q: Filtering data by comparing date SQL I have table with following data :

Order_ID
status_update
status_date

A
Received
01/01/2020

A
Pending
01/05/2020

A
Processing
01/07/2020

A
Delivered
01/15/2020

B
Received
02/01/2020

C
Received
02/15/2020

C
Delivered
02/20/2020

D
Received
05/01/2020

D
Delivered
05/10/2020

Now, I would like to get full order history between 01/15/2020 to 04/25/2020 with last status update is Delivered.
Result would look like :

Order_ID
status_update
status_date

A
Received
01/01/2020

A
Pending
01/05/2020

A
Processing
01/07/2020

A
Delivered
01/15/2020

C
Received
02/15/2020

C
Delivered
02/20/2020

How can i write an SQL query to get this result?

A: Assuming you want the history for all orders that were delivered between  2020-01-01 and 2020-04-25:
SELECT *
FROM   orders o
WHERE  EXISTS (
   SELECT FROM orders o1
   WHERE  o1.order_id = o.order_id
   AND    o1.status_update = 'Delivered'
   AND    o1.status_date BETWEEN '2020-01-15' AND '2020-04-25'
   )
ORDER  BY order_id, status_date

That includes rows before 2020-01-15, as long as the delivery date is in the time frame.
Add another predicate to the outer SELECT to cut off rows before 2020-01-01 (or any date):
AND    o.status_date >= '2020-01-15'

db<>fiddle here
Aside: always use unambiguous ISO format for dates.

A: You can use something like this:
select * from test a
inner join (
  select distinct order_id from test
  where status_update = 'Delivered'
) b on a.order_id = b.order_id
where status_date between '2020-01-01' and '2020-04-25'

Example: https://dbfiddle.uk/?rdbms=postgres_13&fiddle=fddcc53f80e94c2c1c48f4e557904505
Result:

order_id | status_update | status_date | order_id
:------- | :------------ | :---------- | :-------
A        | Received      | 2020-01-01  | A
A        | Pending       | 2020-01-15  | A
A        | Processing    | 2020-01-07  | A
A        | Delivered     | 2020-01-15  | A
C        | Received      | 2020-02-15  | C
C        | Delivered     | 2020-02-20  | C

The same query will work for:

*

*MySQL - https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=fddcc53f80e94c2c1c48f4e557904505

*SQL Server - https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=fddcc53f80e94c2c1c48f4e557904505
Edit
If you want to get all records for order ID that got delivered between 15th Jan and 25th April, you can do this:
select * from test a
inner join (
  select distinct order_id from test
  where status_update = 'Delivered'
  and status_date between '2020-01-15' and '2020-04-25'
) b on a.order_id = b.order_id

That'll give you the result, I believe, you desire.
Example: https://dbfiddle.uk/?rdbms=postgres_13&fiddle=5e0d226f455068fafa54228837a8313f

A: You don't mention the specific database you are using, but the query below should work on most databases:
select *
from t
where status_date between date '2020-01-01' and date '2020-04-25'
  and order_id in (
  select order_id
  from t
  where status_update = 'Delivered'
);

Result:
 order_id  status_update  status_date
 --------- -------------- -----------
 A         Received       2020-01-01
 A         Pending        2020-01-15
 A         Processing     2020-01-07
 A         Delivered      2020-01-15
 C         Received       2020-02-15
 C         Delivered      2020-02-20

A: Try the following query:
SELECT Order_ID, status_update, status_date
FROM (
  SELECT
    *,
    SUM(CASE status_update WHEN 'Delivered' THEN 1 ELSE 0 END) OVER(
      PARTITION BY Order_ID
    ) AS with_delivery
  FROM test
  WHERE status_date BETWEEN '2020-01-01' and '2020-04-25'
) AS t
WHERE with_delivery > 0;

The result is as you expect:
+----------+---------------+-------------+
| order_id | status_update | status_date |
+----------+---------------+-------------+
| A        | Received      | 2020-01-01  |
| A        | Pending       | 2020-01-15  |
| A        | Processing    | 2020-01-07  |
| A        | Delivered     | 2020-01-15  |
| C        | Received      | 2020-02-15  |
| C        | Delivered     | 2020-02-20  |
+----------+---------------+-------------+

db<>fiddle


text:
Q: text box with multiple bindings? Is there a way have a single textbox bind to two things. I want to have one binding set to "OneWay" and the Other set to "OneWayToSource". Basically I want to combine these two textboxes into one (and preferably with little to no code behind).
<TextBox Text="{Binding Path=ActionParameter.Value, Mode=OneWayToSource}" />

<TextBox Text="{Binding Path=StatusSignal.Value, Mode=OneWay}" />

A: You can use MultiBinding to set 2 or more bindings to your TextBox
Example:
<TextBox>
    <TextBox.Text>
        <MultiBinding StringFormat="{}{0}{1}">
            <Binding Path="ActionParameter.Value" Mode="OneWayToSource" />
            <Binding Path="StatusSignal.Value" Mode="OneWay" />
        </MultiBinding>
    </TextBox.Text>
</TextBox>

But depending on what you need to do with the 2 properties you may need to use a IMultiValueConverter to process the properties.
Example:
<TextBox>
    <TextBox.Resources>
        <local:TextConverter x:Key="MyConverter"/>
    </TextBox.Resources>
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource MyConverter}">
            <Binding Path="ActionParameter.Value" Mode="OneWayToSource" />
            <Binding Path="StatusSignal.Value" Mode="OneWay" />
        </MultiBinding>
    </TextBox.Text>
</TextBox>


text:
Q: How to show normal date format in the table headers in grafana? I have a following table generated with SQL query in Grafana.

I need to group data by date and that's why using a transformation called Grouping to matrix. But unfortunately it's converting my date into a unix timestamp.

Question: How to show human readable date format after this transformation?

A: I solved this problem by converting a date into a string using concat function of mysql.
I changed the sql query from select date from table for instance, to select concat('', date) from table


text:
Q: Oracle Data Modeller and synonyms I've been searching the web for two days and still cannot find a way to generate DDL code with public synonyms. Would be very grateful for any advice.

A: I think you are dealing with two different and distinct uses of the term "synonym":
1) In logical (entity) modelling, synonyms are alternative business names for an entity, e.g. the entity CUSTOMER may have synonyms PURCHASER and CLIENT.
2) In the physical (database) model, public synonyms are used to remove the need to specify the schema that owns a table.  Commonly, the synonym and table name are the same e.g. "CREATE PUBLIC SYNONYM customers for MYSCHEMA.CUSTOMERS;"
It would be very unusual to want public synonyms generated in the database for the business synonyms defined in the logical model.


text:
Q: Searching value in list for Value map I am using Value maps in QGIS and QField.
I use Value Maps with long lists (+500 diff values) all the time, but it is tedious to scroll through the list if I need a value from the bottom of the list.
Is there a way to type (e.g. first letters of the value I'm looking for) so sort off filter in my value-map list?
I know it is possible, because I have done it once before.
I especially want this for Qfield, but if I know how to do it in QGIS, it is no problem transfering this setup to QField.
Small example of 'my' value map list (in reality +500) values:
I will often need to select 'watermelon' but since it is on the bottom of my list, I always have to scroll down a lot.
[Apple
Banana
Cucumber
Eggplant
Fruit
Grapefruit
... - Hundreds of other values - ...
Watermelon]

A: Perhaps you could use value relation with types and subtypes. This is a kind of filter and it limits the choice of values.
See https://www.northrivergeographic.com/archives/qgis-3-2-drive-down-lists-aka-value-relation-widget
An autocomplete function would be nice but I don't know how to do it.


text:
Q: How do you return a pointer to an object in order to use in functions that access the objects methods? I've looked everywhere, and I cannot find a clear answer for my exact question here. Or perhaps I have found the answer, but I don't understand it completely.
I have 3 objects:
Foo Object1;
Foo Object2;
Foo Object3;

I have a function where a user chooses from a list of strings that correlate to objects. When the user inputs, say "B", I want to now perform operations on Object2.
Here is essentially what I have.
string getOption()
{
    string option;

    cout << "Option Menu" << endl;
    cout << "A - Option 1" << endl;    // Object1
    cout << "B - Option 2" << Lendl;   // Object2
    cout << "C - Option 3" << endl;    // Object3

    cin >> option;

    return option;

Now that I have the input, I want to perform numerous options on the object. Something like:
void modifyFooString(foo userSelectedObject)
{
    // Local variables
    string userInput;

    userInput = readInput(); // Function that reads valid input

    userSelectedObject.setMethod(userInput);
}

But with numerous functions. It's in a while loop, so I need to modify the object and then re-prompt the user if they want to make changes to a different object.
When I look at this problem, I think a pointer can be used. For example:
void getOption(Foo* &choice)
{
    string option;

    cout << "Option Menu" << endl;
    cout << "A - Option 1" << endl;    // Object1
    cout << "B - Option 2" << Lendl;   // Object2
    cout << "C - Option 3" << endl;    // Object3

    cin >> option;

    if (option == "A")
        choice = &Object1;

    else if (option == "A")
        choice = &Object2;

    if (option == "A")
        choice = &Object3;
}

So ideally, I can use the pointer now in the functions proceeding the getOption() function to modify the selected object. However, when I try to implement it like this, it's just not working.
How do I return a pointer that can be used to modify a selected object?
Thanks

A: You might have more success with
if (option == "A")
    choice = &Object1;
else if (option == "B")
    choice = &Object2;
else if (option == "C")
    choice = &Object3;

You should also clarify what 'it's just not working' actually means.
Since you want to return something, it more natural to use a C++ return statement.
Foo* getOption()
{
    ...
    if (option == "A")
        return &Object1;
    else if (option == "B")
        return &Object2;
    else if (option == "C")
        return &Object3;

A: Same as john's answer, but with the if-else-ladder being replaced by something I think clearer :)
Foo* getOption() {
   ...
   return option == "A" ? &Object1 :
          option == "B" ? &Object2 :
          option == "C" ? &Object3 :
                          nullptr  ;
}

A: A minimal example for your problem,
#include "stdafx.h"
#include <iostream>
#include <conio.h>

using namespace std;
class Foo
{
public:
    int id;
    int data;
    Foo(int tid,int tdata)
    {
        id = tid;
        data = tdata;
    }
};

Foo *Object1 = new Foo(1,0);
Foo *Object2 = new Foo(2,0);
Foo *Object3 = new Foo(3,0);

Foo* getOption()
{
    char option;

    cout << "Option Menu" << endl;
    cout << "A - Option 1" << endl;    // Object1
    cout << "B - Option 2" << endl;   // Object2
    cout << "C - Option 3" << endl;    // Object3

    cin >> option;

    switch (option)
    {
    case 'A':
        return Object1;
        break;
    case 'B':
        return Object2;
        break;
    case 'C':
        return Object3;
        break;
    default:
        cout << option ;
        break;
    }
        return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    cout << (getOption())->id;
    _getch();
    return 0;
}

In this example you will answer

1 for option == A
2 for option == B
3 for option == C

The main changes I have done are,
1. changed

    if (option == "A") // comparing A
        choice = &Object1;

    else if (option == "A") // Comparing B
        choice = &Object2;

    if (option == "A") //comparing C
        choice = &Object3;

to

  switch (option)
    {
    case 'A':
        return Object1;
        break;
    case 'B':
        return Object2;
        break;
    case 'C':
        return Object3;
        break;
    default:
        cout << option ;
        break;
    }

2. changed
 option == "A" to  option == 'A' format // when I have used if instead of switch

try this and let me know if it is helpful for you


text:
Q: MvcSiteMapProvider is using ascx I have donwloaded the Nuget package, MvcSiteMapProvider.
In one project it only downloaded the razor views. In my other, I have both the Razor and ascx files.  Also in that project it is default to using the ascx. I want it to use the razor pages instead.  Does anyone know how to switch this.

A: When the NuGet package detects no files with a .aspx extension in your project or detects any files with a .cshtml or a .vbhtml extension, it will install the .cshtml templates. Unfortunately, there is no reasonable default when both .aspx and .cshtml extensions are detected or no files with the above extensions are detected, so this is a "best guess".
To install the Razor templates, you just need to delete the .ascx templates and copy the .cshtml templates from here.


text:
Q: How to test NgRx selector which uses props? I have the following selector:
export const selectTableById = createSelector(selectRestaurantState, (state: RestaurantState, props) =>
  state.tables.find((table) => table.id === props.id)
);

Which uses the props to add additional information to the selctor when calling it.
In unit test i am trying something like this:
  it("should ...", () => {
    expect(selectTableById.projector(state, { props: { id: "id" } })).toEqual(...);
  });

but i have not found info about how to call the projector function with props

A: Found it:
const tables = ...
const state = <RestaurantState>{ tables };

it("should select table matched by id from props", () => {
    const props = { id: "t2" };
    expect(selectTableById.projector(state, props)).toEqual(tables[1]);
});

My problem was that, i added the wrong state (the whole appstate rather than just the restaurant state) to the projector funciton, and the props was badly formatted.


text:
Q: How nn.Linear works in shape(batch_size, seq_length, hidden_size)? In self.classifier, I assume there should be different weights to apply on tokens. Below is the huggingface's implementation.
def __init__(self, config, num_labels=2):
    super(BertForTokenClassification, self).__init__(config)
    self.num_labels = num_labels
    self.bert = BertModel(config)
    self.dropout = nn.Dropout(config.hidden_dropout_prob)
    self.classifier = nn.Linear(config.hidden_size, num_labels)
    self.apply(self.init_bert_weights)

def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):
    sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
    sequence_output = self.dropout(sequence_output)
    logits = self.classifier(sequence_output)

    if labels is not None:
        loss_fct = CrossEntropyLoss()
        # Only keep active parts of the loss
        if attention_mask is not None:
            active_loss = attention_mask.view(-1) == 1
            active_logits = logits.view(-1, self.num_labels)[active_loss]
            active_labels = labels.view(-1)[active_loss]
            loss = loss_fct(active_logits, active_labels)
        else:
            loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
        return loss
    else:
        return logits


text:
Q: Group heat map by fill I am trying to order a heat map in geom_tile()
 x <- structure(list(id = c("1", "1", "1", "2", "2", "3", "3", "3"),
                     time = c("1", "2", "3", "1", "3", "1", "2", "3"),
                     response = c( "0", "1", "1", "1", "1", "0", "0", "1")),
                .Names = c("id", "time", "response"), class = "data.frame")

df %>%
  ggplot() + geom_tile(aes(time, id, fill=response))

id is numeric and time and response are factors. My heat map should have id on the y-axis and time on the x-axis.  I'm trying to group sets of responses so that each line is an id but that id's who follow the same pattern of 0,0,0 for the time periods are grouped together in blocks.  I've tried order, reorder, and scale_y_continuous, but none of them change the order of responses.
This answer comes close to what I'm looking for, but none of the answers seem to work.

A: I don't know if I understand your question correctly. What I observed that your sample data does not let you make any order.
Sample data:
id = c(1, 1, 1, 2, 2,2, 3, 3, 3)
time = c(1, 2, 3, 1, 3,2, 1, 2, 3)
response = c(0, 1, 1, 1, 1, 0, 0, 1)

df=cbind(id,time, response)
df<-as.data.frame(df)

df$id <- factor(df$id, levels=c("1", "2", "3"))
df$time <- factor(df$time, levels=c("1", "2", "3"))
df$response<- factor(df$response, levels=c("0", "1"))

df
  id time response
1  1    1        0
2  1    2        1
3  1    3        1
4  2    1        1
5  2    3        1
6  2    2        0
7  3    1        0
8  3    2        1
9  3    3        0

Sample code:
df$id<- factor(df$id, levels=unique(df$id[order(df$response)]))

ggplot(df, aes(time,id, fill=response)) +
  geom_tile()+
  labs(x="Time",y="Id")+
  theme_minimal()

Plot:

Well, based on what you suggest I think the relevant change would be
 df$id<- factor(df$time, levels=unique(df$id[order(df$time)]))

I also had to improve the data again
Sample data:
 id = c(1, 1, 1, 2, 2,2, 3, 3, 3, 2)
time = c(1, 2, 3, 1, 3,2, 1, 2, 3, 2)
response = c(0, 1, 1, 1, 1, 0, 0, 1,0,0)

df=cbind(id,time, response)
df<-as.data.frame(df)

df
   id time response
1   1    1        0
2   2    2        1
3   3    3        1
4   1    1        1
5   3    3        1
6   2    2        0
7   1    1        0
8   2    2        1
9   3    3        0
10  2    2        0


text:
Q: Can you setup UART Reception on dsPIC33EP512MU814 on eval board dsPICDEM MCLV-2 According to microchip, the dsPIC33EP512MU814 can be integrated with the dsPICDEM MCLV-2 Development Board using dsPIC33EP512MU814 Plug-In-Module
However, according to the dsPICDEM MCLV-2 Interface map the UART Rx and Tx of the evaluation board are pins 49 and 50, respectively. So then according to plug-in-module interface map that UART Rx must be mapped to pin SDA2/RP100/RF4, and UART Tx must be mapped to SCL2/RP101/RF5.
I'm aware that you can map out UART Tx to RP101 by simply assigning
RPOR9BITS.RP101R = 1;

However I was expecting the pin of UART Rx to be RPIx not an RPx.
Does this mean you can't perform UART Reception?

A: From the datasheet (emphasis mine):

The number of available pins is dependent on the particular device and
  its pin count. Pins that support the Peripheral Pin Select feature
  include the designation "RPn" or "RPIn" in their full pin designation,
  where "RP" designates a remappable function for input or output and
  "RPI" designates a remappable functions for input only, and "n" is the
  remappable pin number.

Since an "RPx" pin can be either input or output, you can remap the UART Rx to it.
RPINR18 = 0x0064;      // UART Rx PPS -> RP100


text:
Q: Non type-variable argument in the Constraint: Enum A => Ord A I am new to Haskell.
I want to implement Ord class for a Custom Data type using Enum class.
It works fine if I implement Enum class and use the fromEnum function directly in the implementation of compare function required for Ord class.
But as Type Signatures and Type Level Constraints are for Readability and Documentation. I want to Specify the Ord instance of my custom data depends on Enum instance.
When I write the below code it throws an error.
data DayOfWeek
  = Mon | Tue | Weds | Thu | Fri | Sat | Sun
  deriving (Eq, Show)

instance Enum DayOfWeek => Ord DayOfWeek where
  compare a b = compare (fromEnum a) (fromEnum b)

instance Enum DayOfWeek where
  toEnum 1 = Mon
  toEnum 2 = Tue
  toEnum 3 = Weds
  toEnum 4 = Thu
  toEnum 5 = Fri
  toEnum 6 = Sat
  toEnum 7 = Sun

  fromEnum Mon = 1
  fromEnum Tue = 2
  fromEnum Weds = 3
  fromEnum Thu = 4
  fromEnum Fri = 5
  fromEnum Sat = 6
  fromEnum Sun = 7

Error:
* Non type-variable argument in the constraint: Enum DayOfWeek
  (Use FlexibleContexts to permit this)
* In the context: Enum DayOfWeek
  While checking an instance declaration
  In the instance declaration for `Ord DayOfWeek'

Can we write Constraints on Concrete Types

A: Your code compiles if we enable a pair of extensions, writing in the first line of the file:
{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}

Still, I think it's not worth it. I'd remove the context instead, since that is what most existing code does.
Further, I'm not sure about why do you think it's important to document the fact that one instance depends on the other. I would regard that as an implementation detail, hence something I'd like to hide from the user, rather than to point out.


text:
Q: Getting a value of object for user-defined classes for while, if and for statements I am trying to get a bool value out of user defined object.
For example with float or int I can do something like
float a = 3.5
if (a) doSomething();

I want my class to look like this:
class Socket {
...
...
};
...
Socket T;

if (!T) cout << "Error occured";
else {
   doStuff();
}

Of course I can define a function that returns bool (like bool isValid();) and call it directly, but I would like to know if it is possible.

A: In C++11, you can safely convert your type to a boolean value:
explicit operator bool() const {return isValid();}

If your compiler doesn't support that, then you could write the same thing without explicit; however, that can be a bit dangerous because it enables implicit conversions to any numeric type. Instead, you could use a hack known as the safe bool idiom:
private:
    typedef void (Socket::*safe_bool)() const;
    void safe_true() const {}
public:
    operator safe_bool() const {return isValid() ? &Socket::safe_true : 0;}

This returns a pointer type which can't be converted into anything except bool.


text:
Q: jQuery remove class from parent on click I have an element that once you click on it, it adds and removes a class with jQuery. When you click on a child element I want the classes to swap again.
I tried doing it with .parent but that doesn't seem to work..
This is the html:

And jQuery:
$('.block').click(function(){
    $(this).removeClass('inactive'),
    $(this).addClass('active');
});

$('.close').click(function(){
    $(this).parent().addClass('inactive');
    $(this).parent().removeClass('active');
});

EDIT
Solution:
$('.block').click(function(){
    $(this).addClass('active');
    $(this).removeClass('inactive');
});

$('.close').click(function(e){
    $(this).parent('.block').toggleClass('inactive active');
    e.stopPropagation();
});

A: Because the .close is a child of the .block the event is propagating back up and also triggering the handler oon the .block, which means that the classes are getting reverted straight away. You can use .stopPropagation() to stop this happening:

$('.block').click(function(){
    $(this).removeClass('inactive'),
    $(this).addClass('active');
});

$('.close').click(function(e){
    $(this).parent().addClass('inactive');
    $(this).parent().removeClass('active');
    e.stopPropagation();
});
.inactive{ background-color:red}

    in the block
  in the close

There are a number of other enhancements you can make to simplify your code, but they are tangential to the question, for completeness

*

*chain your methods to save repeating yourself

*consider iftoggleClass is more appropriate than addClass/removeClass.

$('.block').click(function(){
    $(this).removeClass('inactive').addClass('active');
});

$('.close').click(function(e){
    $(this).parent().addClass('inactive').removeClass('active');
    e.stopPropagation();
});
.inactive{ background-color:red}

    in the block
  in the close


text:
Q: Request loses "error" field after adding "params" into @RequestMapping in order to handle a few situations with the same resource path, eg:
/path/to/resource?param1=a
/path/to/resource?param2=a
I introduced into @RequestMapping params. Looks like this now:
@Override
@RequestMapping(value = PM_DATA_ROUTE, params = {"system", "className", "source", "fromTimestampInNanos",
        "toTimestampInNanos"})
public List<PmDataInformationWrapper> getPmData(
        @Valid TimestampRangePmDataRequestParameter timestampRangePmDataRequestParameter) {
    LOGGER.info(REQUEST_RECEPTION_LOG, timestampRangePmDataRequestParameter);
    return pmDataManagerAdapter.getPmData(timestampRangePmDataRequestParameter);
}

@Override
@RequestMapping(value = PM_DATA_ROUTE, params = {"system", "className", "source", "fromTimestampInNanos",
        "durationInNanos"})
public List<PmDataInformationWrapper> getPmData(
        @Valid TimestampDurationPmDataRequestParameter timestampDurationPmDataRequestParameter) {
    LOGGER.info(REQUEST_RECEPTION_LOG, timestampDurationPmDataRequestParameter);
    return pmDataManagerAdapter.getPmData(timestampDurationPmDataRequestParameter);
}

these values like system, className, etc - are names of fields encapsulated into object request parameters that I'm expecting in controller method signature.
This works fine, besides one little issue. If I don't put this "params" explicitly into @RequestParam and then miss something from client side - the error response is meaningful and looks like this:

"errors": [
      "'timestampInNanos' parameter cannot be omitted!"
    ],

The message itself comes from validation. Doesn't matter.
After I added this params into @RequestMapping, the error response of the same situation looks like this:

"exception": "org.springframework.web.bind.UnsatisfiedServletRequestParameterException",
    "errors": []

No even single word about missing params, because in this case it does not even step into the controller method (which is actually reasonable).
Usually I was looking for the errors in ServletRequestAttributes of request, which contains errorAttributes.
Now I have no idea what to do about.
Does anyone have some ideas how to get some more meaningful message about missing params in this particular case?
I'm aware that if we don't step into the desired method, and then just jump into default error handling controller - it might be difficult to say anything, but on the other hand - APIs like this are not rare, so there is probably some good practice how to handle such a situation...
Thanks in advance!


text:
Q: Storing Bash function parameters in variables I want to define and get all the required variables that are passed to a function as parameters:
function explain_vars() {
  echo "Explaining vars '$@':" >&2
  for _var in "$@"; do
    printf "  $_var: '${!_var}'\n" >&2
  done
  printf "\n" >&2
}

function read_params() (
  ## Define local variables
  _vars=(v1 v2 v3)
  local ${_vars[@]}

  ## Read variables from input:
  read ${_vars[@]} <<< "$@"
  explain_vars "${_vars[@]}"
)

The read takes puts all parameters in the specified variables, default delimiter here is space. So if I pass different strings as second parameter, read will store only the first string in the second parameter, and all the rest to the following parameters:
$ read_params one "two dot one" "three" "four"
Explaining vars 'v1 v2 v3':
  v1: 'one'
  v2: 'two'
  v3: 'dot one three four'

As we can see, variable v2 is not synchronized with given parameters anymore. Moreover, it fails at reading empty strings:
$ read_params one "" " " '' ' ' "two dot one" "three" "four"
Explaining vars 'v1 v2 v3':
  v1: 'one'
  v2: 'two'
  v3: 'dot one three four'

By looping through the all-parameters variable $@ inside the function it is possible to distinguish variables:
function raw_params() (
  echo "Explaining row parameters:"
  for _v in "${@}"; do
    printf "  '$_v'\n"
  done
)

$ raw_params one "" " " '' ' ' "two dot one" "three" "four"
Explaining row parameters:
  'one'
  ''
  ' '
  ''
  ' '
  'two dot one'
  'three'
  'four'

To me the read command offers benefit and quickness at defining, controlling and checking requested parameters that are passed to functions. However this works only for single and non-empty stringed parameters. Is it possible to read all different parameters in variables like the read command does, but respecting spaces and empty parameters? Or is there a better approach maybe?

A: From the original question seems read command is not correctly understood, read is a builtin which reads one line for standard input, IFS environment variable is used as field separator and -d option allows to change record delimiter (default is newline), for more information see read in bash manual.
The function arguments are retrieved using special variable "$@", bash syntax to assign an array is just
_vars=( "$@" )   # no space between variable name and = and no space between = and (

As a space is not valid in a variable name ${!_var} expansion will fail writing an error bash: ...: bad substitution, if _var contains an expression with a space.
function keyword is useless because of (), the use of parenthesis around the body of function instead of braces { ;} starts a new sub-shell.

A: I'm not sure what you are hoping to accomplish with this code, but this would appear to solve your problem for the case of three input parameters. Perhaps it shows you a way forward even if it doesn't completely do what you want.
read_params () (
  ## Define local variables
  _vars=(v1 v2 v3)
  local ${_vars[@]}

  local i
  for ((i=1; i<=$#; ++i)); do
     ## Read variables from input:
     printf -v "${_vars[i-1]}" "${!i}"
  done
  explain_vars "${_vars[@]}"
)

A: I rewrote my function in a script according to tripleee's answer. printf works fine except for assigning empty values ('' and "") to arrays. For that, we need to format the string we pass to printf -v with '%s'. For the example I pass an array of parameters to my function twice: once per assigning them to my regular local parameters; a second time to pass the same parameters to my last local array variable. Here is the code:
$ cat parse-local-vars.sh
#!/usr/bin/env bash
function explain_vars() {
  echo "Explaining vars '$@':" >&2
  for _var in "$@"; do
    printf "  $_var: '${!_var}'\n" >&2
  done
}

function parse_params() (
  #
  # Stores given parameters in defined local variables _vars.
  # Last variable will be treated as an array and
  # remaining parameters will be stored therein.
  #

  ## Define local variables
  local _vars=(v1 v_empty_double_quote v_spaced_double_quote v_empty_single_quote v_spaced_single_quote v2_1 v3 v4 args)
  local ${_vars[@]}

  ## Make sure we assign parameters to variables
  [ ${#_vars[@]} -gt 0 ] \
    || return 1

  _args_pos=$(( ${#_vars[@]}-1 ))
  _args_counter=0
  local p
  for ((p=1; p<=$#; ++p)); do
     ## Read variables from input:
     if [ $p -le $_args_pos ]; then
       #printf -v "${_vars[p-1]}" '%s' "${!p}"
       printf -v "${_vars[p-1]}" "${!p}"
     else
       #printf -v "${_vars[_args_pos]}[$_args_counter]" '%s' "${!p}"
       printf -v "${_vars[_args_pos]}[$_args_counter]" "${!p}"  # Without the '%s' assigning empty variable to an array does not work
       _args_counter=$(( _args_counter+1 ))
     fi
  done
  explain_vars "${_vars[@]}"
  echo "exlaining array args[@]: '${args[@]}'"
  for _v in "${args[@]}"; do
    echo "   >'$_v'"
  done
)

params_to_test=(one "" "  " '' '  ' "two dot one" "three" "four")
parse_params "${params_to_test[@]}" "${params_to_test[@]}"

As one can see, here I use printf -v without formatting the parameter string (no use of '%s'):
$ bash parse-local-vars.sh
Explaining vars 'v1 v_empty_double_quote v_spaced_double_quote v_empty_single_quote v_spaced_single_quote v2_1 v3 v4 args':
  v1: 'one'
  v_empty_double_quote: ''
  v_spaced_double_quote: '  '
  v_empty_single_quote: ''
  v_spaced_single_quote: '  '
  v2_1: 'two dot one'
  v3: 'three'
  v4: 'four'
  args: 'one'
exlaining array args[@]: 'one       two dot one three four' (6 values)
   >'one'
   >'  '
   >'  '
   >'two dot one'
   >'three'
   >'four'

The empty parameters "" and '' are not passed to the array (6 values).
Allowing the string formatting of printf by toggling the following comments:
printf -v "${_vars[_args_pos]}[$_args_counter]" '%s' "${!p}"
#printf -v "${_vars[_args_pos]}[$_args_counter]" "${!p}"  # Without the '%s' as,signing empty variable to an array does not work

Leads to this output:
$ bash parse-local-vars.sh
Explaining vars 'v1 v_empty_double_quote v_spaced_double_quote v_empty_single_quote v_spaced_single_quote v2_1 v3 v4 args':
  v1: 'one'
  v_empty_double_quote: ''
  v_spaced_double_quote: '  '
  v_empty_single_quote: ''
  v_spaced_single_quote: '  '
  v2_1: 'two dot one'
  v3: 'three'
  v4: 'four'
  args: 'one'
exlaining array args[@]: 'one         two dot one three four' (8 values)
   >'one'
   >''
   >'  '
   >''
   >'  '
   >'two dot one'
   >'three'
   >'four'

This is the expected results, as empty strings are correctly assigned to the array (8 values). I haven't figured out what is going on with passing empty strings to an array with printf -v, but using formatted strings with printf -v seems to be the safe way to go. Any correction, explanation and improvements are welcome.


text:
Q: form.onsumbit subclass i write smart extension for chrome and I inject my javascript inside all frame in frameset page...
In one of frame I want to replace onsumbit for form.
I want to analyze (x, y) values for image type field before make submit.
I can find element by name to get form.
I can get onsubmit property.
But how to make check sending values before submit?
Thanks.

A: Hm, something like this?
var formEl = document.getElementById("form1");

var originalOnSubmit = formEl.onsubmit;

formEl.onsubmit = function() {
    if(all_ok) {
        originalOnSubmit();
    } else {
        return false;
    }
}


text:
Q: Count Total Number of XmlNodes in C# I'm trying to find a way to get the total number of child nodes from an XmlNode recursively.
That it is to say I want to count all the children, grand children etc.
I think its something like
node.SelectNodes(<fill in here>).Count

but I don't know what the XPath is.

A: XPath supports something called Axis specifier, so the code you're looking for is
node.SelectNodes("descendant::*").Count

A: The XPath you are after is:
descendant::node()   (1)
or
descendant::*   (2)
The first XPath expresion (1) above selects any node (text-node, processing-instruction, comment, element) in the subtree rooted by the current node.
(2) selects any element node in the subtree rooted by the current node.

A: using System.Xml.Linq;

node.DescendantNodes().Count();

A: If you're doing an unfiltered count, which your question implies, you could just traverse the them using the ChildNodes property:
private int CountChildren(XmlNode node)
{
   int total = 0;

   foreach (XmlNode child in node.ChildNodes)
   {
      total++;
      total += CountChildren(child);
   }
   return total;
}

A: You could use somthing like this:
private static int CountNodes(XmlNode node)
{
    int count = 0;

    foreach (XmlNode childNode in node.ChildNodes)
    {
        count += CountNodes(childNode);
    }

    return count + node.ChildNodes.Count;
}

A: I think this will do it for you though not through xPath:
void CountNode(XmlNode node, ref int count)
{
    count += node.ChildNodes.Count;

    foreach (XmlNode child in node.ChildNodes)
    {
        CountNode(child, ref count);
    }
}

For reference here is a link to the count function in xpath.
http://msdn.microsoft.com/en-us/library/ms256103.aspx
so if you were looking for all the same type of nodes you could do
//Your_node

to select all the nodes
//*


text:
Q: Java Generics: compareTo and "capture#-of ?" I'm trying to write an implementation of a BinaryTree whose object can be of any type that implements Comparable.  However, I realize that won't completely work.  For example, A String and a Double wouldn't be able to be inserted into the same tree, even though they both implement Comparable.
So, I would like to know if it's possible to write the code such that the BinaryTree can be instantiated with any value whose type implements Comparable, but any ensuing elements added to the tree must all share the same supertype as the root's value.
Here's the code I have so far:
public class BinaryTree {

    private Node root;

    public BinaryTree() {

        this.root = null;
    }

    public Node lookup(Comparable<Object> value) {

        return lookup(this.root, value);
    }

    private Node lookup(Node node, Comparable<Object> value) {

        Node match = null;

        if (match != node) {

            if (value == node.value) {
                match = node;
            } else if (value.compareTo(node.value) < 0) {
                return lookup(node.left, value);
            } else {
                return lookup(node.right, value);
            }
        }

        return match;
    }

    public Node lookupNonRecursively(Comparable<Object> value) {

        return lookupNonRecursively(this.root, value);
    }

    private Node lookupNonRecursively(Node node, Comparable<Object> value) {

        Node match = null;

        if (match != node) {

            if (value == node.value) {
                match = node;
            } else {

                Node root = node;
                boolean found = false;

                while (!found && root != null) {

                    if (root.value.compareTo(value) < 0) {

                        if (root.left == null) {

                            root.left = match = new Node(value);
                            found = true;
                        } else {
                            root = root.left;
                        }
                    } else {
                        if (root.right == null) {

                            root.right = match = new Node(value);
                            found = true;
                        } else {
                            root = root.right;
                        }
                    }
                }
            }
        }

        return match;
    }

    public Node insert(Comparable<Object> value) {

        return insert(this.root, value);
    }

    private Node insert(Node node, Comparable<Object> value) {

        if (node == null) {
            node = new Node(value);
        } else {
            if (node.value.compareTo(value) <= 0) {
                insert(node.left, value);
            } else {
                insert(node.right, value);
            }
        }

        return node;
    }

    public Node insertNonRecursively(Comparable<Object> value) {

        return insertNonRecursively(this.root, value);
    }

    private Node insertNonRecursively(Node node, Comparable<Object> value) {

        if (node == null) {
            node = new Node(value);
        } else {

            Node root = node;
            boolean inserted = false;

            while (!inserted) {

                if (node.value.compareTo(root.value) < 0) {

                    if (root.left == null) {
                        root.left = node = new Node(value);
                        inserted = true;
                    } else {
                        root = root.left;
                    }
                } else {
                    if (root.right == null) {
                        root.right = node = new Node(value);
                        inserted = true;
                    } else {
                        root = root.right;
                    }
                }
            }
        }

        return node;
    }

    public static class Node {

        private Node left;
        private Node right;
        private Comparable<Object> value;

        public Node(Comparable<Object> value) {

            this.left = null;
            this.right = null;
            this.value = value;
        }
    }
}

And as a test, this will throw the error, The method insert(Comparable<Object>) in the type BinaryTree is not applicable for the arguments (Integer), if I try to run code like the following:
BinaryTree tree = new BinaryTree();
tree.insert(new Integer(1));

You can see I've implemented some different BinaryTree methods for this class, but the same rules would need to apply: any value passed into lookup() or insert() would also need to share the root's supertype.  I have a feeling this is where some variant of <T extends Comparable<? super T>> is going to come into play, but my mind is just not figuring this one out.
Any ideas for how I might accomplish this?
As noted by @jp-jee, here's my solution (also with logic and other bugs fixed from untested first attempt), which works beautifully:
public class BinaryTree<T extends Comparable<T>> {

    private Node<T> root;

    public BinaryTree() {

        this.root = null;
    }

    public Node<T> lookup(T value) {

        return lookup(this.root, value);
    }

    private Node<T> lookup(Node<T> node, T value) {

        Node<T> match = null;

        if (match != node) {

            if (value.equals(node.value)) {
                match = node;
            } else if (value.compareTo(node.value) < 0) {
                return lookup(node.left, value);
            } else {
                return lookup(node.right, value);
            }
        }

        return match;
    }

    public Node<T> lookupNonRecursively(T value) {

        return lookupNonRecursively(this.root, value);
    }

    private Node<T> lookupNonRecursively(Node<T> node, T value) {

        Node<T> match = null;

        if (match != node && value != null) {

            if (value.equals(node.value)) {
                match = node;
            } else {

                Node<T> searchRoot = node;
                boolean found = false;

                while (!found && searchRoot != null) {

                    if (value.equals(searchRoot.value)) {
                        match = searchRoot;
                        found = true;
                    } else if (value.compareTo(searchRoot.value) < 0) {
                        searchRoot = searchRoot.left;
                    } else {
                        searchRoot = searchRoot.right;
                    }
                }
            }
        }

        return match;
    }

    public void insert(T value) {

        this.root = insert(this.root, value);
    }

    private Node<T> insert(Node<T> node, T value) {

        if (node == null) {
            node = new Node<T>(value);
        } else {
            if (value.compareTo(node.value) <= 0) {
                node.left = insert(node.left, value);
            } else {
                node.right = insert(node.right, value);
            }
        }

        return node;
    }

    public void insertNonRecursively(T value) {

        this.root = insertNonRecursively(this.root, value);
    }

    private Node<T> insertNonRecursively(Node<T> node, T value) {

        if (node == null) {
            node = new Node<T>(value);
        } else {

            Node<T> runner = node;
            boolean inserted = false;

            while (!inserted) {

                if (value.compareTo(runner.value) < 0) {

                    if (runner.left == null) {
                        runner.left = new Node<T>(value);
                        inserted = true;
                    } else {
                        runner = runner.left;
                    }
                } else {
                    if (runner.right == null) {
                        runner.right = new Node<T>(value);
                        inserted = true;
                    } else {
                        runner = runner.right;
                    }
                }
            }
        }

        return node;
    }

    public static class Node<T extends Comparable<T>> {

        private Node<T> left;
        private Node<T> right;
        private T value;

        public Node(T value) {

            this.left = null;
            this.right = null;
            this.value = value;
        }

        public Node<T> getLeft() {
            return left;
        }

        public Node<T> getRight() {
            return right;
        }

        public T getValue() {
            return value;
        }
    }
}

A: Make your Binary Tree generic like
public class BinaryTree<T extends Comparable<T>>{
   ...
}

Whenever creating a BinaryTree instance, specify the containied type:
new BinaryTree<MyClass>();

Where MyClass must implement Comparable<MyClass>, i.e. be comparable to Objects of the same class.
Your methods would read as (example):
 public Node lookup(T value) { ... }

The same applies for your Node class. Make it generic the same way.


text:
Q: Computationally cheap substitute of VRP by clustering locations based on Distance I have a list of locations, and a list of vehicle capacities. I want to cluster locations such that number of points in clusters are equal to capacities of vehicles. Also, while forming clusters, I don't want distance between locations in a cluster to be more than a threshold.
For example, the locations I have is :
points = array([[33.    , 41.    ],
       [33.9693, 41.3923],
       [33.6074, 41.277 ],
       [34.4823, 41.919 ],
       [34.3702, 41.1424],
       [34.3931, 41.078 ],
       [34.2377, 41.0576],
       [34.2395, 41.0211],
       [34.4443, 41.3499],
       [34.3812, 40.9793]])

vehicle capacities are as follows:
capacities = [3, 4, 2]

Max distance between two consecutive locations in a cluster should be less than say 3 kms.
i.e. If locations 1->2->3->4 are in a cluster then this distance limit applies to orders 1,2 and 2,3 and 3,4.
Any solution to this problem? I don't want to use vrpy or ortools.


text:
Q: Browser console not seeing JavaScript variables using Webpack's dev server Im using Webpack's dev server. It loads up a working page fine however I don't have access to JavaScript variables in my browser console. EG if I have the following in a JavaScript file:
const body = document.querySelector('body');

Then entering body in my browser console says its not defined.
Im using Webpack 3.5.5 (latest). Im running the build script from my package.json:
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open"
  },

In my webpack.config.js I was specifying the devServer but removing it seems to make no difference.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
  entry: './src/script.js',
  /*
  devServer: {
    contentBase: './dist'
  },
  */

Is this a configuration issue or is there another way that your supposed to access JavaScript variables?

A: I think this is the expected behavior. Webpack wraps the content of your script.js file into a module. Any variables you declare in there will be private. If you need to access a variable in the browser console, you can attach it to the window object.
const body = document.querySelector('body');
window.body = body;


text:
Q: What handles the keyboard NumLock LED? I want to find confirmation that the keyboard on a PC type computer controls the NUM_LOCK LED locally or if the Computer System software sends commands to the keyboard to manage this LED based upon it seeing scan codes from the Num Lock key.
I ask this because I was recently doing some experimentation with a separate USB Numerical Keypad and found that when its Num Lock button is pushed there is no NUM_LOCK scan code sent to the computer at that time although its NUM_LOCK LED comes on. Using an online browser based keyboard test I see that this weird keypad, when in the NumLock mode will send the following for each of the other key pad keys:: Numlock Down Scan Code - Number Button Down Scan Code - Number Button Up Scan Code - Numlock Up Scan Code.
In the same keyboard test my regular keyboard sends a NumLock Down and then NumLock Up scan codes as the Num Lock button is pressed and released.
Why would this USB Keypad work differently that the regular keyboard?

A: PC host is responsible for sending LED state to keyboard and keyboard itself is responsible for preserving last set LED state. In Windows LED state is updated by keyboard driver to be in sync with VK_CAPITAL/VK_NUMLOCK/VK_SCROLL/VK_KANA virtual-key codes state of the current thread.
Modern keyboards are working via Device Class Definition for HID 1.11 (USB HID spec). Bluetooth keyboards are using this spec too under the hood.
According to the Appendix C: Keyboard Implementation of the spec:
Synchronization between LED states and CAPS LOCK, NUM LOCK, SCROLL LOCK,
COMPOSE, and KANA events is maintained by the host and NOT the keyboard. If
using the keyboard descriptor in Appendix B, LED states are set by sending a
5-bit absolute report to the keyboard via a Set_Report(Output) request.
According to B.1 Protocol 1 (Keyboard) of Appendix B: Boot Interface Descriptors":
The following table represents the keyboard output report (1 byte).

Bit
Description

0
NUM LOCK

1
CAPS LOCK

2
SCROLL LOCK

3
COMPOSE

4
KANA

5 to 7
CONSTANT

Note. The LEDs are absolute output items. This means that the state of each LED must be included in output reports (0 = off, 1 = on). Relative items would permit reports that affect only selected controls (0 = no change, 1 = change).


text:
Q: how to refresh ListView.builder flutter How can I refresh my ListView.builder when adding item to the list?
ListView.builder(
      itemCount: propList.length,
      scrollDirection: Axis.horizontal,
      shrinkWrap: true,
      itemBuilder: (context,index)=> Text(propList[index]),
    )

my button is
FlatButton(onPressed: (){propList.add('text');}, child: Text('add'))

A: Assuming you've extended the StatefulWidget, you must call setState everytime you change the state. Ex:
setState(() { propList.add('text'); });

Here's a quick example:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) => MaterialApp(home: MyList());
}

class MyList extends StatefulWidget {
  @override
  _MyListState createState() => _MyListState();
}

class _MyListState extends State<MyList> {
  List<String> propList = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My List'),
      ),
      body: ListView.builder(
        itemCount: propList.length,
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        itemBuilder: (context,index)=> Text(propList[index]),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() => propList.add('text')),
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

A: You can try: onPressed: setState(() { propList.length; });

A: Here I've created flat_list widget which has similar specifications as in React Native's FlatList. Below will simply work.
FlatList(
  onRefresh: () async {
    await Future.delayed(const Duration(seconds: 2));
  },
  data: items.value,
  buildItem: (item, index) {
    var person = items.value[index];

    return ListItemView(person: person);
  },
),


text:
Q: Convertir un arreglo a un archivo .json bueno este es mi codigo
var miJson = JSON.stringify(miArray);
pero yo necesito que todos los datos de la variable "miJson" esten en un archivo con la extension .json

A:
Puedes crear archivos usando la API de File System

Por ejemplo:
var fs = require('fs');
var file = 'miJson.json';
var data = JSON.stringify(miArray);

fs.writeFile(file, data, function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("El archivo se guardo con exito!");
});


text:
Q: Selecting values from IQueryable with IsNullOrWhitespace check I am trying to do the following with a IQueryable expression:
(from Person p in s
   select new
   {
           label = p.FirstName + " "
       + (string.IsNullOrWhiteSpace(p.MiddleName) ? p.MiddleName + " " : "")
                   + p.LastName,
       value = p.Id
       }).ToList();

I am getting following error:
LINQ to Entities does not recognize the method 'Boolean
IsNullOrWhiteSpace(System.String)' method, and this method cannot be
translated into a store expression.

What is the solution for this?

A: String.IsNullOrWhitespace is a static function of the string object and cannot be used with Entity Framework queries, whereas p.FirstName.StartsWith("S") is a method of the entity property and can be used.
To answer your question you will have to roll your own inline.  Try this:
(from Person p in s
   select new
   {
       label = p.FirstName + " "
       + ((p.MiddleName != null && p.MiddleName != string.Empty) ? p.MiddleName + " " : "")
                   + p.LastName,
       value = p.Id
   }).ToList();


text:
Q: How to show "Open In..." when a user tries to open email attachments in iOS I've seen some iOS apps have this function:
When a user tries to open an email attachment, they can press and hold on the attachment for a couple of seconds, and a popup menu will appear displaying two buttons. One button reads "Open in iBooks" (for example). When user clicks it, then the app will be run and open the attachment.
I would like to know how to register my application to be associated with a particular document type.
Also what happens to the document when it is opened? Is it copied to a location that can be read by the application, or does the application receive some sort of object representing the document?
If anyone knows how to do this, please let me know. Thx very much.

A: http://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/RegisteringtheFileTypesYourAppSupports.html%23//apple_ref/doc/uid/TP40010411-SW1
Is what you need :-)

A: Your app has to register its ability to open specific file types by setting the CFBundleDocumentTypes in its plist. Here's an example of GoodReader's XML for opening PDFs.
When you app is called to open a file, you can find the information about the file in application:didFinishLaunchingWithOptions:, which is passed a dictionary with the key UIApplicationLaunchOptionsURLKey
You'll get a URL pointing to the file to open. I think that it's read-only and you'll have to save your own version if you want to change it.


text:
Q: google drive save button and cors with headers I'm trying to make "save to drive" button on my site using Google Drive Web APIs, but no results. After clicking on button there are errors like this:
*XMLHttpRequest cannot load http://myFILEsiteONE/file.doc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myMAINsiteTWO' is therefore not allowed access.*

At stackoverflow have a lot of answers about this: all problems solved by headers, which described at google documentation.
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Range
Access-Control-Expose-Headers: Cache-Control, Content-Encoding, Content-Range

But my site already have this headers. There is result of get_headers php function:
array{
['0'] => string'HTTP/1.1 200 OK'
['1'] => string'Server: nginx'
['2'] => string'Date: Tue, 23 Dec 2014 13:41:52 GMT'
['3'] => string'Content-Type: text/html; charset=UTF-8'
['4'] => string'Content-Length: 1643'
['5'] => string'Connection: close'
['6'] => string'Vary: Accept-Encoding'
['7'] => string'X-Powered-By: PHP/5.3.3'
['8'] => string'P3P: policyref="/bitrix/p3p.xml", CP="NON DSP COR CUR ADM DEV PSA PSD OUR UNR BUS UNI COM NAV INT DEM STA"'
['9'] => string'X-Powered-CMS: Bitrix Site Manager (bc446669bda3fecf3857134c6da9af3b)'
['10'] => string'Set-Cookie: PHPSESSID=2ujm04isb6h1e3tk2ddonr4537; path=/; HttpOnly'
['11'] => string'Expires: Thu, 19 Nov 1981 08:52:00 GMT'
['12'] => string'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
['13'] => string'Pragma: no-cache'
['14'] => string'Set-Cookie: BITRIX_SM_GUEST_ID=256066; expires=Fri, 18-Dec-2015 13:41:12 GMT; path=/'
['15'] => string'Set-Cookie: BITRIX_SM_LAST_VISIT=23.12.2014+16%3A41%3A12; expires=Fri, 18-Dec-2015 13:41:12 GMT; path=/'
['16'] => string'Access-Control-Allow-Origin: *'
['17'] => string'Access-Control-Allow-Headers: Range'
['18'] => string'Access-Control-Expose-Headers: Cache-Control, Content-Encoding, Content-Range'
}

I have only FTP-access to hosting.
What i need to try?
p.s. saving to disk from site, where button is placed - working correctly.
Thank you very much!

A: Since you are depending on the Drive SDK and you have credentials, you cannot use an origin wildcard for the Access-Control header. You'll have to change this source to specify your server address as a source.


text:
Q: Evaluate integral $\int e^{\mu (j-l)t}(1-e^{-\mu t})^{j-l-1}dt$ I have to evaluate the following integral, but I don't have any ideas how to do it.
$$\int e^{\mu (j-l)t}(1-e^{-\mu t})^{j-l-1}dt$$
Can anyone help me with this?

A: For simplicity, write $x=e^{\mu t}$ and $n=j-l$, the integrand is $x^n\left (1-x^{-1}\right )^{n-1}$. Using the Binomial Theorem we get$$\left (1-x^{-1}\right )^{n-1}=\sum \limits _{k=0}^{n-1}\binom{n-1}{k}(-1)^kx^{-k}$$then$$x^n\left (1-x^{-1}\right )^{n-1}=\sum \limits _{k=0}^{n-1}\binom{n-1}{k}(-1)^kx^{n-k}.$$Therefore$$e^{\mu nt}\left (1-e^{-\mu t}\right )^{n-1}=\sum \limits _{k=0}^{n-1}\binom{n-1}{k}(-1)^ke^{\mu t(n-k)}.$$Finally\begin{align*}\int e^{\mu nt}\left (1-e^{-\mu t}\right )^{n-1}\,dt & =\int \sum \limits _{k=0}^{n-1}\binom{n-1}{k}(-1)^ke^{\mu t(n-k)}\,dt \\
& =\sum \limits _{k=0}^{n-1}\binom{n-1}{k}(-1)^k\int e^{\mu t(n-k)}\,dt \\
& =\sum \limits _{k=0}^{n-1}\binom{n-1}{k}(-1)^k\frac{e^{\mu t(n-k)}}{\mu (n-k)}+C \\
& =\sum \limits _{k=0}^{j-l-1}\binom{j-l-1}{k}(-1)^k\frac{e^{\mu t(j-l-k-1)}}{\mu (j-l-k)}+C.
\end{align*}


text:
Q: Defining a 'style' initializer for a custom UIView I am re-using a UIView subclass in a few places, but need the layout to be slightly different on occasion - sometimes the subviews are laid out horizontally and sometimes vertically.
I would like to somehow replicate the 'initWithStyle' approach that UITableView and other UIViews employ. It should be possible to 'initWithStyle' but there should be a default also. It should also be possible to change the style using setStyle.
What are the steps to achieve this? I tried defining an enum and a new initializer, but I am out of my depth here.

A: Sounds like you're on the right track, so I'm not sure how helpful I can be.  Create your public initializers and public setStyle methods.  Sorry for any typos.  I'm doing this without an editor.
.h
-(id)initWithFrame:(CGRect)frame;
-(id)initWithFrame:(CGRect)frame style:(MyStyleEnum)myStyleEnum;
-(void)setStyle:(MyStyleEnum)myStyleEnum;

.m
 //here's your default method which passes your default style to your custom init method
-(id)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame style:myStyleEnumDefault];
}

//your custom init method that takes a style
-(id)initWithFrame:(CGRect)frame style:(MyStyleEnum)myStyleEnum {
    self = [super initWithFrame:frame];

    if(self) {
        [self setStyle:myStyleEnum];
    }

    return self;
}

//this can be called after initialization
-(void)setStyle:(MyStyleEnum)myStyleEnum {
    //make sure the view is clear before you layout the subviews
    //[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];//not needed adjusting constraints and not repopulating the view

    //change the view constraints to match the style passed in
    //the acutally changing, should probably be done in separate methods (personal preference)
    if(myStyleEnum == myStyleEnumDefault) {
       //change constraints to be the default constraints
    } else if(myStyleEnum == myStyleEnumA) {
        //change constraints to be the A constraints
    } else if(myStyleEnum == myStyleEnumB) {
         //change constraints to be the B constraints
    }

}


text:
Q: Replace eregi_replace preg_replace
Possible Duplicate:
Converting ereg expressions to preg

How do I convert this function with this parameters
eregi_replace("[][,.?&\"#{(_\\@)\=+\,\?.;/:!%*()|}]+", "", $data);
to preg_replace?

A: Your answer:
    preg_replace('/[][,.?&\"#{(_\@)\=+\,\?.;/:!%*()|}]+/', "", $data)
And please, pre_replace for more simples questions, in these places not everyone is as benevolent as me, probably you would have no answer, search before asking for asking


text:
Q: Is there any notation for general $n$-th root $r$ such that $r^n=x$? As we know that the notation for the $n$-th principal root is $\sqrt[n]{x}$ or $x^{1/n}$. But the principal root is not always the only possible root, e.g. for even $n$ and positive $x$ the principal root is always positive but there is also another negative root. E.g. consider $r^2=4$, then $\sqrt 4 =+2$, but $r=-2$ is also a valid solution. Since $x$ is a function of $r$ for some given $n$, so let
$$r^n=x=f(r).$$
We have $r=f^{-1} (x)$. Here $r \neq \sqrt[n]x$ because $\sqrt[n]x$ is the principal root not the general. So is there any notation like $\sqrt[n]{\phantom{aa}}$ for the general $n$-th root of the equation $r^n=x$?

A: I'd say:
$$r=z^{\frac{1}{n}}e^{\frac{2i\pi k}{n}}$$
It is a multivalued function with $k=0,\dots,n-1$

A: In complex analysis, $\sqrt[n]{x}$ is regarded as a multivalued function. Or you can write it as $$\sqrt[n]{x}=\exp{\frac{\operatorname{Log}(x)}{n}},\space x\ne0.$$
$\operatorname{Log}(x)$ is the inverse function of $\exp(x)$, see here.

A: For a non-negative real number $x$ there is always a unique choice of non-negative real $n$-th root, which is usually denoted by $\sqrt[n]{x}$. Furthermore, if $x$ is negative there is a unique choice of $n$-th root if $n$ is odd and none if $n$ is even.
In short, if $x \geq 0$ is real and $n$ is even, then the only real $n$-th roots of $x$ are $\pm \sqrt[n]{x}$ (and you can use this symbol), while if $x$ is real and $n$ is odd there is only one $n$-th root of $x$, denoted $\sqrt[n]{x}$.

You should understand, though, that taking roots usually involves a choice. In particular, every non-zero complex number has exactly $n$ $n$-th roots.
Now, you could keep the above choices for real numbers, but in general there is no canonical choice of root1. What we usually say instead is something like: "let $w$ be an $n$-th root of $z$". The nice thing, though, is that the other roots are then easily recoverable, because they are all of the form
$$
\zeta_n^i w \qquad \text{for } i \in \{0,\dotsc,n-1\}
$$
where $\zeta_n$ is a primitive $n$-th root of unity, i.e. a complex number such that $\zeta_n^n = 1$ and $\zeta_n^m \neq 1$ for every $0 < m < n$. Again, a choice is involved here, but you can always take
$$
\zeta_n = e^{2\pi i/n}
$$
TL;DR: If you wish to denote the generic $n$-th root of a complex number $z$ you may probably get away with the notation $z^{1/n}$. Just bear in mind that in general this is inherently ambiguous and you should treat this symbol more like a place-holder for an actual $n$-th root of $z$ than as a number.
[1] Technically, one could still define a unique choice of $n$-th root e.g. by taking the root with least argument (in $[0,2\pi)$). While this convention (or a similar one) may be used in analysis, I've never seen it in algebra or number theory.

A: $$z^n=c\implies z=\omega^k\sqrt[n]c$$
Where $\omega$ is a primitive $n^{th}$ root of unity, and $0\le k\in\Bbb{Z}\le n-1$

A: There is no privileged or standardized notation. It is a matter of definition, which is dependent on what is convenient for you. Sometimes you want to have a function that outputs an $n$-th root of the input, in which case you would define:

$a^b = \exp(b\ln_π(a))$ where $\ln_π$ is the principal branch of the natural logarithm.

This gives a well-defined function for any complex $a,b$ such that $\arg(a) \ne π$ (or equivalently $a$ is not on the non-positive real line). This function is differentiable everywhere in its domain, which is why it is often used. It is also continuous if a point on the negative real line is approached from the upper half-plane, and it coincides with the usual definition of exponentiation for positive real base and real exponent. Note that it does not coincide with the definition of exponentiation for negative real base and fractional real exponent. $(-8)^{\frac{1}{3}}$ is $(-2)$ in the 'real' world but is $(-2) \exp(\frac{2πi}{3})$ in the 'complex' world.
At other times we do not need a function that outputs a complex number but rather we work with sets of complex numbers. In that case we can define (for sets of complex numbers $a,b$:

$a^b = \exp(b\ln(a))$ where $ab = \{ zw : z \in a \land w \in b \}$ and $\exp(a) = \{ \exp(z) : z \in a \}$ and $\ln(a) = \{ z : \exp(z) \in a \}$.

If everything is suitably redefined to handle sets of complex numbers, we will get that this function is differentiable 'everywhere' except at $a = 0$. Not only that, some usual rules of real exponentiation hold. For example, $a^b a^c = a^{b+c}$ for any complex $a,b,c$ such that $a \ne 0$, and $a^c b^c = (ab)^c$ for any complex $a,b,c$ such that $ab \ne 0$. Some other rules still do not hold, such as $(\{3\}^{\{2\}})^{\{\frac{1}{2}\}} = \{3,-3\}$.


text:
Q: TerminateProcess and deadlocks Is it real that the TerminateProcess function in Windows could hang because the threads inside the process were stuck in a deadlock?
Example: Process A is running under Process B's control, now Process A gets into a deadlock and Process B detects this and decides to 'Kill' process A using TerminateProcess.
Would it be successful in killing the hung Process A?

A: Yes, all kernel objects held by the process will be released, including locks.
The main problem with TerminateProcess is that the process has no say in the matter: if it's holding on to any global state (files, shared memory, etc) then you have no guarantee those things are in a consistent state after the process is terminated.

A: Yes. So long as you have the right permissions, TerminateProcess will kill the other process dead, regardless of how well hung it is.

A: TerminateProcess will kill each thread (as if TerminateThread had been used on each and every thread in the process).
But it won't kill threads that are stuck in the kernel (e.g. due to device driver bug).


text:
Q: Can I use a Windows -> Class Library inside a WP7 application? I'm creating a library application that will act as a wrapper for an exposed API. This library ideally should work on any desktop application, but truth be told I'm intending to use this on the WP7 once I'm done creating the library.
Would this work?

A: From silverlight.net:

Silverlight is the application development platform for Windows Phone 7. High performance gaming is also supported through the XNA Framework.

You can't reference a .NET assembly which was compiled against the full .NET Framework in a Silverlight application.
Develop your library for Silverlight and all should be fine.


text:
Q: How to add a log into email merge from excel to outlook I'm using the folowing code to send out surveys to my customers. Now I'm looking for a way to add in the email my company's logo, however I'm not sure on how to change the code in order to achieve this.
would be possible to get your support on this question?
Thank you.
Marcelo
Sub mailmerge1()
 Application.ScreenUpdating = False
 Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Dim table1 As ListObject
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With
    Set table1 = ActiveWorkbook.ActiveSheet.ListObjects("Table1")
    Set rng = Nothing
    Set rng = ActiveSheet.Range("K2:M17")
    ' You can also use a sheet name here.
    'Set rng = Sheets("YourSheet").UsedRange

    For i = 1 To table1.ListRows.Count

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    Range("J2") = i
    On Error Resume Next
    With OutMail
        .SentOnBehalfOfName = "tsc@volvo.com"
        .To = Range("J5")
        .BCC = ""
        .Subject = "Let us know what you think"
        .HTMLBody = RangetoHTML(rng)
        '.Display
            ' In place of the following statement, you can use ".Display" to
            ' display the e-mail message.
        .send

    End With

    Next i
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing

 Application.ScreenUpdating = True
 End Sub

A: Example
    With OutMail
        .SentOnBehalfOfName = "tsc@volvo.com"
        .To = Range("J5")
        .BCC = ""
        .Subject = "Let us know what you think"
        .Attachments.Add "C:\Users\0m3r\Pictures\Hello.png", olByValue, 0
        .HTMLBody = RangetoHTML(rng) & vbCrLf & _
            "<BODY><IMG src=""cid:Hello.png"" width=200> </BODY>"
        .Display
            ' In place of the following statement, you can use ".Display" to
            ' display the e-mail message.
'        .Send

    End With

Make sure not to use spaces on your logo file name-