text:
Q: Transform an array without using `transpose` Looking for a way to take the swingers array below and swap all the partners while keeping male/female pairs. What I find confusing is how to iterate over two dimensional arrays

Implement a Swingers game. The method swingers should take an array
  of couple arrays and return the same type of data structure, with the
  couples mixed up. Assume that the first item in the couple array is a
  man, and the second item is a woman. Don't pair a person with someone
  of their own gender (sorry to ruin your fun). An example run of the
  program:

swingers([
  ["Clyde", "Bonnie"],
  ["Paris", "Helen"],
  ["Romeo", "Juliet"]
])

A: Sure, you don't need to use transpose at all:
def swingers(pairs)
  gents = pairs.map(&:first)
  ladies = pairs.map(&:last)
  gents.shuffle.zip(ladies.shuffle)
end

A: The answer depends on what "couples mixed up" means. I suspect that if Bob and Zelda came to the party together, they probably would not be paired with each other. (I'm just going on what I've heard about swingers' parties). Let's say "couples" attend the party and a "valid pairing" is one where no pairing is a couple.
couples = [
  ["Clyde", "Bonnie"],
  ["Paris", "Helen"],
  ["Romeo", "Juliet"]
]

Without randomization
The word "random" does not appear in the problem description, so any  valid pairing may be acceptable. If that's the case, here's one way you could do that:
couples.map(&:first).zip(couples.map(&:last).rotate 1)
  #=> [["Clyde", "Helen"], ["Paris", "Juliet"], ["Romeo", "Bonnie"]]

With randomization
If randomization is required, here's a way to obtain a valid random pairing:
def pair_em(couples)
  h = Hash[couples]
  gents, ladies = h.keys.shuffle, h.values.shuffle
  a = gents.map { |g| [g, (h[g]==ladies.first) ? ladies.pop : ladies.shift] }
  # Swap last two gents' ladies if last pairing was a couple
  (a[-2][-1], a[-1][-1] = a[-1][-1], a[-2][-1]) if h[a[-1].first] == a[-1].last
  a
end

10.times { p pair_em(couples) }
[["Paris", "Bonnie"], ["Clyde", "Juliet"], ["Romeo",  "Helen"]]
[["Romeo",  "Helen"], ["Paris", "Bonnie"], ["Clyde", "Juliet"]]
[["Romeo",  "Helen"], ["Paris", "Bonnie"], ["Clyde", "Juliet"]]
[["Romeo", "Bonnie"], ["Clyde",  "Helen"], ["Paris", "Juliet"]]
[["Clyde", "Juliet"], ["Romeo",  "Helen"], ["Paris", "Bonnie"]]
[["Paris", "Bonnie"], ["Romeo",  "Helen"], ["Clyde", "Juliet"]]
[["Paris", "Bonnie"], ["Clyde", "Juliet"], ["Romeo",  "Helen"]]
[["Romeo",  "Helen"], ["Clyde", "Juliet"], ["Paris", "Bonnie"]]
[["Paris", "Juliet"], ["Romeo", "Bonnie"], ["Clyde",  "Helen"]]
[["Clyde", "Juliet"], ["Romeo",  "Helen"], ["Paris", "Bonnie"]]

Is it necessary to shuffle both the gents and ladies (as I've done) to ensure that the randomization is unbiased? I don't think so, but I'm not sure about that.
Alternatively, one could simply loop using @Chris' solution until a valid pairing is obtained.


text:
Q: DojoToolkit: dojox.charting.DataSeries, how to connect to data refresh event? I'm new to JavaScript and Dojo so please bear with me. I'm trying to create a Pie chart using DataSeries object, like this:
var skillStore = new dojo.data.ItemFileReadStore({
    url: "/data/skillhead.json"
});

function formatPieChartData(store, item) {
  var tooltips = {
    AVAILABLE: "Available agents",
    ONACD: "Agents on ACD calls",
    INACW: "Agents in ACW",
    INAUX: "Agents in AUX",
    AGINRING: "Agents with ringing phones",
    OTHER: "Agents otherwise occupied",
  };

  var ivalue = store.getValue(item, "value");
  var legend = store.getValue(item, "legend");
  var tooltip = tooltips[store.getValue(item, "field")];

  var o = { y: ivalue, legend: legend, tooltip: tooltip }
  return o;
}

/* This is how the data looks like after massaging
var chartData = [
    { y: 10, legend: "AVAIL", tooltip: "Available agents" },
    { y: 20, legend: "ONACD", tooltip: "Agents on ACD calls" },
    { y: 30, legend: "INACW", tooltip: "Agents in ACW" },
    { y: 40, legend: "INAUX", tooltip: "Agents in AUX" },
    { y: 50, legend: "INRING", tooltip: "Agents with ringing phones" },
    { y: 60, legend: "OTHER", tooltip: "Agents otherwise occupied" }
];
 */

var series = new dojox.charting.DataSeries(skillStore,
    { query: {
        field: new RegExp("INACW|INAUX|AGINRING|OTHER|" +
                  "AVAILABLE|ONACD")
    } },
    formatPieChartData);

dojo.addOnLoad( function() {

chart = new dojox.charting.Chart("chartNode");
chart.setTheme(dojox.charting.themes.PrimaryColors);

chart.addPlot("default", {
    type: "Pie",
    radius: 85,
    labels: false,
    ticks: false,
    markers: false
});
chart.addSeries("default", series);

var highlight = new dojox.charting.action2d.Highlight(chart, "default");
var tip = new dojox.charting.action2d.Tooltip(chart, "default");

grid.startup();
chart.render();

legend = new dojox.charting.widget.Legend({
        chart: chart,
        horizontal: false,
        style: "font-size: 11px;",
        },
        "chartLegend");
legend.startup();

setTimeout(function(){ legend.refresh() }, 1000);
});

It works fine, except one thing: I don't like the fixed timeout. I have to refresh legend after the data is loaded, otherwise it is not displayed; however I don't know which event to attach to in order to refresh legend right after the data is fetched. I see DataSeries class has onFetchError event but no onFetchSuccess event. How do I know that the data was loaded successfully?

A: I know this is late, but I'm posting it anyway in case anyone has the same issue. I took a look through DataSeries.js and they have an undocumented hook they are using. I can't promise you this will stay the same throughout api updates, it looks something like:
dojo.connect(dataSeries, "_onFetchComplete", myObj, "myFunction");

See http://dojotoolkit.org/reference-guide/dojo/connect.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I plot a running cumulative total from individual records in R? I have a dataset where different cities go in and out of a program, like this example dataset:
example.dat <- data.frame (c(1000, 2000, 3000), c("15-10-01", "16-05-01", "16-07-01"), c("16-06-01", "16-10-01", "17-08-01"))
colnames(example.dat) <- c("Population", "Enter.Program", "Leave.Program")

This gives you a data frame that looks like:
Population  Enter.Program Leave.Program
1000        15-10-01      16-06-01
2000        16-05-01      16-10-01
3000        16-07-01      17-08-01

First, I'd like to create an output table like this:
Per.Begin   Per.End     Total.Pop.In
15-10-01    16-04-30    1000
16-05-01    16-05-30    3000
16-06-01    16-06-30    2000
16-07-01    16-09-30    5000
16-10-01    17-07-30    3000
17-08-01    18-04-26    0

And then plot this in ggplot as a graph that looks like either a step function or kind of like a jagged rectangular surface where the top edge is the running total, kind of like a cumulative density function but where the y-axis can go down as well as up, and where the x-axis goes in steps that are the width of time periods.
Here are the steps I've blocked out, but I don't know how to execute:

*

*Make column of unique dates

*Make column of period change end dates (i.e., next unique date minus one day)

*Calculate running sum of the cities within each period (i.e., third column)

*Plot in ggplot

A: Using dplyr (because you tagged the question with it) you can do what you want.  The main things that need to happen are:

*

*Break out your entries and exits making your population positive and negative.

*Get all the dates from your earliest to your last so you can have the desired blocky lines. It is probably possible to do this without every date, but this is easy and requires less thinking.

Code is below
library(dplyr)
library(ggplot2)

example.dat <- data.frame (c(1000, 2000, 3000), c("15-10-01", "16-05-01", "16-07-01"), c("16-06-01", "16-10-01", "17-08-01"))
colnames(example.dat) <- c("Population", "Enter.Program", "Leave.Program")

changes = example.dat %>%
  select("Population","Date"="Enter.Program") %>%
  bind_rows(example.dat %>%
              select("Population","Date"="Leave.Program") %>%
              mutate(Population = -1*Population)) %>%
  mutate(Date = as.Date(Date,"%y-%m-%d"))

startDate = min(changes$Date)
endDate = max(changes$Date)
final = data_frame(Date = seq(startDate,endDate,1)) %>%
  left_join(changes,by="Date") %>%
  mutate(Population = cumsum(ifelse(is.na(Population),0,Population)))

ggplot(data = final,aes(x=Date,y=Population)) +
  geom_line()

UPDATE
If you don't want to have every date from the earliest to the latest, you can use a blurgh for loop to add the needed rows to get a pretty result.  Here we walk through and duplicate each date after the first with the preceding cumulative sum. It's not pretty, but it makes the graph.
library(dplyr)
library(ggplot2)

example.dat <- data.frame (c(1000, 2000, 3000), c("15-10-01", "16-05-01", "16-07-01"), c("16-06-01", "16-10-01", "17-08-01"))
colnames(example.dat) <- c("Population", "Enter.Program", "Leave.Program")

changes = example.dat %>%
  select("Population","Date"="Enter.Program") %>%
  bind_rows(example.dat %>%
              select("Population","Date"="Leave.Program") %>%
              mutate(Population = -1*Population)) %>%
  mutate(Date = as.Date(Date,"%y-%m-%d")) %>%
  arrange(Date) %>%
  mutate(Population = cumsum(Population))

for(i in nrow(changes):2){
  changes = bind_rows(changes[1:(i-1),],
            data_frame(Population = changes$Population[i-1],Date = changes$Date[i]),
            changes[i:nrow(changes),])
}

ggplot(data = changes,aes(x=Date,y=Population)) +
  geom_line()


text:
Q: How to place 2 Input boxes on 1 line Could I ask how I could place these input boxes and the Sumbit button on the same line please?

            <form action = "Login.php" method = "post">
               Username: <input type = "text" name "Username" size = "10">
               Password: <input type = "text" name "Password" size = "10">
               <input type = "Submit">
            </form>

Thats the source code I have... It shows above my NavBar to the left, however I expected this to show on that same line, but it never it placed it as all under each other.
Thanks.

A: *

*Don't use tables for layout

*use label tag

*Assign style float: left to both: labels and input fields. Then add clear below them (if you have any issues with elements overlapping each other).

Alternative would be to assign display: inline to the input fields.

A: You can apply this style to the form:
form {
    display: inline-block;
    width: 400px; /* or whatever width makes it work for you */
}

A: Try this for your css.
input {
   float: left;
}

If you want to add some spacing. You can do something like this
input {
       float: left;
       margin-right: 5px;
}

A: Change the inner table definition to something like:
<form action="Login.php" method="post">

                Username:
                <input type="text" name "Username" size="10" />
            Password:
                <input type="text" name "Password" size="10" />

                    <input type="Submit" />

</form>

Fiddle link.


text:
Q: Cannot declare List property in the JPA @Entity class. It says 'Basic' attribute type should not be a container I have a JPA @Entity class Place, with some properties holding some information about a place, such as name of place, description, and URLs of some images.
For the URLs of images, I declare a List<Link> in my entity.

However, I am getting this error:

Basic attribute type should not be a container.

I tried to remove @Basic, but the error message is still there. Why does it shows this error?

A: Change @basic to @OneToMany for List types

A: Or you can mark it as @Transient if it doesn't exist on DB table.
@Transient
private List<String> authorities = new ArrayList<>();

A: You can also use @ElementCollection:
@ElementCollection
private List<String> tags;

A: You are most likely missing an association mapping (like @OneToMany) and/or @Entity annotation(s).
I had a same problem in:
@Entity
public class SomeFee {
    @Id
    private Long id;
    private List<AdditionalFee> additionalFees;
    //other fields, getters, setters..
}

class AdditionalFee {
    @Id
    private int id;
    //other fields, getters, setters..
}

and additionalFees was the field causing the problem.
What I was missing and what helped me are the following:

*

*@Entity annotation on the generic type argument (AdditionalFee) class;

*@OneToMany (or any other type of association that fits particular business case) annotation on the private List<AdditionalFee> additionalFees; field.

So, the working version looked like this:
@Entity
public class SomeFee {
    @Id
    private Long id;
    @OneToMany
    private List<AdditionalFee> additionalFees;
    //other fields, getters, setters..
}

@Entity
class AdditionalFee {
    @Id
    private int id;
    //other fields, getters, setters..
}

A: As the message says, @Basic should not be used for containers (e.g. Java collections). It is only to be used for a limited list of basic types. Remove the @Basic annotation on that field.
If, as you say in the question, the error message is still there, you might need to try the following steps in order:

*

*Save the file

*Close and reopen the file

*Clean and rebuild the project

*Restart the IDE

(these are generic steps, which I use when an IDE is generating a compilation error that obviously makes no sense.)

A: The error seems not have impact on GAE since I can run the app and store data into storage. I guess it's a bug in IntelliJ IDEA and you can simply ignore it.

A: This can also happen when your class is missing its @Entity annotation. When you get weird warnings like these, sometimes it helps to try and compile and see if the compiler complains.

A:
'Basic' attribute type should not be a container

This error occurs when you declare an existing entity as an attribute in the current Entity without declaring the relationship type which could be either of the JPA relationships.
Detailed Article on JPA relationships


text:
Q: Jenkins - MavenBuild.getMavenArtifacts() Returns Null Since Jenkins 1.460, calling getMavenArtifacts() on an instance of MavenBuild is returning null, whereas previously that would work fine.
Have there been breaking changes in the Jenkins API, or is this a Jenkins bug?
The code I'm executing is a post-build System Groovy script, that exposes the Maven version of a build as an environment variable for subsequent steps in the Jenkins build process to use:
import hudson.model.*;
import hudson.util.*;

def thr = Thread.currentThread();
def currentBuild = thr?.executable;
def mavenVer = currentBuild.getMavenArtifacts().getModuleRecords()[0].mainArtifact.version;
def newParamAction = new hudson.model.ParametersAction(new hudson.model.StringParameterValue("MAVEN_VERSION", mavenVer));
currentBuild.addAction(newParamAction);

A: I found a workaround, although I don't know why an unannounced breaking change was made to the API - hopefully it's a bug that will get fixed.
Substitute:
def mavenVer = currentBuild.getMavenArtifacts().getModuleRecords()[0].mainArtifact.version;

for
def mavenVer = currentBuild.getParent().getModules().toArray()[0].getVersion();


text:
Q: Query across parents not returning any data I'm making a query on firebase-firestore, but it doesnt return any data
my code is.
 Here is where all categories are printed and where you get the id of each category:

        Categorias

          <mat-icon>category</mat-icon>
          {{categoria.nome}}

this is my query, No error, but no data:
produtos: Observable<Produtos[]>;
  produtosCollection: AngularFirestoreCollection<Produtos>;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private produtoService: ProdutosService,
    private afs: AngularFirestore
    ) { }

ngOnInit() {
        const categoria = this.route.snapshot.paramMap.get('id');
        this.produtosCollection = this.afs.collection('produtos', ref => {
          return ref.where('categoria', '==', categoria);
        });
        this.produtos = this.produtosCollection.valueChanges();
      }

Only the content of tag h1 is being prepared the rest nothing:

Test

{{produto.descricao}}


text:
Q: How can I merge all the changes from 1 branch to another In git, I have a branch with multiple commits, can I merge all the changes in that branch to another brach that I just created?
Thank you.

A: In a terminal:
$ cd path_to_you_rep
$ git checkout new_branch
$ git merge old_branch


text:
Q: Contents of text file into SQL Server table, using SSIS I have a number of flat text files whose contents I need to import into an SQL Server table that I have previously created. I am using a SSIS package that utilises an import column task. This works, however, it fails to preserve any line feeds.
Just to clarify, the text on each of the files is meant to be imported into one column/row, so if the text on the file is
The cat is big
and the dog is small

the line feed needs to be preserved when imported into SQL Server. At the moment, what I get is:
The cat is big and the dog is small

Many thanks in advance.
EDIT:
Paths.txt:
C:\Users\xxxx\Documents\DEV_SANDPIT_TEST_RESOURCES\TextFileToTableField\test1.txt
C:\Users\xxxx\Documents\DEV_SANDPIT_TEST_RESOURCES\TextFileToTableField\test2.txt
C:\Users\xxxx\Documents\DEV_SANDPIT_TEST_RESOURCES\TextFileToTableField\test3.txt
C:\Users\xxxx\Documents\DEV_SANDPIT_TEST_RESOURCES\TextFileToTableField\test4.txt
test1.txt

data flow:

Hope that helps.

A: By default SSIS row delimiter is set to {CR}{LF}. If the text file are generated on a unix-like system then the line delimiter is only {LF}. This could be one reason why you don't see two lines when importing, so if you are not able to see what the actual delimiter is (notepad++ will do) then just test by changing the header and row delimiters in SSIS connection manager to {LF}.


text:
Q: Losing transparent background when downloading an external PNG image I'm displaying an external image in an image view by fist downloading it like this:
bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());

