text:
Q: Why are links in HTML files with URI scheme tel: and sms: in href not working on Android? On android (at least on some of my devices) links with hrefs pointing to tel: and sms: URIs are not working. Instead of opening the SMS or Telephone App after clicking such a link, the browser instead redirects to a blank page whose URL is in the form sms:+123456789 or +123456789.
I've tried removing the body, including or excluding the country code, using + or 00 as the international dialing prefix.
call
sms

This issue was not 100% consistent over all of the devices where I have tested this. The issue is that in a browser (on a company intranet site) we need the ability to quickly make calls and send messages with prefilled data like phone number and with sms messages body text ideally as well. Such links worked fine on devices running Android 4, 5, 6, 7 but on Android 8 and 9, these links were broken. I have tested this particularly on Asus Zenfone 5 devices with Android 8 and 9. The expected behavior is: an  link is clicked, the browser starts an intent, the Phone app with a predialed number () pops up or the SMS app with a prefilled number and body of an SMS message pops up (). Instead, either nothing happens, or a new browser tab opens with the href URI in the address bar. I have tested and had this behavior on all my Android 8 and 9 devices using Chrome, Firefox Focus, Firefox, Edge on both 8 and 9, but not in any of those browsers on Android 5 and 6 (where the links work as expected). I always used the same HTML file. Not even w3schools and other example code scripts worked on of the Asus Zenfone 5s.


text:
Q: Deleting first object in Core Data (Swift) I am requesting Core Data to return me its Entity entries in ascending order based on contentid:
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!

let sort = NSSortDescriptor(key:"contentid", ascending:true)
fetchRequest.sortDescriptors = [sort]

let fetchedResults = managedObjectContent.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]

How do I delete the first object in Core Data's returned, ascending entries?
I have also tried getting a single object by specifying:
fetchRequest.fetchLimit = 1

Thinking that this would return an [NSManagedObject], I attempted to then perform:
managedObjectContext.deleteObject(fetchedResults)

But it threw the error: cannot invoke method deleteObject with type '([NSManagedObject])'. What exactly am I doing incorrectly? Do I need to convert [NSManagedObject] to NSManagedObject, perhaps?

A: Try this:
let fetchedResults = context.executeFetchRequest(fetchRequest, error: nil)
if let result = fetchedResults?.first as? NSManagedObject {
    context.deleteObject(result)
}

executeFetchRequest returns [AnyObject]? so you must unwrap it, take first object and cast it to NSManagedObject. After that you will be able to perform delete with this object.

A: Try with managedObjectContext.deleteObject(fetchedResults[0])
, checking first that fetchedResults[0] exists.
Also you can use: managedObjectContext.deleteObject(fetchedResults.first)

A: Retrieve the first object from the returned array, then use deleteObject:
You can find a lot of useful information on Apple Documentation
--EDIT--
From Apple Doc

func executeFetchRequest(_ request: NSFetchRequest,
                     error error: NSErrorPointer) -> [AnyObject]?
Return Value
An array of objects that meet the criteria specified by
  request fetched from the receiver and from the persistent stores
  associated with the receiver's persistent store coordinator. If an
  error occurs, returns nil. If no objects match the criteria specified
  by request, returns an empty array.

Notice the return value of executeFetchRequest is an array, not a NSManagedObject

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add line plot to histogram in R I have a histogram plotted in R with the code shown below. I am trying to do 2 things:

*

*How to show percent[%] above each bars?

*Add a line plot on the top of existing histogram. That shows the percent[%] accumulation from left to right. For example, see attached figure as an example. The line plot starts at 12.5% then add the next bar (~22.92%) to 12.5%. So, it would plot at ~35.42%. It will add each bar % as its goes from left to right. Is there a way to make a similar line plot on my existing histogram chart in R?

Any help or guidance would be very much appreciated. Thanks!
    library(tidyverse)

    HoursfromSLA <- c("-100","-100","-100","-100","-100","-100","-100","-100","-100","-100","-100","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-80","-50","-50","-50","-50","-50","-50","-50","-50","-50","-50","-20","-20","-20","-20","-20","-20","-20","-20","-20","-20","20","20","20","20","50","50","50","50","50","50","50","50","75","75","75","75","75","75","100","100","100","100","135","135","135","135","225","225","225","225","310","310","350","350","400","400","500","500","500","500","675","675")

    data <- data.frame(HoursfromSLA)
    data$group <- ifelse(data$HoursfromSLA<0, "Green", "Red")
    data$HoursfromSLA <- as.numeric(data$HoursfromSLA)

    ggplot(data, aes(x=data, fill = group)) +
      geom_vline(xintercept = 0, colour="black") +
      geom_histogram(mapping = aes(x=HoursfromSLA, y=..count../sum(..count..)*100), col=I("white"), show.legend=FALSE, bins=25) +
      scale_fill_manual(values = c("Green" = "darkgreen", "Red" = "darkred")) +
      scale_x_continuous(name = "Time to SLA", breaks = seq(-150, 720, 30)) +
      scale_y_continuous(name = "[%]")

A: There might be a better way to do this with binned scales, but you could make a dataframe of the percentages for each column and work with that:
data$HoursfromSLA2 <- as.numeric(as.character(cut(data$HoursfromSLA, breaks=seq(-120,900,30),labels = seq(-120,900-30,30)+15)))
data2 <- aggregate(data=data, HoursfromSLA~HoursfromSLA2+group, length )
data2$perc <- 100*data2$HoursfromSLA/sum(data2$HoursfromSLA)
ggplot(data2, aes(x=HoursfromSLA2, y=perc)) +
  geom_col(aes(fill=group),width =30) +
  geom_text(aes(vjust=-.5,label=round(perc,1))) +
  geom_line(aes(x=HoursfromSLA2-15,y=cumsum(perc))) +
  geom_point(aes(x=HoursfromSLA2-15,y=cumsum(perc))) +
  geom_text(vjust=-1,hjust=1,aes(x=HoursfromSLA2-15,y=cumsum(perc), label=round(cumsum(perc),1))) +
  theme_bw()+  scale_fill_manual(values = c("Green" = "darkgreen", "Red" = "darkred")) +
  scale_x_continuous(name = "Time to SLA", breaks = seq(-150, 720, 30)) +
  scale_y_continuous(name = "[%]") +
  geom_vline(xintercept=0) +
  theme(legend.position = "none")


text:
Q: Autofac - resolving through factory methods I just can't seem to wrap my brain around this situation in Autofac:

*

*My business logic needs an object of type IFinal.

*The implementing class Final has several dependencies that are not known by the business logic, but can be directly resolved via the IoCContainer.

*Final also has other dependencies that are only known by the business logic at run time.

*I want to be able to use Interceptors on IFinal, so class Final should be registered and resolved via IFinal.

So I tried to create a factory for IFinal, but I can't seem to get the resolution right.
Example code:
    public static void Main(string[] args)
    {
        ContainerBuilder builder = new ContainerBuilder();

        builder.RegisterType<Dependency>().As<IDependency>();

        builder.RegisterType<Final>().As<IFinal>();

        // this fails because context c is not available at the time finalObjectFactoryMethod is used
        builder.Register<Factory>((c,p)=>{
            var dependency = c.Resolve<IDependency>();
            Func<int, IFinal> finalObjectFactoryMethod =
                rta => c.Resolve<IFinal>(
                    new TypedParameter(typeof(IDependency), dependency),
                    new TypedParameter(typeof(int), rta)
                );
            return new Factory(finalObjectFactoryMethod);
        }).As<IFactory>();

        // this works but doesn't use the resolve mechanism for IFinal
        /*
        builder.Register<Factory>((c,p)=>{
            var dependency = c.Resolve<IDependency>();
            Func<int, IFinal> finalObjectFactoryMethod = rta => new Final(dependency, rta);
            return new Factory(finalObjectFactoryMethod);
        }).As<IFactory>();
        */

        IContainer container = builder.Build();

        IFactory factory = container.Resolve<IFactory>();
        IFinal final = factory.GetFinalObject(42);
    }
}

public interface IDependency{}

public class Dependency: IDependency{}

public interface IFinal
{
    void Test();
}

public class Final: IFinal
{
    public Final(IDependency dependency, int runtimeArgument){}

    public void Test(){}
}

public interface IFactory
{
    IFinal GetFinalObject(int runtimeArgument);
}

public class Factory: IFactory
{
    readonly Func<int, IFinal> _finalObjectFactoryMethod;

    public Factory(Func<int, IFinal> finalObjectFactoryMethod)
    {
        _finalObjectFactoryMethod = finalObjectFactoryMethod;
    }

    public IFinal GetFinalObject(int runtimeArgument)
    {
        return _finalObjectFactoryMethod(runtimeArgument);
    }
}

Google and Autofac documentation could not help me on this.
Somehow there seems to be a knot in my brain, maybe I just try to use the wrong pattern.
I'm pretty sure there is a solution for this, but I just can't find it.

A: You have to add a factory delegate to Final:
public class Final : IFinal
{
    public delegate IFinal Factory(int runtimeArgument);

    public Final(IDependency dependency, int runtimeArgument) { }

    public void Test() { }
}

Autofac is clever enough to fill the other parameters in so your factory delegate can only have parameters you specify at runtime and the other ones are resolved by magic.
Then you register the type:
    builder
        .RegisterType<Final>()
        .As<IFinal>();

Here's the complete example:
public static void Main(string[] args)
{
    ContainerBuilder builder = new ContainerBuilder();

    builder
        .RegisterType<Dependency>()
        .As<IDependency>();

    builder
        .RegisterType<Final>()
        .As<IFinal>();

    using(var container = builder.Build())
    using (var scope = container.BeginLifetimeScope())
    {

        var finalFactory = scope.Resolve<Final.Factory>();
        IFinal final = finalFactory(42);
    }
}

You don't need the Factory class at all. The delegate can either be resolved directly from scope or used the same way as any other dependency and injected by Autofac. Just juse Final.Factory as your dependency.
The documentation describes this technique in the Delegate Factories

A: Great example of "ask the right question and you'll find the right answer".
I've been trying to get this to work for 2 days now and 1 hour after I posted my question here, I found the answer myself :P
Here's the working code including Interceptor:
class MainClass
{
    public static void Main(string[] args)
    {
        ContainerBuilder builder = new ContainerBuilder();

        builder.RegisterType<Interceptor>();

        builder.RegisterType<Dependency>().As<IDependency>();

        builder.RegisterType<Final>().As<IFinal>();

        builder.Register<IFinal>((c, p) =>
        {
            IDependency dependency = c.Resolve<IDependency>();
            int runtimeArgument = p.Named<int>("runtimeArgument");
            return new Final(dependency, runtimeArgument);
        }).As<IFinal>()
       .EnableInterfaceInterceptors()
       .InterceptedBy(typeof(Interceptor));

        builder.Register<Factory>((c,p)=>{
            Factory.FactoryMethod finalObjectFactoryMethod = c.Resolve<Factory.FactoryMethod>();
            return new Factory(finalObjectFactoryMethod);
        }).As<IFactory>()
       .EnableInterfaceInterceptors()
       .InterceptedBy(typeof(Interceptor));

        IContainer container = builder.Build();

        IFactory factory = container.Resolve<IFactory>();
        IFinal final = factory.GetFinalObject(42);
        final.Test();
    }
}

