text:
Q: Button running a whole new class I want my button to run a whole new class that will do different things inside. I don't know if that is even possible cause i'm really bad at java. My code looks like this at the moment:
public class MainMenu {
    private class GardenActivities {
        public GardenActivities() {
            JFrame GardenAct = new JFrame();
            GardenAct.setSize(400, 400);
            GardenAct.setVisible(true);
        }
    }

    public static void main(String[] args) {
        JFrame choice = new JFrame();
        choice.setSize(700, 500);
        choice.setLocationRelativeTo(null);
        choice.setTitle("Seeds");
        choice.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 1));
        JButton Labora = new JButton();
        Labora.setText("Laboratory");
        Labora.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ev) {
                      GardenActivities();
                }
        });

        JButton Garden = new JButton();
        Garden.setText("Garden");
        Garden.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ev) {
            }
        });

        choice.getContentPane().add(panel);
        ButtonGroup group = new ButtonGroup();
        group.add(Garden);
        group.add(Labora);
        panel.add(Garden);
        panel.add(Labora);
        choice.setVisible(true);
    }
}

Just like I said. I need something to run my GardenActivities class just by pressing Garden button.

A: Your code doesn't compile, does it? When that happens, you need to post compilation errors with your question so that we can help you with them.
You need to add the key word new before the GardenActivities() statement.
@Override
public void actionPerformed(ActionEvent ev) {
  new GardenActivities(); // here
}

Also, put the GardenActivities in its own file. There's no reason for making it a private inner class and many reasons not to do this.
Having said this, I recommend against having one JFrame create and display another JFrame since an application should have usually only one JFrame. Instead consider swapping JPanel "views" using a CardLayout, or if you must show a different window, consider showing the second dependent window as a modal or non-modal dialog.
Also more unsolicited advice: Your main method is doing way too much. Most of the code inside of the static main method should go inside the non-static main gui class, whatever that is, perhaps in its constructor or in an initGui() method that the constructor calls. The main method should just create an instance of the main gui class, make it visible, and that's about it.

And regarding:

I don't know if that is even possible cause i'm really bad at java.

Keep writing lots and lots of code, a ton of code, and keep reviewing tutorials and textbooks, and this will change.

A: One way to do what you want, we make the GardenActivities class implement ActionListener itself.
Then your code would look something like this:
Garden.addActionListener(new GardenActivities());

Otherwise, your plan should work.
NOTE
See comments for opposing opinions about why one would want to leave the ActionListener in the anonymouse inner class and have it call into GardenActivities.
Thank you @HovercraftFullOfEels

A: I think that you just need to add:
new GardenActivities();
Into your JButton's actionPerformed() method.
Good Luck!

A: As others have pointed out, this:
 @Override
                public void actionPerformed(ActionEvent ev)
                    {
                      GardenActivities();
                    }

Should look like:
 @Override
                public void actionPerformed(ActionEvent ev)
                    {
                      new GardenActivities();
                    }

There is no reason to create an inner class, and GardenActivities can be, and should be, its own class.


text:
Q: C# tree population i need to create a tree like using the letters of a string.
for example: BAT the tree will look like this
                       #
              /        |      \
              B        A       T
             / \      / \     / \
            A   T    B   T   B   A
            |   |    |   |   |   |
            T   A    T   B   A   B

i tried using a recursion..but always showed stack overflow.
Can anyone suggest an efficient algorithm for this.The logic should work for any no of letters.
i have not added my code here because its totally wrong.I am new to programming using data structures.
Given below is the code i have written:
                   using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tree_recursion
{
    class Program
    {
        static void Main(string[] args)
        {
            String str;
            Console.WriteLine("Word : ");
            str = Console.ReadLine();
            str = str + "*";
            int len = str.Length;
            int i=0;
            Char[] letters = new char[len];
            letters = str.ToCharArray();
            Node root = new Node('#');
            Node ret_node=new Node();
            for (int j = 0; j < len;j++ )
            {
                i = j;
                ret_node = root.Addnode(letters[i++]);
            }
        }
    }
    class Node
    {
        public char c;
        public List<Node> Child = new List<Node>();
        public Node()
        {
        }
        public Node(char ch)
        {
            Node n=new Node();
            n.c=ch;
        }
        public Node Addnode(char ch)
        {
            if (ch == '*')
            {
                return null;
            }
            else
            {
                Node n1 = Addnode(ch++);
                this.Child.Add(n1);
                return n1;
            }
        }

    }
}

A: This works for me.
First define a tree structure:
public class Tree<T>
{
    public T Value { get; private set; }
    public IEnumerable<Tree<T>> Children { get; private set; }

    public Tree(T value, IEnumerable<Tree<T>> children)
    {
        this.Value = value;
        this.Children = new List<Tree<T>>(children);
    }

    public string Dump()
    {
        return this.Dump(0);
    }

    protected string Dump(int level)
    {
        var query =
            (new [] { "".PadLeft(level, '-') + this.Value.ToString() })
            .Concat(this.Children.Select(x => x.Dump(level + 1)));

        return String.Join(System.Environment.NewLine, query);
    }
}

Your node structure made things a little more difficult to work with.
Then you can build a tree like this:
var text = "ABC";

Func<IEnumerable<char>, IEnumerable<Tree<char>>> build = null;
build = xs =>
    from x in xs
    select new Tree<char>(x, build(xs.Except(new [] { x })));

var tree = new Tree<char>('#', build(text));

The result of running Dump on this tree is:
#
-A
--B
---C
--C
---B
-B
--A
---C
--C
---A
-C
--A
---B
--B
---A

redpajama_set_name: RedPajamaStackExchange


text:
Q: find all public variables in a netbeans project? I'm debugging a project with many classes and forms and would be very useful for me to find all the public variables used in the project.
Is there any way to do this in Netbeans? Neither I have been able to find a pluging for Netbeans to achieve this.
Thanks a lot.

A: It should be possible with http://code.google.com/p/reflections/
import static org.reflections.ReflectionUtils.getAllFields;
import static org.reflections.ReflectionUtils.withModifier;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashSet;
import java.util.Set;

import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;

public class PublicFieldsReflectionsTest
{
    public static void main(String[] args)
    {
        Reflections reflections = new Reflections(
            "de.your.project.prefix",
            ClasspathHelper.forClass(Object.class),
            new SubTypesScanner(false));
        Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);
        Set<Field> allPublicFields = new LinkedHashSet<Field>();
        for (Class<?> c : allClasses)
        {
            //System.out.println("Class "+c);
            allPublicFields.addAll(getAllFields(c, withModifier(Modifier.PUBLIC)));
        }
        for (Field field : allPublicFields)
        {
            System.out.println(field);
        }
    }
}


text:
Q: Two forms of struct declaration in Go I've got two forms of struct declaration in the function scope. As far as I could see the bellow-listed snippet woks just fine. The question is what's the difference between the two declaration ways? Is that only a semantic question or there is something tricky under the covers?
package main

import "fmt"

func main() {
    type Person1 struct {
        Name string
        Id int
    }
    person1 := &Person1{Name : "John Smith", Id : 10}
    fmt.Printf("(%s, %d)\n", person1.Name, person1.Id)
    var person2 struct {
        name string
        id int
    }
    person2.name = "Kenneth Box"
    person2.id = 20
    fmt.Printf("(%s, %d)\n", person2.name, person2.id)
}

A: One is a named type - you can create multiple variables of that type, if you need to, using the type name.
The other type has no name.  You cannot create more variables of the type other than by using the := operator.

A: person1 is a pointer to a struct, while person2 is a struct value itself. If you had done person1 := Person1{Name : "John Smith", Id : 10} then it would be the same


text:
Q: how to bind a list of tuple in a listbox? I have a listbox like this:
<ListBox x:Name="list1" ItemsSource="{Binding MyListWithTuples}">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <Label Content="{Binding value1}" />
                                    <Label Content="{Binding value2}" />
                                </StackPanel>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>

In my view model I have this collection:
private ObservableCollection<(decimal value1, decimal value2)> _myCollection= new ObservableCollection<(decimal value1, decimal value2)>();
        public ObservableCollection<(decimal vaule1, decimal value2)> MyCollection
        {
            get { return _myCollection; }
            set
            {
                _myCollection= value;
                base.RaisePropertyChangedEvent("MyCollection");
            }
        }

But the data isn't show. However if I convert the tuple to a dictionary, I can bind to Key and Value properties and the data is shown. But I would like to avoid to convert the tuple into a dictionary.
Are there some way to bind the listbox to a list of tuples?
Thanks.

A: Unlike the Tuple Class, the new C# tuple types only define fields, but no properties. So you can't use them with WPF data binding.
However, with
public ObservableCollection<Tuple<decimal, decimal>> MyCollection { get; }

you could use this XAML:
<ListBox ItemsSource="{Binding MyCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Label Content="{Binding Item1}" />
                <Label Content="{Binding Item2}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


text:
Q: How to schedule Azure Database import? We have a weekly development build which I push out to our testing environment setup on Azure. Now I would like to always grab the latest productive database to have fresh data and immediatly see any occuring problems.
How can I automate Azure Database import/restore? Bacpac export on the productive environment is running fine and I can import it to my local database or manually in Azure.
I've seen the possibility to trigger a database restore over the REST API but only PointInTime not pointing to different .bacpac.
Next there is DACFx but there must be some tool around which already does this before writting this myself.
Thanks!

A: You should look at sqlpackage.exe it is basically a wrapper around the DacFx Api and will let you publish a bacpac to azure from the command line so you can include it in your build:
http://msdn.microsoft.com/en-us/library/hh550080%28v=vs.103%29.aspx


text:
Q: Como agrupar por Id sql server Tengo una consulta la cual suma los valores que son iguales siempre y cuando sean iguales (IdFactura, NombreProveedor) pero ahora quiero que desaparezcan los valores que son duplicados, pero al correr el query me manda el error

Column 'FacturasPendientes.FechaFactura' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause

La consulta que estoy haciendo es la siguiente, ya lo intente con .*
SELECT IdFactura,FechaFactura,a.CodigoProveedor,NombreProveedor,SUM(Total) Over(Partition by IdFactura, NombreProveedor) as Total,FechaDPP,FechaFinal,Pagado,Comentario,b.TipoDePago FROM FacturasPendientes a INNER JOIN CatalogoProveedores b
ON a.CodigoProveedor = b.CodigoProveedor WHERE FechaDPP BETWEEN '2019-12-18 00:00:00.000' AND '2019-12-19 23:59:59.000' AND Pagado ='0' GROUP BY IdFactura

A: El error es porque te sobra el group by, puesto que estas utilizando una función de ventana.
Además ese filtro de fechas, puede no ser del todo correcto, porque si tienes una factura el 2019-12-19 23:59:59.997 que es un rango válido para un datetime, no te vendría. Puedes cambiarlo por:
SELECT  DISTINCT
    IdFactura
  , FechaFactura
  , a.CodigoProveedor
  , NombreProveedor
  , SUM(Total) Over(Partition by IdFactura, NombreProveedor) as Total
  , FechaDPP
  , FechaFinal
  , Pagado
  , Comentario
  , b.TipoDePago
