text:
Q: Why does my WCF Data Service fail to start the second time I run it? I created an ASP.NET app containing a WCF Data Service using Visual Studio 2015, based on the AdventureWorks2014 OLTP, by following this walkthrough.
When I build the app and run it in a debugger (on IIS Express), the service loads fine and I see the XML metadata displayed in my browser, and can make further requests to subpaths to view the rows of my database. I can continue to make such requests as long as the debugging session continues.
As soon as I stop the debugger and start it again, without a rebuild in between, my browser instead displays an error:

The type 'AdventureWorks.Internal.WebService.DataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.

[InvalidOperationException: The type 'AdventureWorks.Internal.WebService.DataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.]
   System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +741
   System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1417
   System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +53
   System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +660

[ServiceActivationException: The service '/DataService.svc' cannot be activated due to an exception during compilation.  The exception message is: The type 'AdventureWorks.Internal.WebService.DataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found..]
   System.Runtime.AsyncResult.End(IAsyncResult result) +386
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +174
   System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +7
   System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129

This happens when I develop either in Visual Studio 2015 or 2017.
I'm using Windows 10 with my ASP.NET app targeting .NET Framework 4.6.1.
DataService.svc:
<%@ ServiceHost Language="C#" Factory="System.ServiceModel.Activation.WebServiceHostFactory, System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Service="AdventureWorks.Internal.WebService.DataService" %>

DataService.svc.cs:
namespace AdventureWorks.Internal.WebService
{
    //[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class DataService : DataService<AdventureWorksDatabaseEntities>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
        }
    }
}

Web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  </system.webServer>
  <connectionStrings>
    <add name="AdventureWorksDatabaseEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\AdventureWorksDatabase.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v13.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
</configuration>

A: This error occurs due to namespace inconsistencies. please check all the namespaces. it should work.


text:
Q: How to get access to Google Androidpublisher API using JWT? So there is a way to authorize on Google API services using JWT tokens described here: Service account authorization without OAuth.
I've tried to follow this instruction:
1. Create a service account. Be sure to keep the JSON file you get when you create the account.
Done.
2. Get the API's service name and API name from the service definition file on GitHub.
I went to Google APIs GitHub repository and started searching. I need to get access to Androidpublisher API. So, at first i've tried to examine the folders structure and underestand where the required API is. No luck. Then i've tried to search the whole repo for *.yaml files by keywords "androidpublisher" and "android". No luck again. I've actually found something by keyword "publisher": it was pubsub API, but it seems that it's not what i'm looking for.
Ok let's read that again:
If the API you want to call has a service definition published in the Google APIs GitHub repository, you can make authorized API calls using a JWT instead of an access token.
So basically it means that any API may or may not be published there.
In this SO question i've found a way to authorize for Androidpublisher API using JSON file with credentials and Java client library for Google Play Developer API:
private static Credential authorizeWithServiceAccount() throws IOException {
    log.info("Authorizing using Service Account");
    try (FileInputStream fileInputStream = new FileInputStream(JSON_PATH)) {
        return GoogleCredential.fromStream(fileInputStream, HTTP_TRANSPORT, JSON_FACTORY)
                .createScoped(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER));
    }
}

So i assume that there is a way to authorize there using JWT tokens. But i can't use Java library, because my service will run on C++. And unfortunately Google didn't provide a library for C++ developers.
At one point i was so desperate that i've even tried to compile this code on Java and run it just to see WHERE it is sending its HTTP requests to (using debugger or Wireshark). But i'm not a Java developer and after a hour of resolving a dependencies issues i've still had some problems with "missing Java Key Store" (or something like that) while running the code. So i gave up.
So my final question is: what are the Service name and API name for Androidpublisher API?
I should have been able to retrieve those values in the second step of this instruction. But i failed. I feel like that is the only piece of information i'm missing right now to complete my task.

A: I found a way to access Adndoidpublisher API without following step:
2. Get the API's service name and API name from the service definition file on GitHub.
I can create a JWT token and then use it to obtain an API access token. The way of doing this is described here in HTTP/REST tab.
Then i can just access the API in the ordinary way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert article with titles in Excel to table of titles Let's say I have raw text in this structure:
:subtitle1; texttext text ;subtitle2; text text ;subtitleN; text text text
and I want to create table where column names are "subtitleX" and column values 'text text' - after ;


text:
Q: Multiplying matrices in c using pointers When I input both the matrices, the resultant matrix doesn't show the proper answer, is my algorithm wrong or I am not supposed to use pointers in that way?
 Please help!
main() {

    int a[3][3],b[3][3],c[3][3],*p[3],*q[3],*r[3],j1=0;

    // 1st Matrix

    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            scanf("%d",&a[i][j]);
        }
    }

    // 2nd matrix

    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            scanf("%d",&b[i][j]);
        }
    }

    // Assigning pointers

    for(int i=0;i<3;i++) p[i]=&a[i][0];
    for(int i=0;i<3;i++) q[i]=&b[i][0];
    for(int i=0;i<3;i++) r[i]=&c[i][0];

    // Resultant Matrix

    for(int i=0;i<3;i++){
        *(*(r+i)+j1) = 0;
        for(j1=0;j1<3;j1++){
            printf("%d\t",*(*(r+i)+j1));
             *(*(r+i)+j1) += *(*(p+i)+j1) * *(*(q+j1)+i);
        }
        j1 = 0;
    }

    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            printf("%d\t",c[i][j]);
        }
        printf("\n");
    }
}

A: Your loops iterate through two dimensions and perform an element-wise multiplication of the arrays a and b with b transposed. I suspect you want to perform a matrix multiplication rather than an element-wise multiplication. To do that, you need three loops:

*

*Two loops iterate indices i and j through the rows and columns of c.

*One loop iterates some variable, say k, through the common dimension of a and b and sums the products of a[i][k] with b[k][j].


text:
Q: getting funtion undefined on Renderer.js in Aura component I am working on to fetch records on a scroll in custom lookup lightning component, But getting the following error on doSearch function, But function is present in helper.js file, Please suggest any advice
rendrer.js
({
  afterRender: function(component, event, helper) {
    this.superAfterRender();

    var didScroll = false;
    var elem = document.getElementById("lookuplist-items");
    elem.addEventListener("scroll", function() {
      didScroll = true;
    });

    var scrollCheckIntervalId = setInterval(
      $A.getCallback(function() {
        if (didScroll && component.isValid()) {
          didScroll = false;
          console.log("scroll", elem);
          if (elem.scrollTop + elem.offsetHeight + 10 >= elem.scrollHeight) {
            console.log(
              "ttt",
              elem.scrollTop,
              elem.offsetHeight,
              elem.scrollHeight
            );
            // component.set(component.get("v.noOfRecords") + 5);
            helper.doSearch(component, event, 10);
          }
        }
      }),
      1000
    );

    component.set("v.scrollCheckIntervalId", scrollCheckIntervalId);
  },

  unrender: function(component, helper) {
    this.superUnrender();

    var scrollCheckIntervalId = component.get("v.scrollCheckIntervalId");

    if (!$A.util.isUndefinedOrNull(scrollCheckIntervalId)) {
      window.clearInterval(scrollCheckIntervalId);
    }
  }
});