public interface IDependency{}

public class Dependency: IDependency{}

public interface IFinal
{
    void Test();
}

public class Final: IFinal
{
    public Final(IDependency dependency, int runtimeArgument){}

    public void Test(){}
}

public interface IFactory
{
    IFinal GetFinalObject(int runtimeArgument);
}

public class Factory: IFactory
{
    public delegate IFinal FactoryMethod(int runtimeArgument);

    readonly FactoryMethod _finalObjectFactoryMethod;

    public Factory(FactoryMethod finalObjectFactoryMethod)
    {
        _finalObjectFactoryMethod = finalObjectFactoryMethod;
    }

    public IFinal GetFinalObject(int runtimeArgument)
    {
        return _finalObjectFactoryMethod(runtimeArgument);
    }
}

public class Interceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine($"call {invocation.Method.Name}");
        invocation.Proceed();
        Console.WriteLine($"return from {invocation.Method.Name}");
    }
}

The interceptor now writes this to the console:
call GetFinalObject
return from GetFinalObject
call Test
return from Test

Maybe this can help anyone else.

A: I found the solution in the other comments very unsatisfying. That's why I wrapped my head around the example. Perhaps you or others can benefit from it.
Though the example is syntactically correct, my hypothesis is that it is incorrect from a semantical point of view.
Some explanation:
I prefer to code compile time dependencies using constructor injection (like you and others already do). Runtime dependencies on the other hand are passed using method arguments.
Therefor I suggest to redesign your classes in such a way that runtimeArgument is passed to the Test() method. For me it looks like this argument is not needed at an earlier stage.
public interface IDependency { }

public class Dependency : IDependency { }

public interface IFinal
{
    void Test(int runtimeArgument);
}

public class Final : IFinal
{
    public Final(IDependency dependency) { }

    public void Test(int runtimeArgument)
    {
        Console.WriteLine($"Argument is {runtimeArgument}.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var svc = Service;
        svc.Test(42);
    }

    private static IFinal Service
    {
        get
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<Final>()
                .As<IFinal>();

            builder.RegisterType<Dependency>()
                .As<IDependency>();

            var container = builder.Build();

            using var scope = container.BeginLifetimeScope();
            {
                return scope.Resolve<IFinal>();
            }
        }
    }
}


text:
Q: Как в VestaCP отключить phppgadmin? Сканер показывает наличие критических уязвимостей на phppgadmin. Можно ли его как-то скрыть или вообще отключить? Скорее всего с отключением вряд-ли, т.к. одна из баз использует pgsql. Посоветуйте как выйти из положения? Может делать какое-то полное отключение удаленного доступа к юрл, отключая саму весту? или блокируя порт?

A: Можно закрыть доступ с помощью пароля на уровне веб-сервера.
AuthType Basic
AuthName "Private"
AuthUserFile /usr/share/phpPgAdmin/.htpasswd
Require valid-user

в файл /etc/httpd/conf.d/phppgadmin.conf где-нибудь между строками
  <Directory /usr/share/phpPgAdmin/>
  </Directory>

и сгенерируйте файл для пароля командой
htpasswd -cb /usr/share/phpPgAdmin/.htpasswd <пользователь> <пароль>

Перезапустите веб-сервер apache
systemctl restart httpd

ps: некоторые моменты (типа команды перезапуска или расположение файлов конфигурациий) могут отличаться от версий дистрибутивов.


text:
Q: How to properly login to Google Play Games services in Unity? I'm just looking for some help from someone who has expert nce working with Google Play Games Services in Unity on Android. Basically, I've got my project all set up in the Google Developer console, and using the most recent version of the Google-made plugin for Unity.
I've got my package signinf, and onstart in my game I call
Social.localUser.Authenticate((bool success) => {
    return;
});