Then setting this bitmap to the ImageView like this:
imageView.setImageBitmap(bitmap);

This works all good except that one of the images is a PNG and I lose the transparent background when using the BitmapFactory.
Can anyone tell me how I can keep the transparent background?

A: not sure if this will help, but try following this advice and adding Options to make sure that your image is pulled in as ARGB_8888
http://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeFile(java.lang.String, android.graphics.BitmapFactory.Options)


text:
Q: How to start kafka server programmatically we are trying to start the kafka server (zookeeper and broker) programmatically in our application. Any api / library available for the same?

A: Yes, you can use embedded Kafka, which will run zookeeper and kafka server for you. It is generally used for testing kafka producer/consumer where there is no need to explicitly run them.
For more detail refer
To run it, we write EmbeddedKafka.start() at the start and  EmbeddedKafka.stop() at the end.


text:
Q: How to do something if a marker is touched for 3 seconds I have an application with google maps api v2 with some markers on it. For each marker if I click on it it apears a ballon with some details about it title etc.
With SystemClock it only waits for 3 seconds but it does the action.
I want to do something if a user is pressing of X seconds on that marker? I tried using a thread but I did't manage to do it.
if (onBalloonTap(currentFocusedIndex, currentFocusedItem)) {
            long thisTime = 0;
            thisTime = SystemClock.uptimeMillis();
            if (thisTime > 3000) {

                DirectionsTask getDirectionsTask = new DirectionsTask();
                getDirectionsTask.execute(getCurrentLocation(),
                        currentFocusedItem.getPoint());
            }

A: something like that ?
    GeoPoint p = null, currentP = null;
    boolean isActivated = false;
    view.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction()==MotionEvent.ACTION_DOWN) {
                isActivated = false;
                currentP = p ;
            }
            if(currentP == p && event.getEventTime()-event.getDownTime()>3000 && !) {
                Toast.makeText(AudioPlayerActivity.this, "3 sec", Toast.LENGTH_LONG).show();
                isActivated = true; //avoid displaying a lot of toast } return true; } });
            }
            if(event.getAction()==MotionEvent.ACTION_UP) {
                currentP = null; p = null;
            }
        }
    });

     //extends Overlay type, works if the method is called when "action down"
     public boolean onTap(GeoPoint p, MapView    mapView)  {
          this.p = p;
          return true;
     }


text:
Q: Is this a normal form for $4$-forms on manifolds? Starting from a $2$-form $\omega$ which is nondegenerate and closed on a $2n$-dimensional manifold, it is always possible to find local coordinates $x_1,y_1,\ldots,x_n,y_n$ so that the form $\omega$ can be written locally as
$$\sum_{k:1}^n a_Idx_k\wedge dy_k.$$ It is well-known that we can also say more on the functions $a_I$ (Darboux theorem).
Take $\psi$, a $4$-form nondegenerate and closed on a $4n$-dimensional manifold. It is not true, in general, that locally $\psi$  can be written as
$$\sum_{k:1}^n a_Idx_{4k-3}\wedge dx_{4k-2}\wedge dx_{4k-1}\wedge dx_{4k}$$
where $a_I$ are in $C^{\infty}(M)$ when n>1.
Someone knows if there are some conditions on the manifold that assure that this can be done?


text:
Q: ¿Que hago para que el DataGridView no guarde la ultima fila? Tengo un DataGridView en el cual ingreso datos directamente pero se crea una nueva fila y al momento de guardar en la Base de Datos se guarda con 0, y cuando quiero volver a llenarla me manda este error:

error: 23505 duplicate key value violates unique constraint

Este es el código:
foreach (DataGridViewRow row in tblarticulo.Rows)
{
    NpgsqlCommand guardar = new NpgsqlCommand("pro_factura", conexion, transaccion);
    guardar.CommandType = CommandType.StoredProcedure;
    guardar.Parameters.Clear();
    guardar.Parameters.AddWithValue("@d_codigod", Convert.ToInt32(row.Cells["column1"].Value));
    guardar.Parameters.AddWithValue("@d_descripcion", Convert.ToString(row.Cells["Column2"].Value));
    guardar.Parameters.AddWithValue("@d_cantidad", Convert.ToInt32(row.Cells["column3"].Value));
    guardar.Parameters.AddWithValue("@d_precio", Convert.ToInt32(row.Cells["column4"].Value));
    guardar.Parameters.AddWithValue("@d_valtotal", Convert.ToInt32(row.Cells["column5"].Value));
    guardar.Parameters.AddWithValue("@f_codigo", Convert.ToInt32(row.Cells["column6"].Value = codigofactura.Text));
    guardar.ExecuteNonQuery();
}

A: Hay varias formas en que podrías hacerlo, yo lo haría usando un ciclo forde la siguiente manera:
for (int i = 0; i < tblarticulo.Rows.Count -1; i++)
{
    NpgsqlCommand guardar = new NpgsqlCommand("pro_factura", conexion, transaccion);
    guardar.CommandType = CommandType.StoredProcedure;
    guardar.Parameters.Clear();
    guardar.Parameters.AddWithValue("@d_codigod", Convert.ToInt32(tblarticulo.Rows[i].Cells["column1"].Value));
    guardar.Parameters.AddWithValue("@d_descripcion", Convert.ToString(tblarticulo.Rows[i].Cells["Column2"].Value));
    guardar.Parameters.AddWithValue("@d_cantidad", Convert.ToInt32(tblarticulo.Rows[i].Cells["column3"].Value));
    guardar.Parameters.AddWithValue("@d_precio", Convert.ToInt32(tblarticulo.Rows[i].Cells["column4"].Value));
    guardar.Parameters.AddWithValue("@d_valtotal", Convert.ToInt32(tblarticulo.Rows[i].Cells["column5"].Value));
    guardar.Parameters.AddWithValue("@f_codigo", Convert.ToInt32(tblarticulo.Rows[i].Cells["column6"].Value = codigofactura.Text));
    guardar.ExecuteNonQuery();
}