Helper.js
 doSearch: function(cmp, event, limit) {
    console.log("inside");
    if (limit) cmp.set("v.noOfRecords", limit);
    debugger;
    // Get the search string, input element and the selection container
    var searchString = cmp.get("v.searchString");
    var inputElement = cmp.find("lookup");
    var lookupList = cmp.find("lookuplist");
    var lookupListItems = cmp.find("lookuplist-items");
    var lookupDiv = cmp.find("lookup-div");
    var strLabel = cmp.get("v.label");
    var enhancedDiv = cmp.find("enhancedDiv");

A: According to the documentation, the parameters are:
afterRender: function(component, helper) {

Unlike controller  methods, there is no event parameter. Remove this parameter from your function signature, and it should work.


text: Q: TI SensorTag CC2650 | Data Logging when offline I'm new to using the TI SensorTag CS2650. I'm required to data log when the bluetooth is offline. I believe I can do so by modifying the firmware and using the flash ROM on board, however not so sure on how to implement it. Any help would be of great assistance.


text:
Q: Is there a difference between using export default vs. export default DefineComponent in Vue 3 with Typescript? I'm creating some basic Vue 3 components and I noticed that most of the time I can use either
export default {
  ...
};

or
export default defineComponent({
  ...
});

On the Vue 3 documentation, I see that with Define Component you can define types within the constructor.
If I'm making a very basic component with no need for types like this, is there any difference between using export default vs defineComponent? Which one is preferred?

A: Yes.
TS won't allow you to use this type without defineComponent or any or harder things
export let a = {
  data: () => ({ a: 1 }),
  methods: {
    x() {
      this.a
      // ^! Property 'a' does not exist on type '{ x(): void; }'.(2339)
    },
    y(this: { a: number }) {
      this.a // this works
    }
  }
}

In JS almost no, defineComponent is a no-op (e => e)


text:
Q: MVC passing ID from view to a controller If I have the following on the view
@Html.DisplayFor(model => model.sLevelid)

Controller
Public actionresult GetName(int id)
{

}

How can I pass the id to a controller so I can create a linq query to get the name the id belongs to on a separate table in the database?
thanks in advance

A: Something like this in your view:
// GetName here refers to the name of the action on your controller
@{ Html.RenderAction("GetName", new { id = @Model.sLevelid }); }

Then your controller action would look like this:
public PartialViewResult GetName(int id)
{
    var model = // Use Linq to get whatever you need by the id

    return PartialView("_GetName", model);
}

You'd then create a partial view in your ~/Views/Shared/ folder, giving it the name _GetName.cshtml.  That view would then look something like this:
@model TheTypeOfModelGetNameReturns

<div>@Model.SomeProperty</div>

A: I believe it will work if you use the name "sLevelid" in the Controller method signature:
Public actionresult GetName(int sLevelid)

Then you can use this id to find the object with a linq query. This works because the name in the form post matches the name of the int in the signature, so the framework automatically binds it to the int variable.
Also, check that the View is called "GetName.cshtml", as it has to match the name of the method, under normal circumstances.


text:
Q: com.google.firebase.database.DatabaseException: Class java.lang.Class has generic type parameters, please use GenericTypeIndicator instead I am using firebase for my android app, and whenever I try to convert dataSnapshot to object I get the following error:
com.google.firebase.database.DatabaseException: Class java.lang.Class has generic type parameters, please use GenericTypeIndicator instead

Here is my class:
class DatabaseApi<T> {

    suspend fun getData(path: String): DatabaseResult<Class<T>?> {
        val databaseResult = DatabaseHelper().get(path)

        return try {
            convertDatabaseSnapshot(databaseResult.value)
        } catch (e: Exception) {
            DatabaseResult.failed(e.toString())
        }
    }

    fun <T> convert(cls: Class<T>, snapShot: DataSnapshot): DatabaseResult<T?> {
        return try {

            val data = snapShot.getValue(cls)
            DatabaseResult.success(data)
        } catch (e: Exception) {
            val message = e.message ?: ""
            DatabaseResult.failed(message)
        }
    }

    inline fun <reified T> convertDatabaseSnapshot(snapShot: DataSnapshot): DatabaseResult<T?> {
        return convert(T::class.java, snapShot)
    }
}

And this is the code where I am getting the error:
val data = snapShot.getValue(cls)


text:
Q: what is the derivative of this function I need help in this following question. I have tried many attempts but really confused on how to solve it. Therefore, i would appreciate any help from you guys. Thanks allot
$$f(x) = \dfrac{\ln x}{e^{x^2 + 2}}$$

A: $$f(x) = \dfrac{\ln x}{e^{x^2 + 2}}$$
We use the quotient rule: $$f(x) = \dfrac {g(x)}{h(x)} \implies f'(x) = \dfrac{g'(x)h(x) - g(x)h'(x)}{(h(x))^2}$$
Here, $$g(x) = \ln x \implies g'(x) = \dfrac 1x$$ $$h(x) = e^{x^2 + 2} \implies h'(x) = 2x\cdot e^{x^2 + 2}$$
Note we need the chain rule for finding $h'(x)$.
Can you take it from here? You'll be able to simplify once you "plug into" the formula given by the quotient rule.

 $$\dfrac{\frac 1x \cdot e^{x^2 + 2} - \ln x(2xe^{x^2+ 2})}{(e^{x^2 + 2})^2} = \dfrac{e^{x^2 + 2}\Big(\frac 1x - 2x\ln x\Big)}{e^{2(x^2 + 2)}} = \dfrac{1- 2x^2 \ln x}{xe^{x^2 + 2}}$$

A: Hint: Rewrite the function as:
$$f(x) = \ln x e^{-x^2-2}$$
Now, use the product rule to find the result.
$$\dfrac{d}{dx} ( uv) = v \dfrac{du}{dx} + u \dfrac{dv}{dx}$$
Spoiler

 f'(x) = $-2e^{-x^2-2}~x~\ln x + \dfrac{e^{-x^2-2}}{x}$

Of course, you could have also just used the quotient and should give that a go!

A: another occasionally useful device is to rewrite as:
$$(e^{x^2 + 2})f(x) = ln \;x$$ and use the product rule on the LHS to get:
$$(2xe^{x^2+2})f(x) + (e^{x^2 + 2})f'(x) = \frac 1x
$$ so
$$ f'(x) = (\frac1x -2x \;ln \;x)(e^{x^2 + 2})^{-1}
$$


text:
Q: Program doesnt continue after long time foreach in worker role I have C# worker-role which downloading files encoding them and uploading to FTP , due to field of files I have in XAML file which define workrole foreach loop.
After all files are downloaded,encoded and upload I have there code activity which sends me email.
My problem is that when I run this workrole and there are for example 10 files each 1,5 GB huge the foreach loop takes about 2 days to complete then the email activity doesnt hit and workrole ends in froeach loop but when i run it witth 10 files each 10 Mb huge the email activity is hitted and processed what could it be ?
<Foreach loop..../>
    <Sequence sap:VirtualizedContainerService.HintSize="586,146">
      <sap:WorkflowViewStateService.ViewState>
        <scg3:Dictionary x:TypeArguments="x:String, x:Object">
          <x:Boolean x:Key="IsExpanded">True</x:Boolean>
        </scg3:Dictionary>
      </sap:WorkflowViewStateService.ViewState>
      <local1:FeedbackEmail sap:VirtualizedContainerService.HintSize="200,22" IngestFTPConfig="IngestFTPConfig] />
</Sequence>


text:
Q: Select statement throwing null exception Getting a mysterious null exception in second Select statement.
public static string GetSNFromDeviceMacAddress(string macAddress)
{
    string commzSerialNumber = null;
    var dbFactory = EndpointHost.AppHost.TryResolve<IDbConnectionFactory>();
    try
    {
        OrmDataLib.Device device;
        OrmDataLib.Commz commz;
        using (var db = dbFactory.OpenDbConnection())
        {
            // first select works fine
            device = db
                .Select<OrmDataLib.Device>(q => q.MacAddress == macAddress)
                .FirstOrDefault();
            if (null != device)
            {
                // mysterious null exception
                commz = db
                    .Select<OrmDataLib.Commz>(c => c.Id == device.Commz_Id)
                    .FirstOrDefault();
                if (null != commz)
                    commzSerialNumber = commz.SerialNumber;
            }
        }
    }
    catch { }
    return commzSerialNumber;
}

A: Turns out the receiving DTO was supposed to permit a null value and wasn't.
The property,
Commz.Site_id was declared:
public int Site_id { get; set; }

And should have been declared as:
public int? Site_id { get; set; }


text:
Q: struct outputs are being overwritten by last user input Im a beginner to C and I'm having trouble with structs.
after I've asked user for all attributes, id like to print all the values of the struct. The problem is that after I've got input all the attributes to a struct and it loops back again to ask for attributes a second time, the first struct input gets replaced by the second struct input.
I'm pretty sure that I'm allocating the same memory space over and over and thus causing the problem but I'm stuck on how to fix it. Id appreciate any advice on what i can do. thanks!
                    case 2:
                        printf ("Please input a SKU number:");
                            scanf ("%d", &item[MAX_ITEMS].sku_);
                        printf ("Quantity:");
                            scanf ("%d", &item[MAX_ITEMS].quantity_);
                        printf ("Price:");
                            scanf ("%f", &item[MAX_ITEMS].price_);
                        printf ("The item is successfully added to the inventory");
                    break;

to print out the sku, quantity and price
                switch (menuSelection) {
                    case 1:
                        printf ("Inventory\n");
                        printf ("=========================================\n");
                        printf ("Sku         Price       Quantity\n");

                                for (i =0 ; i<=MAX_ITEMS; i++){
                                printf ("%d %.2f %d\n", item[i].sku_, item[i].price_, item[i].quantity_);
                                }

                        printf ("=========================================\n");
                    break;

here is my whole code:
#include <stdio.h>
#define MAX_ITEMS 10

struct Item{
    int sku_;
    float price_;
    int quantity_;
}item[MAX_ITEMS];

int main (void) {

int size=0;
int menuSelection;
int i=0;

    printf ("Welcome to the Shop\n");
    printf ("===================");

    do {
    printf ("\nPlease Select from the following options:\n");
    printf ("1) Display the inventory.\n");
    printf ("2) Add to shop.\n");
    printf ("0) Exit.\n");

    printf ("select:");
    scanf ("%d", &menuSelection);

            if (menuSelection <0 && menuSelection >2){
              printf ("Invalid input, try again: Please select from the following options:");
            }

            else {

                switch (menuSelection) {
                    case 1:
                        printf ("Inventory\n");
                        printf ("=========================================\n");
                        printf ("Sku         Price       Quantity\n");

                                for (i =0 ; i<=MAX_ITEMS; i++){
                                printf ("%d %.2f %d\n", item[i].sku_, item[i].price_, item[i].quantity_);
                                }

                        printf ("=========================================\n");
                    break;

                    case 2:
                        printf ("Please input a SKU number:");
                            scanf ("%d", &item[size].sku_);
                        printf ("Quantity:");
                            scanf ("%d", &item[size].quantity_);
                        printf ("Price:");
                            scanf ("%f", &item[size].price_);
                        printf ("The item is successfully added to the inventory");
                    break;

                    case 3:
                    break;
                }

            }

    } while (menuSelection != 0);

return 0;
}

A: You create an array of Item objects with the length of MAX_ITEMS, currently being 10. That is, your objects have the indices of 0 to 9. Yet when asking the user for input, you always store the data at item[MAX_ITEMS] which is out of bounds of your array.
As a side note, when printing your array, you always print it whole, meaning also uninitialised items.
You have to store how many items are already "added to the shop" and use this number to determine the next array index where user input has to be stored. When printing you only have to iterate over the items already stored. Don't forget bounds checking, e.g. don't allow new user input when your shop is full.

A: The problem is that you always save the new values in the same place:
item[MAX_ITEMS].sku_

Instead, you should have a counter that show how many items are stored and save the new values in the place that is equal to the counter:
item[counter].sku_

and after every insertion you should increase the counter:
counter++;

So, your code should look like this:
int counter=0;
...
case 2:
    printf ("Please input a SKU number:");
    scanf ("%d", &item[counter].sku_);
    printf ("Quantity:");
    scanf ("%d", &item[counter].quantity_);
    printf ("Price:");
    scanf ("%f", &item[counter].price_);
    printf ("The item is successfully added to the inventory");
    counter++;
break;

I hope I was helpful

A: The item you defined is a array with size of MAX_ITEMS, so the problem of you is not about struct but array.
In most of computer programming language, indexing an array should use a offset start on zero. That is, MAX_ITEMS of item[MAX_ITEMS] is out of range for the array, you got a bug and do not find it. When you adding a item to your shop, you should code like this:
case 2:
  if (last < MAX_ITEMS - 1)
  {
    printf ("Please input a SKU number:");
    scanf ("%d", &item[last].sku_);
    // ...
    last ++; // on success
  }
  else
  {
    print("oops, shop is full.");
  }


text:
Q: ajax + servlet country state city list I am trying to populate city, country and statelist using ajax, and servlets.
Now I know how to get the XMLhttpRequest object. There is a standard mechanism to do that and depending on the cross browser compatibility, you do get a ActiveX or a xml object..
Then you send a request to the actionservlet, using xmlhttprequest.open() and you send the request and you have an event handler function to take care of onreadystatechange issue, Now, when it comes to receiving the response, I get an error stating that the response is not completely received, i.e the status != 4... now.
I was wondering, how does the entire mechanism work..
how to put the parameters in the request, send it to servlet, and then I know how to retreieve the param from the URL.. but then how to send a valid response...??
I am confused on the ajax part, because I am not using / not use PHP. It is harder to think. Please suggest what should be done.
Is there any easier way to populate a city, country and state list??

A: Just let the servlet return the desired dropdown options in the desired format based on the request parameters in the doGet() method. Here's an example which returns it in JSON format with help of Google Gson:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String type = request.getParameter("type"); // Returns "country" or "state".
    String value = request.getParameter("value"); // Value of selected country or state.
    Map<String, String> options = optionDAO.find(type, id); // Do your thing to obtain them from DB. Map key is option value and map value is option label.
    String json = new Gson().toJson(options); // Convert Java object to JSON string.

    response.setContentType("application/json"); // Inform client that you're returning JSON.
    response.setCharacterEncoding("UTF-8"); // Important if you want world domination.
    response.getWriter().write(json); // Write JSON string to response.
}

Assuming that the above servlet is mapped on an url-pattern of /options, you could use it as in the following JSP example with help of jQuery. I am recommending jQuery because you would otherwise end up with 10 times as much JavaScript code needed for this "simple" task.
<%@ page pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 3983929</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('#country').change(function() { fillOptions('state'); });
                $('#state').change(function() { fillOptions('city'); });
            });
            function fillOptions(dropdownId) {
                var dropdown = $('#' + dropdownId);
                $.getJSON('options?type=' + dropdownId + '&value=' + $(this).val(), function(opts) {
                    $('>option', dropdown).remove(); // Clean old options first.
                    if (opts) {
                        $.each(opts, function(key, value) {
                            dropdown.append($('<option/>').val(key).text(value));
                        });
                    } else {
                        dropdown.append($('<option/>').text('Please select ' + dropdownId));
                    }
                });
            }
        </script>
    </head>
    <body>
        <form>
            <select id="country" name="country">
                <c:forEach items="${countries}" var="country">
                    <option value="${country.key}" ${param.country == option.key ? 'selected' : ''}>${country.value}</option>
                </c:forEach>
            </select>
            <select id="state" name="state">
                <option>Please select country</option>
            </select>
            <select id="city" name="city">
                <option>Please select state</option>
            </select>
        </form>
    </body>