FROM FacturasPendientes a INNER JOIN CatalogoProveedores b
    ON a.CodigoProveedor = b.CodigoProveedor
WHERE FechaDPP >= '2019-12-18 00:00:00.000' AND FechaDPP < '2019-12-20 00:00:00.000'
AND Pagado ='0'

Otra opción es utilizar group by en vez de distinct y Over.


text:
Q: Instance with Canonical Livepatch Service requires restart I'm by no means a sysadmin, so maybe this is a simple oversight. Isn't the whole point of the Livepatch Service to prevent mission-critical servers from having to restart after a kernel update?
Livepatch on the Google Cloud Compute Server in question has been installed since October 18th. Immediately before installing the livepatch service, I performed one last restart.
This is what I'm currently presented with upon login:
login as: ubuntu
Authenticating with public key "key" from agent
Welcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-45-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

Get cloud support with Ubuntu Advantage Cloud Guest:
  http://www.ubuntu.com/business/services/cloud

1 package can be updated.
0 updates are security updates.

*** System restart required ***
Last login: Tue Nov  1 09:57:46 2016 from X.X.X.X

If I check the status of the livepatch service, everything looks fine:
ubuntu@server:~$ canonical-livepatch status
kernel: 4.4.0-45.66-generic
fully-patched: true
version: ""

Anything else I need to be doing to prevent these required restarts? Are there other packages that would need a full restart? All packages are managed through Ubuntu's own package manager.

A: Here you can find a lengthy FAQ about ubuntu live patch:
http://blog.dustinkirkland.com/2016/10/canonical-livepatch.html
I copied the questions which are of interest for you:

Q: What kinds of updates will be provided by the Canonical Livepatch Service?
A: The Canonical Livepatch Service is intended to address high and critical severity Linux kernel security vulnerabilities, as identified by Ubuntu Security Notices and the CVE database. Note that there are some limitations to the kernel livepatch technology -- some Linux kernel code paths cannot be safely patched while running. We will do our best to supply Canonical Livepatches for high and critical vulnerabilities in a timely fashion whenever possible. There may be occasions when the traditional kernel upgrade and reboot might still be necessary. We'll communicate that clearly through the usual mechanisms -- USNs, Landscape, Desktop Notifications, Byobu, /etc/motd, etc.
Q: What about non-security bug fixes, stability, performance, or hardware enablement updates?
A: Canonical will continue to provide Linux kernel updates addressing bugs, stability issues, performance problems, and hardware compatibility on our usual cadence -- about every 3 weeks. These updates can be easily applied using 'sudo apt update; sudo apt upgrade -y', using the Desktop "Software Updates" application, or Landscape systems management. These standard (non-security) updates will still require a reboot, as they always have.


text:
Q: Programmatically authentication in LifeRay I'm using LifeRay and need some kind of special authentication: my users have x.509 certificates which are validated by an Apache Webserver. After a successful validation, the user is redirected to Tomcat and in there LifeRay.
Now I want to do the following: get the subject DN of the user's certificate programmatically and log in the LifeRay user that is connected to this DN.
So far, I have the following:

*

*Created a hook "login.events.pre" where I get the DN from the certificate

*Search the LifeRay DB for a user with this DN (using UserLocalServiceUtil.getUserByOpenId())

*Authenticate user using UserLocalServiceUtil.authenticateByScreenName()

My question now: is that the "best"/cleanest way to do this or should I use other methods for querying the LifeRay DB, authenticating the user etc. For instance, instead of a hook I could create an Ext-Extensions for LifeRay. Additionally, I found some stuff like "com.liferay.portlet.login.util.LoginUtil.login" or User user = PortalUtil.getUser(request); to get a user.
Is there a place in the docu where those questions are answered? The API is not that comprehensive...


text:
Q: How do I add more to JNI interface I followed a tutorial and built a JNI interface in Android studio. But I don't know how to add more to it by calling other functions in my C library. I am not even sure if I can see my library yet; I figure if I call one of the functions I would know. So my question is I do not understand the file in my JNI folder. I see it is written in C. Why is the #include different from the usual C includes I have seen which is something like #include  or I believe you can also say #include "foo.c" also? Why are there _'s in the package names? How do I call a function in one of my libraries two levels below the JNI folder? I read the JNI specification and still don't understand how JNIenv works.
For example, just to test this, I tried adding random.c to my file. It is located two levels below my JNI folder; ndk-builder says there is no such file. So I think I need to work on my Andorid.mk and make sure the build environment has visibility to random.c. Is that true? Can I somehow specify the fully qualified path to random.c?
#include "com_example_sansari_ndktest_MainActivity.h"
#include <random.c>

 JNIEXPORT jstring JNICALL
 Java_com_example_sansari_ndktest_MainActivity_HelloJNI
   (JNIEnv *env, jobject obj)
{
 (*env)->NewStringUTF(env,"Hi From Sean");
}

@JP; Thanks. So I should be able to say something like the following in the above file:
(*env)->random();
And be able to receive an integer in my main activity? random() declares a static integer, modifies it, and returns it.
@JP. Thanks. so I can say
random(); in my C file, and the value would show up in my MainActivity. Well that is good news; thanks. Now i gota figure out how to fix my Andorid.mk.
@JP. Thanks. i took it out. I really appreciate all your help.


text:
Q: Gson parsing with a multiple return type json object I'm trying to parse a json object that is int when it's good, and string when it's not, here's an example :
id: "11271",
title: "Top Gun: An IMAX 3D Experience",
year: 1986,
mpaa_rating: "PG",
runtime: 110,
release_dates: {
theater: "2013-02-08",
dvd: "1998-10-20"
},
ratings: {
critics_rating: "Rotten",
critics_score: 50,
audience_rating: "Upright",
audience_score: 48
},

id: "771270981",
title: "Identity Thief",
year: 2013,
mpaa_rating: "R",
runtime: "",
release_dates: {
theater: "2013-02-08"
},
ratings: {
critics_score: -1,
audience_score: 97
},

the problem in question is the "runtime"
the cause of problem is : "java lang NumberFormatException : Invalid double : ""
and you sure know that with Gson you need to create a class that goes like this :
private int runtime;
public void setRuntime(int runtime) {
    this.runtime = runtime;
}

public int getRuntime() {

        return runtime;
    }

}

How can i trick the program, know that it's not my API.

A: By changing private int runtime; to private String runtime;
Depending what you do afterwards, you can check if its a int, if it is , deal with it as int, else deal with it as String.


text:
Q: Making a `REST` call to `graphql` endpoint using apache `httpclient` in java I am trying to make a simple rest call to graphql endpoint but getting a 400 error from the server. Have been struck in this for a while.
Payload
query = "{\n" +
            "   lookup(dob: \"01/01\", preSsn : { ssn: \"{actualvalue}\"})\n" +
            "   {\n" +
            "       items {\n" +
            "           individualCrdNumber\n" +
            "           firstName\n" +
            "           middleName\n" +
            "           lastName\n" +
            "           suffixName\n" +
            "       }\n" +
            "   }\n" +
            "}";

Error message: {"statusCode":400,"statusDescription":"Bad Request","message":"","messageDetails":[]}
Code:
    HttpClient client = getHttpsClient();
    HttpPost httpPost = new HttpPost(URL);
    StringEntity input = new StringEntity(query, ContentType.APPLICATION_JSON);
    httpPost.setEntity(input);
    final String plainCred = "userName"+":"+"password";
    final String base64Creds = Base64.getEncoder().encodeToString(plainCred.getBytes());

    httpPost.addHeader("Authorization", "Basic " + base64Creds);
    httpPost.addHeader("Content-Type", "application/json");
    httpPost.addHeader("Accept", "application/json");
    httpPost.addHeader("Cache-Control", "no-cache");

    HttpResponse response = client.execute(httpPost);

A: The query needs to be wrapped in an object assigned to a query element. This object can also contain a variables element for value binding:
{
  "query": "...",
  "operationName": "...",
  "variables": { "myVariable": "someValue", ... }
}

See the spec regarding GraphQL over HTTP using POST.
Try
String query =
        "{" +
          "\"query\" : \"query {"+
            "lookup(dob: \"01/01\", preSsn : { ssn: \"{actualvalue}\"})" +
            "{items{individualCrdNumber firstName middleName lastName suffixName}}" +
          "}" +
        "}";


text:
Q: How does Dropwizard know how to serialize Joda DateTime objects, and how can I modify it? I'm looking at a REST API which uses DropWizard. DropWizard appears to somehow magically know how to serialize joda DateTime objects to a string formatted like this:
YYYY-MM-DD HH:MM:SS

But if I write a test which uses an ObjectMapper to serialize a joda DateTime object, I get something like:
{"month_of_year":1,"hour_of_day":0,"minute_of_hour":15,"second_of_minute":3,"millis_of_second":0,"week_of_weekyear":3,"weekyear":2018,"year_of_era":2018,"year_of_century":18,"century_of_era":20,"millis_of_day":903000,"second_of_day":903,"minute_of_day":15,"day_of_year":18,"day_of_week":4,"day_of_month":18,"year":2018,"era":1,"millis":1516259703000,"chronology":{"zone":{"uncached_zone":{"cachable":true,"fixed":false,"id":"America/Denver"},"fixed":false,"id":"America/Denver"}},"zone":{"uncached_zone":{"cachable":true,"fixed":false,"id":"America/Denver"},"fixed":false,"id":"America/Denver"},"after_now":true,"before_now":false,"equal_now":false}

How does DropWizard know how to serialize this?
The field I'm serialized is annotated like this:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "YYYY-MM-dd HH:mm:ss")
DateTime myDate;

I understand that I'm supplying a format string there, but I'd like to understand why ObjectMapper (in my test) doesn't respect it, while DropWizard does. (The annotation is a Jackson annotation, not a DropWizard one, so it confuses me that ObjectMapper.writeValue() wouldn't respect it).
When looking at the source of the @JsonFormat annotation, I see:
/**
 * Datatype-specific additional piece of configuration that may be used
 * to further refine formatting aspects. This may, for example, determine
 * low-level format String used for {@link java.util.Date} serialization;
 * however, exact use is determined by specific JsonSerializer
 */
public String pattern() default "";

This leads me to believe that Jackson doesn't actually supply the JsonSerializer that recognizes this pattern attribute, and at the same time leads me to believe that DropWizard does have such a JsonSerializer. How can I configure/modify/override the JsonSerializer that DropWizard is apparently using?