Donde le estas diciendo que lo recorra hasta que sea menor que el total de filas -1 y ahora en vez de obtener los datos así:

row.Cells["column1"].Value

Lo debes hacer así:

tblarticulo.Rows[i].Cells["ColumnX.."].Value

Si quieres seguir usando el foreach, solo debes validar que se ejecute tu código dentro del ciclo, si la fila no esta vacía:
foreach (DataGridViewRow row in tblarticulo.Rows)
{

    if (!string.IsNullOrEmpty(row.Cells["column1"].Value.ToSring()))
    {
        //...
        //...
    }
}

A: En lo personal no me gusta tener la fila, y siempre se la quito para no tener problemas posteriores, además de que se ve mejor sin ella.
Si se la quitas igual solucionarías tu error, la linea de codigo para ya no tener dicha fila es:
tblarticulo.AllowUserToAddRows = false;

Siendo tblarticulo un DataGridView esta linea debería ir después de crear tu objeto, también podria ir en el constructor de tu ´Form´.
Ej:
public Form1()
{
    InitializeComponent();
    tblarticulo.AllowUserToAddRows = false;
}

Con eso la ultima fila de tu DataGridView ya no seria visible y se solucionaría tu error.


text:
Q: Need help writing "backgroundless" widget for wxWidgets (wxGTK) using GTK2 My question is concerned with GTK2 and wxWidgets (actually wxGTK).
In wxGTK all controls have grey background by default and it is impossible to remove it. I have a textured panel with custom child controls and each of my controls has an ugly grey border which I can't remove. I can only set some background color and make the panel's color the same. So I need a kind of "backgroundless" control in wxGTK.
I have many years of MS Windows experience before Linux. As far as I remember, in MS Windows each windowed control (i.e. widget) receives a WM_ERASEBKGND message (event) and then WM_PAINT message. The background is drawn in WM_ERASEBKGND event handler, so you can easily leave the parent control's background untouched and paint all of widget's elements on top of it by simply rewriting this handler.
That's not the case with wxGTK (and GTK2)!
Actually all widgets in wxGTK are based on custom "wxPizza" GTK widget, which is derived from GtkFixed widget. Any of wxPizza widgets has its own gdk window, so it is impossible to implement custom windowless widgets using standard wxGTK controls, based on "wxPizza" widget.
So I decided to implement another one GTK2 widget to make "backgroundless" controls available to wxWidgets. I implemented a windowless GTK2 widget, derived from GtkFixed. To make it windowless I used gtk_widget_set_has_window function (another way is to set a GTK_NO_WINDOW flag).
Everything works, except for draw coordinates, which are in parent window coordinate space. So the widget's elements are drawn at the parent window's top left position. That's the problem that I can't resolve. Maybe I need to add a GtkEventBox to my custom widget?
Maybe there are another ways to implement such functionality (backgroundless widgets) in GTK2? What do you think about that?
Thanks in advance,
Ilya

A: Your question is pretty old, but as there is now a trivial solution, it is better to write about it here, use the following code before your Create() call:
SetBackgroundStyle(wxBG_STYLE_TRANSPARENT);

We got this into wxWidgets 2.9.4 I believe.


text:
Q: How to input attribute for the polygon using ArcGIS API for Javascript? I'm new at ArcGIS programming, I'm trying to input attribute for the polygon with draw script using ArcGIS API for JavaScript based on this: https://developers.arcgis.com/javascript/3/jssamples/toolbar_draw.html.
I try to input the attribute via windows pop up(the windows pop up was for base form input) using event draw complete,based on this: https://developers.arcgis.com/javascript/3/jsapi/draw-amd.html#event-draw-complete, but i fail because i don't know how to using it. My code was like this :
function initToolbar() {
  tb = new Draw(map);
  tb.on("draw-complete", addToMap);

  // event delegation so a click handler is not
  // needed for each individual button
  on(dom.byId("tool"), "click", function(evt) {
    if (evt.target.id == "tool") {
      return;
    }
    var tool = evt.target.id.toLowerCase();
    //map.hideZoomSlider();
    tb.activate(tool);
  });
}

function addToMap(evt) {
  tb.deactivate();
  //map.showZoomSlider();
  switch (evt.geometry.type){
    case "point":
    case "multipoint":
      symbol = new SimpleMarkerSymbol();
      break;
    case "polyline":
      symbol = new SimpleLineSymbol();
      break;
    default:
      symbol = new SimpleFillSymbol();
      break;
  }
  var graphic = new Graphic(evt.geometry, symbol);
  map.graphics.add(graphic);
}

Anyone can tell me, how to input attribute with another method ?

A: You could make a form with dojo framework, as ArcGis Javascript API is based on this framework.
Let's take this example from Dojo website : https://dojotoolkit.org/reference-guide/1.10/dijit/form/Form.html
This form asks for 2 values, a name and a date of birth.
Let's assume that corresponds to the attributes of your polygon.
Now, let's adapt it to your needs.
First, we take the html we need to build our form

    Name:	<input type="text" id="name" name="name" required="true" data-dojo-type="dijit/form/ValidationTextBox"/>

    Date of birth:	<input type="text" id="dob" name="dob" data-dojo-type="dijit/form/DateTextBox"/>

<button data-dojo-type="dijit/form/Button" type="submit" name="submitButton" value="Submit">Submit</button>
<button data-dojo-type="dijit/form/Button" type="reset">Reset</button>

Now, the javascript code to handle the form. Make sure to merge it with your code, do not replace it.
require(["dojo/parser", "dojo/on", "dijit/registry", "dijit/form/Form", "dijit/form/Button", "dijit/form/ValidationTextBox", "dijit/form/DateTextBox", "dojo/domReady!"],
function(parser, on, registry) {
  var attributes = {};
  parser.parse();
  var myForm = registry.byId("myForm");
  on(myForm, "submit", function(){
    if(this.validate()){
      attributes = myForm.getValues();
      delete attributes['submitButton'];
      return true;
    }else{
      alert('Form contains invalid data. Please correct first');
      return false;
    }
  });

  on(myForm, "reset", function(){
    return confirm('Press OK to reset widget values');
  });
});

Finally, modify the last lines of your code, so it attaches the attributes from the form to the polygon, as described on the API doc :
var graphic = new Graphic(evt.geometry, symbol, attributes);
map.graphics.add(graphic);


text:
Q: how do I place 2 buttons on top of each other while keeping them centered? I would like to put 2 buttons on top of each other while still keeping both of them centered. I managed to put them on top of each other through the display: block, and through the flex-direction: column. However, I still don't know how to center them. The text-align doesn't seem to work. could somebody explain to me why this doesn't work, please?
button{
    border: none;
    padding-top: 10px;
    padding-bottom: 10px ;
    color: white;
    font-weight: bold;
    width: 200px;
    margin-bottom: 5px;
    border-radius: 5px;
}

.btn-group{
    display: flex;
    flex-direction: column;
    text-align: center;
}

#increment-btn{
    background: darkred;
}

#save-btn{
    background-color: green;
}

This is the HTML:

        <button id="save-btn" onclick="save()">SAVE</button>
        <button id="increment-btn" onclick="increment()">INCREMENT</button>

A: You may use   align-items: center; , it is a flex-direction: column;, so it will be align on the horizontal axis :)

button {
  border: none;
  padding-top: 10px;
  padding-bottom: 10px;
  color: white;
  font-weight: bold;
  width: 200px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.btn-group {
  display: flex;
  flex-direction: column;
  align-items: center;
}

#increment-btn {
  background: darkred;
}

#save-btn {
  background-color: green;
}

  <button id="save-btn" onclick="save()">SAVE</button>
  <button id="increment-btn" onclick="increment()">INCREMENT</button>

Aside, flex or grid children do not really need to be reset to block if it is an inline element , they become part(cells) of the generated grid . (float is also ignored)

A: Use align-items: center; in your .btn-group instead of text-align: center;.
For further information this site is very helpful.


text:
Q: Validating and passing controller-level parameters with ASP.NET MVC attribute routing I have an ASP.NET controller where every single method will have a shared parameter.  With attribute routing, I can add this parameter in the controller's route.
However, I still need to add that parameter along with a validation attribute in every single method.  Is there a way for me to do the validation in one place or avoid having to pass it in to every single method?
This is the current working code:
[ApiController]
[Route("[controller]/{name}")]
public class ExampleController : ControllerBase
{
    [HttpGet]
    public string Sample([StringLength(10)][FromRoute]string name)
    {
    }

    [HttpGet]
    [Route("defaults")]
    public string GetDefaults([StringLength(10)][FromRoute]string name)
    {
    }

    [HttpGet]
    [Route("objects/{id}")]
    public string Sample([StringLength(10)][FromRoute]string name, [FromRoute]string id)
    {
    }
}

Is it possible to get something close to this? (I know the validation parameter on the controller is invalid, but I'd like to just have to apply it once)
[ApiController]
[StringLength(10)]
[Route("[controller]/{name}")]
public class ExampleController : ControllerBase
{
    [HttpGet]
    public string Sample()
    {
    }

    [HttpGet]
    [Route("defaults")]
    public string GetDefaults()
    {
    }

    [HttpGet]
    [Route("objects/{id}")]
    public string Sample([FromRoute]string id)
    {
    }
}

A: You can do this using a custom action filter to validate the name parameter:
public class ValidateNameParameterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionParameters.ContainsKey(name))
        {
            // the trick is to get the parameter from filter context
            string name = filterContext.ActionParameters[name] as string;

            // validate name

            if (/*name is not valid*/)
            {
                // you may want to redirect user to error page when input parameter is not valid
                filterContext.Result = new RedirectResult(/*urlToRedirectForError*/);
            }

            base.OnActionExecuted(filterContext);
        }
    }
}

Now you can apply the filter to your controller, or specific actions:
[ApiController]
[Route("[controller]/{name}")]
[ValidateNameParameter] // <-- execute this for all actions in the controller
public class ExampleController : ControllerBase
{
    [HttpGet]
    public string Sample([StringLength(10)][FromRoute]string name)
    {
    }

    [HttpGet]
    [Route("defaults")]
    public string GetDefaults([StringLength(10)][FromRoute]string name)
    {
    }

    [HttpGet]
    [Route("objects/{id}")]
    // [ValidateNameParameter] // <-- execute for this specific action
    public string Sample([StringLength(10)][FromRoute]string name, [FromRoute]string id)
    {
    }
}

See this tutorial for more information.

A: As Hooman Bahreini said ,  you could customize a action filter that inherits ActionFilterAttribute and use it as a attribute on the controller .In Asp.net core , ActionArguments replaces ActionParameters
public class ValidateNameParameterAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionArguments.ContainsKey("name"))
        {
            string name = filterContext.ActionArguments["name"] as string;

            if(name!=null && name.Length>10)
            {
                filterContext.Result = new BadRequestObjectResult("The length of name must not exceed 10");
            }
        }
    }
}

For more details on Filters in ASP.NET Core , you could refer to here .


text:
Q: mklink directory in wwwroot stops showing updated data after a few iterations of changes to files in the directory On Windows 10 using IIS as the Web Server, it seems that directories created under wwwroot with the mklink command at some point stop seeing changes made to files in that directory.  The following is what I did to test this out:
I created a directory C:\test and then created a symlink to that directory on C:\inetpub\wwwroot using the following DOS command:
mklink /D C:\inetpub\wwwroot\test C:\test