</html>

Here I am assuming that you've already prepopulated the ${countries} as being a Map<String, String> in a servlet which has preprocessed the request to this JSP for the initial display.


text:
Q: No puedo adicionar las foreign key de la tabla usuario Antes de la tabla usuario cree las tablas correspondientes para agregar las foraneas
    create table acreditacion(idacre int not null auto_increment,
                     nomacre varchar(50) not null,
                     primary key(idacre)) ENGINE = InnoDB;

    -- 2. creando tabla coordinacion

    create table coordinacion(idcoord int not null auto_increment,
                     nomcoord varchar(50) not null,
                     ubicacion varchar(20) not null,
                     primary key(idcoord)) ENGINE = InnoDB;

    -- 3. creando titulo_universitario

    create table titulo_universitario(idtitulo int not null auto_increment,
                             nomtitulo varchar(20) not null,
                             primary key(idtitulo)) ENGINE = InnoDB;

    -- 4. creando tabla perfil

    create table perfil(nroperfil int not null auto_increment,
               nomperfil varchar(15) not null,
               primary key(nroperfil)) ENGINE = InnoDB;

    -- 5. creando tabla dedicacion

    create table dedicacion(iddedicacion int not null auto_increment,
                   nomdedicacion varchar(20) not null,
                   primary key(iddedicacion)) ENGINE = InnoDB;

    -- 6. creando tabla programa

    create table programa(idprograma int not null auto_increment,
                 tipoprograma varchar(5) not null,
                 nomprograma varchar(100) not null,
                 primary key(idprograma)) ENGINE = InnoDB;

    -- 7. creando tabla cargo

   create table cargo(idcargo int not null auto_increment,
              nomcargo varchar(20) not null,
              primary key(idcargo)) ENGINE = InnoDB;

    -- 8. creando tabla proyecto

   create table proyecto(idproyecto int not null auto_increment,
                 nomproyecto text not null,
                 resumen varchar(200) null,
                 idacre int null,
                 primary key(idproyecto),
                 foreign key(idacre) references acreditacion(idacre)) ENGINE = InnoDB;

   -- 9. creando tabla nucleo_academico

   create table nucleo_academico(idnucleo int not null auto_increment,
                         nomnucleo varchar(150) not null,
                         idcoord int not null,
                         primary key(idnucleo),
                         foreign key(idcoord) references coordinacion(idcoord)) ENGINE = InnoDB;

Hasta aqui todo me va bien ahora cuando intento crear la tabla usuario que es la siguiente:
   -- 10. creando tabla de usuario

   create table usuario(ci int not null,
                prnombre varchar(20) not null,
                segnombre varchar(20) null,
                prapellido varchar(20) not null,
                segapellido varchar(20) null,
                sexo char not null,
                fecnac date not null,
                rolobservacion varchar(100) not null,
                fechaing date not null,
                fecha_ult_ascenso date not null,
                tipo char not null,
                correo varchar(150) not null,
                contraseña varbinary(20) not null,
                pregunta text not null,
                respuesta varchar(200) not null,
                telefono varchar(15) not null,
                tipo_est varchar(50) not null,
                idcoord int not null,
                nroperfil int not null,
                iddedicacion int not null,
                idprograma int not null,
                idcargo int not null,
                ciasesor int null,
                primary key(ci),
                foreign key(idcoord) references coordinacioncepec(idcoord),
                foreign key(nroperfil) references perfil(nroperfil),
                foreign key(iddedicacion) references dedicacion(iddedicacion),
                foreign key (idprograma) references programa(idprograma),
                foreign key(idcargo) references cargo(idcargo)) ENGINE = InnoDB;

He revisado el codigo y creo no tener errores de sintaxis, gracias por su atencion, feliz dia !

A: en la parte de código intente cambiar
            idcoord int not null,
            nroperfil int not null,
            iddedicacion int not null,
            idprograma int not null,
            idcargo int not null,
            ciasesor int null,

por el siguiente si le funciona,
            idcoord int(11) not null,
            nroperfil int(11) not null,
            iddedicacion int(11) not null,
            idprograma int(11) not null,
            idcargo int(11) not null,
            ciasesor int(11) null,

la otra seria utilizar el alter table
            alter table "nombre table "add
            foreign key(idcoord) references coordinacioncepec(idcoord),
            foreign key(nroperfil) references perfil(nroperfil),
            foreign key(iddedicacion) references dedicacion(iddedicacion),
            foreign key (idprograma) references programa(idprograma),
            foreign key(idcargo) references cargo(idcargo)