A: Your test is not using the right ObjectMapper. DW in its bootstrap will configure the ObjectMapper for you with reasonable defaults (that's DW's whole thing - everything is somewhat reasonable and pre-configured).
So, in your case, your test would need to use Jackson.newObjectMapper(). Try this:
public static void main(String[] args) throws JsonProcessingException {

    ObjectMapper myMapper=  new ObjectMapper();
    ObjectMapper dwMapper = Jackson.newObjectMapper();
    System.out.println(myMapper.writeValueAsString(new X()));
    System.out.println(dwMapper.writeValueAsString(new X()));
}

public static class X {
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "YYYY-MM-dd HH:mm:ss")
    DateTime now = DateTime.now();
}

Will print:
{"now":{"era":1,"dayOfYear":18,"dayOfWeek":4,"dayOfMonth":18,"year":2018,"weekOfWeekyear":3,"millisOfDay":37615193,"monthOfYear":1,"hourOfDay":10,"minuteOfHour":26,"secondOfMinute":55,"millisOfSecond":193,"weekyear":2018,"yearOfEra":2018,"yearOfCentury":18,"centuryOfEra":20,"secondOfDay":37615,"minuteOfDay":626,"zone":{"fixed":false,"uncachedZone":{"cachable":true,"fixed":false,"id":"Europe/London"},"id":"Europe/London"},"millis":1516271215193,"chronology":{"zone":{"fixed":false,"uncachedZone":{"cachable":true,"fixed":false,"id":"Europe/London"},"id":"Europe/London"}},"afterNow":false,"beforeNow":true,"equalNow":false}}
{"now":"2018-01-18 10:26:55"}

And for completeness, these are the modules that are registered for you:
private static ObjectMapper configure(ObjectMapper mapper) {
        mapper.registerModule(new GuavaModule());
        mapper.registerModule(new LogbackModule());
        mapper.registerModule(new GuavaExtrasModule());
        mapper.registerModule(new JodaModule());
        mapper.registerModule(new AfterburnerModule());
        mapper.registerModule(new FuzzyEnumModule());
        mapper.registerModules(new Jdk8Module());
        mapper.registerModules(new JavaTimeModule());
        mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy());
        mapper.setSubtypeResolver(new DiscoverableSubtypeResolver());

        return mapper;
    }

These are all overwritable in the bootstrap.
Please not that I might be on an older version of DW, so it might be slightly different in the latest.
Artur


text:
Q: Split dataframe by empty row I'm trying to split a horrendously formatted dataframe into a list of dataframes based on the rows of NA's between blocks i.e. Loc_1, Loc_2, Loc_3. I've tried Splitting dataframes in R based on empty rows and Divide or split dataframe into multiple dfs based on empty row and header title with no luck. I think the difference in my case is I haven't got a single col without an NA value, as each new chunk starts with NAs for two rows in the first two columns, and there are loads of NAs scattered throughout. Any ideas? This is my first post, so please shout if I need to post more info!
df <- data.frame(
  a = c(NA, NA, "Loc_1", "Loc_1", "Loc_1", NA, NA, NA, "Loc_2", "Loc_2", "Loc_2", NA, NA, NA, "Loc_3", "Loc_3", "Loc_3"),
  b = c(NA, NA, "25:11:2020", "26:11:2020", "27:11:2020", NA, NA, NA, "25:11:2020", "26:11:2020", "27:11:2020",NA, NA, NA, "25:11:2020", "26:11:2020", "27:11:2020"),
  c = c("Var1", "Unit/1", 1:3, NA, "Var3", "Unit/3", NA, 1, 2, NA,"Var1", "Unit/1", 1:3),
  d = c("Var2", "Unit/2", NA, NA, 1, NA, "Var1", "Unit/1", NA, NA, 1, NA, "Var3", "Unit/3", NA, NA, 1)
)

       a          b      c      d
1   <NA>       <NA>   Var1   Var2
2   <NA>       <NA> Unit/1 Unit/2
3  Loc_1 25:11:2020      1   <NA>
4  Loc_1 26:11:2020      2   <NA>
5  Loc_1 27:11:2020      3      1
6   <NA>       <NA>   <NA>   <NA>
7   <NA>       <NA>   Var3   Var1
8   <NA>       <NA> Unit/3 Unit/1
9  Loc_2 25:11:2020   <NA>   <NA>
10 Loc_2 26:11:2020      1   <NA>
11 Loc_2 27:11:2020      2      1
12  <NA>       <NA>   <NA>   <NA>
13  <NA>       <NA>   Var1   Var3
14  <NA>       <NA> Unit/1 Unit/3
15 Loc_3 25:11:2020      1   <NA>
16 Loc_3 26:11:2020      2   <NA>
17 Loc_3 27:11:2020      3      1

A: How about this Base R solution:
n <- rowSums(is.na(df)) == ncol(df)
cs <- cumsum(n) + 1
s <- split(df[!n, ], cs[!n])

s

#> $`1`
#>       a          b      c      d
#> 1  <NA>       <NA>   Var1   Var2
#> 2  <NA>       <NA> Unit/1 Unit/2
#> 3 Loc_1 25:11:2020      1   <NA>
#> 4 Loc_1 26:11:2020      2   <NA>
#> 5 Loc_1 27:11:2020      3      1
#>
#> $`2`
#>        a          b      c      d
#> 7   <NA>       <NA>   Var3   Var1
#> 8   <NA>       <NA> Unit/3 Unit/1
#> 9  Loc_2 25:11:2020   <NA>   <NA>
#> 10 Loc_2 26:11:2020      1   <NA>
#> 11 Loc_2 27:11:2020      2      1
#>
#> $`3`
#>        a          b      c      d
#> 13  <NA>       <NA>   Var1   Var3
#> 14  <NA>       <NA> Unit/1 Unit/3
#> 15 Loc_3 25:11:2020      1   <NA>
#> 16 Loc_3 26:11:2020      2   <NA>
#> 17 Loc_3 27:11:2020      3      1

You can neatly set all your data together again in a long format in this way with unpivotr:
library(unpivotr)
library(dplyr)
library(purrr)

map_dfr(s,
        ~ as_cells(.x) %>%
         behead("up", "var") %>%
         behead("up", "uom") %>%
         behead("left", "loc") %>%
         behead("left", "date") %>%
         # filter(!is.na(chr)) %>%  # do you need the NAs?
         mutate(value = as.numeric(chr)) %>%
         select(var, uom, loc, date, value),
        .id = "df")

#> # A tibble: 18 x 6
#>    df    var   uom    loc   date       value
#>    <chr> <chr> <chr>  <chr> <chr>      <dbl>
#>  1 1     Var1  Unit/1 Loc_1 25:11:2020     1
#>  2 1     Var1  Unit/1 Loc_1 26:11:2020     2
#>  3 1     Var1  Unit/1 Loc_1 27:11:2020     3
#>  4 1     Var2  Unit/2 Loc_1 25:11:2020    NA
#>  5 1     Var2  Unit/2 Loc_1 26:11:2020    NA
#>  6 1     Var2  Unit/2 Loc_1 27:11:2020     1
#>  7 2     Var3  Unit/3 Loc_2 25:11:2020    NA
#>  8 2     Var3  Unit/3 Loc_2 26:11:2020     1
#>  9 2     Var3  Unit/3 Loc_2 27:11:2020     2
#> 10 2     Var1  Unit/1 Loc_2 25:11:2020    NA
#> 11 2     Var1  Unit/1 Loc_2 26:11:2020    NA
#> 12 2     Var1  Unit/1 Loc_2 27:11:2020     1
#> 13 3     Var1  Unit/1 Loc_3 25:11:2020     1
#> 14 3     Var1  Unit/1 Loc_3 26:11:2020     2
#> 15 3     Var1  Unit/1 Loc_3 27:11:2020     3
#> 16 3     Var3  Unit/3 Loc_3 25:11:2020    NA
#> 17 3     Var3  Unit/3 Loc_3 26:11:2020    NA
#> 18 3     Var3  Unit/3 Loc_3 27:11:2020     1

If you don't want one unique dataframe at the end, use map instead of map_dfr and remove , .id = "df"

A: You could try:
library(dplyr)
library(purrr)

df %>%
  group_split(grp = cumsum(rowSums(is.na(.)) == ncol(.)), .keep = FALSE) %>%
  map_at(.at = -1, tail, -1)

[[1]]
# A tibble: 5 x 4
  a     b          c      d
  <chr> <chr>      <chr>  <chr>
1 NA    NA         Var1   Var2
2 NA    NA         Unit/1 Unit/2
3 Loc_1 25:11:2020 1      NA
4 Loc_1 26:11:2020 2      NA
5 Loc_1 27:11:2020 3      1

[[2]]
# A tibble: 5 x 4
  a     b          c      d
  <chr> <chr>      <chr>  <chr>
1 NA    NA         Var3   Var1
2 NA    NA         Unit/3 Unit/1
3 Loc_2 25:11:2020 NA     NA
4 Loc_2 26:11:2020 1      NA
5 Loc_2 27:11:2020 2      1

[[3]]
# A tibble: 5 x 4
  a     b          c      d
  <chr> <chr>      <chr>  <chr>
1 NA    NA         Var1   Var3
2 NA    NA         Unit/1 Unit/3
3 Loc_3 25:11:2020 1      NA
4 Loc_3 26:11:2020 2      NA
5 Loc_3 27:11:2020 3      1

A: Not sure your desired output. Here is my best guess. I added more code trying to remove the first two rows for each loc as those are just column names, and then assign the new column names based on the original first row. This additional step allows you to convert the Var columns to numeric.
library(tidyverse)

# A helper function to filter rows with any non-NA values
rowAny <- function(x) rowSums(x) > 0

df_list <- df %>%
  # Remove rows with all NA
  filter(rowAny(across(everything(), .fns = function(x) !is.na(x)))) %>%
  # Fill the Loc information
  fill(a, .direction = "up") %>%
  # Split the data frame by a
  split(.$a) %>%
  # Remove the first two rows and change the column names to the first row (Var1, Var2, Var3, ...)
  map(function(x){

    # Prepare new column names
    x2 <- x %>%
      slice(1) %>%
      t() %>%
      as.vector()

    x_names <- c(names(x)[1:2], x2[3:length(x2)])

    # Remove the first two rows and assign new column names
    x3 <- x %>%
      slice(-1:-2) %>%
      set_names(x_names) %>%
      # Change the columns to numeric
      mutate(across(x2[3:length(x2)], .fns = as.numeric))

    return(x3)
  })

df_list
# $Loc_1
#       a          b Var1 Var2
# 1 Loc_1 25:11:2020    1   NA
# 2 Loc_1 26:11:2020    2   NA
# 3 Loc_1 27:11:2020    3    1
#
# $Loc_2
#       a          b Var3 Var1
# 1 Loc_2 25:11:2020   NA   NA
# 2 Loc_2 26:11:2020    1   NA
# 3 Loc_2 27:11:2020    2    1
#
# $Loc_3
#       a          b Var1 Var3
# 1 Loc_3 25:11:2020    1   NA
# 2 Loc_3 26:11:2020    2   NA
# 3 Loc_3 27:11:2020    3    1