Then, in the C:\test directory, I created a small HTML file called test.html with the following content:
<html>
<body>
This is test 1
</body>
</table>

Then, on the same computer, I open Microsoft Edge and go to the following page:
http://localhost/test/test.html

It works and displays This is a test 1 as is expected.  Then I modify the file in Notepad to show This is test 2.  Again it works.  However, after a few iterations, in my case up to This is test 5, the browser stops showing the updated file.  It just shows This is test 4.  I can change the file to display numbers 6, 7, 8, etc, but the browser stays at This is test 4.
At first I thought it was a caching issue but I turned off caching in IIS and the problem persists.  I even rebooted after disabling caching and it starts working again for a few iterations and then stops updating again.
If you create directory test under C:\inetpub\wwwroot so test is NOT a symlink and go through the above exercise then it works perfectly, just like it is supposed to.
To get around this issue, I created a batch file makelink.bat with the following commands:
rmdir C:\inetpub\wwwroot\test
mklink /D C:\inetpub\wwwroot\test C:\test
timeout 300
makelink

This forces a recreation of the symlink every five minutes which causes the correct info to show up again in a browser for a few more iterations.  Obviously, this is not an ideal solution.
Is this a bug in Windows 10 or am I doing something wrong?

A: You can try to disable IIS caching in the registry, then reboot and try again.
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\InetInfo\Parameters\DisableMemoryCache (REG_DWORD)

When this registry key is set to a nonzero value, the file cache is disabled, you can set it to 1.


text:
Q: Searchlogic: how do I define a namedscope so that I can use OR on an associated model? So, I found this: Searchlogic OR condition results in undefined method
But that only works for fields on the model your are searching on directly.
I have a suscription model, but I want to search over the different subscriptions' account names OR their other_field, for example.
from the above link (and modified) I'd like to be able to do something similar to this:
  named_scope :account_name_full_domain_like, lambda{ |name|{
     :conditions => ["accounts.name LIKE ? OR accounts.full_domain LIKE ?", "%" + name + "%", "%" + name + "%"],
     :joins => "LEFT JOIN `accounts` ON `accounts`.id = `subscriptions`.account_id"
    }}

but now I get an error on this:
27:     <% form_for @search do |f| %>