A: al margen de que cuando declaras una llave foránea debes usar la sentencia completa de CONSTRAINT mas el nombre de la unión de tablas como podrás observar en el código.
Tambien te equivocaste en el nombre de la tabla de coordinacion, en la creación de la tabla solo pones coordinacion y en las llaves foráneas pones coordinacioncepec, el nombre debe ser el mismo puesto que estas vinculando esa llave foránea a una tabla que ya existe
Idealmente cuando declares una llave primaria también no olvides el atributo de AUTO_INCREMENT
Aquí te pongo el código ya funcional puesya crea las tablas en general
CREATE DATABASE demo;

USE demo;

create table acreditacion(
idacre int not null auto_increment,
nomacre varchar(50) not null,
primary key(idacre))ENGINE = InnoDB;

    -- 2. creando tabla coordinacion

create table coordinacion
(idcoord int not null auto_increment,
nomcoord varchar(50) not null,
ubicacion varchar(20) not null,
primary key(idcoord)) ENGINE = InnoDB;

    -- 3. creando titulo_universitario

create table titulo_universitario
(idtitulo int not null auto_increment,
nomtitulo varchar(20) not null,
primary key(idtitulo)) ENGINE = InnoDB;

    -- 4. creando tabla perfil

create table perfil(nroperfil int not null auto_increment,
               nomperfil varchar(15) not null,
               primary key(nroperfil)) ENGINE = InnoDB;

    -- 5. creando tabla dedicacion

    create table dedicacion(iddedicacion int not null auto_increment,
                   nomdedicacion varchar(20) not null,
                   primary key(iddedicacion)) ENGINE = InnoDB;

    -- 6. creando tabla programa

    create table programa(idprograma int not null auto_increment,
                 tipoprograma varchar(5) not null,
                 nomprograma varchar(100) not null,
                 primary key(idprograma)) ENGINE = InnoDB;

    -- 7. creando tabla cargo

   create table cargo(idcargo int not null auto_increment,
              nomcargo varchar(20) not null,
              primary key(idcargo)) ENGINE = InnoDB;

    -- 8. creando tabla proyecto

   create table proyecto(idproyecto int not null auto_increment,
                 nomproyecto text not null,
                 resumen varchar(200) null,
                 idacre int null,
                 primary key(idproyecto),
                 foreign key(idacre) references acreditacion(idacre)) ENGINE = InnoDB;

   -- 9. creando tabla nucleo_academico

   create table nucleo_academico(idnucleo int not null auto_increment,
                         nomnucleo varchar(150) not null,
                         idcoord int not null,
                         primary key(idnucleo),
                         foreign key(idcoord) references coordinacion(idcoord)) ENGINE = InnoDB;

create table usuario(
                                ci int not null AUTO_INCREMENT,
                prnombre varchar(20) not null,
                segnombre varchar(20) null,
                prapellido varchar(20) not null,
                segapellido varchar(20) null,
                sexo char not null,
                fecnac date not null,
                rolobservacion varchar(100) not null,
                fechaing date not null,
                fecha_ult_ascenso date not null,
                tipo char not null,
                correo varchar(150) not null,
                contraseña varbinary(20) not null,
                pregunta text not null,
                respuesta varchar(200) not null,
                telefono varchar(15) not null,
                tipo_est varchar(50) not null,
                idcord int not null,
                nroperfi int not null,
                iddedicacio int not null,
                idprogram int not null,
                idcarg int not null,
                ciaseso int null,
                CONSTRAINT pk_usuarios primary key(ci),
                CONSTRAINT fk_usuarios_coordinacion foreign key(idcord) references coordinacion(idcoord),
                CONSTRAINT fk_usuarios_perfil foreign key(nroperfi) references perfil(nroperfil),
                CONSTRAINT fk_usuarios_dedicacion foreign key(iddedicacio) references dedicacion(iddedicacion),
                CONSTRAINT fk_usuarios_programa foreign key (idprogram) references programa(idprograma),
                CONSTRAINT fk_usuarios_cargo foreign key(idcarg) references cargo(idcargo)
                ) ENGINE = InnoDB;


text:
Q: Dropdown icon in custom quill theme not showing correctly I am using angular 2 webpack (with CLI) and i use ngx-quill plugin
I have begun to create my own theme like this :
import extend from 'extend';
import Emitter from 'quill/core/emitter';
import BaseTheme, {
    BaseTooltip
} from 'quill/themes/base';
import {
    Range
} from 'quill/core/selection';
import * as Quill from 'quill';

const TOOLBAR_CONFIG = [
    [{
        header: ['1', '2', '3', false]
    }],
    ['bold', 'italic', 'underline', 'link'],
    [{
        list: 'ordered'
    }, {
        list: 'bullet'
    }],
    ['clean']
];

class SortieSportTheme extends BaseTheme {
    constructor(quill, options) {
        if (options.modules.toolbar != null && options.modules.toolbar.container == null) {
            options.modules.toolbar.container = TOOLBAR_CONFIG;
        }
        super(quill, options);
        this.quill.container.classList.add('ql-snow');
    }

    extendToolbar(toolbar) {
        toolbar.container.classList.add('ql-snow');
        var icons = Quill.import('ui/icons');
        this.buildButtons([].slice.call(toolbar.container.querySelectorAll('button')), icons);
        this.buildPickers([].slice.call(toolbar.container.querySelectorAll('select')), icons);

        this.tooltip = new SortieSportTooltip(this.quill, this.options.bounds);
        if (toolbar.container.querySelector('.ql-link')) {
            this.quill.keyboard.addBinding({
                key: 'K',
                shortKey: true
            }, function(range, context) {
                toolbar.handlers['link'].call(toolbar, !context.format.link);
            });
        }
    }
}
SortieSportTheme.DEFAULTS = extend(true, {}, BaseTheme.DEFAULTS, {
    modules: {
        toolbar: {
            handlers: {
                link: function(value) {
                    if (value) {
                        let range = this.quill.getSelection();
                        if (range == null || range.length == 0) return;
                        let preview = this.quill.getText(range);
                        if (/^\S+@\S+\.\S+$/.test(preview) && preview.indexOf('mailto:') !== 0) {
                            preview = 'mailto:' + preview;
                        }
                        let tooltip = this.quill.theme.tooltip;
                        tooltip.edit('link', preview);
                    } else {
                        this.quill.format('link', false);
                    }
                }
            }
        }
    }
});

class SortieSportTooltip extends BaseTooltip {
    constructor(quill, bounds) {
        super(quill, bounds);
        this.preview = this.root.querySelector('a.ql-preview');
    }

    listen() {
        super.listen();
        this.root.querySelector('a.ql-action').addEventListener('click', (event) => {
            if (this.root.classList.contains('ql-editing')) {
                this.save();
            } else {
                this.edit('link', this.preview.textContent);
            }
            event.preventDefault();
        });
        this.root.querySelector('a.ql-remove').addEventListener('click', (event) => {
            if (this.linkRange != null) {
                let range = this.linkRange;
                this.restoreFocus();
                this.quill.formatText(range, 'link', false, Emitter.sources.USER);
                delete this.linkRange;
            }
            event.preventDefault();
            this.hide();
        });
        this.quill.on(Emitter.events.SELECTION_CHANGE, (range, oldRange, source) => {
            if (range == null) return;
            if (range.length === 0 && source === Emitter.sources.USER) {
                let LinkBlot = Quill.import('formats/link');
                let [link, offset] = this.quill.scroll.descendant(LinkBlot, range.index);
                if (link != null) {
                    this.linkRange = new Range(range.index - offset, link.length());
                    let preview = LinkBlot.formats(link.domNode);
                    this.preview.textContent = preview;
                    this.preview.setAttribute('href', preview);
                    this.show();
                    this.position(this.quill.getBounds(this.linkRange));
                    return;
                }
            } else {
                delete this.linkRange;
            }
            this.hide();
        });
    }

    show() {
        super.show();
        this.root.removeAttribute('data-mode');
    }
}
SortieSportTooltip.TEMPLATE = [
    '',
    '<input type="text" data-formula="e=mc^2" data-link="https://quilljs.com" data-video="Embed URL">',
    '',
    ''
].join('');

export default SortieSportTheme;

I use my theme using quill register :
import SortieSportTheme from "app/sortiesport/common/quill/theme";
import * as Quill from 'quill';

constructor(
    Quill.register('themes/sortiesport', SortieSportTheme);
)

and in view :
<quill-editor #editor theme="sortiesport"></quill-editor>

Its works but i have a strange behavior with dropdown icon :