text:
Q: VB Script with reference script is not working in ScriptControl c# Hi I am executing a VB script using script control in c#.
If it is a standalone script then it works fine for me by using the below code.
            ScriptControl SC = new ScriptControl();
            SC.Language = ScriptType;
            SC.AddObject("Repository", RP);
            SC.AddCode(scriptcontents);
            Object[] runobject = { };
            string result = SC.Run(ScriptName, runobject);

But when i tried to run a VBScript that contains reference of other scripts then its not executing in the script control and throws error.
Referencing other scripts in a script by

!INC Local Scripts.Constants-VBScript

Is there any way to add reference scripts of a script in script control ?

A: VBscripts in Enterprise Architect have a few "extensions" that are problematic when executing it via a generic scripting host.

*

*Includes: EA uses the syntax !INC <scriptGroup>.<ScriptName> to include other scripts. This is however an EA specific syntax that is not known to other script interpreters. In order to avoid this you can replace the include statement the whole code of the included script.

*Variable typing: In EA scripts you can write something like Dim myVar as EA.Element this is very useful in the EA script editor because it allows for code completion, but the syntax is not known to any other script interpreter. These type declaration should be removed.

*Session and Repository: In EA you can use the Session and Repository
object without defining it. If you want to execute a script using the
ScriptControl then you'll have to add those as an object. For
Repository this can be done using
scriptController.AddObject("Repository", eaRepository);
For a complete working example see The Enterprise Architect Add-in Framework on Github.
This code reads the scripts from the model and MDG's, takes care of includes, and adds the Repository object.
It doesn't handle variable typing and the Session object.


text:
Q: How can I use channels to know when all goroutines started by a loop are completed I'm currently trying to range over a map to do concurrent database requests rather than synchronously, obviously because of the speed boost.
My problem is I have something like this:
var mainthreads = make(chan *mainthread)
var mainthreadsFetched = make(chan struct{})
for containerid := range containers {
    go func() {
        rows, err := db.Query("SELECT thread_id, belongs_to, thread_name, access_level FROM forum_mainthread WHERE belongs_to = ?", containerid)
        defer rows.Close()
        if err != nil {
            log.Println(err)
        }
        for rows.Next() {
            mainthread := &MainThread{}
            err := rows.Scan(&mainthread.MainThreadID, &mainthread.BelongsTo, &mainthread.ThreadName, &mainthread.AccessLevel)
            if err != nil {
                log.Println(err)
            }
            mainthreads <- mainthread
        }
    }()
    mainthreadsFetched <- struct{}{}
}

// Get all mainthreads
<-mainthreadsFetched
// Do other stuff after complete

Obviously mainthreadsFetched <- struct{}{} is being called almost instantly because the loop finishes faster than you can blink, how can I create a new channel per loop that will not block each new goroutine from starting, but rather let the loop start all goroutines and then send out on a channel when every goroutine is done.

A: Using sync.WaitGroup is a great solution, and the one usually used.
Alternatively, you can receive on mainthreadsFetched len(containers) times, instead of just 1. That will guarantee that all go routines have completed. You'll need to move the send line to the end of the go routine (or, better, into a defer).
Also, since containerid is in the for loop, its value changes. You need to pass it as a parameter to the go routine closure.

A: So the best way I could come up with doing this is to use sync.WaitGroup and do something like this:
var wg sync.WaitGroup
var mainThreadFetched = make(chan MainThread)
for containerid := range containers {
    wg.Add(1)
    go func(containerid int64) {
        rows, err := db.Query("SELECT thread_id, belongs_to, thread_name, access_level FROM forum_mainthread WHERE belongs_to = ?", containerid)
        defer rows.Close()
        if err != nil {
            log.Println(err)
        }
        for rows.Next() {
            mainthread := MainThread{}
            err := rows.Scan(&mainthread.MainThreadID, &mainthread.BelongsTo, &mainthread.ThreadName, &mainthread.AccessLevel)
            if err != nil {
                log.Println(err)
            }
            mainThreadFetched <- mainthread
        }
        wg.Done()
    }(containerid)
}

go func() {
    wg.Wait()
    close(mainThreadFetched)
}()

for mainthread := range mainThreadFetched {
    containers[mainthread.BelongsTo].MainThreads = append(containers[mainthread.BelongsTo].MainThreads, mainthread)
}

// Do other stuff

Now I can read from the mainThreadFetched channel and then when the WaitGroup is satisfied it will close the channel allowing the loop to end and continue on

A: I don't see where you are reading mainthreads. If it's not a buffered channel, you would need to solve that some way or another. I'm going to provide a few solutions for solving it - None are more "correct" than the other - it just depends on your needs.
Variant A
This is the simplest solution but it presumes you have some other goroutine reading mainthreads (which may already be the case)
var mainthreads = make(chan *mainthread)
var mainthreadsFetched = make(chan struct{})
go somethingWhichReadsMainThreads()
for containerid := range containers {
    go func(containerid int) {
        // build query omitted for brevity
        for rows.Next() {
            // omitted for brevity
            mainthreads <- mainthread
        }
        mainthreadsFetched <- struct{}{}
    }(containerid)
}

for i := 0; i < len(containers); i++ {
    <-mainThreadsFetched
}
close(mainthreads)
// Do other stuff after complete

Variant B
This one uses the select statement to deal with reading the threads separate from the completion notifications without needing yet another goroutine.
var mainthreads = make(chan *mainthread)
var mainthreadsFetched = make(chan struct{})
for containerid := range containers {
    go func(containerid int) {
        // build query omitted for brevity
        for rows.Next() {
            // omitted for brevity
            mainthreads <- mainthread
        }
        mainthreadsFetched <- struct{}{}
    }(containerid)
}

numComplete := 0
readRunning := true
for readRunning {
    select {
    case thread := <-mainthreads:
        // do something with thread, like threads = append(threads, thread)
    case <-mainthreadsFetched:
        numFetched++
        if numFetched == len(containers) {
            readRunning = False
        }
    }
}
// Do other stuff after complete

Variant C
This one uses the fact that you aren't using the 'zero value' (nil) for passing real data, so you can use that as a signal value instead of a separate struct channel. It has the advantage that it is far less code, but it does feel like spooky action at a distance.
var mainthreads = make(chan *mainthread)
for containerid := range containers {
    go func(containerid int) {
        // build query omitted for brevity
        for rows.Next() {
            // omitted Scan for brevity
            mainthreads <- mainthread
        }
        mainthreads <- nil // nil signals to us we are done
    }(containerid)
}

numComplete := 0
for thread := range mainthreads {
    if thread != nil {
        // do something with thread, like threads = append(threads, thread)
    } else {
        numFetched++
        if numFetched == len(containers) {
            break
        }
    }
}
// Do other stuff after complete


text:
Q: How to know the problem when i make this Full Backup Scenario? i'm working new on database administrator and i have some questions
if i want to make SQL full backup database every Saturday at 6:00 AM
and for some reasons the device was shutdown
the questions are :
whats the issues for my backup ? is it rollback ?
how can i know that was happened , when its not the time of work ?
what the a good plan to be sure to take the backup every week with out problems

A: If the database is down when the backup is supposed to start the backup can not run. If the database goes offline while the backup is running the backup will simply stop. It'll need to be restarted after the database comes back online.
There won't be anything logged that there was a backup running when the database went offline. You'd need to look at the job history of the backup job to see if it was running when the database went offline.
There's no way to guarantee that the backups run without issue.


text:
Q: Trying to reduce size of memory allocations in debug compilations for C++ I have a software that is compiled in debug mode for ease of support (getting dump files, etc.). Visual studio version is 2008.
We have noticed that our memory allocations suffer a huge overhead as a result. Every memory allocation (even of a single pointer) done when DEBUG is defined takes with it a big header identifying the allocating file, line, etc.
We are trying to stay in DEBUG and yet reduce the overhead. It seems that defining _AFX_NO_DEBUG_CRT should do the trick - but defining it on the project level or in our stdafx.h file leads to a long list of compilation errors:
c:\program files (x86)\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(66) : error C2059: syntax error : '__asm'
c:\program files (x86)\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(66) : error C2143: syntax error : missing ')' before '{'
....
The error is the same is reported under : #define _AFX_NO_DEBUG_CRT causes a stream of compilation errors, but the requirement to create your own new is not relevant here and I found no solution there.
Another alternative I saw in posts is playing with _CrtSetDbgFlag - but that seems just to avoid writing the information to the heap - but still allocates the memory for it - that's not what we are looking for.
Any ideas?

A: #define _CRTDBG_MAP_ALLOC

From MSDN, The #define statement maps the base versions of the CRT heap functions to the corresponding debug versions. By including crtdbg.h, you map the malloc and free functions to their debug versions, _malloc_dbg and _free_dbg, which keep track of memory allocation and deallocation. This is what you want to avoid.
This mapping occurs only in a debug build (in which _DEBUG is defined). Release builds use the ordinary malloc and free functions.
To serve your purpose,
just #undef _CRTDBG_MAP_ALLOC.
Go to Visual Studio project settings - > Debug settings, go to C/C++ Preprocessor settings, Add _CRTDBG_MAP_ALLOC macro under "Undefine Preprocessor Definitions" settings.
You should be able to generate a DEBUG executable which will not generate overheard during memory allocations at runtime.