undefined method `subscription_subscription_path' for #<ActionView::Base:0x11061dbc0>

EDIT:
figured it out:
had to include .search in my call for assignment of the @search var
@search = Subscription.search.account_name_full_domain_like(term)

A: Provided your named scope is on your Subscription model, you will be returning subscription records. Your condition and join seem to be valid. I am not sure what the relationship of this named scope is to the instance variable @search you seem to be using in your view.
Is the path 'subscription_subscription_path' where you were expecting to submit this form to? If so, run "rake routes", and ensure that you have a path named 'subscription_subscription_path'.
If you want to submit to an alternate path, you can specify the url to submit to in form_for by doing something like the following:
<% form_for @search, :url => subscription_path(@search) %>

More information on specifying a URL for form_for can be found here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for


text:
Q: Split string of variable length, variable delimiters Read the question posed here, but mine is a little more complicated.
I have a string that is variable in length, and the delimiter can sometimes be two dashes, or sometimes it can be just one. Let's say in my table the data that I want to break out is stored in a single column like this:
+ -----------------------------------------+
| Category                                 |
+------------------------------------------+
| Zoo - Animals - Lions                    |
| Zoo - Personnel                          |
| Zoo - Operating Costs - Power / Cooling  |
+------------------------------------------+

But I want to output the data string from that single column into three separate columns like this:
+----------+--------------------+-----------------+
| Location | Category           | Sub-Category    |
+----------+--------------------+-----------------+
| Zoo      | Animals            | Lions           |
| Zoo      | Personnel          |                 |
| Zoo      | Operating Costs    | Power / Cooling |
+----------+--------------------+-----------------+

Hoping for some guidance as the samples I've been finding on Google seem to be simpler than this.

A: Here is a solution that uses solely string functions:
select
    left(
        category,
        charindex('-', category) - 2
    ) location,
    substring(
        category,
        charindex('-', category) + 2,
        len(category) - charindex('-', category, charindex('-', category) + 1)
    ) category,
    case when charindex('-', category, charindex('-', category) + 1) > 0
        then right(category, charindex('-', reverse(category)) - 2)
    end sub_category
from t

Demo on DB Fiddle:

location | category         | sub_category
:------- | :--------------- | :--------------
Zoo      | Animal           | Lions
Zoo      | Personnel        | null
Zoo      | Operating Costs  | Power / Cooling

A: You can also use a string splitter. Here is an excellent one that works with your version. DelimitedSplit8K
Now we need some sample data.
declare @Something table
(
    Category varchar(100)
)

insert @Something values
('Zoo - Animals - Lions')
, ('Zoo - Personnel')
, ('Zoo - Operating Costs - Power / Cooling')

Now that we have a function and sample data the code for this is quite nice and tidy.
select s.Category
    , Location = max(case when x.ItemNumber = 1 then Item end)
    , Category = max(case when x.ItemNumber = 2 then Item end)
    , SubCategory = max(case when x.ItemNumber = 3 then Item end)
from @Something s
cross apply dbo.DelimitedSplit8K(s.Category, '-') x
group by s.Category

And this will return:
Category                                |Location|Category       |SubCategory
Zoo - Animals - Lions                   |Zoo     |Animals        |Lions
Zoo - Operating Costs - Power / Cooling |Zoo     |Operating Costs|Power / Cooling
Zoo - Personnel                         |Zoo     |Personnel      |NULL

A: You've tagged this with [sql-server-2017]. That means, that you can use JSON-support (this was introduced with v2016).
Currently JSON is the best built-in approach for position- and type-safe string splitting:
A mockup, to simulate your issue
DECLARE @mockup TABLE (ID INT IDENTITY, Category VARCHAR(MAX))

INSERT INTO @mockup (Category)
VALUES ('Zoo - Animals - Lions')
      ,('Zoo - Personnel')
      ,('Zoo - Operating Costs - Power / Cooling');

--The query
SELECT t.ID
      ,A.[Location]
      ,A.Category
      ,A.subCategory
FROM @mockup t
CROSS APPLY OPENJSON(CONCAT('[["',REPLACE(t.Category,'-','","'),'"]]'))
WITH ([Location] VARCHAR(MAX) '$[0]'
     ,Category VARCHAR(MAX) '$[1]'
     ,SubCategory VARCHAR(MAX) '$[2]') A;

The result (might need some TRIM()ing)
ID  Location    Category            subCategory
1   Zoo         Animals             Lions
2   Zoo         Personnel           NULL
3   Zoo         Operating Costs     Power / Cooling

The idea in short:
We use some simple string operations to transform your string into a JSON array:
a b c    => [["a","b","c"]]

Now we can use OPENJSON() together with a WITH-clause to return each fragment by its position with a fixed type.

A: Bit of  hack, but it works:
DECLARE @t TABLE (Category VARCHAR(255))

INSERT @t (Category)
VALUES ('Zoo - Animals - Lions'),('Zoo - Personnel'),('Zoo - Operating Costs - Power / Cooling')

;WITH split_vals AS (
    SELECT Category AS Cat,TRIM(Value) AS Value,ROW_NUMBER() OVER (PARTITION BY Category ORDER BY Category) AS RowNum
    FROM @t
    CROSS APPLY STRING_SPLIT(Category,'-')
), cols AS (
    SELECT
        Cat,
        CASE WHEN RowNum = 1 THEN Value END AS Location,
        CASE WHEN RowNum = 2 THEN Value END AS Category,
        CASE WHEN RowNum = 3 THEN Value END AS [Sub-Category]
    FROM split_vals
)
SELECT STRING_AGG(Location, '') AS Location,
       STRING_AGG(Category, '') AS Category,
       STRING_AGG([Sub-Category], '') AS [Sub-Category]
FROM cols
GROUP BY Cat;


text:
Q: seam-gen gives names like clientClientId and facilityFacilityId is there a reason for this madness? I get a lot of redundant variable names from seamGen  (clientClientId and facilityFacilityId)
and I often change them manually to eliminate confusion.  Is Seam doing something special (AOP related magic) with these names?  Is there a way to prevent seam-gen from doing this?

A: Sounds like your DB has composite primary keys, maybe?

A: Is this the case for all entities generated?  Are your table names in the form of n_SOME_TABLE_NAME?  I read somewhere that seam-gen doesn't always play well with that format.


text:
Q: Rabbitmq message expiration Messages are not getting dropped after the expiration time.
Using spring-rabbit java client I am sending the message with the header set with expiration:10000.
For reference here is the message present in Rabbitmq queue,
Properties
priority:   0
delivery_mode:  2
headers:
expiration: 10000
content_encoding:   UTF-8
content_type:   text/plain
Please help me if I need to set anything in Rabbitmq server or any extra parameter need to set?

A: expiration is a well-known message property, not a simple header.
Properties are known to the broker, headers are generally arbitrary key/values used by the source and destination application, although some x-* headers have meaning to RabbitMQ.
This message expires just fine:

With spring-amqp, it's a property on MessageProperties.


text:
Q: Django: Check the data in a Django-admin form Hello I have 2 models Sight and SightPic, The problem is that I want to make validation that will submit the form in only certain rules. I want to have only one picture to be is_front ==True and make validation of the form if there are more than one or none to throw an error
In My clean functuion if I
print(len(images.filter(is_front=True))) It will show me data that is not the data in the form but the data in the database (Which is normal) how can I check the data in the form?
models.py
class Sight(models.Model):
       name=Charfield(...)
       description=Charfield(...)
       ...

class SightPicture(models.Model):
       sight=ForeignKey(Sight)
       picture=ImageField(...)
       is_front=BooleanField

Admin.py
class SightPicInline(admin.TabularInline):
        model = SightPicture
        fields = ("image_tag", "picture", "is_front")
        readonly_fields = ("image_tag",)

class SightAdmin(admin.ModelAdmin):
        model = Sight
        inlines = [SightPicInline, ...., ....]

admin.site.register(Sight, SightAdmin)

A: You can override clean method for ModelAdmin:
from django import forms
class SightAdmin(admin.ModelAdmin):

     class Meta:
        model = Sight
        inlines = [SightPicInline, ...., ....]
     def clean(self):
        if Sight.objects.filter(is_front=self.cleaned_data.get("is_front")).exists():
             raise forms.ValidationError("You can at max select one image as front")
        #more validations here
        return self.cleaned_data

A: since inline models data isn't available in self.cleaned_data you can try and access inline models data from self.data property, add a form for Sight model admin and specify the form class in Model Admin form=SightForm
from django import forms

SightForm(forms.ModelForm):
    def clean(self):
        start=self.data['sight_sightpicture-INITIAL_FORMS']
        end=self.data['sight_sightpicture-TOTAL_FORMS']
        front_images_count=0
        for i in range(start,end):
            is_front=self.data['sight_sightpicture-{}-is_front'.format(i)]
            if is_front:
                front_images_count+=1
            if front_images_count>1:
                raise forms.ValidationError("Error message here")
            return self.cleaned_data


text:
Q: checking conditions in array positions using bash for comma separated values The following is the data in my file and i want to load it using bash script
eth0/0,up,up,text
eth0/1,up,up,text2
eth0/2,down,down,text3

i want to load these in array and compare each lines
if [ ${myArray[2]} == "up" ]; then
echo ${myArray[3}
elif ${myArray[2]} == "down"; then
echo ${myArray[3]}
else
echo "error"
fi

I want to compare the arrays and provide the last array as the output
Output
eth0/0 up text


text:
Q: Android-MarqueeRepeatlimit="marquee_forever" tag in XML i want to set MarqueeRepeatLimit="marquee_forever" at run-time is there any possible way to do that, if anyone known about this help me and thanks in advance

A: This should get you going
mTextView.setMarqueeRepeatLimit(-1);


text:
Q: Debian 10: Cannot add my user to group I am trying to add my user to group smbgroup
sudo usermod -G smbgroup <username>

When I run this command no error is produced, however when I then run groups I do not see smbgroup listed in the output.
What am I doing wrong?

A: Did you log in again before running groups? If not, you won't see the new group show up yet.
You can check the configuration was changed in the meantime with getent group smbgroup or simply checking /etc/groups.

A: Login to that group:
$ newgrp smbgroup


text:
Q: Как добавить hr после каждой p?

What is Lorem Ipsum?

First

Where does it come from?

Second

Why do we use it?

Third

Необходимо с помощью JavaScript вставить после каждого тега p тег hr, для визуального отделения абзацев друг от друга. Нельзя модифицировать указанную разметку, надо только написать script с кодом.
Что можно сделать? Какой использовать метод DOM?

A: Зачем здесь jquery, так то проще ;)
Pure HTML&CSS:

p{
    margin: 3px 0px;
    border-bottom: 1px solid black;
}

What is Lorem Ipsum?

First

Where does it come from?

Second

Why do we use it?

Third

A:

document.querySelectorAll('p').forEach((elem) => {
    elem.insertAdjacentHTML('afterend', '
');
});

What is Lorem Ipsum?

First

Where does it come from?

Second

Why do we use it?

Third

A: А можно использовать ещё псевдоэлемент ::after

*, *::after, *::before {
  box-sizing: border-box;
}

p::after {
  content: '';
  display: block;
  position: static;
  width: 100%;
  height: 1px;
  background-color: black;
  margin: 10px 0;
}

What is Lorem Ipsum?

First

Where does it come from?

Second

Why do we use it?

Third


text:
Q: About split function of Visual Basic I want to Split the carton no line by line from "ASN_importdata" to new table "ASN_importdata2"
But the result is not my expected.
Someone can help me to solve this problem?
Source_ASN_Importdata:
CNO       SKU    QTY    GW
---------------------------------
Y.01-03   AAA    600    60
Y.04      AAB    100    10
Y.04      AAC    100    10
Y.05-07   ABC    600    60

Expected:
CNO       SKU    QTY    GW
---------------------------------
01        AAA    200    20
02        AAA    200    20
03        AAA    200    20
04        AAB    100    10
04        AAC    100    10
05        ABC    200    20
06        ABC    200    20
07        ABC    200    20

Actual result:
CNO       SKU    QTY    GW
---------------------------------
01        AAA    300    30
03        AAA    300    30
04        AAB    100    10
04        AAC    100    10
05        ABC    300    30
07        ABC    300    30

Code:
Private Sub txtconvert_Click()

    Dim db As DAO.Database
    Dim rsSource As DAO.Recordset
    Dim rsOut As DAO.Recordset
    Dim SplitToRows() As String
    Dim I As Integer
    Dim strCTN As String

    Set db = CurrentDb
    Set rsSource = db.OpenRecordset("ASN_Importdata")
    Set rsOut = db.OpenRecordset("ASN_Importdata2")
    If (Not rsSource.BOF And Not rsSource.EOF) Then

    Do Until rsSource.EOF
        strCTN = Replace(rsSource!cno, "Y.", "")

        SplitToRows = Split(strCTN, "-", -1)

        For I = 0 To CInt(UBound(SplitToRows()))
        rsOut.AddNew

        rsOut("CNO") = SplitToRows(I)
        rsOut("SKU") = rsSource("SKU")
        rsOut("QTY") = rsSource("QTY") / (UBound(SplitToRows()) + 1)
        rsOut("GW") = rsSource("GW") / (UBound(SplitToRows()) + 1)
        rsOut.Update

    Next I
        rsSource.MoveNext
    Loop
        MsgBox "Done!"
    Else
        MsgBox "No record"
    End If
    rsSource.Close
    Set rsSource = Nothing
    rsOut.Close
    Set rsOut = Nothing
    Set db = Nothing

End Sub


text:
Q: C# Playing a flash video causes an error with wmode=direct I'm trying to play a flash movie inside of my C# window forms application, everything goes well and I can successfully load my .swf files.
However one of my flash files will not work as it requires wmode=direct
The moment that I change wmode to direct, I get this error:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
This error only occurs when I change the wmode to direct, I've looked around but I haven't found a way to resolve this problem.
Here's my code:
public Form1()
{
    InitializeComponent();
    axShockwaveFlash1.WMode = "Direct";
    axShockwaveFlash1.LoadMovie(0, swf_location);
    axShockwaveFlash1.Play();
}

How do I stop this error and have my application work correctly?
Any hints or help would be much appreciated

A: This issue is now resolved in flash player 14:
https://bugbase.adobe.com/index.cfm?event=bug&id=3768778


text:
Q: how to define hibernate.c3p0 connection Pool in wildfly 10 standalone.xml I have a issue of connection drop with the Mysql DB after a long idle Time i.e. I get different types of errors including "maximum Packet Allowed Size" error, "Last Packet recieved 8499970 milliseconds ago" error etc.
I am Using Hibernate-JPA with the JPA version 2.0
Currently The datasource Configuration in my Wildfly standalone.xml is:
<datasources>

                <datasource jndi-name="java:/MySQLDS" pool-name="MySQLDS" enabled="true" use-java-context="true">
                    <connection-url>jdbc:mysql://localhost:3306/opera</connection-url>
                    <driver>mysqlDriver</driver>
                    <security>
                        <user-name>admin</user-name>
                        <password>admin</password>
                    </security>
                </datasource>
                <drivers>

                    <driver name="mysqlDriver" module="com.mysql">
                        <xa-datasource-class>com.mysql.jdbc.Driver</xa-datasource-class>
                    </driver>
                </drivers>
            </datasources>

The persistence.xml file looks Like this:
 <persistence version="2.0"
        xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
        <persistence-unit name="metadatatool-persistence">
         <jta-data-source>java:/MySQLDS</jta-data-source>
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
                <!-- Hibernate properties -->
                <property name="hibernate.show_sql" value="false" />
                <property name="hibernate.format_sql" value="false" />
                <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />

                <!-- Configuring Connection Pool -->
                <property name="hibernate.c3p0.min_size" value="5" />
                <property name="hibernate.c3p0.max_size" value="20" />
                <property name="hibernate.c3p0.timeout" value="600" />
                <property name="hibernate.c3p0.max_statements" value="2000" />
                <property name="hibernate.c3p0.idle_test_period" value="30" />
                <property name="hibernat.c3p0.automaticTestTable" value="conTestTable" />
            </properties>
    </persistence-unit>
    </persistence>

I have included the c3p0-4.1.1-final Jar in my project but it looks like it is not working I am still getting no connection error after Idle time, and I can't find a proper step by step solution anywhere
EDIT
I have defined another property in my persistence.xml I dont Know if It will work or not
<property name="hibernate.connection.url"
                value="jdbc:mysql://192.168.1.1:3306/opera?zeroDateTimeBehavior=convertToNull&autoReconnect=true;reconnectAtTxEnd=true;autoReconnectForPools=true" />
        <property name="hibernate.connection.username" value="root" />

EDIT Update
I Used the above defined properties and I didn't got the connection error now, however I did found a ERROR in the Log file which is below, the deployment is working fine though
error is:  java.lang.IllegalStateException: UT000010: Session not found BDnAhOKBakcD8h9izG1Dembs0DFHWwWgYFVYPEKm

Also the connection String I used in this property is this the right approach ? What side-effects can I face ?

A: It is not necessary to configure your own connection pool implementation (such as c3po) in any full Java EE implementation, such as WildFly/JBoss EAP, WebSphere, GlassFish, etc.
All of these servers provide you with connection pool implementations and management tools to configure them.
In WildFly you can set this up with your DataSource configuration in the management console or use the CLI. See WildFly 10 DataSource configuration.
You should be able to reduce your persistence.xml to:
<persistence version="2.0"
        xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="metadatatool-persistence">
        <jta-data-source>java:/MySQLDS</jta-data-source>
        <properties>
            <!-- Hibernate properties -->
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.format_sql" value="false" />
        </properties>
    </persistence-unit>
</persistence>

I left the SQL generation properties there for convenience, although they're not necessary when false all of the time.
After this you need to ensure that your DataSource is configured correctly.
<datasource jta="true"
            jndi-name="java:/MySQLDS"
            pool-name="MySQLDS" enabled="true" use-ccm="true">
    <connection-url>jdbc:mysql://localhost:3306/opera</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <driver> mysqlDriver </driver>
    <security>
        <user-name>admin</user-name>
        <password>admin</password>
    </security>
    <validation>
        <valid-connection-checker
            class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
        <background-validation>true</background-validation>
        <exception-sorter
            class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
    </validation>
</datasource>

Note the connection validation configuration that you have missing. This was added for free when the DataSource was set up through the admin console.
You should never modify the standalone.xml file by hand.

A: This is what I usually do :
<jee:jndi-lookup id="dataSource" jndi-name="java:/MySQLDS"/>

And then use the datasource in your persistence context like that:
 <property name="dataSource" ref="dataSource"/>

Have a look at spring docs


text:
Q: SQL query works when run as query on server, but will not work from PHP code I'm running this via PHP and well the first query gets run perfectly then right after it I run the second query and it does nothing. Its rows never get updated for some reason, but when I type out the query manually on the sql server, it works perfectly.
Anyone have any idea why its not working in the php code?
$qry = "UPDATE Matches SET winner ='$winner' WHERE TOURN_KEY = '$tournKey'AND MATCH_KEY='$matchKey' ";

$result = @mysql_query($qry);

$qryPoints = "UPDATE members, MemberBets SET members.points = members.points + MemberBets.amountBet + MemberBets.amountBet WHERE members.member_id=MemberBets.member_id and MemberBets.MATCH_KEY ='$matchKey' and MemberBets.TOURN_KEY = '$tournyKey' and MemberBets.player = '$winner'";

$resultPoints = @mysql_query($qryPoints);

A: You appear to have a typo.  You have a $tournKey variable in the first query and a $tournyKey variable in the second.  Since you say the first query works, I'm guessing the second variable name is wrong.


text:
Q: Problem with one variable in a binary logistic regression I analyzed four binary variables with a binary logistic regression.
I used for the analysis of all four binary y-variables the same set of 9 x-variables (a-i).
My problem deals with one of this four regressions. The results of the binary logistic regression shows that the x-variable "c" takes surprising high values regarding the regression coefficient B, Wald and Exp(B) (see table 1) indicating that this variable problematic.
That is why I excluded this variable "c" from this one of four regressions.
I am now in a difficult situation. I already wrote the scientific publication about this analysis, and I have to send it within a few days to the Journal. When I did this analysis, I asked my supervisor about this one variable c and he said it would be ok to leave this one variable out, whereas I did not do it in the other three regressions.
But he is really no expert in statistics.
I am trying to include a few sentences in the paper to explain why I did it. If the Reviewers are not fine with it, it would be o.k.. I would be fine with calculating it again and I think the paper all in all is great, and I would be surprised if I would get a rejection.
But the explanation should be plausible with respect to the special characteristics of this variable c within the regression results. The problem is that I cannot calculate until submitting the paper.
Could you give me some advice? What do you think about the regression results regarding this variable "c"?
(I know, I break the rule of thumb of 10 events per item in logistic regressions; that´s a limitation I already mentioned in this paper)
Table1 regression results

Table2 correlation matrix


text:
Q: Cypress run gives the error "Warning: We failed processing this video." and fails the job I am running Cypress tests in parallel (chrome browser).
And I see the below issue every time when cypress run is executed.
I would need to videos for debugging purpose.
Any possible solutions to fix this issue?
Warning: We failed to record the video.
12:57:58
12:57:58  This error will not alter the exit code.
12:57:58
12:57:58  Error: ffmpeg exited with code 1
12:57:58
12:57:58      at ChildProcess.<anonymous> (/root/.cache/Cypress/9.5.2/Cypress/resources/app/node_modules/fluent-ffmpeg/lib/processor.js:182:22)
12:57:58      at ChildProcess.emit (node:events:394:28)
12:57:58      at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)

Tried to turn off Video Compression but still the issue occurs.


text:
Q: show partial sum converges almost surely I am trying to show giving a sequence $(X_n) \subseteq L^2$ of independent random variables with zero mean and  $\sum_{n\in N}E[X_n^2]< \infty$ , $\sum_{n\in N}X_n$ converges a.s.
For this I wanna get  $\sum_{n\in N} \mathbb{P}(|\sum_{k=1}^{n}X_k|>\epsilon)<\infty$. As if I can show it , then by Borel-Cantelli lemma,  $\sum_{n\in N}X_n$ converges to zero almost surely.
But I dont know how to get $\sum_{n\in N} \mathbb{P}(|\sum_{k=1}^{n}X_k|>\epsilon)<\infty$,
I tried this:
By Chebychev's inequality, $\mathbb{P}(|\sum_{k=1}^{n}X_k|>\epsilon)\leq \mathbb{E}[X_n^2]/\epsilon^2 $, follows that  $\sum_{n\in N}\mathbb{P}(|\sum_{k=1}^{n}X_k|>\epsilon)\leq\sum_{n\in N}\mathbb{E}[X_n^2]/\epsilon^2$. However, letting $\epsilon\longrightarrow 0$ doesn't make the right side bounded. Seems doesnt work...
I am wondering if anyone can show the correct way to do it. Thanks in advance.

A: We can apply Kolmogorov three series theorem. We have to check that

*

*$\sum_{j=1}^{+\infty}P(|X_j|>1)$ is convergent. It's the case, as $P(|X_j|>1)\leq EX_j^2$.

*$\sum_{j=1}^{+\infty}E[X_j\chi_{\{X_j\leq 1\}}]$ is convergent. We have, as $EX_j=0$, $$E[X_j\chi_{\{X_j\leq 1\}}]=-E[X_j\chi_{\{|X_j|>1\}}]\leq \sqrt{EX_j^2}\sqrt{P(|X_j|\geq 1)}\leq EX_j^2.$$

*$\sum_{j=1}^{+\infty}\operatorname{Var}(X_j\chi_{\{|X_j|\leq 1\}})$ is convergent. But since the expectation of $X_j $ is $0$,  $$\operatorname{Var}(X_j\chi_{\{|X_j|\leq 1\}})\leq \operatorname{Var}(X_j)=EX_j^2,$$
and we can conclude.


text:
Q: PCI RAID controller compatibility Recently I've been thinking of buying a cheap RAID controller. I'm not experienced at all, and just want to mess around; nothing business affiliated, no specific expectations.
The controllers I've been thinking of buying are either PCI 2.2 or PCI 2.3 compliant, while the motherboard I plan on using is PCI 2.2 compliant (a Gigabyte GA-8PE800 rev 1.1).
So, my questions are:

*

*Would the PCI 2.3 RAID controller be compatible with my motherboard?

*Similarly, would the PCI 2.2 one be fine with a PCI 2.3/3.0 motherboard?

*Is there anything else (other than the PCI version) to be considered (in terms of compatibility)?

A: Generally speaking you can place a higher level PCI card in a lower level slot, but not all lower level cards will work in higher level slots due to missing +5v line in 2.2 and higher slots. There is generally no compatibility issues after PCI 2.2
You may run into trouble with some 2.1 or older cards that require the +5v bus to operate, not all do, in fact very few require it. From version 2.2 on, there is essentially no compatibility issues to be concerned with.


text:
Q: How to kill or close a Python instance in terminal before running script Sometimes I utilize the shift + enter Python runner (python.execSelectionInTerminal), which enters the highlighted code into a Python instance in the integrated terminal.
But when I try to run my code (arrow in top right corner), it pastes the bash script into the Python instance:
>>> print("Example")
Example
>>> /Users/freddy/.../main.py
  File "<stdin>", line 1
    /Users/freddy/.../main.py
    ^
SyntaxError: invalid syntax

Note: using the f5 debug option automatically opens and runs the debug bash script in a new terminal (which is what I want), but this doesn't happen when I click the run arrow.

How do I:

*

*Close or kill the Python instance in the integrated terminal before running the script (with the arrow in the top right corner)? Or even just type exit() before the run command if vs-code can detect Python is open.

By clicking the arrow, I am doing the same as the python.execInTerminal or Python: Run Python File in Terminal shortcut


text:
Q: SQL Statement in VBA can not recognize my excel worksheet
Error: Invalid Object Name 'Tabelle1$'

I am trying to reference to Tabelle1 as a worksheet.
As I am new to vba I don't understand why the script can't recognize it, or what I have to do so that it does.
Thanks for any help.
Sub WriteDataIntoSQLTable()

Dim cn                    As Object
Dim strQuery              As String

Set cn = CreateObject("ADODB.Connection")
strQuery = "[dbo].[MyTable]"

 With cn
     .Provider = "sqloledb"
     .ConnectionString = "Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=SSPI;"
     .Open
End With

s = "INSERT INTO [ODBC;Driver=SQLOLEDB;Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=SSPI;Trusted_Connection=Yes].strQuery( ldf_nr,datum, abteilung_na, positions_nr, positions_na, ma_nr, ma_na, ma_plan_beginn, ma_plan_ende, ma_plan_pause, ma_plan_dauer_netto  ) " _
& "SELECT  a.Col1, a.Col2, a.Col3, a.Col4, a.Col5, a.Col6, a.Col7, a.Col8, a.Col9, a.Col10, a.Col11 " _
& "FROM [Tabelle1$] as a" _
& "LEFT JOIN [ODBC;Driver=SQLOLEDB;Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=SSPI;Trusted_Connection=Yes].strQuery as b ON a.Col1 = b.[ldf_nr]" _
& "WHERE b.[ldf_nr] Is Null"
cn.Execute s
cn.Close
    Set cn = Nothing
End Sub

A: there is what is working for me :
With Worksheets("Tabelle1").ListObjects.Add(SourceType:=0, Source:="ODBC;DRIVER=SQL Server;SERVER=*SERVER ADRESS*;UID=*ID*;PWD=*PASSWORD*;APP=Microsoft Office 2010;WSID=*PC NAME*;DATABASE=*DATABASENAME*", Destination:=Worksheets("Tabelle1").Range("$A$1")).QueryTable
        .CommandText = Array("*SQL String Query*")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "Tabelle1"
        .Refresh BackgroundQuery:=False
    End With

You need to replace things between "*" by your data to make it work.


text:
Q: Set state based on url params react-router v6 okay so I have this form where the user can query a search with type "radio buttons" search input and a react-select filled with categories, the button works as a link front end form for clarification
{selectedOption ?
<Link to={`/annonser${typeToRoute}${selectedOptionToRoute}${searchToRoute}`} >
                    <button>Hitta annons / mönster</button>
                    </Link>: <Link to={`/annonser${typeToRoute}${searchToRoute}`} >
                    <button>Hitta annons / mönster</button>

where I then want to query db to get data based on the url params with useParams hook and then set the state
const { type, category, search} = useParams();
    const categoryRef = db.collection("articles").where("subCategory", "==", category)

I want the user to be able to search any of the alternatives seperatly aswell I will not use any form validation to make sure the user have everything not null. Is this the right way to go about it? Because you cant have optional params in route component in v6 for some reason? Is there any other way to achieve what im trying to do or am I on the right track? Thanks in advance never done anything like this before. Let me know if my question is asked poorly since I dont have alot of experience asking questions here.

A: If you want optional route path parameters then see this answer, the gist being you declare a route for each that can match. The issue here though is that the order matters, "type" would need to be provided for "category" to be optional, and both "type" and "category" would need to be provided for "search" to be optional.
Here's an example showing why this isn't ideal:
<Route path="/annonser/:type" element={.....} />
<Route path="/annonser/:type/:category" element={.....} />
<Route path="/annonser/:type/:category/:search" element={.....} />

This is ok until you want the combination of "type" and "search". If you try path="/annonser/:type/:search" then this has the same specificity as path="/annonser/:type/:category", so whichever route is listed first is the one that'll be matched.
Using the queryString method then all or none, and anything between, can be provided/optional and valid.
Example:

*

*Route <Route path="/annonser" element={.....} />

*URL "annonser?type=customType&category=foo&search=bar"
Use the useSearchParams hook to access queryString parameters.
const [searchParams] = useSearchParams();

...

const type = searchParams.get("type");         // "customType"
const category = searchParams.get("category"); // "foo"
const search = searchParams.get("search");     // "bar"

const categoryRef = db.collection("articles").where("subCategory", "==", category)

Any queryString parameter not provided, when queried, will return null.


text:
Q: Triple integral limits over pyramid I am just studying triple integrals in my calculus class and I have the following problem as homework and I am not sure how to start:
Let $P$ be a pyramid defined by the base [-2,2]x[-2,2] in XY plane and tip (0,0,5). Compute the volume in 2 ways using triple integrals:
once as $dzdxdy$ and then as $dxdydz$.
Since I am new in this type of problems I would appreciated some help. Thank you

A: If you have a volume $A$, and want to express $\int_A f(x,y,z)\,d(x,y,z)$ as an iterated integral, i.e. as $$
  \int_A f(x,y,z) \,d(x,y,z) = \int_{A_x} \int_{A_y(x)} \int_{A_z(x,y)} f(x,y,z) \,dz\,dy\,dx
$$
you have to find $$\begin{eqnarray}
  A_x &\subset& \mathbb{R} \\
  A_y &\,:\,& A_x \to \mathcal{P}({\mathbb{R}}) \\
  A_z &\,:\,& \{(x,y) \,:\, x \in A_x, y \in A_y(x)\} \to \mathcal{P}(\mathbb{R})
\end{eqnarray}$$
such that $$
  A = \left\{(x,y,z) \,:\, x \in A_x,\, y \in A_y(x),\, z \in A_z(x,y,z) \right\}.
$$

Integration order $dz\,dx\,dy$
Let's look at the case of a pyramid with base $[-2,2]\times [-2,2]$ in the $x,y$-plane, tip at $(0,0,5)$, and integration order $dz\,dx\,dy$. We have $$
  A = \left\{(x,y,z) \,:\, x \in [-2,2], y \in [-2,2], 0 \leq z \leq \tfrac{5}{2}\min \{2-|x|,2-|y|\}\right\} \text{.}
$$
So $A_y$ doesn't actually depend on $x$, and $A_z(x,y) = [0, \tfrac{5}{2}\min \{2-|x|,2-|y|\}]$. Therefore, $$
  \int_A 1 \,d(x,y,z) = \int_{-2}^2 \int_{-2}^2 \int_0^{\tfrac{5}{2}\min \{2-|x|,2-|y|\}} 1 \,dz\,dy\,dx \text{.}
$$
Integration order $dx\,dy\,dz$
For integration order $dx\,dy\,dz$ we have to find $$\begin{eqnarray}
  A_z &\subset& \mathbb{R} \\
  A_y &\,:\,& A_z \to \mathcal{P}({\mathbb{R}}) \\
  A_x &\,:\,& \{(z,y) \,:\, z \in A_z, y \in A_y(z)\} \to \mathcal{P}(\mathbb{R})
\end{eqnarray}$$
such that $$
  A = \left\{(x,y,z) \,:\, x \in A_x(z,y),\, y \in A_y(z),\, z \in A_z \right\}.
$$
Obviously, $A_z = [0,5]$. For a fixed $z \in A_z$, $(x,y,z) \in A$ exactly if $$\begin{eqnarray}
  z &\leq& \tfrac{5}{2}(2 - |x|) &\Leftrightarrow& |x| \leq \tfrac{2}{5}z - 2 &\text{ and } \\
  z &\leq& \tfrac{5}{2}(2 - |y|) &\Leftrightarrow& |y| \leq \tfrac{2}{5}z - 2 \text{,}\\
\end{eqnarray}$$
which means $$
    \int_A 1 \,d(x,y,z) = \int_0^5 \int_{-\frac{2}{5}z + 2}^{\frac{2}{5}z - 2} \int_{-\frac{2}{5}z + 2}^{\frac{2}{5}z - 2} 1 \,dx\,dy\,dz \text{.}
$$


text:
Q: Design Pattern for enterprise application I read few articles about composite pattern and I want to know whether its applicable in following situation,
I found that "A Composite Entity object can represent a coarse-grained
object and all its related dependent objects"
public class PatientRegistrationDTO
{
    public string RegistrationNo;
    public string ID;
    public DateTime AdmitDate;
}

public class PersonDTO
{
     public string ID{ get; set; }
     public string FullName { get; set; }
     public string FirstName { get; set; }
}

by using these two objects I need to create
public class Patient
  {
        public string ID{ get; set; }
        public string FullName { get; set; }
        public DateTime AdmitDate;
  }

Can I use Composite pattern for enterprise applications in here?
Is it possible for me to add some class like below?
public class PatientDTO
{
    public static Patient ConvertToEntity(PatientRegistrationDTO pregDTO, PersonDTO person)
    {
        Patient p = new Patient();
        p.ID= pregDTO.ID;
        p.FullName = person.FullName;
        p.AdmitDate = pregDTO.AdmitDate;

        return p;
    }
}

A: The composite pattern implies that when you call a method perform() on a composite (perform() being part of the interface contract of IComponent), the call is redirected to all its sub-components, until they are leaf elements that do an actual thing.
In your case I see absolutely no difference between the coarse and the fine grain, and which entity group/represent others as a composite.
So I would say no, the composite pattern really doesn't apply here.
the wikipedia class diagram may explicit my point of view: ( in this diagram perform = operation)

A: Your classes are allowing data to be modified by external forces via the public members. Since these are supposed to be Entity objects, enforce the immutability of the data. If you need to change a piece of the data, throw away the stale object and create a new one with the new data. Example:
public sealed class PatientRegistrationDTO
{
    private readonly string registrationNo;

    private readonly string id;

    private readonly DateTime admitDate;

    public PatientRegistrationDTO(string registrationNo, string id, DateTime admitDate)
    {
        this.registrationNo = registrationNo;
        this.id = id;
        this.admitDate = admitDate;
    }

    public string RegistrationNo
    {
        get
        {
            return this.registrationNo;
        }
    }

    public string ID
    {
        get
        {
            return this.id;
        }
    }

    public DateTime AdmitDate
    {
        get
        {
            return this.admitDate;
        }
    }
}

public sealed class PersonDTO
{
     private readonly string id;

     private readonly string fullName;

     private readonly string firstName;

     public PersonDTO(string id, string fullName, string firstName)
     {
         this.id = id;
         this.fullName = fullName;
         this.firstName = firstName;
     }

     public string ID
     {
         get
         {
             return this.id;
         }
     }

     public string FullName
     {
         get
         {
             return this.fullName;
         }
     }

     public string FirstName
     {
         get
         {
             return this.firstName;
         }
     }
}

And, finally, I would use composition to do this:
public sealed class Patient
{
    private readonly PatientRegistrationDTO patientRegistration;

    private readonly PersonDTO person;

    public Patient(PatientRegistrationDTO patientRegistration, PersonDTO person)
    {
        // Appropriate nullity checks as needed here.
        this.patientRegistration = patientRegistration;
        this.person = person;
    }

    public string ID
    {
        get
        {
            return this.patientRegistration.ID;
        }
    }

    public string FullName
    {
        get
        {
            return this.person.FullName;
        }
    }

    public DateTime AdmitDate
    {
        get
        {
            return this.patientRegistration.AdmitDate;
        }
    }
}


text:
Q: how to stop cloning of attribute or tag in Jquery I have a problems in Jquery. I want to clone a attribute or tag which is drag from one div1 to another div2 that is fine. But problems is when i dragging or moving position of existing tag on div2 then cloning is star
I want to cloning only when i drag from div1 to div2, Please tell me where am i wrong and what is wrong.
This is my div1

                            <input type="text" name="text_field">

This is div2

This Jquery Code

My layout like this

A: Attach a cloning function to the Jquery mouseup event:
 $(selector).mouseup(function(){
    //put cloning code here
    });

Refer Demo Here


text:
Q: How can I extract an exact set of words from a string using a regex? I've looked everywhere and haven't been able to find a question that answers this specific use case (maybe I've missed it). But basically I'm wanting to extract the following text from a string: Welcome James:
This text must be at the start of the string, e.g:
Welcome James: Now some text follows...blahblah - This would be a match
However
This is some text Welcome James: some more text... - This would not be a match.
So basically I'd hard code Welcome James: into the regex (I don't need any other variables of Welcome <name>:.
Is this possible? All I've been able to find is regexes that match single words without spaces or characters.

A: To search at the start of a string, just prefix the regex with the ^ (caret) character:
/^Welcome James/

A: Here is the answer :) But @charles gave it too!
^(Welcome James)


text:
Q: Inconsistent behaviour of MariaDB while using having, order by and limit without group by TL;DR
Always use group by.
Problem description
I have a problem with select query that uses having, order by and limit in MariaDB:
mysql  Ver 15.1 Distrib 10.1.9-MariaDB, for Linux (x86_64) using readline 5.1
Defintions
Let's suppose we have the following simple test table with two rows:
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
    `weight` INT(11) NOT NULL,
    `x` INT(11) NOT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;

INSERT INTO `test` (`weight`, `x`) VALUES (1, 33);
INSERT INTO `test` (`weight`, `x`) VALUES (1, 44);

And we also have a simple proxy function TestProxy that just passes through the first argument:
DROP FUNCTION IF EXISTS `TestProxy`;
delimiter //
CREATE FUNCTION `TestProxy`(
        x double(9,6)
) RETURNS double(8,2)
        NO SQL
BEGIN
        RETURN x;
END//
delimiter ;

Working query with where
If I run the following select query using where condition, I expectantly get one row:
SELECT
    `test`.weight,
    `test`.x
FROM `test`
    WHERE 35 <= TestProxy(`test`.x)
ORDER BY weight ASC
LIMIT 0, 1;

Non-working query with having
However, If I replace where with having I get empty set in MariaDB. In MySQL I expectantly get one row:
SELECT
    `test`.weight,
    `test`.x
FROM `test`
    HAVING 35 <= TestProxy(`test`.x)
ORDER BY weight ASC
LIMIT 0, 1;

Working query with having but without TestProxy function
Furthermore, when I use having and I replace TestProxy with test.x again I expectantly get one row:
SELECT
    `test`.weight,
    `test`.x
FROM `test`
    HAVING 35 <= `test`.x
ORDER BY weight ASC
LIMIT 0, 1;

Working query with having but wrapped with select
At last, when I wrap the query with select and move limit to the wrapper I expectantly get one row:
SELECT * FROM (
SELECT
    `test`.weight,
    `test`.x
FROM `test`
    HAVING 35 <= TestProxy(`test`.x)
ORDER BY weight ASC
) as table1
LIMIT 0, 1;

However, this query is very slow.
Query with having that works depending on order by
After reading and analyzing answers of @slaakso and @gordon-linoff, I've investigated it even further, simplified the problem and realized that one row is returned only when it first appears on the result set that would be returned before applying limit.
So the following query will result with one row:
SELECT
    33 = TestProxy(`test`.x) as tp
FROM `test`
HAVING tp
ORDER BY x ASC
LIMIT 0, 1;

And the following query will result with an empty set:
SELECT
    33 = TestProxy(`test`.x) as tp
FROM `test`
HAVING tp
ORDER BY x DESC
LIMIT 0, 1;

Working query with having and group by
If I add group by the query works as expected in MariaDB returning one row:
SELECT
    33 = TestProxy(`test`.x) as tp
FROM `test`
GROUP BY tp
HAVING tp
ORDER BY x DESC
LIMIT 0, 1;

Summary
Could someone explain why is there inconsistency in MariaDB? Am I missing something or is that a bug in MariaDB?
I guess this has something to do with optimizing queries but I am not sure how to check it out.
Does anyone have a suggestion to how to fix it? It is obviously a simplified example; I need having for my complex queries.

A: One possibility is very subtle. This is the query that "works" in MySQL but doesn't "work" in MariaDB:
SELECT `test`.weight, `test`.x
FROM `test`
HAVING 35 <= TestProxy(`test`.x)
ORDER BY weight ASC
LIMIT 0, 1;

My suspicion is around the use of an expression not in the select list, along with having without group by.
The documentation explicitly states:

Another MySQL extension to standard SQL permits references in the
  HAVING clause to aliased expressions in the select list.

Nothing in your query is an aliased expression in the select list.
My guess is confusion due to the having being used without a group by.  Because the expression is not in the select, possibly MySQL/MariaDB is deciding to evaluate it once, on an indeterminate row, rather than once per row.  The difference in results between the two databases may simply be due to the row being chosen.
In any case, in any other database, having without a group by generally looks awkward.  Having without a group by and no aggregation functions is not allowed.

A: WHERE and HAVING are not interchangeable. HAVING should only to be used as a condition to GROUP BY. MySQL/MariaDB are quite liberal in terms of how SQL can be written and therefore do not issue a warning/error and you might sometime get unexpected results.
In your case, the function call seems to be executed after the ORDER BY / LIMIT combo causing the funtion only to receive the row with value 33.


text:
Q: Populate specific Div from particular Jquery array How to output a particular JQuery array into a particular Div.   For example I want to pull the (phrases[0]) array into Div id="div01", and the (phrases[1]) array into Div id="div02".  I have read up all the functions of JQuery but can't find this.
var phrases = [
['nihao', 'orange', '你 好', 'hello'],
['zaijian', 'red', '你 好', 'goodbye']
];

makePhrase = function(phrase){
var div = $('
' +phrase[0]+ '
'     +phrase[2]+ '
' +phrase[3]+ '
');

And then I need a line to say (in effect):

.append makePhrase( phrases[0] ) to Div id="div01"

but do not know the correct method.  This is only my second day of learning JQuery so I would appreciate a spell-it-out answer which then I can learn more from through further investigation! I hate being the noob but any help would be appreciated.

A: You are very close; Try this:
var phrases = [
    ['nihao', 'orange', '你 好', 'hello'],
    ['zaijian', 'red', '你 好', 'goodbye']
    ];

makePhrase = function(phrase) {
    var div = '
Chinese: ' + phrase[0] + '
Pinyin:' + phrase[2] + '
English: ' + phrase[3] + '
';
    return div;
}

$("#div01").append(makePhrase(phrases[0]));
$("#div02").append(makePhrase(phrases[1]));

And proof it works over at jsfiddle: http://jsfiddle.net/SKssF/14


text:
Q: Azure resource manager template website app settings I am trying to add app settings to my Azure Website via the JSON template files as part of the Azure Resource Manager.
In an Azure Resource template json file, there are examples for creating connectionStrings directly from the JSON template file with a sub-dependency of type 'config' with properties for 'connectionStrings' as in the final example here http://haishibai.blogspot.co.uk/2014/09/tutorial-building-azure-template.html I have also checked in the website schema definition for websites here http://schema.management.azure.com/schemas/2014-06-01/Microsoft.Web.json#/definitions/sites and cannot see that it is possible.
Is it possible to define a websites app settings for resource manager deployments from the JSON template file? And if so any links or details would be greatly appreciated.
(I have already tried properties of appSettings inside the config resource and inside the website resource)

A: Here is the solution for the latest release 2014-06-01 version of API.
"resources": [
    {
        "apiVersion": "2014-06-01",
        "name": "[parameters('webSiteName')]",
        "type": "Microsoft.Web/sites",
        "location": "[parameters('webSiteLocation')]",
        "tags": {
            "[concat('hidden-related:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('webSiteHostingPlanName'))]": "Resource",
            "displayName": "WebSite"
        },
        "dependsOn": [
            "[concat('Microsoft.Web/serverfarms/', parameters('webSiteHostingPlanName'))]"
        ],
        "properties": {
            "name": "[parameters('webSiteName')]",
            "serverFarm": "[parameters('webSiteHostingPlanName')]"
        },
        "resources": [
            {
                "apiVersion": "2014-04-01",
                "name": "MSDeploy",
                "type": "extensions",
                "dependsOn": [
                    "[concat('Microsoft.Web/Sites/', parameters('webSiteName'))]"
                ],
                "properties": {
                    "packageUri": "[concat(parameters('dropLocation'), '/', parameters('webSitePackage'), parameters('dropLocationSasToken'))]",
                    "dbType": "None",
                    "connectionString": "",
                    "setParameters": {
                        "IIS Web Application Name": "[parameters('webSiteName')]"
                    }
                }
            },
            {
                "apiVersion": "2014-04-01",
                "name": "web",
                "type": "config",
                "dependsOn": [
                    "[resourceId('Microsoft.Web/Sites', parameters('webSiteName'))]"
                ],
                "properties": {
                    "connectionStrings": [
                        {
                            "ConnectionString": "AzureWebJobsStorage",
                            "Name": "CustomConnectionString1"
                        },
                        {
                            "ConnectionString": "AzureWebJobsStorage",
                            "Name": "CustomConnectionString2"
                        }
                    ],
                    "appSettings": [
                        {
                            "Name": "Key1",
                            "Value": "Value1"
                        },
                        {
                            "Name": "Key2",
                            "Value": "Value2"
                        }
                    ]
                }
            }
        ]
    },

A: Adding as a sub/child resource fails to work using the later API's, however adding a "siteConfig" property with an "appSettings" element, as stated above, seems to work. I am using the API Version 2016-03-01
{
        "type": "Microsoft.Web/sites",
        "name": "[variables('webappName')]",
        "apiVersion": "2016-03-01",
        "location": "[parameters('location')]",
        "tags": "[parameters('tags')]",
        "kind": "app",
        "properties": {
            "name": "[variables('webappName')]",
            "serverFarmId": "[variables('targetResourceId')]",
            "hostingEnvironment": "[parameters('hostingEnvironment')]",
            "netFrameworkVersion": "[parameters('netFrameworkVersion')]",
            "use32BitWorkerProcess": false,
            "webSocketsEnabled": true,
            "alwaysOn": true,
            "managedPipelineMode": "integrated",
            "clientAffinityEnabled": true,
            "hostNameSslStates": [
                {
                    "name": "[variables('hostName')]",
                    "sslState": "SniEnabled",
                    "thumbprint": "[parameters('certThumb')]",
                    "ipBasedSslState": "NotConfigured",
                    "hostType": "Standard"
                }
            ],
            "siteConfig": {
               "appSettings": "[variables('appSettings')]"
            }
        },
        "dependsOn": [
            "[concat('Microsoft.Web/serverfarms/', variables('hostingPlanName'))]"
        ],
        "resources": []
    }

And my variable looks like this.....
"appSettings": [
            {
                "name": "WEBSITE_NODE_DEFAULT_VERSION",
                "value": "8.9.3"
            },
            {
                "name": "WEBSITE_PRIVATE_EXTENSIONS",
                "value": "0"
            },
            {
                "name": "MobileAppsManagement_EXTENSION_VERSION",
                "value": "latest"
            },
            {
                "name": "WEBSITE_LOAD_CERTIFICATES",
                "value": "*"
            }
        ]

A: I have a sample that shows how to do this here. It looks like this:
    {
      "apiVersion": "2014-11-01",
      "name": "appsettings",
      "type": "config",
      "dependsOn": [
        "[resourceId('Microsoft.Web/Sites', parameters('siteName'))]"
      ],
      "properties": {
        "AppSettingKey1": "Some value",
        "AppSettingKey2": "My second setting",
        "AppSettingKey3": "My third setting"
      }
    }

Please make sure you use the newest 2014-11-01 API, as the way it deals with app settings is a bit different from the older API.

A: With thanks to Simon Pedersen - properties/siteConfig/appSettings works as of November 2015.
{
    "apiVersion": "2014-06-01",
    "name": "[concat(parameters('siteName'),copyIndex())]",
    "type": "Microsoft.Web/sites",
    "location": "[parameters('siteLocations')[copyIndex()]]",
    "tags": {
        "[concat('hidden-related:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
        "displayName": "Website"
    },
    "dependsOn": [
        "[concat('Microsoft.Web/serverfarms/', concat(parameters('hostingPlanName'),copyIndex()))]",
        "[concat('Microsoft.Storage/storageAccounts/', parameters('newStorageAccountName'))]"
    ],
    "properties": {
        "name": "[concat(parameters('siteName'),copyIndex())]",
        "serverFarm": "[concat(parameters('hostingPlanName'),copyIndex())]",
        "siteConfig": {
            "appSettings": [
                {
                    "name": "AzureStorageAccount",
                    "value": "[concat('DefaultEndpointsProtocol=https;AccountName=',parameters('newStorageAccountName'),';AccountKey=',listKeys(variables('storageid'),'2015-05-01-preview').key1)]"
                }
            ]
        }
    },
    "copy": {
        "name": "siteCopy",
        "count": "[parameters('numberOfSites')]"
    }
}


text:
Q: Error reading Excel file with openpyxl 2.6.2 (was working under openpyxl 2.5.12) I wrote a script that checks if Excel files contain the worksheet "Budget". This is working with Python 3.7 and openpyxl 2.5.12. However, since Anaconda updated openpyxl to version 2.6.2 it is no longer working (see error message below). I am having issues resolving this error message. Any help is appreciated.
# Import modules:
import os
import pandas as pd
from openpyxl import load_workbook
from pathlib import Path, PureWindowsPath

# Set correct path to Excel files:

excel_folder = PureWindowsPath("C:\\Users\\c3post\\Desktop\\Excel")
correct_excel_folder = Path(excel_folder)
print('Working directory: ', correct_excel_folder, '\n\n')

# Change current working directory so that opening relative paths will work:
os.chdir(correct_excel_folder)

# Add files to list:
files = os.listdir(correct_excel_folder)

# Filter 'xlsx' files and add them to new list:
files_xlsx = [f for f in files if f[-4:] == 'xlsx']

# Filter out xlsx files that do not contain the worksheet "Budget"
files_budget = []

for file in files_xlsx:
    wb = load_workbook(file)
    ws = wb.worksheets
    if 'Budget' in str(ws):
        files_budget.append(file)

print('Files that contain worksheet "Budget": ', files_budget, '\n\n')
print('Files that do not contain worksheet "Budget": ', set(files_xlsx) - set(files_budget))

Error message:

KeyError                                  Traceback (most recent call last)
<ipython-input-2-fa1881e560e0> in <module>
     29
     30 for file in files_xlsx:
---> 31     wb = load_workbook(file)
     32     ws = wb.worksheets
     33     if 'Budget' in str(ws):

~/anaconda3/lib/python3.7/site-packages/openpyxl/reader/excel.py in load_workbook(filename, read_only, keep_vba, data_only, keep_links)
    310     reader = ExcelReader(filename, read_only, keep_vba,
    311                         data_only, keep_links)
--> 312     reader.read()
    313     return reader.wb

~/anaconda3/lib/python3.7/site-packages/openpyxl/reader/excel.py in read(self)
    272         self.read_theme()
    273         apply_stylesheet(self.archive, self.wb)
--> 274         self.read_worksheets()
    275         self.parser.assign_names()
    276         if not self.read_only:

~/anaconda3/lib/python3.7/site-packages/openpyxl/reader/excel.py in read_worksheets(self)
    226                 ws._rels = rels
    227                 ws_parser = WorksheetReader(ws, fh, self.shared_strings, self.data_only)
--> 228                 ws_parser.bind_all()
    229
    230             # assign any comments to cells

~/anaconda3/lib/python3.7/site-packages/openpyxl/worksheet/_reader.py in bind_all(self)
    401
    402     def bind_all(self):
--> 403         self.bind_cells()
    404         self.bind_merged_cells()
    405         self.bind_hyperlinks()

~/anaconda3/lib/python3.7/site-packages/openpyxl/worksheet/_reader.py in bind_cells(self)
    324
    325     def bind_cells(self):
--> 326         for idx, row in self.parser.parse():
    327             for cell in row:
    328                 style = self.ws.parent._cell_styles[cell['style_id']]

~/anaconda3/lib/python3.7/site-packages/openpyxl/worksheet/_reader.py in parse(self)
    148                 element.clear()
    149             elif tag_name == ROW_TAG:
--> 150                 row = self.parse_row(element)
    151                 element.clear()
    152                 yield row

~/anaconda3/lib/python3.7/site-packages/openpyxl/worksheet/_reader.py in parse_row(self, row)
    270         if keys != set(['r', 'spans']) and keys != set(['r']):
    271             # don't create dimension objects unless they have relevant information
--> 272             self.row_dimensions[attrs['r']] = attrs
    273
    274         cells = [self.parse_cell(el) for el in row]

KeyError: 'r'


text:
Q: Search for a column in a bigQuery project or dataset I am looking for a table in my bigQuery project to give me information about parts size. I am not sure which dataset and table I have to search for.
In the project, there are tens of datasets with tens of tables in each. How I can find "partSize" in which table?
Is there any query to search schemas of all the tables in a dataset or project?

A: Data Catalog has a search function

A: select
  table_catalog,
  table_schema,
  table_name,
  column_name
from  dataset_name.INFORMATION_SCHEMA.COLUMNS
where lower(column_name) like '%partsize%'

Can give you for a specific dataset, the name of the tables where you can find the column you are looking for.
If there a lot of dataset:
select

concat("select table_catalog, table_schema, table_name, column_name from  ", schema_name, ".INFORMATION_SCHEMA.COLUMNS where lower(column_name) like '%%';")

from `region-us`.INFORMATION_SCHEMA.SCHEMATA

Can generate a query for all the datasets that are in that region. Pasting the results in the clipboard and back in the console should work. It is a bit ugly though, maybe there is a better way.