Do you have any ideas why my custom theme (based on SnowTheme) is having this problem.
If i remove the theme="sortiesport" from quill-editor in view everything work correctly.
Do you think i have to add something in my .angular-cli.json file ?
The custom theme could be in any folder in the project ?
.angular-cli.json :
    {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "barcelona"
  },
  "apps": [{
    "root": "src",
    "outDir": "dist",
    "assets": [
      "assets",
      "favicon.ico",
      "upload.php",
       {
         "glob": "**/*",
         "input": "../node_modules/monaco-editor/min/vs",
         "output": "assets/monaco/vs/"
       }
    ],
    "index": "index.html",
    "main": "main.ts",
    "polyfills": "polyfills.ts",
    "test": "test.ts",
    "tsconfig": "tsconfig.app.json",
    "testTsconfig": "tsconfig.spec.json",
    "prefix": "app",
    "styles": [
      "../node_modules/font-awesome/css/font-awesome.min.css",
      "../node_modules/fullcalendar/dist/fullcalendar.min.css",
      "../node_modules/quill/dist/quill.core.css",
      "../node_modules/quill/dist/quill.snow.css",
      "../node_modules/nanoscroller/bin/css/nanoscroller.css",
      "../node_modules/primeng/resources/primeng.min.css",
      "../node_modules/dragula/dist/dragula.css",
      "styles.scss"
    ],
    "scripts": [
      "../node_modules/jquery/dist/jquery.js",
      "../node_modules/nanoscroller/bin/javascripts/jquery.nanoscroller.js",
      "assets/layout/js/ripple.js",
      "assets/layout/js/day-schedule-selector.js",
      "../node_modules/moment/moment.js",
      "../node_modules/chart.js/dist/Chart.js",
      "../node_modules/fullcalendar/dist/fullcalendar.js",
      "../node_modules/fullcalendar/dist/locale/fr.js",
      "../node_modules/quill/dist/quill.js"
    ],
    "environmentSource": "environments/environment.ts",
    "environments": {
      "dev": "environments/environment.ts",
      "prod": "environments/environment.prod.ts"
    }
  }],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [{
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "scss",
    "component": {}
  }
}


text:
Q: When does OneDrive for Business change file contents? According to a recent article, one user found that his file contents were changed after sync. I repeated the expiriment with an HTML file and found it unchanged. However, I don't doubt that in some circumstances this could happen. I've seen lots of changes to files uploaded to SharePoint, generally related to SharePoint Designer.
The question is, why would this happen? If we don't know the cause, I wonder if there are repeatable cases of this or if there are flaws in the article author's methods.

A: Comparing OD4B to Box is not apples-to-apples.
If i have columns in the library, and those columns have default values, then I expect the updated metadata to be in the files once they are added to SharePoint.
Just more haters being haters.
=================================================
The observed behavior is called Property demotion and is well documented in the 2010 docs: http://msdn.microsoft.com/en-us/library/office/aa543341(v=office.14).aspx

A: In OpenXML (i.e. docx files) Sharepoint adds metadata to the document.


text:
Q: TypeError: expected httplib.Message, got . when using requests.get(url) on GAE My aim is to build a web crawler and host it on GAE. However,when I try to execute a very basic implementation I get the following error:
    Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "E:\WSE_NewsClusteriing\crawler\crawler.py", line 14, in get
    source_code = requests.get(url)
  File "libs\requests\api.py", line 67, in get
    return request('get', url, params=params, **kwargs)
  File "libs\requests\api.py", line 53, in request
    return session.request(method=method, url=url, **kwargs)
  File "libs\requests\sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "libs\requests\sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "libs\requests\adapters.py", line 376, in send
    timeout=timeout
  File "libs\requests\packages\urllib3\connectionpool.py", line 559, in urlopen
    body=body, headers=headers)
  File "libs\requests\packages\urllib3\connectionpool.py", line 390, in _make_request
    assert_header_parsing(httplib_response.msg)
  File "libs\requests\packages\urllib3\util\response.py", line 49, in assert_header_parsing
    type(headers)))
TypeError: expected httplib.Message, got <type 'instance'>.

My main.py is as follows:
import sys
sys.path.insert(0, 'libs')

import webapp2
import requests
from bs4 import BeautifulSoup

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        url = 'http://www.bbc.com/news/world'
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.findAll('a', {'class': 'title-link'}):
            href = 'http://www.bbc.com' + link.get('href')
            self.response.write(href)

app = webapp2.WSGIApplication([
    ('/', MainPage),
], debug=True)

The thing is that the crawler works fine as a standalone python application.
Can someone help me figure out what's wrong here? Does the requests module cause some compatibility issues with GAE?

A: I would advise against using the requests library on App Engine for the time being as it is not officially supported. It is therefore very likely to encounter compatibility issues. As per the URL Fetch Python API article, supported libraries include urllib, urllib2, httplib and using urlfetch directly. Some features of the requests library may also be based on the urllib3 library given their collaboration. This library is also not yet supported.
Feel free to consult the URL Fetch for simple examples of urllib2 and urlfetch requests. If there's some way that these libraries are not working for you, feel free to point us as such in your question.

A: This is almost two years old question but I actually stumbled upon this on appengine just now.
For the benefit of those who may come across similar issue, docs describes how to issue HTTP(S) requests
import requests
import requests_toolbelt.adapters.appengine

# Use the App Engine Requests adapter. This makes sure that Requests uses
# URLFetch.
requests_toolbelt.adapters.appengine.monkeypatch()

Referance https://cloud.google.com/appengine/docs/standard/python/issue-requests


text:
Q: Regex for Singapore Addresses I am doing Android. I have been googling for regex formula to validate Singapore addresses. I have come across many regex pattern but all did not work for me, as most are for US addresses.
The current regex pattern that I am using now is:
\d{1,3}.?\d{0,3}\s[a-zA-Z]{2,30}\s[a-zA-Z]{2,15}

which did not do much. Below are a few sample of Singapore addresses:

*

*2 Orchard Turn #B4-47 ION ORCHARD Singapore 238801

*68 Marine Parade Road #03-26B parkway Parade 449269

*Nanyang Polytechnic 180 Ang Mo Kio Avenue 8 Singapore 569830
Additional Notes: The postal code (6 digit numbers behind) will appear for every addresses
------------------------------------------------EDIT----------------------------------------
I need a regex that can detect and extract an address from a text output, that has other information as well.
For example:
Jean Watson
Managing Director

+65 96622235
68 Marine Parade Road #03-26B parkway Parade 449269

A: I have this for you :)  satisfy your all 3 inputs
  (\d{1,3}.)?.+\s(\d{6})$

See DEMO

Regex Explanation:

(\d{1,3}.) - this matches at-least 1 or max 3 digits
? - makes it 0 or 1
.+ - matches any character 1 or more times
\s - matches single white space
(\d{6})$ - matches ends with 6 digits

A: The following pattern:
^.+?(?<!\d)\d{6}$

Will match lines which:

*

*start with a digit (one or more) followed by .)

*end with 6 digits (postcode)


text:
Q: Wrong Values with Datagrid using WCF I have already a WCF restful apps working and I try to get the json to the Winforms but it give me wrong values and sometimes blocked
this my code for button of Winforms
private void button1_Click(object sender, EventArgs e)
    {
        WebClient proxy = new WebClient();
        string serviceURL = string.Format("http://localhost:55495/EventService.svc/GetAllEvents/");
        byte[] data = proxy.DownloadData(serviceURL);
        Stream stream = new MemoryStream(data);
        DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(EventDataContract));
        EventDataContract Eventdatacontract = obj.ReadObject(stream) as EventDataContract;

        string format = "MMM ddd d HH:mm yyyy";
        dataGridView1.ColumnCount = 4;
        dataGridView1.Columns[0].Name = "Event ID";
        dataGridView1.Columns[1].Name = "Text";
        dataGridView1.Columns[2].Name = "Start Date";
        dataGridView1.Columns[3].Name = "End Date";

        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            string[] row = new string[] { Eventdatacontract.EventID.ToString(), Eventdatacontract.Text, Eventdatacontract.Start_Date.ToString(format), Eventdatacontract.End_Date.ToString(format) };
            dataGridView1.Rows.Add(row);
        }

    }

for the data it shows like this

A: byte[] data = proxy.DownloadData(serviceURL);

is responsible for the blocking UI. You should consider making this call asynchronously, i.e.:
byte[] data = await Task.Run(() => proxy.DownloadData(serviceURL));

NOTE: When using the await keyword within a method you have to change the method signature.
In your case:
private async void button1_Click(object sender, EventArgs e)

UPDATE
As you found a working solution, you could also add async functions here to ensure a non blocking UI:
Note:
http://msdn.microsoft.com/en-us/library/hh191443.aspx#BKMK_NamingConvention

By convention, you append "Async" to the names of methods that have an Async or async modifier.

using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
...
private async Task<JArray> GetRESTDataAsync(string uri)
{
    var webRequest = (HttpWebRequest)WebRequest.Create(uri);
    var webResponse = (HttpWebResponse) await webRequest.GetResponseAsync();
    var reader = new StreamReader(webResponse.GetResponseStream());
    string s = await reader.ReadToEndAsync();
    return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<JArray>(s));
}

You could also use return await JsonConvert.DeserializeObjectAsync<JArray>(s); but Json.NET has marked it as obsolete and recommend using Task.Factory.StartNew().

A: this is the solution for me, just install Install-Package Newtonsoft.Json and add it to reference
public void  button1_Click(object sender, EventArgs e)
    {
        try
        {
            dataGridView1.DataSource = GetRESTData("http://localhost:55495/EventService.svc/GetAllEvents");
        }
        catch (WebException webex)
        {
            MessageBox.Show("Es gab so ein Schlamassel! ({0})", webex.Message);
        }
    }

    private JArray GetRESTData(string uri)
    {
        var webRequest = (HttpWebRequest)WebRequest.Create(uri);
        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        var reader = new StreamReader(webResponse.GetResponseStream());
        string s = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<JArray>(s);
    }