text:
Q: Gridview Edit update Delete by on row click Asp.net Update And Cancel button not functioning and these buttons are out side from the gridview
Scenario:
The problem with the default asp.net gridview design is that the GridView edit column always occupies some screen real estate. Additionally in the edit mode the GridView expands horizontally disturbing the page layout. that`s why i want to render an editable GridView without displaying the default Edit, Update and Cancel buttons
Example:

What i have done already
when you see the html source of Gridview you will find the following Edit, Update, cancel Link button with an event called dopostback
e.g
Edit

If you somehow generate the same above script and execute it for some client side event (click of a button for example) then you can essentially send the same commands to the GridView control. The easiest way to do so is to handle RowDataBound event of the GridView Control so i decided to use it on RowDataBound event of Gridview control as shown below:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex == GridView2.EditIndex)
            {
                //update or cancel buttons
                LinkButton updateBtn = (LinkButton)e.Row.Cells[0].Controls[0];
                string updateScript = ClientScript.GetPostBackClientHyperlink(updateBtn, "");
                Button1.Attributes["onclick"] = updateScript;

                string cancelScript = string.Format("javascript:__doPostBack('ctl00$ContentPlaceHolder1$GridView2','Cancel${1}')",
                                      GridView1.ID, e.Row.RowIndex);
                Button2.Attributes["onclick"] = cancelScript;
            }
            else
            {
                //edit button
                string editScript = string.Format("javascript:__doPostBack('ctl00$ContentPlaceHolder1$GridView2','Edit${1}')",
                                    GridView1.ID, e.Row.RowIndex);
                e.Row.Attributes["onclick"] = editScript;
            }

        }
        if (GridView2.EditIndex >= 0)
        {
            Button1.Enabled = true;
            Button2.Enabled = true;
        }
        else
        {
            Button1.Enabled = false;
            Button2.Enabled = false;
        }
    }

Now when i click on any row of gridview it will become an editable row which should be cancel and update by the cancel and update button which are outside of the gridview but they are not working...
Any help or suggestion would be appreciated .
Note: still you need to include the edit,update, cancel linkbutton in Gridview which you can latter hide from the gridview by using script like jquery below..
e.g
$(document).ready(function () {
    $("#GridView2 th:first-child").hide();
    $("#GridView2 td:first-child").hide();
});

A: From what I understand, you are just trying to remove the edit/update buttons from inside the grid to an external location.
You can programmatically set the edit index of the grid, by setting it's EditIndex property to the index you want. You can of course base this decision on the currently selected row of the grid.
After that, you need to databind the grid and change your button from "Edit" to "Update" (if you are using a toggle like solution) or enable/disable them as needed.
The logic for the update can then use the UpdateRow method on the Grid to persist the changes. You can follow the example here to see how to force the edit programmatically. In your case, on button click, you need to pass in the current edit index, like this:
myGrid.UpdateRow(myGrid.EditIndex, true);

EDIT:
I completely bypassed the fact that you want the edit to happen on row click, and that is not as easy to do since clicking the row will not cause a postback. You can probably use something like this to that effect. It basically boils down to setting a client side event on the entire row at creation on the server. I have not tested that though, and I personally think that part alone should be another question entirely since it can be isolated to "how to cause a postback from a row click of a gridview".

A: I found solution for that. Replace your GridView1_RowDataBound function body with that:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex == GridView1.EditIndex)
            {
                //update or cancel buttons
                LinkButton updateBtn = (LinkButton)e.Row.Cells[0].Controls[0];
                string updateScript = string.Format("document.getElementById('{0}').click(); return false;", updateBtn.ClientID);
                Button1.OnClientClick = updateScript;

                LinkButton cancelBtn = (LinkButton)e.Row.Cells[0].Controls[2];
                string cancelScript = string.Format("document.getElementById('{0}').click(); return false;", cancelBtn.ClientID);
                Button2.OnClientClick = cancelScript;
            }
            else
            {
                //edit button
                LinkButton editBtn = (LinkButton)e.Row.Cells[0].Controls[0];
                string editScript = string.Format("document.getElementById('{0}').click();", editBtn.ClientID);
                e.Row.Attributes["onclick"] = editScript;
            }

        }
        if (GridView1.EditIndex >= 0)
        {
            Button1.Enabled = true;
            Button2.Enabled = true;
        }
        else
        {
            Button1.Enabled = false;
            Button2.Enabled = false;
        }
    }

First I got rid of js calls to __doPostBack with isn't good practice as julealgon mentioned in comments. Instead of that I build script that does getElementById, searches for particular linkbutton by unique client id and simulates 'click' on that link. All link buttons are still on the form but are hidden as you call your document.ready script so you won't get js error 'item not found...'
Second very important thing is to return 'false' at the end of OnClientClick script for Button1 and Button2 (OnClientClick works the same as Attributes["onclick"]).
This is to prevent button postback, without that another postback is triggered by button itself and because there is no OnClick event implemented server-side that rebinds grid and sets editindex some information is lost and when 'grid' postback is triggered (proper one, caused by link button) it does not work.
My answers assumes that all grid's server-side events like RowUpdating, RowCancelingEdit and RowEditing work or that your grid has related SqlDataSource or ObjectDataSource that implements those. In another words I assume that if you use generated Edit, Update, Cancel buttons in grid rows it all works as expected.


text:
Q: Can i add watermark on a series of pictures? I have a strong amount of pictures, which i would like to "protect" by adding watermark on them. Is there any way of adding watermark by using vb.net or C# ?

A: public void AddWatermark(string filename, string watermarkText, Stream outputStream) {
    Bitmap bitmap = Bitmap.FromFile(filename);
    Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);
    Color color = Color.FromArgb(10, 0, 0, 0); //Adds a black watermark with a low alpha value (almost transparent).
    Point atPoint = new Point(100, 100); //The pixel point to draw the watermark at (this example puts it at 100, 100 (x, y)).
    SolidBrush brush = new SolidBrush(color);

    Graphics graphics = null;
    try {
        graphics = Graphics.FromImage(bitmap);
    } catch {
        Bitmap temp = bitmap;
        bitmap = new Bitmap(bitmap.Width, bitmap.Height);
        graphics = Graphics.FromImage(bitmap);
        graphics.DrawImage(temp, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel);
        temp.Dispose();
    }

    graphics.DrawString(text, font, brush, atPoint);
    graphics.Dispose();

    bitmap.Save(outputStream);
}

A: Use ImageMagick with the .Net wrapper.

A: This blog post promises:

This article shall describe an approach to building a simple watermarking utility that may be used to add watermarks to any supported image file format. The resulting application shall permit the user to open any supported image file format into a scrollable picture box, to define the text to be applied as a watermark (with a default version supplied), to set the font and color of the watermark, to define the opacity of the watermark, to determine whether or not the watermark appears at the top or bottom of the image, and to preview the watermark prior to saving it to the image.

It should provide a good starting point.


text:
Q: How to sort dictionary keys by their appearance in a file I know that a dictionary is an unordered data type, but that it can be sorted alphabetically with the sorted() function. However, I wonder if it is definitely impossible to sort the dictionary's keys by their appearance in a file. For example, I want to extract fruit names from a txt-file and map them to the line number and timestamp. The resulting dictionary looks like this:
mydict = {
    'orange': [['1', '00:00:03,950'],  # 'fruit': [['line number', 'timestamp']]
         ['9', '00:00:24,030'],
         ['11', '00:00:29,640']],
    'cherry': [['20', '00:00:54,449']],
    'apple': [['14', '00:00:38,629']],
    'banana': [['2', '00:00:06,840'],
          ['3', '00:00:09,180'],
          ['4', '00:00:10,830']],
}

Now, I would like to sort the keys by their appearance in the file, i.e. ascending by their line number being the value's first list item.
So the desired output would be:
{'orange': [['1', '00:00:03,950'],
         ['9', '00:00:24,030'],
         ['11', '00:00:29,640']],
 'banana': [['2', '00:00:06,840'],  # changed
          ['3', '00:00:09,180'],
          ['4', '00:00:10,830']]}
 'apple': [['14', '00:00:38,629']],
 'cherry': [['20', '00:00:54,449']]}  # changed

If you consider this as a stupid question because this is not possible due to the dictionary's unordered nature, you can just comment this and I will then remove this question. However, I am thankful for any help and clarification.

A: If you want to sort the list associated with each fruit, you could do the following:
>>> mydict = {k : sorted(v, key=lambda x : int(x[0])) for k, v in mydict.items()}
>>> mydict

{'orange': [['1', '00:00:03,950'],
            ['9', '00:00:24,030'],
            ['11', '00:00:29,640']],
 'cherry': [['20', '00:00:54,449']],
 'apple': [['14', '00:00:38,629']],
 'banana': [['2', '00:00:06,840'],
            ['3', '00:00:09,180'],
            ['4', '00:00:10,830']]}

This is iterating over the key value pairs of the dictionary, and sorting the elements of each value by the int of their first element.
But to be clear, as of Python 3.7, the normal dict is ordered.  So here, you see that the fruit names are appearing in the same ordered they were created - in earlier Python this wasn't the case.
You also say you want to sort the keys (the fruit names), but it looks like you want to sort the values (the line numbers and timestamps).  If you want to additionally sort the fruit names, you could throw sorted on the call to get the items:
>>> mydict = {k : sorted(v, key=lambda x : int(x[0])) for k, v in sorted(mydict.items())}
>>> mydict

{'apple': [['14', '00:00:38,629']],
 'banana': [['2', '00:00:06,840'],
            ['3', '00:00:09,180'],
            ['4', '00:00:10,830']],
 'cherry': [['20', '00:00:54,449']],
 'orange': [['1', '00:00:03,950'],
            ['9', '00:00:24,030'],
            ['11', '00:00:29,640']]}

# now mydict's keys are in alphabetical order, and its values are also ordered by line number


text:
Q: Do compiler default options refer to implicit defaults, or default explicit Visual Studio project settings? In the Visual Studio compiler options documentation, various options are described (in a somewhat inconsistent way) as "on by default", "off by default", or similar.
As an example, this page states that /Zc:forScope is on by default.
The product being described in this set of documentation is "Visual Studio 2013" (as opposed to specifically the C++ compiler). My question therefore is, does this refer to the fact that a newly created project will pass the /Zc:forScope option to the compiler explicitly on the command line (which I have verified it does), or does it mean that the option is implicit if you call cl.exe without specifying it?
In a more general sense, if the documentation for a specific compiler option mentions a default behaviour, then can I safely ignore the switch on the command line if the default behaviour is what I want?
My assumption has always been that defaults are implicit, but then I noticed that newly created Visual Studio projects explicitly pass some of them (e.g. the aforementioned /Zc:forScope, or /analyze-). If my assumption is correct, then why the redundancy?
EDIT: I have found contradictory information in the documentation. If you run cl.exe /? then some of the options are described as "default" (suggesting that the defaults are implicit), but then this page describes a default "when an application is compiled in the development environment", which suggests to me that it is an IDE default.


text:
Q: What RegEx separates terms of Polynomial I have a String 5x^3-2x^2+5x
I want a regex which splits this string as
5x^3,
-2x^2,
5x
I tried "(-)|(\\+)",
but this did not work. As it did not consider negative power terms.

A: You can split your string using this regex,
\+|(?=-)

The way this works is, it splits the string consuming + character but if there is - then it splits using - but doesn't consume - as that is lookahead.
Check out this Java code,
String s = "5x^3-2x^2+5x";
System.out.println(Arrays.toString(s.split("\\+|(?=-)")));

Gives your expected output below,
[5x^3, -2x^2, 5x]

Edit:
Although in one of OP's comment in his post he said, there won't be negative powers but just in case you have negative powers as well, you can use this regex which handles negative powers as well,
\+|(?<!\^)(?=-)

Check this updated Java code,
List<String> list = Arrays.asList("5x^3-2x^2+5x", "5x^3-2x^-2+5x");
for (String s : list) {
    System.out.println(s + " --> " +Arrays.toString(s.split("\\+|(?<!\\^)(?=-)")));
}

New output,
5x^3-2x^2+5x --> [5x^3, -2x^2, 5x]
5x^3-2x^-2+5x --> [5x^3, -2x^-2, 5x]

A: Maybe,
-?[^\r\n+-]+(?=[+-]|$)

or some similar expressions might have been worked OK too, just in case you might have had constants in the equations.
Demo
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpression{

    public static void main(String[] args){

        final String regex = "-?[^\r\n+-]+(?=[+-]|$)";
        final String string = "5x^3-2x^2+5x\n"
             + "5x^3-2x^2+5x-5\n"
             + "-5x^3-2x^2+5x+5";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

RegEx Circuit
jex.im visualizes regular expressions:

A: In below program , You can get break of every single variable. So debug it and combine regex as you need it. It will work fine for all input.
import java.util.regex.*;

class Main
{
  public static void main(String[] args)
  {
    String txt="5x^3-2x^2+5x";

    String re1="([-+]\\d+)";    // Integer Number 1
    String re2="((?:[a-z][a-z0-9_]*))"; // Variable Name 1
    String re3="(\\^)"; // Any Single Character 1
    String re4="([-+]\\d+)";    // Integer Number 2
    String re5="([-+]\\d+)";    // Integer Number 1
    String re6="((?:[a-z][a-z0-9_]*))"; // Variable Name 2
    String re7="(\\^)"; // Any Single Character 2
    String re8="([-+]\\d+)";    // Integer Number 3
    String re9="([-+]\\d+)";    // Integer Number 2
    String re10="((?:[a-z][a-z0-9_]*))";    // Variable Name 3

    Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6+re7+re8+re9+re10,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(txt);
    if (m.find())
    {
        String int1=m.group(1);
        String var1=m.group(2);
        String c1=m.group(3);
        String int2=m.group(4);
        String signed_int1=m.group(5);
        String var2=m.group(6);
        String c2=m.group(7);
        String int3=m.group(8);
        String signed_int2=m.group(9);
        String var3=m.group(10);
        System.out.print("("+int1.toString()+")"+"("+var1.toString()+")"+"("+c1.toString()+")"+"("+int2.toString()+")"+"("+signed_int1.toString()+")"+"("+var2.toString()+")"+"("+c2.toString()+")"+"("+int3.toString()+")"+"("+signed_int2.toString()+")"+"("+var3.toString()+")"+"\n");
    }
  }
}


text:
Q: No he podido obtener datos del wsdl del dane Estoy intentando obtener datos del wsdl del dane. He revisado como acceder a traves de soap. Cuando ingreso a la direccion http://appweb.dane.gov.co/sipsaWS/SrvSipsaUpraBeanService?wsdl con un get me arroja la siguiente informacion sobre como esta el servicio:
    <?xml version='1.0' encoding='UTF-8'?>
<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is Oracle JAX-WS 2.1.5. -->
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is Oracle JAX-WS 2.1.5. -->
<definitions xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:tns="http://servicios.sipsa.co.gov.dane/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://servicios.sipsa.co.gov.dane/" name="SrvSipsaUpraBeanService">
    <types>
        <xsd:schema>
            <xsd:import namespace="http://servicios.sipsa.co.gov.dane/" schemaLocation="http://appweb.dane.gov.co:80/sipsaWS/SrvSipsaUpraBeanService?xsd=1"/>
        </xsd:schema>
    </types>
    <message name="consultarInsumosSipsaMesMadr">
        <part name="parameters" element="tns:consultarInsumosSipsaMesMadr"/>
    </message>
    <message name="consultarInsumosSipsaMesMadrResponse">
        <part name="parameters" element="tns:consultarInsumosSipsaMesMadrResponse"/>
    </message>
    <message name="promedioAbasSipsaMesMadr">
        <part name="parameters" element="tns:promedioAbasSipsaMesMadr"/>
    </message>
    <message name="promedioAbasSipsaMesMadrResponse">
        <part name="parameters" element="tns:promedioAbasSipsaMesMadrResponse"/>
    </message>
    <message name="promediosSipsaCiudad">
        <part name="parameters" element="tns:promediosSipsaCiudad"/>
    </message>
    <message name="promediosSipsaCiudadResponse">
        <part name="parameters" element="tns:promediosSipsaCiudadResponse"/>
    </message>
    <message name="promediosSipsaMesMadr">
        <part name="parameters" element="tns:promediosSipsaMesMadr"/>
    </message>
    <message name="promediosSipsaMesMadrResponse">
        <part name="parameters" element="tns:promediosSipsaMesMadrResponse"/>
    </message>
    <message name="promediosSipsaParcial">
        <part name="parameters" element="tns:promediosSipsaParcial"/>
    </message>
    <message name="promediosSipsaParcialResponse">
        <part name="parameters" element="tns:promediosSipsaParcialResponse"/>
    </message>
    <message name="promediosSipsaSemanaMadr">
        <part name="parameters" element="tns:promediosSipsaSemanaMadr"/>
    </message>
    <message name="promediosSipsaSemanaMadrResponse">
        <part name="parameters" element="tns:promediosSipsaSemanaMadrResponse"/>
    </message>
    <portType name="SrvSipsaUpraService">
        <operation name="consultarInsumosSipsaMesMadr">
            <input message="tns:consultarInsumosSipsaMesMadr"/>
            <output message="tns:consultarInsumosSipsaMesMadrResponse"/>
        </operation>
        <operation name="promedioAbasSipsaMesMadr">
            <input message="tns:promedioAbasSipsaMesMadr"/>
            <output message="tns:promedioAbasSipsaMesMadrResponse"/>
        </operation>
        <operation name="promediosSipsaCiudad">
            <input message="tns:promediosSipsaCiudad"/>
            <output message="tns:promediosSipsaCiudadResponse"/>
        </operation>
        <operation name="promediosSipsaMesMadr">
            <input message="tns:promediosSipsaMesMadr"/>
            <output message="tns:promediosSipsaMesMadrResponse"/>
        </operation>
        <operation name="promediosSipsaParcial">
            <input message="tns:promediosSipsaParcial"/>
            <output message="tns:promediosSipsaParcialResponse"/>
        </operation>
        <operation name="promediosSipsaSemanaMadr">
            <input message="tns:promediosSipsaSemanaMadr"/>
            <output message="tns:promediosSipsaSemanaMadrResponse"/>
        </operation>
    </portType>
    <binding name="SrvSipsaUpraPortBinding" type="tns:SrvSipsaUpraService">
        <soap12:binding transport="http://www.w3.org/2003/05/soap/bindings/HTTP/" style="document"/>
        <operation name="consultarInsumosSipsaMesMadr">
            <soap12:operation soapAction=""/>
            <input>
                <soap12:body use="literal"/>
            </input>
            <output>
                <soap12:body use="literal"/>
            </output>
        </operation>
        <operation name="promedioAbasSipsaMesMadr">
            <soap12:operation soapAction=""/>
            <input>
                <soap12:body use="literal"/>
            </input>
            <output>
                <soap12:body use="literal"/>
            </output>
        </operation>
        <operation name="promediosSipsaCiudad">
            <soap12:operation soapAction=""/>
            <input>
                <soap12:body use="literal"/>
            </input>
            <output>
                <soap12:body use="literal"/>
            </output>
        </operation>
        <operation name="promediosSipsaMesMadr">
            <soap12:operation soapAction=""/>
            <input>
                <soap12:body use="literal"/>
            </input>
            <output>
                <soap12:body use="literal"/>
            </output>
        </operation>
        <operation name="promediosSipsaParcial">
            <soap12:operation soapAction=""/>
            <input>
                <soap12:body use="literal"/>
            </input>
            <output>
                <soap12:body use="literal"/>
            </output>
        </operation>
        <operation name="promediosSipsaSemanaMadr">
            <soap12:operation soapAction=""/>
            <input>
                <soap12:body use="literal"/>
            </input>
            <output>
                <soap12:body use="literal"/>
            </output>
        </operation>
    </binding>
    <service name="SrvSipsaUpraBeanService">
        <port name="SrvSipsaUpraPort" binding="tns:SrvSipsaUpraPortBinding">
            <soap12:address location="http://appweb.dane.gov.co:80/sipsaWS/SrvSipsaUpraBeanService"/>
        </port>
    </service>
</definitions>

Pero cuando intento consumir el servicio no me arroja nada. Estoy cometiendo algun error de como la estoy solicitando? No tengo mucho conocimiento de como se debe de consumir este tipo de servicios y ya en algun otro momento lo hice sin ningun inconveniente pero como tal no he podido encontrar mayor documentacion y otra respuesta en la pagina del DANE o en internet. Agradezco mucho el apoyo que se me pueda brindar con este caso.
    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://servicios.sipsa.co.gov.dane/">
   <soap:Body>
    <consultarInsumosSipsaMesMadr xmlns="http://schemas.xmlsoap.org/wsdl/">
        <codProducto>500</codProducto>
    </consultarInsumosSipsaMesMadr>
  </soap:Body>
</soap:Envelope>


text:
Q: How can I use mutate() with a string column? I have a tibble something like
data <- tibble(string = c("A", "B", "C"), number = c(1,2,3))
Then I defined a function
foo <- function(string, number){
  result <- paste(replicate(number, string), collapse = "")
  return(result)
}

so that foo("A", 3) = "AAA". Now what I want to do is to add a new column new where the value for each row is foo(s, n), given that s and n are the values of string and number for the same row. I tried to do this by doing something like
mutate(data, new = foo(string, number))
but I failed and don't know why.

A: Try rowwise, therefore foo is calculated for each row.
data %>%
  rowwise() %>%
  mutate(new = foo(string, number))

Output:
# A tibble: 3 x 3
# Rowwise:
  string number new
  <chr>   <dbl> <chr>
1 A           1 A
2 B           2 BB
3 C           3 CCC

The problem might be that foo cant handle vectors. Like in this examples.
So a rowwise apprach is needed.
foo(c("A", "B"), c(1,2))
# Error in integer(n) : invalid 'length' argument

foo(data$string, data$number)
# Error in integer(n) : invalid 'length' argument

A: In this scenario, there is no need to define a new function.  This will work-
data %>% mutate(new = strrep(string, number))

# A tibble: 3 x 3
  string number new
  <chr>   <dbl> <chr>
1 A           1 A
2 B           2 BB
3 C           3 CCC


text:
Q: Rails 3.2: Replace null values with empty string from json serialization I am using Rails 3.2 serialization to convert ruby object to json.
For Example, I have serialized ruby object to following json
{
  "relationship":{
    "type":"relationship",
    "id":null,
    "followed_id": null
  }
}

Using following serialize method in my class Relationship <  ActiveRecord::Base
def as_json(opts = {})
  {
   :type        => 'relationship',
   :id          => id,
   :followed_id => followed_id
  }
end

I need to replace null values with empty strings i.e. empty double quotes, in response json.
How can I achieve this?
Best Regards,

A: I don't see the problem here. Just make it via || operator:
def as_json(opts = {})
  {
   :type        => 'relationship',
   :id          => id || '',
   :followed_id => followed_id || ''
  }
end

A: Probably not the best solution, but inspired by this answer
def as_json(opts={})
  json = super(opts)
  Hash[*json.map{|k, v| [k, v || ""]}.flatten]
end

-- Edit --
As per jdoe's comment, if you only want to include some fields in your json response, I prefer doing it as:
def as_json(opts={})
  opts.reverse_merge!(:only => [:type, :id, :followed_id])
  json = super(opts)
  Hash[*json.map{|k, v| [k, v || ""]}.flatten]
end

A: using below method you will get modified hash or json object. it will replace blank string with nill. need to pass the hash in parameter.
def json_without_null(json_object)
  if json_object.kind_of?(Hash)
    json_object.as_json.each do |k, v|
      if v.nil?
        json_object[k] = ""
      elsif  v.kind_of?(Hash)
        json_object[k] = json_without_null(v)
      elsif v.kind_of?(Array)
        json_object[k] = v.collect{|a|  json_without_null(a)}
      end
    end
  end
  json_object
end


text:
Q: Build summary table with dimension values in measures I recently engaged in OLAP and encountered the following problem.
First, some of the domain. There are auctions in which people can participate (Members). Auctions are created by users (Organizers) who turn belongs one of the Retailers.
There is quite a long and complicated chain links:
Retailers <- Organizers <- Auctions <- Fact of participation -> Members

All this is presented in the following tables DW:
DimRetailer (Id, Name)
DimOrganizer (Id, Name, RetailerId)
FactAuction (Id, DateTime, OrganizerId)
FactParticipation (UserId, AuctionId)
DimUser (Id, Name)

Tables filled with the following data:
insert into DimRetailer values (1, 'Retailer 1'), (2, 'Retailer 2')
insert into DimOrganizer values (1, 'Organizer 1', 1), (2, 'Organizer 2', 1),
    (3, 'Organizer 3', 2), (4, 'Organizer 4', 2)
insert into DimUser values (1, 'Member 1'), (2, 'Member 2'), (3, 'Member 3')
insert into FactAuction values (1, '2014/04/20', 1), (2, '2014/04/21', 2),
    (3, '2014/04/20', 3), (4, '2014/04/21', 4)
insert into FactParticipation values (1, 1), (1, 2), (1, 3), (1, 4), (2, 2),
    (3, 3), (3,4)

I need to make the result table of the form:
    Member    |    Retailer    |    Organizer
-------------------------------------------------
   Member 1   |   Retailer 1   |   Organizer 1
              |                |   Organizer 2
              |   Retailer 2   |   Organizer 3
              |                |   Organizer 4
   Member 2   |   Retailer 1   |   Organizer 2
   Member 3   |   Retailer 2   |   Organizer 3
              |                |   Organizer 4

This table shows the auctions which Organizers participated member
Is it possible to do this in SSAS and in what direction to dig?

A: In SSAS terms I would create FactParticipation as a Measure Group (with a hidden Count Measure), then reference Members to Auctions via a "Many-to-Many Relationship" (via FactParticipation).
In DW terms this would be called a "Bridge Table".
Note some really old client tools like Excel 2003 struggle to query this design accurately.


text:
Q: Number pyramind, with recursive method. Java Beginner I am a new member here, and I am also a beginner in JAVA. The thing that seems the most abstract to me is recursion, and so I have some difficulties finishing a program that should have this output if we write 3 for example:
1
12
123
12
1
Or if we write 5 for example it should print out this:
1
12
123
1234
12345
1234
123
12
1
And I can do this program with for loop, but I have to use recursion, and here is what I have done so far:
public class Aufgabe3 {

    private static void printSequenz(int n) {
if(n<1){
    return;
   }
        printMany(n);
        printSequenz(n-1);
    }

    private static void printMany(int n){
        for(int i=1;i<=n;i++){
            System.out.print(i);
        }
        System.out.println();
    }

    public static void main(String[] args) {
printSequenz(5);
    }

}

I would be really happy if someone would help me :).

A: You need to implement two recursive functions:
void printLoToHi(int n)
{
    if (n < 1)
        return;
    printLoToHi(n-1);
    printMany(n);
}

void printHiToLo(int n)
{
    if (n < 1)
        return;
    printMany(n);
    printHiToLo(n-1);
}

Then, you need to call them sequentially:
printSequenz(int n)
{
    printLoToHi(n);
    printHiToLo(n-1); // -1 in order to avoid printing the highest twice
}

Or in a more "symmetrical manner":
printSequenz(int n)
{
    printLoToHi(n-1); // print lowest to second highest
    printMany(n);     // print the highest
    printHiToLo(n-1); // print second highest to lowest
}

A: You could do it like this:
private static void printSequenz(int n) {

    printSequenz(1,n, true);

}

private static void printSequenz(int current, int total, boolean goingUp) {
    if(!goingUp && current<1){
        return;
    }

    printMany(current);
    if(current+1>total){
        goingUp=false;

    }
    if(goingUp){
        printSequenz(current+1,total,goingUp);
    } else {
        printSequenz(current-1,total,goingUp);
    }

}

private static void printMany(int n) {
    for (int i = 1; i <= n; i++) {
        System.out.print(i);
    }
    System.out.println();
}

public static void main(String[] args) {
    printSequenz(5);
}

A: public class Test {
    public static void main(String args[]) {
        int seq = 6;
        for(int i=1; i<=seq; i++) {
            System.out.println("");
            int low =seq-(seq-i);
            printIncreasing(i,low);
        }
        for(int i=seq-1; i>=1; i--) {
            System.out.println("");
            int low = seq-i;
            printDecreasing(i,low);
        }
    }

    public static void printIncreasing(int high, int low) {
        for(int i = 1; i<=high;i++ ) {
            System.out.print(i);
        }
    }

    public static void printDecreasing(int high, int low) {
        for(int i = 1; i<=high;i++ ) {
            System.out.print(i);
        }
    }
}


text:
Q: Code Pause not working the way I expect I am trying to animate buttons like in the game of Simon, where it generates a random sequence of 4 buttons to press, displays the order though the button animation, then takes user input to match the sequence generated. I found a pause method using Handlers to use in android. I thought I captured the functionality correctly but instead of pausing each request, it paused at the beginning of execution then animates all the buttons at once so knowing the sequence is practically impossible when it flashed all three buttons at once. Here is what I have as far as the button animation goes.
//Send the buttons to animate, this shows the sequence that is stored to match
private void show(final Button first,final Button second,final Button third,final Button fourth)
   {
       int caseChoice = 0;

       for (int i = 0; i < currentCount; i++)
       {
           caseChoice = matching[i];
           switch (caseChoice)
           {
           case 0:
               mHandler.postDelayed(new Runnable() {
                    public void run() {
                        animDelay(first);
                    }
                }, 6000);
               break;
           case 1:
               mHandler.postDelayed(new Runnable() {
                    public void run() {
                        animDelay(second);
                    }
                }, 6000);
               break;
           case 2:
               mHandler.postDelayed(new Runnable() {
                    public void run() {
                        animDelay(third);
                    }
                }, 6000);
               break;
           case 3:
               mHandler.postDelayed(new Runnable() {
                    public void run() {
                        animDelay(fourth);
                    }
                }, 6000);
               break;

           }
       }
   }

   //used to delay button animation, the button it is sent (reusable)
   private void animDelay(Button theButton)
   {
       Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.anim_alpha);
       theButton.startAnimation(animAlpha);
   }

A: Your current code iterates through, posting a delayed action to occur in 6 seconds time.
The loop iterates through very fast, so all the posts for "something to happen in 6 sec" are very close together.
If you want each successive action to be posted later you should do something like:
mHandler.postDelayed(new Runnable() {
                    public void run() {
                        animDelay(first);
                    }
                }, (i * 6000) );


text:
Q: Navigation with BeautifulSoup I am slightly confused about how to use BeautifulSoup to navigate the HTML tree.
import requests
from bs4 import BeautifulSoup

url = 'http://examplewebsite.com'
source = requests.get(url)
content = source.content
soup = BeautifulSoup(source.content, "html.parser")

# Now I navigate the soup
for a in soup.findAll('a'):
    print a.get("href")

*

*Is there a way to find only particular href by the labels? For example, all the href's I want are called by a certain name, e.g. price in an online catalog.

*The href links I want are all in a certain location within the webpage, within the page's  and a certain . Can I access only these links?

*How can I scrape the contents within each href link and save into a file format?

A: With BeautifulSoup, that's all doable and simple.

(1) Is there a way to find only particular href by the labels? For
  example, all the href's I want are called by a certain name, e.g.
  price in an online catalog.

Say, all the links you need have price in the text - you can use a text argument:
soup.find_all("a", text="price")  # text equals to 'price' exactly
soup.find_all("a", text=lambda text: text and "price" in text)  # 'price' is inside the text

Yes, you may use functions and many other different kind of objects to filter elements, like, for example, compiled regular expressions:
import re

soup.find_all("a", text=re.compile(r"^[pP]rice"))

If price is somewhere in the "href" attribute, you can have use the following CSS selector:
soup.select("a[href*=price]")  # href contains 'price'
soup.select("a[href^=price]")  # href starts with 'price'
soup.select("a[href$=price]")  # href ends with 'price'

or, via find_all():
soup.find_all("a", href=lambda href: href and "price" in href)

(2) The href links I want are all in a certain location within the
  webpage, within the page's and a certain . Can I access only these
  links?

Sure, locate the appropriate container and call find_all() or other searching methods:
container = soup.find("div", class_="container")
for link in container.select("a[href*=price"):
    print(link["href"])

Or, you may write your CSS selector the way you search for links inside a specific element having the desired attribute or attribute values. For example, here we are searching for a elements having href attributes located inside a div element having container class:
soup.select("div.container a[href]")

(3) How can I scrape the contents within each href link and save into
  a file format?

If I understand correctly, you need to get appropriate links, follow them and save the source code of the pages locally into HTML files. There are multiple options to choose from depending on your requirements (for instance, speed may be critical. Or, it's just a one-time task and you don't care about performance).
If you would stay with requests, the code would be of a blocking nature - you'll extract the link, follow it, save the page source and then proceed to a next one - the main downside of it is that it would be slow (depending on, for starters, how much links are there). Sample code to get you going:
from urlparse import urljoin

from bs4 import BeautifulSoup
import requests

base_url = 'http://examplewebsite.com'
with requests.Session() as session:  # maintaining a web-scraping session
    soup = BeautifulSoup(session.get(base_url).content, "html.parser")

    for link in soup.select("div.container a[href]"):
        full_link = urljoin(base_url, link["href"])
        title = a.get_text(strip=True)

        with open(title + ".html", "w") as f:
            f.write(session.get(full_link).content)

You may look into grequests or Scrapy to solve that part.


text:
Q: Host a site on a Mac I have
my website locally on my Mac ready to host.
It is accessible locally via http://localhost running on MAMP.
Let's say my static public IP from my ISP  is : 201.23.45.23
and I've already linked that IP with a domain like this : 201.23.45.23 —> http://mysite.online

Goal
I want to make my site accessible on the web, and host it on my local Mac.
I want my clients to see what I see on my http://localhost  when they visit
http://201.23.45.23
or
http://mysite.online

Note
I know that I can purchase a VPS or shared host, but the my intention here is to learn how to do it on my own on my local machine.

Question
Do I need to update my router to open port 80 and configure a port forward for that port?
Do I need to download an extra FTP server app like FileZilla to configure this ?
How would one go about and configure something like this ?
Any hints/suggestions/directions on this will be much appreciated !

A: Usually you don't need any additional tools like FTP-clients because you already have direct access to your file system via the Finder or the shell.

Since your host resides in a private network and connects to the internet via a gateway (your router) remote users don't have direct access to your Mac - they don't even know that it exists.
To enable access for remote users, you have to forward the public port 80 (and possibly port 443) on the router to the respective host's ports. Usually the router interface already contains preconfigured port-forwarding rules or you have to add them yourself:
public-router-ip:public-port –> host-ip:private-port

Here is an example of a D-Link router interface. Here I assume your host has the IP 192.168.0.2 and your web-server has the ports 80/443 open, the router's IP is 201.23.45.23:

All requests to 201.23.45.23:80 and 201.23.45.23:443 are forwarded to your internal host and its respective ports then: 192.168.0.2:80 and 192.168.0.2:443.
Name is here: a human readable name tagging the service. This may be the protocol name (e.g. HTTP) or a service name (e.g. Web server (http)). The drop down menu Application Name will probably auto-populate it - I don't own a D-Link Router so I don't know this.
In IP Address enter the IP address of your local Mac hosting the web server - not your public IP. The drop down menu Computer Name will probably show all available hosts in your internal network.
Public/Private Port as well as Traffic Type are self-explanatory.
The designations may differ slightly in your router's interface!
The standard MAMP http/https ports are 8888 and 8890 though. If you haven't changed this, the proper port-forwarding rules on the router would look like this then:

This means: all requests to 201.23.45.23:80 will be forwarded to 192.168.0.2:8888 and 201.23.45.23:443 to 192.168.0.2:8890 respectively.
You may even tell your clients to access the web server at port 20080/20443 (e.g. mysite.online:20080/main.htm). This is not recommended and inconvenient for your clients - it's just an example to show how to do it.
The forwarding rules with the standard MAMP http/https ports are then:

If you want to operate your own web server like this, I advise to set up a virtual machine (connected to a bridged interface - not NATed!) with VirtualBox, VMware Fusion or Parallels, install OS X & MAMP and run it there.
This will prevent ravaging your real system.


text:
Q: How to get the http response for NSURLConnection without using delegates I would like to know if there is a way to get the HTTP response for a NSURLConnection without making use of the delegate provided by Apple.
For example if I setup a connection in the following manner:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"player.UpdateProfile" forHTTPHeaderField:@"player-profile"];
[self addHttpHeaders:request];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately: YES];

Now here instead of delegating to self and parsing the response in the didReceiveResponse method, can I create a custom delegate where I can parse the response? I don't need a complete tutorial on how to do it but a nudge in the right direction would be appreciated. Thanks

A: NSURLConnection is probably easier to use these days with:
[NSURLConnection sendAsynchronousRequest: urlRequest
                                   queue: [NSOperationQueue mainQueue]
                       completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error)
{
}

This avoids having to create any delegate object at all. Be warned: Its very difficult to cancel this sort of request, so make sure you put safeguards in the response handler.


text:
Q: react-google-maps : Can't get bounds I have the following react component that loads a GoogleMap from 'react-google-maps' library. I'm following the documentation examples but I get undefined from getBounds() function. I think it is due to trying to get the bounds before map is fully loaded but can't find a solution.
@inject("map") @observer
export default class Map extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        const mapStore = this.props.map
        const GettingStartedGoogleMap = withGoogleMap(props => (
            <GoogleMap
                ref={props.onMapLoad}
                style={{
                    height: 100,
                    width: 100,
                }}
                defaultOptions={{ styles: this.mapStyles }}
                defaultZoom={mapStore.zoom}
                defaultCenter={{ lat: mapStore.center.lat, lng: mapStore.center.lng }}>
                {
                    mapStore.markers.map(({ lat, lng }) => {
                        return <Marker
                            position={{ lat, lng }}
                            icon={{
                                url: require('../../images/marker.png')
                            }}
                        />
                    })
                }
            </GoogleMap>
        ))

        return (
            <GettingStartedGoogleMap
                style={{
                    height: 100,
                    width: 100,
                }}
                onMapLoad={(googleMap) => {
                    console.log(googleMap.getBounds())
                }}
                containerElement={

                }
                mapElement={

                } />
        )
    }
}

Thanks in advance

A: you can use 'onIdle' to make sure map is fully ready
<GoogleMap
   ref={props.onMapLoad}
   ...
   onIdle={props.onMapIdle}
>
   ...
</GoogleMap>
and
<GettingStartedGoogleMap
   onMapIdle={ ()=> { console.log('map is ready') } }
   ...
/>


text:
Q: Azure Mobile Services Login Jwt Invalid I am using the Azure Mobile Services library and attempting to create a custom identity provider. I am running the server in Azure. I've created a custom login controller which issues JWTs upon successful login, but the generated JWTs appear to be invalid (signature fails to validate on jwt.io (using the signing key from Kudu), and server rejects the tokens as invalid when used to authenticate). The server-side code is below:
public TenantAuthController()
{
   _serviceContext = new MobileServiceContext();
   _signingKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
   var website = Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME");
   _audience = $"https://{website}/";
   _issuer = $"https://{website}/";
}

[HttpPost]
public IHttpActionResult Post([FromBody] TenantLoginRequest request)
{
   if (string.IsNullOrEmpty(request.TenantName) || string.IsNullOrEmpty(request.Password)) return BadRequest();
   (var valid, var tenant) = ValidateAuthRequest(request);
   if (!valid) return Unauthorized();

   var claims = new[]
   {
      new Claim(JwtRegisteredClaimNames.Sub, $"{tenant.Id}")
   };

   var token = AppServiceLoginHandler.CreateToken(claims, _signingKey, _audience, _issuer, TimeSpan.FromDays(365)); // TODO Token refresh

   return Ok(
      new TenantLoginResponse
      {
         Tenant = tenant,
         Token = token.RawData,
      }
   );
}

I have authentication enabled on the Azure App Service and I've confirmed through remote debugging that the signing key is correct. Is there anything I'm doing wrong in my controller or configuration that would cause the jwt to be invalid?

A: If the token will not parse on JWT.IO, it is invalid. It appears you are attempting to encrypt a value that is not the bearer token. From you code, it seems like you are trying to encrypt your "Tenant ID". The tenant is like subscription name in azure, and is not related to the token.
What is in AppServiceLoginHandler.CreateToken()? Is this custom code, or MSFT code? It seems like this is where your problem is coming from...


text:
Q: ¿Como hacer funcionar un gif cargando al usar el window.location.href al descargar un documento? Tengo el siguiente evento click, que al exportar un pdf, se descarga, pero quería colocar una animación gif cargando mientras se genera. He tratado de hacerlo así:
 $("#export_pdf").click(function (e) {
        e.preventDefault();
        $("#ajax_loader").css("display", "");
        var formato = "PDF";
        var url = "/Obras/Export?format=" + formato + "&nombreObra=" + $('#nombre_obra').val();
        window.location.href = url;
        $("#ajax_loader").hide();
    });

Pero no se alcanza a mostrar la imagen del div cargando ajax_loader.
Estoy exportando un documento en PDF, usando MVC C# y jquery, por lo que no me funcioan usar ajax, así que uso window.location.href.
He intentado de hacerlo, pero no me da resultado. Si alguien tiene alguna idea, se lo agradecería bastante.

A: Depende mucho de la instantaneidad que tenga esa generación. Podrías generar el link de descarga dinámicamente y luego de un segundo pincharlo programáticamente, momento en que ocultas el "loading".
En chrome no va a funcionar porque el atributo download es ignorado, pero lo siguiente podría funcionar en Firefox dado que pidas el PDF al mismo origen desde donde ejecutas el script. En el snippet de más abajo no va a funcionan nunca porque estos snippets se ejecutan en un sandbox que impide el uso de esta clase de recursos externos.
Voy a dejar esta respuesta como experimento:

jQuery(document).ready(function() {

    jQuery('#descargar').on('click', function() {

     jQuery('#loading').addClass('visible');

     var a = document.createElement('a');
     a.innerText='descargando';
   a.target = '_blank';
   a.download = 'mipdf.pdf';
     a.href="https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf";

     document.getElementById('caja').appendChild(a);

      window.setTimeout(function() {
       a.click();
       jQuery('#loading').removeClass('visible');
     },1500);
   });

});
#caja {
height: 150px;
width:150px;
}
#descargar {
 padding:3px;
 border: 1px solid;
 width: 120px;
 cursor: pointer;
}

#milink {
  display:block;

}

#loading {
  opacity:0;
  height:100px;
  width:130px;
  transition: opacity: 1s;

}

#loading.visible {
  opacity: 1;
  transition: opacity 1s;
}

  <button id="descargar">Descarga el PDF</button>

Lo más probable es que firefox en realidad te lleve al visor de PDF del documento que querías descargar.
Pero ya que el documento se sirve desde el backend, en el mismo backend podrías ponerle un header que obligue a tratarlo como attachment para descarga.


text:
Q: Application called an interface that was marshalled for a different thread I get this exception:

The application called an interface that was marshalled for a different thread

from my code:
private void Rec_ResultGenerated(SpeechContinuousRecognitionSession sender,SpeechContinuousRecognitionResultGeneratedEventArgs args)
    {

        switch (args.Result.Text)
        {
            case "switch one":
                status.text="Room 1 light switched"; //Error here
                break;
            case "switch two":
                status.text="Room 2 light switched"; //Error here
                break;
            default:
                break;
        }
    }

Any ideas?


text:
Q: INDEX MATCH formula stops working when creating a table Let's say I have the folowing values setup in excel:
1 | 2 | 3 |

a | b | c |

Above thess values I have a INDEX MATCH formula that looks up a translation of the numbers 1-3:
=INDEX(PartnersProjects[Name];MATCH(K1;PartnersProjects[ID];0))

K1` is the reference to value "1" and picks up "Test1" with current output:
Test1 | Test2 | Test3 |
  1   |   2   |   3   |
  a   |   b   |   c   |

But when I convert the 2 rows with according 3 colums (1-3 and a-c) to a table, the formula in the row above stops working some how. How to solve this?

A: When you make the row 1, 2, 3 as the header row of a table, this forces Excel to evaluate it as a string because these becomes the names of the columns.
You have two solutions:
1- Convert the searched value (K1) to numeric before matching:
=INDEX(PartnersProjects[Name],MATCH(VALUE(K1),PartnersProjects[ID],0))
'                                   ^^^^^^^^^

2- Convert the search range to text, but then you will need an ^array (CSE) formula:
=INDEX(PartnersProjects[Name],MATCH(K1,TEXT(PartnersProjects[ID], "0"),0))
' Ctrl+Shift+Enter                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^