To simply attempt a login. It appears to work but there are a few things. First, it seems to work on any account, rather than only those I've added in the developer console as testers (I'm using the debug key, currently.)
Second, it doesn't show up in my recent games in the Play Games app.
Third, it pops up with a loading screen and then seems to login every time I launch the app, I thought this would only happen once (although it never did come up with a thing asking me to sign in, just a loading screen, I figured I had just set it previously on other games to always sign right in.
And fourth, it doesn't pop-up with my Play Games level and score, like it does on other games I've downloaded from the Play Store and play, when I Start them.
Is this normal? If no, any ideas? I can provide screenshots if needed!


text:
Q: Printing values from a loop in PHP Below is a loop I have in my code. Once when the starting and ending values are a zero the loop prints a value zero (0). But what I need to do here is when the starting and ending value is zero, it should print nothing. Can someone please tell me how to change the approach?
while ($recQ = mysqli_fetch_array($runx))
{
   for($ii=$recQ['start']; $ii<=$recQ['end']; $ii++)
    {
        if (!in_array($ii, $exclude))
        {
            echo $ii.", ";
        }
    }
}

A: what about, adding an additional check to the value using empty() function:
while ($recQ = mysqli_fetch_array($runx))
{
   for($ii=$recQ['start']; $ii<=$recQ['end']; $ii++)
    {
        if (!in_array($ii, $exclude))
        {
            if (!empty($ii)) echo $ii.", ";
        }
    }
}

A: You can skip the execution of the inner loop by using continue; in the main loop:
while ($recQ = mysqli_fetch_array($runx))
{
   if ($recQ['start'] == 0 && $recQ['end'] == 0) {
       continue; // skip the rest of the code inside this loop
   }
   for($ii=$recQ['start']; $ii<=$recQ['end']; $ii++)

A: You can try a bit of a different approach:
$resulting_set = array();

while( $recQ = mysqli_fetch_array($runx) ){

    $my_set = range( $recQ['start'], $recQ['end'] );

    $resulting_set = array_merge(
        $resulting_set,
        array_diff( $my_set, $exclude )
    );

}

echo implode( ', ', $resulting_set);

The code is a bit easier to read and the result won't have the trailing comma + space you'd get from your version (Assuming you don't need it for some reason).
This is also easier to refactor because you can manipulate the array that contains the output a lot easier than outputting on the fly.
To remove 0's from the values, you could just add 0 to your $exclude array.


text:
Q: Swift get data from Firestore database error timestamp I'm trying to get data from firestore database but sometimes created_at is nil it will crash app
for another such as String type, I can set it to empty but for timestamp, I don't know how I can handle it with any help please thanks!

       COLLECTION_TM_TRANSITIONS_UAT
            .whereField("sender_name", isEqualTo: username)
//            .order(by: "created_at", descending: true)
            .addSnapshotListener { documentSnapshot, error in
            if error == nil {
                guard let value = documentSnapshot?.documents else { return }

                self.tmTransitions  += value.map { (queryDocumentSnapshot) -> TmTransition in
                    let data = queryDocumentSnapshot.data()
                    let email = data["email"] as? String ?? ""
                    let is_sender = data["is_sender"] as? Bool ?? false
                    let point = data["point"] as? Int ?? 0
                    let username = data["username"] as? String ?? ""
                    let sender_id = data["sender_id"] as? String ?? ""
                    let receiver_id = data["receiver_id"] as? String ?? ""
                    let created_at = data["created_at"] as? Timestamp
                    let sender_name = data["sender_name"] as? String ?? ""
                    let receiver_name = data["receiver_name"] as? String ?? ""
//                    print("sender_name : \(sender_name)")
//                    print("created_at : \(created_at)")
//
//
//                    let date: Date = created_at!.dateValue()
//                    formatter2.dateFormat = "MM-dd-yyyy HH:mm"

//                 let createdDate = formatter2.string(from: date)
                    return TmTransition(id: queryDocumentSnapshot.documentID, sender_id: sender_id, receiver_id: receiver_id, username: username, is_sender: is_sender, point: point, email: email,created_at: created_at,sender_name: sender_name,receiver_name: receiver_name)

                }

            }

A: Or use guard and use the datevalue():
guard let created_at = data["created_at"] as? Timestamp else {
    print("Cannot cast timestamp")
    return
}
// Then use:
print("Document date: " + created_at.dateValue())


text:
Q: Javascript: get iCheck radio value by name How to get iCheck radio value by name, like $("input[type=radio][name=test]").val()? Seems it is not working. Please see JSFiddle.
HTML

 <input type="radio" checked="" value="a" name="test"> a

 <input type="radio" value="b" name="test"> b

 <input type="radio" value="c" name="test"> c

The  is checked by $(this).val()

The  is checked by $("input[type=radio][name=test]").val()

JS
jQuery(document).ready(function ($) {

    $('input').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $('input').on('ifToggled', function (event) {

        $("#outputbythis").text($(this).val())

        $("#outputbyname").text($("input[type=radio][name=test]").val())

    });

});

A: That's because the selector will return an array.
jQuery(document).ready(function ($) {

    $('input').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $('input').on('ifToggled', function (event) {

        $("#outputbythis").text($(this).val())

        $("#outputbyname").text($("input[type=radio][name=test]:checked").val())

    });

});

this should work


text:
Q: Different servers handle TTFB vs content download differently I have a web page that shows problematic slowness. While debugging it, I have noticed that 90 to 99% of the waiting time is spent on the server after the first request (TTFB), which averages around a horrific 8s. Suspicion goes towards unoptimized queries, lots of inner and outer joins with no proper indexation etc... But this is not the question :)
I have noticed that, on the production server (running Cloudlinux on a dedi box at OVH), for the same TOTAL amount of waiting as on my development machine (Mac OS X running MAMP Pro), the distribution (and behavior) is quite different and wanted to know if anyone knows anything precise about the why:

*

*CloudLinux server: 12.22s (TTFB) + 2.61ms (Content download)

*MAMP Pro: 2.36s (TTFB) + 7.46s (Content download)
Ok, the loads are different between the two servers. But regardless, the pattern is bizarre: on Linux (Apache2 + php 7.3 + MySQL), it seems like the server prepares everything, and when everything is ready, it hands the whole thing to be downloaded, which the browser (Chrome) proceeds doing very quickly.
While on the MAMP server (Apache 2, PHP 7.3, MySQL), it looks like the browser (same Chrome) starts to download and display content even though the server is still working on the remaining of the page.
I am unsure whether this is a behavior set in PHP or Apache configuration, or is inherent to the platform difference. If anyone could point me to the right direction, that would be awesome.
Having the production server behave like my local development machine would be a first step toward making this page a little bit more usable while waiting for the refactoring that is to take place.
EDIT:
To test for PHP buffering the output, I added a .user.ini file with the line php_value output_buffering Off in an attempt to turn any buffering, well, off. This had no incidence, the page still displays when all 'work' is done, and TTFB still constitutes 99% of the total waiting time.


text:
Q: Get a List of Time Values before a (certain) Minutes from the Current time upto the Current Time in Python I need to define a function to get a [list] of str values of time from "M" minutes before the current time, up to the current time (including current time), and then check whether any of the values match the time value in the Time column of a given CSV file.
I thought of the idea for a for loop but could not figure out how to add and append the list for M no. of times (Quality of an Absolute Beginner). So, I adjusted with the following code which only supports M = 1 :
def Time_Check_Min(M= 1):
    #Check the current system time
    timestr = datetime.now()
    Check_TIMEnow = timestr.strftime("%H:%M")

    #Add 'M' min to Current Time
    Ahead_Time = (timestr + timedelta(minutes=M))
    Check_TIME = Ahead_Time.strftime("%H:%M")

    #Check if the current time is mentioned in the Dataframe
    if Check_TIME in df_.Time.values or Check_TIMEnow in df_.Time.values:
        return True
    else:
        return False

I require the output as a list in ('%H:%M') format so as to then check if any of them is present in the CSV. For Example, Taking the current system time to be '16:50' and M = 3 , then the list should contain 4 elements, like :
['16:47', '16:48', '16:49', '16:50']

Also, I thought of using the between time method since I am using pandas. But again, I do not know if this would really help.
Do I need to change my approach? If Yes, then which would be the best way to do so... and if not, HOW to get that damn list?
                    !! Thanks for your Time for these Time_Values !!

A: Not sure how you are defining your time period, but this will make a range from 25 minutes ago and test each minute in the format you need.
current_time = datetime.now()
minutes_prior =  25
start_time = current_time + timedelta(minutes=-minutes_prior))
#pd.date_range(start_time, current_time, freq="1min")

def Time_Check_Min(ttest):
    if ttest in df_.Time.values:
        return True
    else:
        return False

for t in pd.date_range(start_time, current_time, freq="1min"):
    print(t.strftime("%H:%M"))
    #Check if the current time is mentioned in the Dataframe
    Time_Check_Min(t.strftime("%H:%M"))

A: as you're using pandas we can do this with a pandas .date_range function and some handy list slicing.
from typing import Optional
import pandas as pd

def get_time_delta_range(time_value : str, M : Optional[int] = 1) -> list:
    t_range = pd.date_range(
                 '01 Jan 2020', '02 Jan 2020',freq='min')\
                 .strftime('%H:%M').tolist()

    idx = t_range.index(time_value)
    return t_range[idx -M : idx + 1]

vals = get_time_delta_range('16:50', M=3)
print(vals)

['16:47', '16:48', '16:49', '16:50']

then use isin to filter your list.
df_['Time'].isin(vals)

edit.
def get_time_delta_range(dataframe : pd.DataFrame,
                         time_value : str, M : Optional[int] = 1) -> bool:
    t_range = pd.date_range(
                 '01 Jan 2020', '02 Jan 2020',freq='min')\
                 .strftime('%H:%M').tolist()

    idx = t_range.index(time_value)
    t_range_slice = t_range[idx -M : idx + 1]
    return dataframe.isin(t_range_slice).sum().astype(bool)[0]

df = pd.DataFrame({'time' : ['16:04','16:05']})
get_time_delta_range(df,'16:04')
True

get_time_delta_range(df,'16:09')
False


text:
Q: Iterating through Array of Arrays generating unwanted output I am having issues when iterating through an array of arrays in PHP.
I have the following array, which I have posted to the page using Ajax.
Array (
[0] => Array ( [0] => T64 [1] => Array ( [name] => T64 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) )
[1] => Array ( [0] => T65 [1] => Array ( [name] => T65 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) )
[2] => Array ( [0] => T91 [1] => Array ( [name] => T91 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) ) )

I have tried to print all of the inner values using the below method, however it always prints a T (on its own line), before each desired value.
foreach($sOptions as $row => $innerArray){
  foreach($innerArray as $innerRow => $value){
    print $value['dummyA'] . "
";
    print $value['dummyB'] . "
";
    print $value['dummyC'] . "
";
  }
}

Output:
T
T
T
2
2
2
T
T
T
2
2
2
T
T
T
2
2
2
Would anyone be able to give be some incite to where these T values are coming from?

A: can you try to use only one foreach ? I haven't try this solution but you can try to do something of similar
foreach($sOptions as $row => $innerArray){
    $value = $innerArray[1]
    print $value['dummyA'] . "
";
    print $value['dummyB'] . "
";
    print $value['dummyC'] . "
";
}

A: It is obvious. You are trying to get indexed value of the actual value from second level array using a string index that does not exists.
Because any string can be accessed as an array then the non existing string index is interpreted as false so it returns first value, ie zero-index character from the string accessed as an array.
In first case the value T64 is actually accessed as array('T','6','1') so it returned T.
<?php

// simple example
// Get the first character of a string
$str = 'T64';
echo "First character is: ". $str[0] .PHP_EOL;
echo "Second character is: ". $str[1] .PHP_EOL;
echo "Third character is: ". $str[2] .PHP_EOL;

echo PHP_EOL;

echo "Applied to your code:". PHP_EOL;
$sOptions = Array ( Array ( 'T64' ) );

print_r($sOptions[0][0]['invalid string index']);

Look at the demo: https://eval.in/1063420
Output:
First character is: T
Second character is: 6
Third character is: 4

T

Note: turn on error reporting to simplify your debugging ;) How do I get PHP errors to display?
More reading about accessing strings as array in described in PHP manual Strings esspecialy Example #11 and later.

A: You can also use array_column to isolate the part you want to iterate.
foreach(array_column($arr,1) as $row => $value){
    echo $value['dummyA'] . "\n";
    echo $value['dummyB'] . "\n";
    echo $value['dummyC'] . "\n";
}

This means the code will only iterate the following:
array(3) {
  [0]=>
  array(4) {
    ["name"]=>
    string(4) "T64 "
    ["dummyA"]=>
    string(2) "2 "
    ["dummyB"]=>
    string(2) "2 "
    ["dummyC"]=>
    string(2) "2 "
  }
  [1]=>
  array(4) {
    ["name"]=>
    string(3) "T65"
    ["dummyA"]=>
    string(2) "2 "
    ["dummyB"]=>
    string(2) "2 "
    ["dummyC"]=>
    string(1) "2"
  }
  [2]=>
  array(4) {
    ["name"]=>
    string(4) "T91 "
    ["dummyA"]=>
    string(2) "2 "
    ["dummyB"]=>
    string(2) "2 "
    ["dummyC"]=>
    string(2) "2 "
  }
}

https://3v4l.org/YA6Vq


text:
Q: Android NDK: Fatal signal 11 + including the header I have a question with regards to the android ndk. Since this is my first application, I wrote an equivalent C++ application and ran it first on my computer, to make sure that there are no logical errors. I use the g++-4.6 compiler. The program ran perfectly. So I set out to write the Android couterpart, and I ran into a few problems. When I run ndk-build in the command line, the program compiles. But when I side-load the program onto my android, I get the Fatal Signal 11 (SIGSEGV) error. Here is my Android.mk file
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := com_native_method.cpp file2.cpp file3.cpp
LOCAL_C_INCLUDES := header.h
LOCAL_MODULE := com_native_method
include $(BUILD_SHARED_LIBRARY)

I learned android development through youtube and online forums, and I understand that you have to use equivalent types (jint, jdouble, ... etc). But when I run ndk-build in such a case, I notice that I get errors telling me that jint and jdouble are not defined in file2.cpp and file3.cpp, so I changed them back to int, double, while keeping the types in com_native_method.cpp as jdouble and jint. I really can't figure out the problem.
Would appreciate the help,
Thanks,
naxchange


text:
Q: Why do I get a syntax error using the ternary operator? I wrote an if-then-else program, but when changing the code to use the ternary operator I am getting a syntax error and cannot figure out why it will not work:
def are_you_over_21
  puts"How old are you?"
  age = gets.chomp.to_i
  age>=21 ? puts"You're over 21!" : puts"You're too young."
end

are_you_over_21

A: Try this:
age>=21 ? puts("You're over 21!") : puts("You're too young.")

The ternary operator gets confused when the given options have function calls without the parenthesis.
You can also do this:
puts age>=21 ? "You're over 21!" : "You're too young."

A: You'll have to think about the Ruby parser.
This will work fine:
age >= 21 ? puts("You're over 21!") : puts("You're too young.")

The reason is that if you use the puts method without brackets, the parser doesn't understand the : token that comes afterwards; it doesn't realise that it is associated with the ternary operator earlier. You can also do this:
puts age >= 21 ? "You're over 21!" : "You're too young."

This is fine -- the parser doesn't run into any ambiguities here.
You can also do this:
puts "You're #{ age >= 21 ? 'over 21!' : 'too young.' }"

Here's why the ambiguity happens. Let's say you have two functions, x and a, like this:
2.0.0-p195 :033 > def x(y)
2.0.0-p195 :034?>   y + 1
2.0.0-p195 :035?>   end
 => nil
2.0.0-p195 :036 > def a(b)
2.0.0-p195 :037?>   b + 2
2.0.0-p195 :038?>   end
 => nil

The brackets don't make a difference here:
2.0.0-p195 :039 > x a 1
 => 4
2.0.0-p195 :040 > x a(1)
 => 4
2.0.0-p195 :041 > x(a(1))
 => 4
2.0.0-p195 :042 > x(a 1)
 => 4

But if x could take more than one parameter? Now you have to help the parser out:
2.0.0-p195 :043 > def x(y, z)
2.0.0-p195 :044?>   y + z + 1
2.0.0-p195 :045?>   end

Let's make a call without brackets like before:
2.0.0-p195 :047 > x a 1, 2

Are you passing a(1), 2 to x, or are you trying to call a(1, 2) and pass the result to x? By convention Ruby assumes you are trying to call a(1, 2), but a only takes one argument, so you get an error:
ArgumentError: wrong number of arguments (2 for 1)
  from (irb):36:in `a'

So you need brackets:
2.0.0-p195 :052 > x a(1), 2
 => 6

A: Better than doing the unconditional puts in the ternary, which is a conditional statement, why not puts the result of the ternary?
def are_you_over_21
  puts"How old are you?"
  age = gets.to_i
  age >= 21 ? "You're over 21!" : "You're too young."
end

puts are_you_over_21

Also, it isn't an error, but the nature of a number (Integer in your case) means that it will never need a chomp, as numbers do not have new lines.  You never need to use chomp.to_i or chomp.to_f.
Notice that the method now returns an instance of String, rather than nil.  It can now be used as you would like, in this case, using puts to display to the terminal.
Spaces around the comparison operator makes it easier to read.
The method itself may as well not be a method if you are going to prompt, get data, and report.  You would be doing just as well to remove the method definition and just have this as running code.
I have refactored this to be that way:
def are_you_over_21(age)
  age >= 21 ? "You're over 21!" : "You're too young."
end

[18, 20, 21, 22, 100].each do |age|
  puts are_you_over_21(age)
end

# >> You're too young.
# >> You're too young.
# >> You're over 21!
# >> You're over 21!
# >> You're over 21!

Hope that helps.


text:
Q: Can RemoteObjects be used with Granites´s Tide to enable Lazy Loading? We have a Spring+Hibernate+Mysql+Flex/Cairngorm(2)/BlazeDS application. We need to update this application so it can scale better, specifically we need to use the lazy loading feature. So we decided to migrate from BlazeDS to Granite Data Service. We have:
1.- Added the ant gas3 generation tool task for automatic synchronization between domain objects
2.- We have a working application that loads the first level of our graphs, but not deeper objects of the graph.
Our flex project uses RemoteObjects. I understand that to be able to use Lazy Loading we need tide. To use tide api, we would need to change a bunch of code. My question is, can I use RemoteObjects and Tide so I can get Lazy Loading without changing our Flex code, just the configuration files ?

A: No, it is not possible. You need Tide to manage your entities (it has its own cache which ensures that an already known entity is not duplicated in memory) and the lazy-loading (to produce custom queries thanks to the Tide Remote layer to fetch data from the backend) and you need on the server-side a java framework for IOC (Spring, Seam, Guice...) and of course a persistent framework (Hibernate, EJB3...).
Or you can fork granite code to roll your own solution... Not that easy.


text:
Q: node package which support function serialization? I am looking for a serialization library for node.js
JS object is natively serializable by JSON, except functions. Anyway I need also serialization of functions too. This is not to interchange data. I just want to store my program wrote in node REPL as an image form. (you can imagine Smalltalk image)
So what I need is very robust function serialization implementation. Functions should be stored in source code form.
What kind of package can I use for this purpose? Or should I roll one myself?

A: Calling toString on the function will give you valid source code for the function. It may not be the original source code (comments removed for example). You can't solve the problem of closure state being lost, so your function cannot reference any variables it doesn't define itself or are defined as arguments. You can recreate the function using new Function(str)


text:
Q: Cant find whats taking up space on my computer It says my c drive is almost full, but i dont know were they are located, help??

A: You are using WizTree, which is helpful in this case. Go to the 2nd tab to see largest sizes for files and folders. At the top, there is a dropdown menu to limit the amount of results to 100.000, 10.000, 1.000, 100 or all. Set this to 100 and read through the list to see what is taking up.
According to your hard-to-read screenshot, your program files (x86) folder is stuffed with programs that are taking up space.

A: It's strange how it doesn't look much on the usage bar, but it all adds up.

Program Files (x86) : 130 GB
  Windows : 23 GB
  Users : 15.5 GB
  ProgramFiles : 11 GB
  SysVol : 8 GB
  Games : 7 GB
  Recovery : 4 GB
  ProgramData : 4 GB

Believe it or not, that's already 202.5 GB and we've not counted everything
None of it is particularly notable except the 130GB in Program files (x86). It's definitely worth expanding that part of the tree to see the subfolders within that are taking up space

A: You can try to press Win + R and type "cleanmgr". That will clean up all Windows Update Temp files etc.


text:
Q: How to maximize the result of multiplying lengths of the two strings without common characters Given a list of words, find two strings S and T such that:

*

*S and T have no common character

*S.length() * T.length() is maximized

My approach is, building bitmap for each string first and tries to find the maximum multiply. Can you give me a better algorithm with time complexity less then O(n2)?
public class biggest_multiply {
    int biggest(String[] array){
        if(array==null||array.length<=1)
            return 0;
        class bitMap{
            int bit;
            String s;
        }
        bitMap[] bm=new bitMap[array.length];
        for(int i=0;i<array.length;i++){
            bm[i]=new bitMap();
            for(int j=0;j<array[i].length();j++)
                bm[i].bit=bm[i].bit|(1<<(array[i].charAt(j)-'a'));
            bm[i].s=array[i];
        }
        int maximum=0;
        for(int i=0;i<array.length;i++){
            for(int j=i+1;j<array.length;j++)
                if((bm[i].bit&bm[j].bit)==0)
                    maximum=Math.max(maximum, bm[i].s.length()*bm[j].s.length());
        }
        return maximum;
    }
    public static void main(String[] args){
        System.out.println(new biggest_multiply().biggest(new String[]{"aa","aabb","bb","cc"}));
    }
}

A: Sort the words by word.length() descending, so short circuit can be done to speed up. But still O(n^2).
if (bm[i].s.length() * bm[j].s.length() <= max)
    break;

if ((bm[i].bit & bm[j].bit)==0) {
    maximum=Math.max(maximum, bm[i].s.length()*bm[j].s.length());
    break;
}

A: A straight forward solution is to try every possible match of words in S & T. The runtime would be O(n*m), where n is the number of words and m is the size of a word.
A better way is to pre-compute the character map in each word and the size before our iteration. The runtime would reduce to O(n).


text:
Q: field accepts everything! How to restrict the data types accepted by the field? I have a bug my student ID field accepts  everything, including strings, it should accept only integers how can I fix this bug, so I dont really know how to restrict the data type that is accepted by the field student ID. Is there an API or sth that could be used?
This is HTML CODE:

   <!DOCTYPE HTML>

          <form>

              Waiting list for classes

              <form>
                First Name
                <input type="text" name="first ">

                Last Name
                <input type="text" name="last ">

                Student ID number
                <input type="text" name="last ">

                E-mail:
                <input type="email" name="email">

              Phone number:
              <input type="text" name="Phone">

              Which course's waiting list would you like to join?
              <select>
                <option value="Visa">
                  CSE 430
                </option>
                <option value="American express">
                  CSE 328
                </option>
                <option value="Discover">
                  CSE 456
                </option>
                <option value="MasterCard">
                  CSE 786
                </option>
                <option value="American express">
                  CSE 987
                </option>
                <option value="Discover">
                  CSE 775
                </option>
                <option value="MasterCard">
                  CSE 342
                </option>
                <option value="American express">
                  CSE 222
                </option>
                <option value="Discover">
                  CSE 134
                </option>
                <option value="MasterCard">
                  CSE 364
                </option>
              </select>

            Have you ever been on a course's waiting list?

          <input type="radio" name="Phone" value="no" id="phone_no"/>
          YES

          <input type="radio" name="Phone" value="yes" id="phone_yes"/>
          NO, this is the first time

          <button onclick="myFunction()">
            Submit Request
          </button>

        </form>

        </form>

A: HTML
Student Id : <input type="text" id="student_id" />

jQuery
$("#student_id").keypress(function (e) {
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)){
               return false;
    }
   });

This code will allow only integer number in student_id field.
Demo

A: To only accept a number, you can use some new features that come with HTML5.
<input type="number" step="1">

Or
<input type="text" pattern="\d+">

Or you can use jQuery, as stated in other answer. But keep in mind that none of these ways is foolproof. A client can always modify HTML/JavaScript in Developer Tools. So, you still need to validate the data on the server.


text:
Q: Azure databricks CI CD pipeline to delete notebooks on production I have a CI/CD pipeline in place to deploy notebooks from dev to production in an Azure databricks workspace.
However, it is not deleting the notebooks from production, when those notebooks have been removed from development and are no longer in Azure git repository.
I want to delete all notebooks which have been removed from source, as a part of build/release process.
Is there a way to achieve this?

A: The easiest way is when there are new commits in Azure DevOps git repository, you could redeploy the notebooks by checked the Clean Workspace Folderoption:

Otherwise, you could add a powershell script task to compare files in two folders. The follow case may give you a start: Comparing folders and content with PowerShell


text:
Q: How to validate date coming in many format I want to create a function to check the date date can be in many format as given below.

Here 02=Month, 2020 and 20= Year and other are dates
function validateDate($date, $format = 'Y-m-d')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

ob_end_clean();

header('Content-Type: text/csv; charset=utf-8');

header('Content-Disposition: attachment;
filename=attendance_upload_csv'.time().'.csv');

header("Pragma: no-cache");

header("Expires: 0");
$file = fopen('php://output', 'w');
$fieldArr['field_name']['agent_user_name']          = 'Agent User Name';
$fieldArr['field_name']['date_of_violation']        = 'Date Of Violation';

fputcsv($file, $fieldArr['field_name']);

fclose($file);

problem is its not validating all dates, please advise.
Thanks in advance

A: If you're letting the user put whatever they like in the incoming CSV file, that's a bad idea. Since the data input process is out of your direct control, you need to set some rules and expectations instead, which are then enforced by the PHP when it checks the uploaded file.
Issue instructions which tell the user they must input the date in one single format (of your choosing, preferably an unambiguous one such as Y-m-d, so no-one can be in any doubt what the data means when they enter it). If they don't do that, you reject the file. Simple, problem solved.
Your code cannot guess the user's intentions or what they will type. So the solution is to tell them exactly what is required, and then reject anything which doesn't conform to your specification.


text:
Q: error accessing transactional temp table in Oracle 12c I am running into an issue running some UTPL/SQL unit tests in 12c. The environment we have set up runs the tests against an 11g and 12c server and the same unit tests that are passing in 11g are failing in 12c.
The code I am able to provide is limited due to obvious security concerns, but I think just the general description of the problem will be enough. The problems appears to be with the calling functions which are autonomous transactions. This call is basically just adding data to several tables and creating a new product.So it's set up to commit if successful and rollback all product creation when a failure occurs. it does call nested functions that are also autonomous transactions. The problem is when running this in 12c we get:
ORA-14450: attempt to access a transactional temp table already in use

Not sure why this is suddenly a problem in 12c. Has anyone else run unto this? Any help or suggestions is appreciated.


text: Q: How to know weather request in new or old in play 2.x framework? In play 1.x framework, there is a method under play.mvc.Http.Request class isNew(), which identifies whether the request is new or old. In play 2.x there is no such method available. Can anyone tell the alternative for isNew method for the above task?


text:
Q: Is it possible to change default behavior for "top"? For example, when I run top I usually press "C" so I can see the explicit command being run not the executable name if you will.
Is there a way I can modify top such that when I do:
% top

The result is initially displaying the command line and not the executable command?
For example I see initially:
chromium-browser

But would prefer to see:
/usr/lib64/chromium-browser/chromium-browser --type=plugin --plugin-pat

A: It depends on the version of top, but after pressing the "c", press "W" which will save your preferences in your ~/.toprc file.

A: In addition to an excellent answer of @Kevin,
I want to state that some settings can be passed to top from a command line.
So, the problem in question can be solved with a simple aliasing.
For example my alias for top is:
alias top='top -u <my_user_name> -c'


text:
Q: AVAudioPlayer resume from background but pause for other apps My audio starts and stops as I would expect. When I background the app the music keeps playing, if I activate Siri, the music interrupts but then resumes as I would expect.
The issue I have is that, if my sounds are playing in the background, and I start up Apple Music or Podcasts, the audio mixes together which I don't want however if I use Siri, my audio stops then resumes after.
I want my music to stop and the other to take control of the audio just like it does with Siri. I have tried removing .mixWithOthers but when I do that, it seems that once I background my app and I start Siri, afterwards my audio is no longer able to start again even though the code within the .ended case is called.
func commonInit() {
        try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
        NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption), name: .AVAudioSessionInterruption, object: nil)
    }

    var shouldResume: Bool = false

    @objc func handleInterruption(_ notification: Notification) {
        guard let info = notification.userInfo,
              let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
              let type = AVAudioSessionInterruptionType(rawValue: typeValue)
        else { return }

        switch type {
        case .began:
            player?.pause()
        case .ended:
            guard let optionsValue = info[AVAudioSessionInterruptionOptionKey] as? UInt
                else { return }
            let options = AVAudioSessionInterruptionOptions(rawValue: optionsValue)

            if options.contains(.shouldResume) {
                player?.play()
            }
        }
    }

Ideally I want my app to resume after any interruptions, but I also want my app to stop playing if there are any interruptions.
Thanks

A: Adding UIApplication.shared.beginReceivingRemoteControlEvents() after setting the category fixed this issue but I'm not sure why.


text:
Q: How can I remove the "GNOME desktop environment" entry from my login screen after uninstalling GNOME? I installed The GNOME Desktop Environment, with extra components, but I didn't like it, so I uninstalled it. But now at the login screen, besides the password box there's still the button to choose Unity, Gnome and Gnome basic or something like that. How can I completely remove it?

A: I remember reading somewhere that (sudo) deleting what you don't need from /usr/share/xsessions will clean up your login screen. While the titles of the .desktop files are quite explanatory, you could make sure by viewing their contents in a text editor. Just to be safe, copy those .desktop files elsewhere first!
See How can I use LightDM for user-defined sessions? for more.


text:
Q: angularJS can't get scope.data in directive? I use directive in html, I send ajax with $http in directive'link, then I console.log(scope.data), ther is undefined in console of chrome
this is my code
  todoApp.directive('planProgress', function($http) {
    return {
      scope: false,
      link: function(scope, elem, attrs) {
        $http.get('get_default_data', {
          params: {
            'type': 'day'
          }
        }).then(function(data) {
          scope.data = data.data;
        });
        console.log(scope.data);
        elem.progress();
      }
    };
  });

I console.log(scope.data) It's undefined But, there is data attr in scope,
how can I get data in scope?

A: Print console.log inside .then. Since $http is async. JS won't wait for it to complete and executes the next line, hence you get it as undefined
.then(function(data) {
          scope.data = data.data;
          console.log(scope.data);
        });

A: breaking down your link function
    $http.get('get_default_data', {
      params: {
        'type': 'day'
      }
    }).then(function(data) {
      scope.data = data.data;
    });

    console.log(scope.data);
    elem.progress();

You can see, that the console.log is run directly, while the http call is deferred. Therefore, it will log "undefined" and when the call returns scope.data will have a value.
If you want to see what is retrieved, put the 'console.log' into the then.
But in your template you can just access {{data}} and it will be there.

A: $http is asynchronous method so ur console would run before then ,so try add inside your then block because then block always run after successful completion of your response
Try this ,you will understand why it is logging correct value
todoApp.directive('planProgress', function($http) {
    return {
      scope: false,
      link: function(scope, elem, attrs) {
        $http.get('get_default_data', {
          params: {
            'type': 'day'
          }
        }).then(function(data) {
          scope.data = data.data;
        console.log(scope.data);
        });

        elem.progress();
      }
    };
  });


text:
Q: the min and the max in raster calculator Arcgis 10.1 Can you help me where I can find or how to calculate the minimum and maximum with raster calculator in arcgis 10.1

A: you can use zonal statistics as table tools to extract the min and max. Just make sure that the zone has the size of your raster.
You can also use the calculate statistics tool followed with the "get raster properties" tool (note that calculate statistics may not be necessary because it is often computed when you add the data)
EDIT: for min and max per pixel and for a set of raster, you can use Cell Statistics. Note that min and max can also be used in map algebra with Python.

A: You could also use "Con" as a work around. For example if you have Raster_A and Raster_B and interested to find the minimum of two, for the formula use:
Con("Rater_A" > "Raster_B", "Raster_B", "Raster_A")

You could use this method to expand it with any complicated equation or formula. For example you could easily implement this relationship:
Raster_Factor = Min(0.7, Max(0.3, 0.4* Raster_A + 0.2355))

By using this formula:
Con((0.4 * "Raster_A" * + 0.2355) > 0.7, 0.7, Con((0.4 * "Raster_A" + 0.2355)< 0.3, 0.3 , (0.4 * "Raster_A" + 0.2355)))


text:
Q: How to fill an int array with random values from a range with exactly one duplicate for each value? I am trying to create a memory match game using JFrame. I am using a folder that contains .png files (country flags) which will populate a String array using the following code:
public String[] listPngFiles(String filePath) {
    File[] fileReader = fileReader(filePath);
    String[] files = new String[fileReader.length];

    for(int i=0; i<files.length; i++)
        files[i] = "" + fileReader[i];

    arraySize = files.length;
    return files;
}

public File[] fileReader(String filePath) {
    File folder = new File(filePath);
    return folder.listFiles (new FilenameFilter() {
        public boolean accept(File filePath, String filename)
        { return filename.endsWith(".png"); }
    });
}

The reason I am doing is because I want to create a dynamic JButton array that holds each flag in a random sequence, twice. The flags have to re-shuffled every time the program is executed.
This is the code I am currently working on:
int[] flags = new int[arraySize*2];

for (int i=0; i<flags.length; i++){
    flags[i] = -1; // -1 represents "no flag"

    for (int r=0; r<2; r++)
    {
        int pos=0;
        do
        {
            pos = randomize();
            flags[pos] = i; // put the flag into the card at the available position
            }
            while (flags[pos] != -1); // if card[pos] is not -1, it already has a flag in it
        }
    }

Your help on the matter is greatly appreciated.

A: A optimal solution would be to:
Run a loop, add a number twice
Shuffle the array
public static List<Integer> shuffleImages(int numOfPhotos)
{
    List<Integer> list = new ArrayList<>();
    for(int i = 0; i < numOfPhotos; ++i)
    {
     list.add(i);
     list.add(i);
    }
    Collections.shuffle(list);
    System.out.println(list);
    return list;
}

EveryTime you create a new game shuffle the list.
do
{
  List<Integer> list = shuffleImages(10);
  JButton []buttons = new JButton();// assuming this is your array of buttons
  for(int i = 0; i < list.size(); ++i)
  {
    buttons[i].setIcon(new ImageIcon(files[list.get(i)]));//set your background of your buttons
  }
  playGame();
}while();//exit conditon

A: Here is one way to achieve this using a list, a HashMap and two arrays.

*

*Fill an array with random numbers without duplicates.

*Create a second array twice the size of the first one.

*Enter the values of the first array using the HashMap to test the duplicates.

public static void main(String[] args) throws InterruptedException {
    Random r = new Random();
    int[] randoms = new int[5];
    List repeated = new ArrayList();
    int range = 5;

    // This will fill in a first array with unique randoms.
    for (int i = 0 ; i < randoms.length ; i++){
        int rand;
        do{
            rand = r.nextInt(range) + 1;
        }while(repeated.contains(rand));
        repeated.add(rand);
        randoms[i] = rand;
    }

    System.out.println(Arrays.toString(randoms)); // Prints : [2, 3, 5, 1, 4]

    // This will fill the second array with duplicates at random places.
    int[] finalArray = new int[randoms.length * 2];
    HashMap<Integer, Integer> intint = new HashMap<>();
    for (int i = 0 ; i < finalArray.length ; i++){
        int whichOne;
        do{
            whichOne = randoms[r.nextInt(randoms.length)];
            //Thread.sleep(1000);
        }while(intint.get(whichOne) != null && intint.get(whichOne) > 1);
        if (intint.containsKey(whichOne)) intint.replace(whichOne, 2);
        else intint.put(whichOne, 1);
        finalArray[i] = whichOne;
    }

    System.out.println(Arrays.toString(finalArray)); // Prints : [4, 3, 4, 2, 3, 2, 5, 5, 1, 1]

}


text:
Q: UITableViewCell delete button gets covered up UPDATE:
Thanks to information from "Evgeny S" I've been able to determine that what is covering up the delete button is the cell background. I had the following function called at the beginning of cell init:
- (void) setupGradientsWithHeight:(int) the_height
{
    CAGradientLayer* gradient = [CAGradientLayer layer];

    gradient.frame  = CGRectMake(self.bounds.origin.x,
                                 self.bounds.origin.y,
                                 self.bounds.size.width,
                                 the_height);

    gradient.colors = [NSArray arrayWithObjects:
                       (id)[UIColor colorWithRed:218.0f/255.0f
                                           green:218.0f/255.0f
                                            blue:220.0f/255.0f
                                           alpha:1.0].CGColor,
                       (id)[UIColor colorWithRed:180.0f/255.0f
                                           green:180.0f/255.0f
                                            blue:184.0f/255.0f
                                           alpha:1.0].CGColor,nil];

    UIView* bgview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];

    [bgview.layer addSublayer:gradient];
    [self setBackgroundView:bgview];
}

The problem is solved by NOT adding the backgroundview. However, I'm wondering how it might be solved while preserving the gradient background for each cell?
One of two things could be happening. When the delete button appears the background view is either being shifted and then back - or its size is being decreased and then back.
I tried messing with the width component "self.bounds.size.width" for the gradient frame but I still don't see how that could be affecting things because this function is only called once at cell initialization.
ORIGINAL POST:
I had created an App in Xcode4 under iOS6 SDK - but after loading things up in the new environment (Xcode5 and iOS7 SDK) I ran into a problem. Note that I have resolved all build errors and warnings that came up when making the transition.
I have a tableview with some cells. After entering edit mode, if one clicks the red toggle button to initiate delete mode for a cell - the animation begins and the "Delete" button appears - but only briefly and is then suddenly re-hidden.
Another strange thing I should note is that even while the delete button is covered up - you can still click where it should be and delete the cell.
I've tried to take out as much of my "custom code" as possible, I've removed functions that I had overridden and tried to take things back to an original state as possible - but to no avail.
At one point I had seen a strange message in the output log:
"attempting to set a swipe to delete cell when we already have one....that doesn't seem good". For some reason the message is on longer appearing and I can't seem to remember what I was doing at the time.
Any thoughts or recommendations on what might be causing this?
http://www.youtube.com/watch?v=vCAGzSaOwp4

A: - (void)layoutSubviews
{
    [super layoutSubviews];
    [self sendSubviewToBack:self.contentView];
}

A: You can use the colorWithPatternImage but for me it was easier to use the self.layer.content.
for example :
cell.layer.contents = (id)[UIImage imageNamed:@"singleRow.png"].CGImage;

That way the image don't get stretched and it doesn't have to be in exact size.
That way the delete button doesn't get covered up by the cell background image.
By The Way: these custom gradient backgrounds don't seem to match up with the iOS 7 basic appearances, do you think that could be a grounds for not approving the app?

A: I was facing an issue where my UITableView was in editing mode and after deleting 2-3 rows I get message "attempting to set a swipe to delete cell when we already have one....that doesn't seem good" logged and then user Interaction on all cells except one cell gets disabled.
I solved this issue by
[myTableView setEditing:NO animated:NO];
[myTableView setEditing:YES animated:NO];

after each deletion.
This workaround worked in my case.

A: I fixed this by finding the delete button view and bringing it to the front. I did this in layoutSubviews in a UITableViewCell subclass.
Here's a small bit of code that should give you an idea of how to do it:
- (void)layoutSubviews
{
    [super layoutSubviews];

    for (UIView *subview in self.subviews) {

        for (UIView *subview2 in subview.subviews) {

            if ([NSStringFromClass([subview2 class]) isEqualToString:@"UITableViewCellDeleteConfirmationView"]) { // move delete confirmation view

            [subview bringSubviewToFront:subview2];

        }
    }
}

A: This is one of countless bugs in iOS 7.
For some reason the backgroundView is moved by iOS over the delete button.
You can work-around this by subclassing your backgroundView and implementing the setFrame function of your derived view like this:
- (void)setFrame:(CGRect)frame
{
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending) {
        // background view covers delete button on iOS 7 !?!
        [super setFrame:CGRectMake(0, frame.origin.y, frame.size.width, frame.size.height)];
    } else {
        [super setFrame:frame];
    }
}

As a side note: you can avoid the need for a separate sublayer by subclassing and implementing layerClass in your derived view:
+ (Class)layerClass
{
    return [CAGradientLayer class];
}

A: You can avoid the problem by setting background you want for the uitableview and setting  cell.backgroudColor = [UIColor clearColor]; and cell.contentView.backgroundColor = [UIColor clearColor];

A: I've run into a similar problem and have a work around the that puts the Delete button on top of my cell content but the animation is a bit ugly. When done the button is visible and does the right thing.
Create a custom subclass of UITableViewCell and add the following code:
-(void)didTransitionToState:(UITableViewCellStateMask)state
{
    if (state & UITableViewCellStateShowingDeleteConfirmationMask ) {
        [self sendSubviewToBack:self.contentView];

    }

    [super didTransitionToState:state];
}

Improvements on this approach or other pointers would be appreciated.

A: Cleaner, General Solution
Assuming an iOS7 only app, with a technique similar to that posted by chris above, I believe the approach here: https://stackoverflow.com/a/19416870/535054 is going to be cleaner.
In this approach, you don't need to subclass your backgroundView, which could be different for different cells.
Place the code in the answer I've linked to above, in the root of your custom table cell hierarchy, and all of your table cells (that inherit from it), get the fix whenever they use the backgroundView or selectedBackgroundView properties.

A: I'm still seeing this problem after updating to XCode 5.0.1 but I've used a different workaround which is to use a boolean named changeTitle set to NO in willBeginEditingRowAtIndexPath and set to YES in editingStyleForRowAtIndexPath if we're not in row deletion mode.
Then I use that variable to pad the button title with some extra spaces in titleForDeleteConfirmationButtonForRowAtIndexPath.
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && changeTitle) {
        return @"        Delete";
    }
    return @"Delete";
}

It works for me but the main drawback is that the confirmation area is wider than you think it is so an unintentional delete is possible.

A: If you have project started in iOS 6 SDK and use storyboards, this might be the issue with constraints. Try deleting all of cells constraints and fall back to suggested. This could resolve issues with delete button. I had such problems in two different projects and they were resolved described way.

A: And one more workaround:
- (void) layoutSubviews {
    [super layoutSubviews];

    if ([ [ [UIDevice currentDevice] systemVersion] compare: @"7.0" options: NSNumericSearch] != NSOrderedAscending) {
        if (iOS7 == YES) {
            self.backgroundView.frame = CGRectMake(0, self.backgroundView.frame.origin.y,
                                                   self.backgroundView.frame.size.width, self.backgroundView.frame.size.height);
    }
}

A: here is a better way just make sure you subclass UITableviewController for better performance and add this code
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

[super setEditing:editing animated:animated];

CGRect frame = self.tableView.frame;

if(editing){
    [self.tableView setFrame:CGRectMake(0, frame.origin.y, frame.size.width, frame.size.height)];
    //other codes to run if needed
}else{
    [self.tableView setFrame:frame];
    //other codes to run if needed
}

}


text:
Q: UIButton query in swift IOS I have a button which is set at 62,62 square.
I have an image which is 40,40 square.
I want the image in the button (which is easy and done), but I want it at the top of the button frame and I want some text at the bottom. So it looks like this :

Any idea how to do this in swift ?
I have got so far :
button.backgroundColor = UIColor(red: 0.13, green: 0.48, blue: 0.81, alpha: 1.0)
button.tag = i
button.imageView?.image
button.setImage(image, forState: .Normal)
button.setTitle("Test", forState: UIControlState.Normal)

The test setTitle, comes to the right of the image as ... form.
Anyone can advise ?

A: Using the interface builder;

*

*set the image to the Background property of the button. Using code it is button.setBackgroundImage

*from Control section set the horizontal alignment of the text to Bottom. Using code it is
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentBottom


text:
Q: GCP CloudBuild Logs How can I add a custom message to Cloud Build logs?
I've tried using the bash entrypoint with the Docker builder (for example) and echoing some strings, but they don't appear in the build logs. Is there a way to achieve this?

A: Make sure that the builder image you're using has bash in it. I tested this code and replaced the gcloud builder with docker and it is working fine. Here's an example code:
steps:
- name: 'gcr.io/cloud-builders/docker'
  entrypoint: 'bash'
  args:
  - '-eEuo'
  - 'pipefail'
  - '-c'
  - |-
    if (( $(date '+%-e') % 2 )); then
      echo "today is an odd day"
    else
      echo "today is an odd day, with an even number"
    fi

And here's the Logs:


text:
Q: I'm trying to exploit xen hypervisor for studying I am studying xen hypervisor and want to exploit it.
I followed ubuntu community (https://help.ubuntu.com/community/Xen).
Host OS is ubuntu 14.04 LTS and guest OS is centOS 6.7 minimal, and I use 4.4.2 xen.
I succeeded in following above steps and operating guest OS.
Then, I selected vulnerablity for CVE-2015-3456 (VENOM) because it is quite popular. I thought It was good to start. According to venom, qemu is vulnerable and xen uses qemu for HVM guest.
I got POC code below. But it didn't work even though I tried some ways.
#include <sys/io.h>
#define FIFO 0x3f5
int main() {
    int i;
    iopl(3);
    outb(0x0a,0x3f5); /* READ ID */
    for (i=0;i<10000000;i++)
            outb(0x42,0x3f5); /* push */
}

screenshot
Now, I guess this vulnerability may have been already patched and I installed patched xen.
If I think right way, is there way to get unpatched xen and make environment that I want? I'm very appreciate it if you give some advice.


text:
Q: Find the best linear unbiased estimate
I don't even know how to approach this problem ?
Why are two different models given and how do I interpret the covariance matrix?

A: Let $\beta = \left[ {\begin{array}{cc}
   \beta_{11} & \beta_{12} & \beta_{21} & \beta_{22} \end{array} } \right]'$
Re-write the model as
$$\left[ {\begin{array}{cc}
   y_1\\y_2 \end{array} } \right] = \left[ {\begin{array}{cc}
   x_1 & x_2 & 0 & 0 \\ 0 & 0 & x_3 &x_4\end{array} } \right] \beta + \left[ {\begin{array}{cc}
   \epsilon_1\\ \epsilon_2 \end{array} } \right]$$
Let $z=y_2-y_1$ we have
$$\left[ {\begin{array}{cc}
   y_1\\z \end{array} } \right] = \left[ {\begin{array}{cc}
   y_1\\y_2-y_1 \end{array} } \right] = \left[ {\begin{array}{cc}
   x_1 & x_2 & 0 & 0 \\ -x_1 & -x_2 & x_3 &x_4\end{array} } \right] \beta + \left[ {\begin{array}{cc}
   \epsilon_1\\ \epsilon_2 \end{array} } \right]$$
Then $$Cov(y_1,z) = \sigma^2I_2$$
The question becomes (common) linear model
$$Y=X\beta+\epsilon$$
The BLUE (best linear unbiased estimate) of $\beta$ is $\hat\beta = (X'X)^{-1}X'Y$.
Need to construct $X'X$ and $X'Y$ from given sum of square and sum of the cross product.
Generally, for a multivariate linear model, if you can find $A$ such that $Var(AY) = I\sigma^2$, then the multivariate linear can be convert into univariate linear model.


text:
Q: Ios client application needs to add a new client to a twilio conference call dynamically I'm facing a problem with add new member's to a conference call. I have a php server, and ios app as a client. And a twilio system of agents and clients.
Once an agent and client are connected into a conference call, they talk and everything is ok here.
But, there's an option where a client by using his ios app wants to add a new member to the conference call. The new member can be someone a client knows and when he presses in the app a button(+) while in conference with agent, i must catch that phone number on the server route /addNewMember and then i can do this
function addNewMember($addNewMembNumber){
   ...
   $call = $client->account->calls->create(
      $twilioNumber,
      $addNewMembNumber,
      "SOME TWIML CODE",
      array()
   );

}
I can call the client(member) and add him to the conference call. But how can I do this in ios app.
So my question is how can I pass the phone number to my server route while in a call with agent?


text:
Q: Is this even possible to create with a FSM? I have a question that asks me to create  a finite state machine where it only accepts strings that end with a 1000 the issue is, I don't think this is possible because how can the FSM know when the string ends? or am I missing something?

A: The FSM should just be in a terminal state after it sees 1000, switching to a non-terminal state on additional input.


text:
Q: Possible to use Bluetooth headset in Stereo mode with Mic? Okay, so I have this bluetooth headset (it's a Skullcandy Hesh 2 Wireless). I want to use it with my PC which is running Windows 8.1. I can pair it just fine. After pairing it adds three devices under the "Sound" setting window: Hesh 2 Wireless Stereo (corresponding to the Audio Sink service) and Hesh 2 Wireless Hands-Free (one for audio out, the other for audio in). This is where I run into my problem.
The stereo output is awesome for listening to songs, in game sounds and music, watching movies, etc. What I want is the capability to do all of those things while using the built in mic to talk to my friends over Skype or Steam. I cannot find a way to do that. Whenever the mic is active any sound output to the Stereo part just stops. From what I can tell, Windows suspends the stereo part and lets the hands-free part do its thing until I stop talking.
What I'm wondering is: Is this even possible? The headset has a 3.5mm wire as well for those times when the battery is low. Using that wire everything works flawlessly.

A: Your headset needs to support aptX (https://www.aptx.com/products). This is a limitation of the bluetooth A2DP profile. Without aptX, it will not be able to receive hifi stereo sound one way while sending microphone audio the other way.
And no, contrary to some information floating around in various forums you cannot make this work via playing with Windows mixer settings or downloading some application. This is why most gaming headsets that do support two-way audio in stereo quality don't use bluetooth but a proprietary wireless protocol with their own little USB dongle.
EDIT: User "Horn OK Please" below is correct that aptX alone unfortunately is no guarantee of this working! You can get aptX headsets that nonetheless suffer from the same limitation!


text:
Q: JScrollPane adjustmentListener and scrollRectToVisible I need to handle event from JScrollPane when user scrolls it. In here it is suggested to use addAdjustmentListener to either JViewport or Vertical/HorizontalScrollBar.
Is there any difference, which method should I choose?
I would like also to use scrollRectToVisible for the same JScrollPane, should I anticipate AdjustmentListener working for this method?
Also I wonder whether scrollRectToVisible tries to do minimum scrolling to make required rectangular visible or it tries to make it visible in the middle of JViewport ?
UPD: Requirements:
1) There a JScrollPane with one JPanel which has many JLabel(ImageIcon), so some of them are not visible.
2) When a network event comes I need to show one of JLabel (make it visible) to user. If I is not visible originally then JScrollPane should scroll automatically. That's why I mention scrollRectToVisible.
3) Above that JLabel with ImageIcon inside I need to show a message which would explain what has happened to this element. The message currently is implemented as another JLabel with floats thanks to JLayeredPane much higher in hierarchy. The problem now is that if user scrolls JScrollPane that floating JLabel should move accordingly to be on top of correponding JLabel(ImageIcon).
UDP2: SSCCE
I have not implemented floating JLabel yet, but already I don't like how label with index 11 reacts to scrollRectToVisible since it is half cropped.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class JScrollPaneTest {
    protected ArrayList<JLabel> labels = new ArrayList<JLabel>();

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JScrollPaneTest();
            }
        });
    }

    public JScrollPaneTest() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());

                JPanel panel1 = new JPanel ();

                panel1.setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();

                for (int i = 0; i < 20; i++) {
                    JLabel label = new JLabel("  | Label" + i + " |  ");
                    panel1.add(label, gbc);
                    labels.add(label);
                }

                panel1.addMouseListener(new MouseAdapter(){
                    public void mousePressed (MouseEvent me) {
                        JLabel label = labels.get(11);
                        label.scrollRectToVisible(label.getBounds());
                    }
                });

                JScrollPane pane = new JScrollPane(panel1) {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(600, 400);
                    }
                };

                pane.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() {
                    @Override
                    public void adjustmentValueChanged(AdjustmentEvent e) {
                        System.out.println("adjustmentValueChanged: " + e);
                    }
                });

                frame.getContentPane().add(pane);

                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

A: Part of the answer (code in comments is just ... and noticed I had it wrong in the comment ;-)
The method scrollRectToVisible takes a Rectangle in the coordinate system of the component it is called upon. To scroll a child such that it is completely visible, there are basically two options (use one of them):
// either call on child with zero offset
child.scrollRectToVisible(new Rectangle(child.getSize());
// or call on child's parent with child bounds
child.getParent().scrollRectToVisible(child.getBounds());


text:
Q: How to add dynamic google map to my website? I have creating a business directory website, so i need to add google map in to my website.
if one user has selected specific city, locality and search category(For eg: Hotels) mean i need to list the hotels names and address, but the problem is i need to display the all listed hotels icons in map.
i have designed website using HTML, CSS, MYSQL, JS.
i have already tried with WordPress, but could not execute properly.
is it possible?? and any other source there? please help me..

A: Adding a Google map with Places Search box will help you to achieve this.
Check below URL for Example Code
https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

A: Have a look at Directory WordPress theme here but of course you will need to develop this your own. This will help you what you can do to your project!
Regarding putting Marker on Google Map have a look at this sample demonstrated at google map documentation.
You will be using longitude and latitude to display objects on map. Define your own search for it.
So a sample result from search.php can be this json:
{
    search_result: [
        {
            latLng: [40.71958306715651,-74.0379810333252],
            options: {
                icon: "http://preview.ait-themes.com/directory/wp1/wp-content/uploads/sports.png",
                shadow: "http://preview.ait-themes.com/directory/wp1/wp-content/themes/directory/design/img/map-icon/icon-shadow.png",
            },
            data: '

'+"Dance & Relax"+'

'+"276 Canal Street, New York, NY 10013, United States"+'
' + "VIEW MORE" + '

'
        },
        {
            latLng: [40.7053026089413,-73.95326614379883],
            options: {
                icon: "http://preview.ait-themes.com/directory/wp1/wp-content/uploads/sports.png",
                shadow: "http://preview.ait-themes.com/directory/wp1/wp-content/themes/directory/design/img/map-icon/icon-shadow.png",
            },
            data: '

'+"Bike PRO"+'

'+"276 Canal Street, New York, NY 10013, United States"+'
' + "VIEW MORE" + '

'
        }
    ]
}

Use this to map object on google map.


text:
Q: How to fix : Received RST_STREAM with error code 2 when using nginx reverse proxy I'm currently using the dialogflow api on a raspberry.
Everything works fine when calling StreamingDetectIntent method using grpc.
I have to use multiples apis on my product and so, I'm trying to put a reverse proxy in front of them. Like that, I can call only one address
I'm using nginx to reverse proxy my GRPC request to google api.
I have no problem when calling simple method, but when calling a streaming method like StreamingDetectIntent, I got an error during the request.
Dialogflow do not have problem to get the audio flux coming from my client, but I got problem to get the last part of the request, the downstream flux.
Here is the error that my client give me  :
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
        status = StatusCode.INTERNAL
        details = "Received RST_STREAM with error code 2"
        debug_error_string = "{"created":"@1567173815.816362297","description":"Error received from peer ipv4:163.172.143.250:443","file":"src/core/lib/surface/call.cc","file_line":1041,"grpc_message":"Received RST_STREAM with error code 2","grpc_status":13}"
>

and here the error I can see in Nginx log  :
upstream sent frame for closed stream 1 while reading upstream, client: ..., server: exemple.com, request: "POST /google.cloud.dialogflow.v2beta1.Sessions/StreamingDetectIntent HTTP/2.0", upstream: "grpcs://...:443", host: "example.com:443"

I've tried to increase grpc_buffer_size parameter to big value, but didn't worked..
Here is my current Nginx config :
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log debug;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;

    keepalive_timeout  65;

    client_max_body_size 4000M;
    grpc_read_timeout 1d;
    grpc_send_timeout 1d;
    # this seems to fix it; but see comment in README.md
    grpc_buffer_size 100M;

    include /etc/nginx/conf.d/*.conf;

    server {

        # SSL configuration
        listen 443 ssl http2;

        access_log /var/log/nginx/access_grpc.log main;

        location / {
            grpc_pass grpcs://dialogflow.googleapis.com:443;
        }

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key/etc/letsencrypt/live/exemple.com/privkey.pem;
    }

    server {

        if ($host = example.com) {
            return 301 https://$host$request_uri;
        }

        listen 80 ;
        listen [::]:80 ;

        return 404; # managed by Certbot

    }

}

A: There may be a problem with GRPC Metadata (especially with user-agent). Take a look at these issues:
https://github.com/grpc/grpc-go/issues/1888
https://github.com/improbable-eng/grpc-web/issues/145


text:
Q: Justified text alignment with second line indented I am pretty new to Tex.
I want to specify bibliography items so that the text allignment is justified throughout the page, but with the second and third lines indented, like so:

I the above example, I did the indentation manually with \hspace*{5mm}, but as you can see in the first item, it doesn't work well for justified allignment. Is there a way that I could keep the justified allignment of each line, but with the indentation of all but the first line?
I have also not found a bibtex style that would match this requirement. Thank you for your help.
Updated question
Here is the minimal code:
\documentclass{article}
\begin{document}
\section*{SOURCES}

Barbero G., Evangelista L. R., Olivero D. 2000. Asymmetric ionic adsorp-
\hspace*{5mm}tion and cell polarization in liquid crystals. Journal of
Applied Physics, 87, \hspace*{5mm}5: 2646–2648
\\
\\
Bazant M., Kilic M., Storey B., Ajdari A. 2009. Towards an understanding
\hspace*{5mm}of induced-charge electrokinetics at large applied voltages in
concentrated \hspace*{5mm}solutions. Advances in Colloid and Interface
Science, 152, 2: 48–88
\\
\\
Bhuiyan L. B., Outhwaite C. W., Bratko D. 1992. Structure and thermodynami-
\hspace*{5mm}cs of micellar solutions in the modified Poisson-Boltzmann
theory. Chemical \hspace*{5mm}Physics Letters, 193: 203–210

\end{document}

A: A list is possibly the easiest method.
\documentclass{article}
\usepackage{enumitem}

\newenvironment{sources}
 {\section*{SOURCES}
  \begin{itemize}[
    label={},
    leftmargin=5mm,
    itemindent=-5mm,
    labelwidth=0pt,
    labelsep=0pt,
    itemsep=\bigskipamount,
  ]}
 {\end{itemize}}

\begin{document}

\begin{sources}
\item Barbero G., Evangelista L. R., Olivero D. 2000. Asymmetric ionic
adsorption and cell polarization in liquid crystals. Journal of
Applied Physics, 87, 5:~2646–2648

\item Bazant M., Kilic M., Storey B., Ajdari A. 2009. Towards an understanding
of induced-charge electrokinetics at large applied voltages in
concentrated solutions. Advances in Colloid and Interface
Science, 152, 2:~48–88

\item Bhuiyan L. B., Outhwaite C. W., Bratko D. 1992. Structure and thermodynamics
of micellar solutions in the modified Poisson-Boltzmann
theory. Chemical Physics Letters, 193:~203–210
\end{sources}

\end{document}

A: A solution with the hanging package, and another with biblatex-apa and some patches, which allows citations:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{hanging}
\usepackage[style = apa, backend = biber, maxnames = 6]{biblatex}
\addbibresource{sources.bib}
\usepackage{xpatch}

\xpatchbibmacro{name:apa:family-given}{%
\addcomma}{%
}{}{}

\DeclareDelimFormat[bib]{finalnamedelim}{%
  \ifthenelse{\value{listcount}>\maxprtauth}
    {}
    {\finalandcomma\space}}

   \renewbibmacro*{labelyear+extradate}{%
 \iffieldundef{labelyear}
 {\iffieldundef{origyear}
 {}
 {\printtext{\printorigdate}}}%
 {\printtext{\printlabeldateextra}}}

\renewcommand*{\bibpagespunct}{\addcolon\space}

\renewcommand{\bibhang}{5mm}

\defbibheading{sources}{\section*{SOURCES}}
%
\begin{document}

\section*{SOURCES}

\begin{hangparas}{5mm}{1}
Barbero G., Evangelista L. R., Olivero D. 2000. Asymmetric ionic adsorption and cell polarization in liquid crystals. Journal of Applied Physics, 87, 5: 2646–2648

Bazant M., Kilic M., Storey B., Ajdari A. 2009. Towards an understanding of induced-charge electrokinetics at large applied voltages in concentrated solutions. Advances in Colloid and Interface Science, 152, 2: 48–88

Bhuiyan L. B., Outhwaite C. W., Bratko D. 1992. Structure and thermodynamics of micellar solutions in the modified Poisson-Boltzmann theory. Chemical Physics Letters, 193: 203–210
\end{hangparas}
\bigskip

\nocite{*}
\printbibliography[heading = sources]

\end{document}

The sources.bib file:
% Encoding: UTF-8

@Article{BEO,
  author    = {Barbero, G. and Evangelista, L. R. and Olivero, D.},
  title     = {Asymmetric ionic adsorption and cell polarization in liquid crystals},
  journal   = {Journal of Applied Physics},
  year      = {2000},
  volume    = {87},
  number    = {5},
  pages     = {2646–2648},
  owner     = {Bernard},
  timestamp = {26.2018.01},
}

@Article{BKSA,
  author    = {Bazant, M. and Kilic, M. and Storey, B. and Ajdari, A.},
  title     = {Towards an understanding of induced-charge electrokinetics at large applied voltages in concentrated solutions},
  journal   = {Advances in Colloid and Interface Science},
  year      = {2009},
  volume    = {152},
  number    = {2},
  pages     = {48–88},
  owner     = {Bernard},
  timestamp = {26.2018.01},
}

@Article{BOB,
  author    = {Bhuiyan, L. B. and Outhwaite, C. W. and Bratko, D.},
  title     = {Structure and thermodynamics of micellar solutions in the modified Poisson-Boltzmann theory},
  journal   = {Chemical Physics Letters},
  year      = {1992},
  volume    = {193},
  pages     = {203–210},
  owner     = {Bernard},
  timestamp = {26.2018.01},
}


text:
Q: adding slidetoggle to a panel switcher I am trying to add a slidetoggle function to a page, you can see the portion of the page i'm having problems with reproduced in this fiddle: http://jsfiddle.net/nickgardner/YYcH7/10/
I was able to get jquery slidetoggle working in isolation, but it doesn't work when I use it on the page. I'm not sure where the conflict is, any help is much appreciated.
thanks, Nick
http://jsfiddle.net/nickgardner/YYcH7/10/
$('#faq-1-1').click(function() {
    $('#faq-1-1-hide').slideToggle('slow', function() {
        // your code
    });
});

UPDATE :
I used the advice that Floris offered below, which worked except that that panel switcher no longer worked.  Since this was meant to be in a Shopidy page, I tried adding the code that had been commented out into the head (an include) and it is now working.

A: I forked your jsFiddle and made it work: http://jsfiddle.net/n6tFW/
You really only need one $(document).ready function, not three.
This is missing a closing ":
$("#one, #two, #three, #four)
So that should be:
$("#one, #two, #three, #four")
Note that I commented out this line:
jcps.fader(300, '#switcher-panel');
I assume that is some library you have in your code which jsFiddle didn't have. It caused the script to break there.
Over here, you are closing the $(document).ready function too soon:
$('#faq-group a').click(function(){
    $('#faq-group  a').removeClass("active");
    $(this).addClass("active");
});
}); //Closes the $(document).ready function, but you don't want to do that yet!

And then, all that is left is to add an extra }); to the end:
$('#faq-1-1').click(function() {
$('#faq-1-1-hide').slideToggle('slow', function() {

});
});
});

That brings the total of your JS code to this:
$(document).ready(function() {
    $("#one, #two, #three, #four").on('click', function() {
        $('[class$="-dropdown"]').not('.'+this.id.replace('nav','')+'-dropdown').slideUp();
        $('.'+this.id.replace('nav','')+'-dropdown').slideToggle(1000);
    });

    //jcps.fader(300, '#switcher-panel');

    $('#media-side-nav ul li a').click(function() {
        $('#media-side-nav ul li a').removeClass("active");
        $(this).addClass("active");
    });

    $('#faq-group a').click(function() {
        $('#faq-group a').removeClass("active");
        $(this).addClass("active");
    });

    $('#faq-1-1').click(function() {
        $('#faq-1-1-hide').slideToggle('slow', function() {

        });
    });
});

So yeah, the real meat and potatoes of this problem is that you need to indent your code properly. You would catch mistakes like these instantly! And the missing " is just a small mistake, no problem!

A: You have been using the id faq-group several times. This is not valid HTML. Put the divs in a class of that name then it should work!


text:
Q: Unable to bind a content control to same list as a listbox with data templates I am writing an editor which shows a list of parameters in a list box on the left hand side of the user control and with the details shown on the right hand side. There are 6 different types of parameters, each with its own set of values. The list box uses a DataTemplate to display each parameter type.  I would like the editing to work similarly on the right hand side so that when a parameter in the list box is selected, the appropriate template is loaded on the right hand side.  The following abbreviated XAML code works to display the left hand listbox, but fails to display anything on the right hand side, except for the word 'collection'. Parameters is the ObservableCollection with the list of parameters. I was trying to do this with just a set of xaml code in the Content provider resources, but switched to the technique suggested in this Microsoft article: Simple Navigation Technique in WPF using MVVM.  However, this also gives exactly the same result.  The ContentControl should be displaying the appropriate UserControl when an item on the list is selected, but nothing is displayed.  The screen shot should being showing a custom control on the right for the selected parameter, not the word 'Collection'.

Any suggestions?
    <DockPanel Grid.Row="1" DataContext="{Binding Parameters}">
        <ListBox DockPanel.Dock="Left" MinWidth="250"
                 ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"
                 SelectedItem="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Path=DataContext.SelectedParameter}"
                 Margin="0,0,15,0" HorizontalAlignment="Left">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding Path=Icon}" Stretch="None" />
                        <TextBlock Text="{Binding Position}" Margin="10,0,0,0" />
                        <TextBlock Text="{Binding Name}" Margin="10,0,0,0" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <ContentControl Content="{Binding}">
            <ContentControl.Resources>
                <DataTemplate x:Key="InputParameterTemplate" DataType="x:Type local:ParameterDisplayLineInput">
                    <controls:EditInputParameter />
                </DataTemplate>
                <DataTemplate x:Key="OutputParameterTemplate" DataType="x:Type local:ParameterDisplayLineOutput">
                    <controls:EditOutputParameter />
                </DataTemplate>
                <DataTemplate x:Key="LogicParameterTemplate"  DataType="x:Type local:ParameterDisplayLineLogic">
                    <controls:EditLogicParameter />
                </DataTemplate>
                <DataTemplate x:Key="TableParameterTemplate"  DataType="x:Type local:ParameterDisplayLineTable">
                    <controls:EditTableParameter />
                </DataTemplate>
                <DataTemplate x:Key="TimerParameterTemplate"  DataType="x:Type local:ParameterDisplayLineTimer">
                    <controls:EditTimerParameter />
                </DataTemplate>
                <DataTemplate x:Key="NetworkListParameterTemplate"  DataType="x:Type local:ParameterDisplayLineNetworkList">
                    <controls:EditNetworkListParameter />
                </DataTemplate>
            </ContentControl.Resources>
        </ContentControl>
    </DockPanel>

A: Lose that "x:Key"s,So your DataTemplate will apply automatically. (i guess you are having proper binding)
 <DockPanel Grid.Row="1" DataContext="{Binding Parameters}">
    <ListBox DockPanel.Dock="Left" MinWidth="250"
             ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"
             SelectedItem="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Path=DataContext.SelectedParameter}"
             Margin="0,0,15,0" HorizontalAlignment="Left">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="{Binding Path=Icon}" Stretch="None" />
                    <TextBlock Text="{Binding Position}" Margin="10,0,0,0" />
                    <TextBlock Text="{Binding Name}" Margin="10,0,0,0" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <ContentControl Content="{Binding}">
        <ContentControl.Resources>
            <DataTemplate  DataType="x:Type local:ParameterDisplayLineInput">
                <controls:EditInputParameter />
            </DataTemplate>
            <DataTemplate  DataType="x:Type local:ParameterDisplayLineOutput">
                <controls:EditOutputParameter />
            </DataTemplate>
            <DataTemplate   DataType="x:Type local:ParameterDisplayLineLogic">
                <controls:EditLogicParameter />
            </DataTemplate>
            <DataTemplate   DataType="x:Type local:ParameterDisplayLineTable">
                <controls:EditTableParameter />
            </DataTemplate>
            <DataTemplate   DataType="x:Type local:ParameterDisplayLineTimer">
                <controls:EditTimerParameter />
            </DataTemplate>
            <DataTemplate  DataType="x:Type local:ParameterDisplayLineNetworkList">
                <controls:EditNetworkListParameter />
            </DataTemplate>
        </ContentControl.Resources>
    </ContentControl>
</DockPanel>

A: I ended up punting this.  I cheated and stored a pointer to the appropriate editing line user control directly in my Parameter Display Line Model class and then bound the content control to that.  There was no way that I could find to have the content control automatically change to the correct data template for a specific line.  Please don't bother pointing out that this violates the separation of the UI from the Model - I know it and hang my head in shame, but nothing else worked.