text: Q: porque grid layout me muestra los botones como vertical layout? Estoy intentando hacer una interfaz con PyQt5. Arrastro grid layout al formulario y luego arrastro 4 push button detro del grid y me los coloca como di fuera un vertical layout.  Si alguien ha tenido el mismo problema agradeceré me comente como lo solucionó.-


text:
Q: Parameter declaration [] and * (array) Between formal parameters in a function definition, like:
void change (int *s)
{
    s[0] = 42;
}

And another definition:
void change (int s[])
{
    s[0] = 42;
}

They are the same I assume, as *(a+0) is the same as a[0].
Is there a reason to prefer one over the another? Please note, the preference pertains to coding style.

A: Yes, they are exactly the same. All function parameters declared as arrays are adjusted to the corresponding pointer type.
Personally, I prefer the former which actually makes it look like a pointer declaration which is what it is in both cases.

A: I prefer the second one because it is then clear that you intend to use s as an array. (even though it is a pointer technically)
I think it is just another subjective thing though.

A: There is one case where they can be different, in the current C language. C99 allows the following:
void change (int s[static 2])
{
    s[0] = 42;
}

where the [static 2] imposes a constraint on the interface of the function that the pointer passed must be such that s[0] and s[1] access valid objects of type int. In particular, the interface does not permit NULL pointers.
Note that [static 1] is a convenient way to specify simply that the pointer must point to a valid object.


text:
Q: Pyspark with Joblib giving me ambiguous result I am trying to fetch data from teradata--
select ... from table1_1
union all
select .. from table_2
union all
select ... from table_3

NOTE: One or more select .. may fail which should not cause whole union to fail.
from .base import Base
from joblib import Parallel, delayed
import re
import pandas as pd

class TeradataWithSpark(Base):
    def __init__(self, spark, host=None, port=None, database=None, username=None, password=None):
        super().__init__(spark, host, port, database, username, password)
        self._reader = self._spark.read.format("jdbc") \
                .option("url", f'jdbc:teradata://{self._host}/Database={self._database},LOGMECH=LDAP') \
                .option("user", self._username) \
                .option("password", self._password) \
                .option("driver", "com.teradata.jdbc.TeraDriver")

    def run_query(self, query, return_pandasDF=True):
        spark_df = self._reader.option('dbtable', f"({query}) as tbl").load()
        if return_pandasDF:
            return spark_df.toPandas()
        else:
            return spark_df

    def run_queries_and_union_all(self, queries, return_pandasDF=True):
        def run(query):
            try:
                return self._reader.option('dbtable', f"({query}) as tbl").load().toPandas()
            except Exception as e:
                return None

        dfs = Parallel(n_jobs=10, prefer='threads')(delayed(run)(q) for q in queries)
        concat_df = pd.concat(dfs).reset_index(drop=True)
        if return_pandasDF:
            return concat_df
        else:
            return self._spark.createDataFrame(concat_df)

    def split_query_and_run_individually(self, query, separator='union all', return_pandasDF=True):
        queries = re.split(separator, query, flags=re.IGNORECASE)
        return self.run_queries_and_union_all(queries, return_pandasDF)

As you can see split_query_and_run_individually method splits the query based on union all then runs all of the sub queries in parallel threads n_jobs=10.
But the problem I am facing is that the data is corrupted like this
n_jobs = 1
                               src_tbl  total_count   data_date
0     dsl_dim_mdm_....................           61  2022-03-17
1     dsl_agg_call....................      3992202  2022-03-27
2      dsl_call_ac....................       924719  2022-03-27
3      dsl_dim_acc....................         4762  2022-03-31
4                 ....................         6821  2022-03-31
5     dsl_dim_geo_....................      8610038  2022-04-05
6              dsl....................        67116  2022-03-31
7           dsl_rl....................      2087669  2022-04-06
8             dsl_....................          154  2022-04-01
9             dsl_....................        85630  2022-03-27
10  dsl_selling_da....................           53  2021-03-03
11  dsl_speaker_ev....................        17765  2022-03-31
12       dsl_speak....................        26269  2022-08-24
13   dsl_speaker_e....................         4202  2022-04-05
14              ds....................          268  2022-03-31
15      dsl_rltn_r....................       255794  2022-03-18
16     dsl_rltn_nr....................        12088  2022-03-18
17        dsl_rapp....................        81182  2022-01-01
18   dsl_dim_physi....................       109299  2022-03-31
19             dsl....................         4265  2022-02-01
20         dsl_fac....................       117978  2022-04-03
21      dsl_coachi....................          242  2022-03-31
22   dsl_speaker_e....................        16653  2022-03-31
23     dsl_dim_cal....................        17817  2099-12-31
24    dsl_rltn_nrt....................         3304  2022-02-01
Time took: 3.4742537260055544 minutes
-----------
n_jobs=10
                              src_tbl  total_count   data_date
0             dsl_sel................        85630  2022-03-27
1             dsl_sel................        85630  2022-03-27
2             dsl_sel................        85630  2022-03-27
3             dsl_sel................        85630  2022-03-27
4             dsl_sel................        85630  2022-03-27
5             dsl_sel................        85630  2022-03-27
6             dsl_sel................        85630  2022-03-27
7             dsl_sel................        85630  2022-03-27
8             dsl_sel................        85630  2022-03-27
9             dsl_sel................        85630  2022-03-27
10  dsl_speaker_event................        17765  2022-03-31
11   dsl_speaker_even................         4202  2022-04-05
12   dsl_speaker_even................         4202  2022-04-05
13              dsl_s................          268  2022-03-31
14        dsl_rapper_................        81182  2022-01-01
15        dsl_rapper_................        81182  2022-01-01
16     dsl_rltn_nrtl_................        12088  2022-03-18
17        dsl_rapper_................        81182  2022-01-01
18   dsl_dim_physicia................       109299  2022-03-31
19             dsl_cu................         4265  2022-02-01
20         dsl_fact_f................       117978  2022-04-03
21      dsl_coaching_................          242  2022-03-31
22   dsl_speaker_even................        16653  2022-03-31
23     dsl_dim_call_c................        17817  2099-12-31
24    dsl_rltn_nrtl_r................         3304  2022-02-01
Time took: 1.8048373858133953 minutes
-----------
n_jobs=-1
                            src_tbl  total_count   data_date
0   dsl_dim_acc....................         4762  2022-03-31
1   dsl_dim_acc....................         4762  2022-03-31
2   dsl_dim_acc....................         4762  2022-03-31
3   dsl_dim_acc....................         4762  2022-03-31
4   dsl_dim_acc....................         4762  2022-03-31
5   dsl_dim_acc....................         4762  2022-03-31
6   dsl_dim_acc....................         4762  2022-03-31
7   dsl_dim_acc....................         4762  2022-03-31
8   dsl_dim_acc....................         4762  2022-03-31
9   dsl_dim_acc....................         4762  2022-03-31
10  dsl_dim_acc....................         4762  2022-03-31
11  dsl_dim_acc....................         4762  2022-03-31
12  dsl_dim_acc....................         4762  2022-03-31
13  dsl_dim_acc....................         4762  2022-03-31
14  dsl_dim_acc....................         4762  2022-03-31
15  dsl_dim_acc....................         4762  2022-03-31
16  dsl_dim_acc....................         4762  2022-03-31
17  dsl_dim_acc....................         4762  2022-03-31
18  dsl_dim_acc....................         4762  2022-03-31
19  dsl_dim_acc....................         4762  2022-03-31
20  dsl_dim_acc....................         4762  2022-03-31
21  dsl_dim_acc....................         4762  2022-03-31
22  dsl_dim_acc....................         4762  2022-03-31
23  dsl_dim_acc....................         4762  2022-03-31
24  dsl_dim_acc....................         4762  2022-03-31
25  dsl_dim_acc....................         4762  2022-03-31
-----------

As you can see as I increase the number of threads the result becomes ambiguous. What is happening is that the results from each query are overlapping with each other.
I have also implemented the same class with teradatasql library which works just fine with n_jobs=-1. I think self._reader.option('dbtable', f"({query}) as tbl").load() is getting messed up in threads. I tried with ThreadpoolExecutor but similar result. Does anyone know how to solve this issue?
Versions
Python 3.6.8
Spark 2.4.0-cdh6.3.4

A: Thanks to @pltc, here is one solution. Although it is very slow compared to teradatasql library with multithreading although FAIR schedulers on
from .base import Base
import re
import pandas as pd
from pyspark.sql import DataFrame
from functools import reduce

class TeradataWithSpark(Base):
    def __init__(self, spark, host=None, port=None, database=None, username=None, password=None):
        super().__init__(spark, host, port, database, username, password)
        self._reader = self._spark.read.format("jdbc") \
                .option("url", f'jdbc:teradata://{self._host}/Database={self._database},LOGMECH=LDAP') \
                .option("user", self._username) \
                .option("password", self._password) \
                .option("driver", "com.teradata.jdbc.TeraDriver")

    def run_query(self, query, return_pandasDF=True):
        # spark_df = self._reader.option('dbtable', f"({query}) as tbl").load()
        # if return_pandasDF:
        #     return spark_df.toPandas()
        # else:
        #     return spark_df
        return self.split_query_and_run_individually(query, r'union all', return_pandasDF)

    def run_queries_and_union_all(self, queries, return_pandasDF=True):
        dataframes = []
        for each_query in queries:
            try:
                spark_df = self._reader.option('dbtable', f"({each_query}) as tbl").load()
                dataframes.append(spark_df)
            except Exception as e:
                # simply ignoring the query
                print(f'Error while reading the query {each_query}')

        concat_sparkDf = reduce(DataFrame.unionAll, dataframes)
        if return_pandasDF:
            return concat_sparkDf.toPandas()
        else:
            return concat_sparkDf

    def split_query_and_run_individually(self, query, separator=r'union all', return_pandasDF=True):
        queries = re.split(separator, query, flags=re.IGNORECASE)
        return self.run_queries_and_union_all(queries, return_pandasDF)


text:
Q: Android Transforming json String with umlauts I want send a josn string to a php sript on a webserver.
i use this code:
JSONObject json = new JSONObject();
json.put("street", "straße");

json put exactly this to the string, but the php script does not needs straße, it needs stra\u00dfe
is there any way to do this exept String.replace()
maybe this helps for a other solution, the php script deletes the ß in the string

A: You can't send characters to servers, you can only send bytes. You need to figure out where your JSON string is being converted to a byte array and make sure that it includes a charset like UTF-8.
The JSON encoder won't convert ß to \u00df because that's not its job. As far as it is concerned, ß is a legal output character.


text:
Q: Good OPDS Server for Shared Hosting? Does anyone have recommendations for a web-based server I can use to host an OPDS server that does not require something heavy like a VPS?  I realized the FBReader and other mobile e-book readers would allow me to syndicate myself between me and friends.  Google has few answers in this regard, beyond the formal specification website by Google.

A: After doing the same search I found the following candidates :

*

*Calibre2OPDS : http://calibre2opds.com/ (generate static files from a Calibre database)

*Parthagar : http://olpcsf.org/projects/pathagar-sheevaplug-edition (in python)

*COPS : http://blog.slucas.fr/en/oss/calibre-opds-php-server (PHP server using a Calibre database)

So not a full answer, but close enough ;)


text:
Q: What kind of hash function does Aerospike use for UDF modules? Aerospike allows to list already loaded UDF modules. Here is an aql-example (taken from help-portal):
SHOW MODULES

The result contains hash field:
aql> show modules
+---------------------------+-------+------------------------+
| module                    | type  | hash                   |
+---------------------------+-------+------------------------+
| "example1.lua"            | "lua" | "033671e05067888fce09" |
| "example2.lua"            | "lua" | "07b42082cca8e73a96b2" |
+---------------------------+-------+------------------------+
2 rows in set (0.000 secs)

My question (1): I have the example1.lua file (sources of the UDF module), how to calculate (and check) hash for it?
My hypotheses:

*

*hash depends on source file - TRUE

*hash depends on timestamp of loading - failed

*hash depends on filename - TRUE

*md5sum on source file - failed (obviously, see hypothesis 3)

*sha1sum on pure source file - failed (see hypothesis 3)

Actually, I want to check the version for already registered module, and upgrade that module if necessary. As mentioned in the documentation:

the hash value of the file. Most users will not find the hash value useful, but some may use it to verify the version or instance of a UDF on the server.

So, the alternate question (2) is: how to check the version of a registered UDF module?

A: Its a 20-byte sha1 hash of the below 3 fields represented as a json document. The json document is string representation without any newline separator or EOF character.
"content64" : base64 encoding of whole file
"type" : LUA
"name" : filename

Example :
{"content64": "ZnVuY3Rpb24gcHJpbnRfbWV0YShyZWMpCgoJaWYgbm90IGFlcm9zcGlrZTpleGlzdHMocmVjKSB0aGVuCgkJcmV0dXJuICJub3JlYyIKCWVuZAoKCWluZm8ocmVjb3JkLnR0bChyZWMpKQoJaW5mbyhyZWNvcmQubGFzdF91cGRhdGVfdGltZShyZWMpKQoJcmV0dXJuIHJlY29yZC5sYXN0X3VwZGF0ZV90aW1lKHJlYykKZW5kCg==", "type": "LUA", "name": "lut.lua"}

Cross-checking : (Ignore the '' escape character added for the sake of echo command)
$ echo -n {\"content64\": \"ZnVuY3Rpb24gcHJpbnRfbWV0YShyZWMpCgoJaWYgbm90IGFlcm9zcGlrZTpleGlzdHMocmVjKSB0aGVuCgkJcmV0dXJuICJub3JlYyIKCWVuZAoKCWluZm8ocmVjb3JkLnR0bChyZWMpKQoJaW5mbyhyZWNvcmQubGFzdF91cGRhdGVfdGltZShyZWMpKQoJcmV0dXJuIHJlY29yZC5sYXN0X3VwZGF0ZV90aW1lKHJlYykKZW5kCg==\", \"type\": \"LUA\", \"name\": \"lut.lua\"} | sha1sum
998354a59337b229e2dd777a3288e8e8f33568a5  -

$ asinfo -v "udf-list"
filename=lut.lua,hash=998354a59337b229e2dd777a3288e8e8f33568a5,type=LUA;

A: In addition to the @sunil answer
Python example
This routine calculates a hash for a LUA module with AeroSpike's UDF, written in python 3
import base64
import hashlib

# You could pass one argument - full path, and then extract
# name. But here we have only this naive implementation

def udf_module_get_hash(MODULE_PATH, MODULE_NAME_WITHOUT_DIR_WITH_EXT):
    with open(MODULE_PATH, 'rb') as f:
        content = f.read()
    b64 = base64.b64encode(content)

    meta = '{{"content64": "{0}", "type": "LUA", "name": "{1}"}}'.format(
        b64.decode('ascii'),
        MODULE_NAME_WITHOUT_DIR_WITH_EXT
    )
    sha1 = hashlib.sha1()
    sha1.update(meta.encode())

    h = sha1.hexdigest()
    # h is something like '052ac7359e46d1c6c97a5bf1a9854739cd9e481a'
    return h


text:
Q: How to bind subgrid events in expandable ui-grid ng-click event for the sub grid in ui-grid(expandable ui grid) is not working. But the same ( ng-click) is working for the outer grid with 'grid.appScope' scope. But I don't know how to bind the subgrid events in expandable grid. I have kept my code in the below plnkr. 'Click me' is not working in the inner grid.
There is an 'expandableScope' property. But i am not sure how to use it. Plz see the for plnkr code plnkr
I have added below snippet in gridOptions
expandableRowScope: { clickMeSub: function(){alert('hi');} }

I tried to call clickMe method from expandableRowScope like below.
<button class="btn primary" ng-click="grid.expandableRowScope.clickMeSub()">Click Me </button>

Still no luck.

A: Your ng-click on the sub grid needs to just refer to it's own appscope, not the parent grids expandableRowScope.
ng-click="grid.expandableRowScope.clickMeSub()"

should be
ng-click="grid.appScope.clickMeSub()"

Modified Plunker - http://plnkr.co/edit/0o9ViW0TEuYIA4zx0kIW?p=preview


text:
Q: Passing a double pointer to modify string So I have a program that works sometimes, but other times it doesn't. Sometimes putting in a printf statement will make the program magically work (and sometimes a printf will make it break). This makes me think I messed up as far as pointers/allocation goes, as I still have trouble wrapping my head around some things. The program is too long to post all the code, so I'll just show where I think the problem is.
I was given a function that takes a FILE* and a few char**  as parameters, returning an int. The function is parsing a file, storing necessary strings to where the double pointers point to.
Here is how I used the function (alot of code is omitted/simplified):
char **s1;
char **s2;
char **s3;

int main(int argc, char ** argv){
    s1 = (char**)malloc(20);
    s2 = (char**)malloc(20);
    s3 = (char**)malloc(20);

    /* Unnecessary code omitted */
    read(inFile);
}

int read(FILE* in){
    /* omitted code */
    parse(in,s1,s2,s3);
    printf("%s",*s1); /* This is to show how I access the strings */
}

Im pretty sure that somewhere in my program, those strings are getting overwritten because I didn't allocate the memory properly. Hopefully my mistake is visible in the code snippet I gave, because I don't have many other theories for why my code doesn't work

A: Since the API to parse() is specified with char ** I believe it is safe to assume that you really do need the double-indirection in the call, but not in the declaration.
So probably what you need is to skip the malloc() calls and say:
char *s1, *s2, *s3;
...
parse(in, &s1, &s2, &s3);

This would allow parse() to allocate its own space and return the three pointers to its caller by modifying the pointers themselves.  I appreciate your efforts to distill the question to its core but it might be interesting to see the prototype for parse().


text:
Q: Is there a way to implement a generic class for displaying an object fields? I have some classes(e.g. Hospital, Doctor, Nurse etc) and I need to write a generic class that appends to a file an object of a different type. Each class a method that displays its fields, but I can't pass this error "Cannot resolve method 'print' in T"

Here is the code:
package Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileService<T>
{
    private static WriteFileService instance;

    private WriteFileService(){}

    public static WriteFileService getInstance()
    {
        return instance;
    }

    public void appendObject(T object, String fileName)
    {
        try {
            File file = new File(fileName);

            // creates the file if it does not exist
            if (!file.exists())
                file.createNewFile();

            FileWriter fw = new FileWriter(file, true); // append mode = true
            BufferedWriter bufferedWriter = new BufferedWriter(fw);

            object.print(bufferedWriter); //! ERROR: Cannot resolve method 'print' in T

            bufferedWriter.flush();
            bufferedWriter.close();
        }
        catch(IOException e)
        {
            System.out.println("Problem handling the files!");
            e.printStackTrace();
        }
    }
}

Any help regarding the method would be helpful

A: Because of type erasure your T is treated as Object (in runtime) and there is no print() method in Object class.
You can add interface:
public interface Printable {
    void print();
}

and let all your classes implement it.
Then you would need to change this:
public class WriteFileService<T>
to this:
public class WriteFileService<T extends Printable>


text:
Q: What does retranslateUi do in PyQT When running pyuic5 command and generating a python file from QT designer UI file there is a retranslateUi function.
def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

Is this function for multi language support and can I safely delete this function if I have no interest in multi language?
I am adding GUI widgets in a loop so this function would be a hassle to implement in my code.

A: This function is made to implement the multi-language support logic (See 1 and 2).
And you can remove it without problems.


text:
Q: ¿Como exportar base de datos de workbench a phpmyadmin? Buenos dias
Quisiera saber como se exporta una base de datos de workbench a phpmyadmin.Mas concretamente yo deseo exportar una base de datos de tres tablas


text:
Q: how to add action with html button in laravel datatables 8.* I have installed yajra laravel on my project, I try to add action column with html button with id, I am using yajra laravel, these are my yajra laravel version:

*

*"yajra/laravel-datatables-buttons": "3.*"

*"yajra/laravel-datatables-fractal": "1.*",

*"yajra/laravel-datatables-html": "3.*",

*"yajra/laravel-datatables-oracle": "8.*"

How to add Action column with html button with id of data ?
here my datatables code to make datatables in laravel:
public function html()
    {
        $brands = Brands::select(array('brands.id','brands.name','brands.slug','brands.description','brands.logo','brands.published','brands.created_at','brands.updated_at'));
        return $this->builder()
                    ->columns($this->getColumns())
                    ->minifiedAjax()
//                    ->addAction(['width' => '80px'])
                    ->removeColumn('id')
                    ->addColumn($this->actionColumns())
                    ->parameters($this->getBuilderParameters());
    }

this is my complete code for make datatables in laravel:
https://pastebin.com/v1qYGNjb
here the result datatable:

I want to add button edit and delete in column Actions, how to do that with laravel datatables 8?
I am using laravel datatables as a service.

A: public function html()
    {
        $brands = Brands::select(array('brands.id','brands.name','brands.slug','brands.description','brands.logo','brands.published','brands.created_at','brands.updated_at'));
        return $this->builder()
                    ->columns($this->getColumns())
                    ->minifiedAjax()
//                    ->addAction(['width' => '80px'])
                    ->removeColumn('id')
                    ->addColumn('action',function ($data){
                return $this->getActionColumn($data);
            })
                    ->parameters($this->getBuilderParameters());
    }

/**
     * @param $data
     * @return string
     */
    protected function getActionColumn($data): string
    {
        $showUrl = route('admin.brands.show', $data->id);
        $editUrl = route('admin.brands.edit', $data->id);
        return "id' href='$showUrl'>visibilityDetails
                        id' href='$editUrl'>editUpdate
                        <button class='waves-effect btn deepPink-bgcolor delete' data-value='$data->id' >deleteDelete</button>";
    }

*

*Change your addColumn() method and follow this code.

A: //UsersDataTable.php file

class UsersDataTable  extends DataTable{
    public function dataTable( $query ){
        return datatables()
            ->eloquent( $query )
            ->addColumn( 'action', function( $data ){ // $data is data od current row in table
                return view( 'admin.users.action', [ 'data' => $data ] ); // return view with objects (row) data parameters
                //return ''.$data->id.''; // or simply return html here
            } );
    }

    // some of class code here

    protected function getColumns(){
        return [
            Column::make( 'id' ),
            Column::make( 'name' )->title( 'Nazwa' ),
            Column::make( 'email' ),
            Column::make( 'created_at' ),
            Column::make( 'updated_at' ),

            Column::computed( 'action' )
                  ->exportable( FALSE )
                  ->printable( FALSE )
                  ->width( 60 )
                  ->addClass( 'text-center' ),
        ];
    }

}

//UsersController.php file

use App\DataTables\UsersDataTable;
class UsersController extends Controller
{
    public function index(UsersDataTable $dataTable)
    {
        return $dataTable->render('admin.users.index');
    }
}


text:
Q: Нужна помощь в записи отправленного пользователем контакта в БД Не получается записать конкретное отправленное пользователем сообщение(контакт) в БД. Атрибута text у a.message.from_user нет и я не вижу других способов.
@dp.callback_query_handler(lambda a: True)
async def inline_buttons1(a):
    user_id = a.message.chat.id
    if a.data == 'private_office':
        markup_send_contact = ReplyKeyboardMarkup(resize_keyboard=True)
        bt1 = KeyboardButton(text='Отправить свой номер телефона', request_contact=True)
        markup_send_contact.row(bt1)
        await bot.send_message(a.message.chat.id, MESSAGES['send_contact'],
                               reply_markup=markup_send_contact, parse_mode='MarkdownV2')
        conn = sqlite3.connect('bigben.db')
        cursor = conn.cursor()
        cursor.execute('INSERT INTO krasusers(user_id, telefone) VALUES(?,?)', (user_id,
                                                                               a.message.from_user.text, ))
        conn.commit()
        conn.close()

A: Для того, чтобы отловить отправленный пользователем контакт, можете использовать параметр content_types=["contact"], в Вашем хэндлере.
async def create_user(user_id: int, phone: str):
    conn = sqlite3.connect('bigben.db')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO krasusers (user_id, telefone) VALUES (?, ?)', (user_id, phone))
    conn.commit()
    conn.close()

@dp.callback_query_handler(text="private_office")
async def private_office_handler(query: CallbackQuery):
    keyboard = ReplyKeyboardMarkup(resize_keyboard=True).add(
        KeyboardButton(text="Отправить свой номер телефона", request_contact=True)
    )
    await bot.send_message(
        query.from_user.id,
        MESSAGES["send_contact"],
        reply_markup=keyboard,
        parse_mode="MarkdownV2",
    )

@dp.message_handler(content_types=["contact"])
async def contact_handler(message: Message):
    contact = message.contact

    await create_user(message.from_user.id, contact.phone_number)


text:
Q: Orchard blog with Live Writer I'm using Orchard 1.8 and I want to manage a blog with Windows Live Writer 2012.
Is there any simple solution to add a field image to the blog post content type and let the user fill it in Writer?
My idea is show a widget like [image - title - some text] so any advice is welcome.
Thank you.

A: Windows Live Writer only allows for simple blog post editing. It does not do structured data beyond what's provided by standard blogging APIs. It is trivial however to add images inside of a blog post's body.


text:
Q: How to make a function return a list of indices of the characters in the second string that appears in the first string? def get_indices_from_the_second_string(string1, string2):
    '''(str, str) -> list of int
    >>> get_indices_from_the_second_string('AGTACACGTTAC', 'GAATTC')
    [1, 3, 5, 8, 9, 11]
    >>> get_indices_from_the_second_string('AGTACACGTTAC', 'GGATCC')
    [1, 7, 10]
    '''

    acc= []

    for i in range(0, len(string2)):
        for r in range(0, len(string1)):
            if len(acc) == len(string2):
                            break
            if string1[r] == string2[i]:
                acc.append(r)
                i += 1
                r += 1
    return acc

    # the second example is wrong
    # how to make it not reversed only from left to right
    # maybe use find.()???

A: def get_indices_from_the_second_string(string1, string2):
    acc = []
    s2_counter = 0
    for i, letter in enumerate(string1):
        if letter == string2[s2_counter]:
            acc.append(i)
            s2_counter += 1
            if len(acc) == len(string2):
                break
    return acc

a = get_indices_from_the_second_string('GAATTCCGTTAC', 'GAATTC')

A: Remove lines
            i += 1
            r += 1

as for loops increase i and r automatically.
And then modify your code:
lower = 0                             # from this index will be string1 searched

for i in range(0, len(string2)):
    for r in range(lower, len(string1)):
        if string1[r] == string2[i]:
            acc.append(r)
            lower = r + 1             # indexes from 0 to r are already used
            break
        elif r == len(string1) - 1:   # last index did not match
            return acc
return acc

A: Oh, I see what you're doing.
def get_indices_from_the_second_string(string1, string2):
    acc = []
    string1_index = 0
    for char in string2:
        while string1[string1_index] != char:
            string1_index += 1
            if string1_index >= len(string1):
                return acc
        acc.append(string1_index)
        string1_index += 1
        if string1_index >= len(string1):
            return acc
    return acc

A: Use the built in function zip, along with another built in enumerate
acc = []
for i, (a, b) in enumerate(zip(string1, string2)):
    if a==b:
        acc.append(i)
return acc