text:
Q: String encoding error in SQLiteDatabase.rawQuery I am building a SQLite query as a String with String.format and passing it to SQLiteDatabase.rawQuery. The integer parameter I'm passing at the end is hard coded to zero (I'm looking for any value greater than zero). This works normally in all my testing, but I'm getting crash reports from the field. I'm using a crash reporting website that does not give me detailed system/environment information. Here is the code that is crashing:
String query = String.format("SELECT * FROM %s WHERE %s > %d",
                            TableName,
                            ColumnName,
                            0);
Cursor c = db.rawQuery(query, null);

The exception being thrown is the following:
android.database.sqlite.SQLiteException: no such column: Û°: , while
compiling: SELECT * FROM TableName WHERE ColumnName > Û°

And the last few lines in the stack trace before the crash are:
SQLiteCompiledSql.java:-2:in android.database.sqlite.SQLiteCompiledSql.native_compile
SQLiteCompiledSql.java:68:in android.database.sqlite.SQLiteCompiledSql.<init>
SQLiteProgram.java:143:in android.database.sqlite.SQLiteProgram.compileSql

This looks like it must be an encoding error. However, I don't know how to tell what is the cause of this. I'm using SQLiteOpenHelper as a high level way to create and connect to my database, so I'm not explicitly setting an encoding. Also, the error reports are few but they've only come in on devices running ICS, so it's possible that this is something new in the defaults used in the SQLite classes in ICS.

A: You could try,
String sql = "SELECT * FROM ? WHERE ? > ?";
String[] selectionArgs = new String[] { TableName, ColumnName, "0"};
Cursor c = db.rawQuery(sql, selectionArgs);

However, I strongly suggest you make direct use of the SQLiteDatabase's query method instead. Given that it protects against SQL injections, it seems likely it will also protect against the strange encoding bugs too.
String[] selectionArgs = new String[] { ColumnName };
Cursor c = db.query(TableName, null, "? > 0", selectionArgs, null);

A: I agree that query rather than rawQuery is a better solution, but String.Format() has a form that selects the locale. Not using this has bitten me in a few similar circumstances:
String query = String.format(Locale.US,
                             "SELECT * FROM %s WHERE %s > %d",
                             TableName,
                             ColumnName,
                             0);


text:
Q: whats the better way to implement "paging" for several views? iphone I am trying to implement a viewcontroller which has in it a list of views where you can scroll horizontally from one to another.
First I tried to implement by using a scroll view with the total width of the views. (but if the views are 30 per example, the result its not good... (30 x 320) not mentioning I would had to add all the content of the views (buttons, subviews, etc))
Then I was thinking about using an UIPageViewController and make my views, a view controller that repeats it self but changes the content.
Can anyone help me by telling what's the best option that I have?
Thank you and best regards,
João Garcia.

A: The best way to do it is actually with a UIScrollView with the paging property set to YES. Look at this tutorial to get started.
Hope you get it working soon!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add a division inequality constraint I need to resolve this simple optimization problem with Google OR-Tools CP-SAT solver in Python:
Goal = MAXIMIZE (X+Y+Z)
Constraint: Z/(X+Y+Z) <= 0.25

I don't know how to write the constraint properly since it is not linear.
Could you help me?

A: You have to create an intermediate variable and set its value using model.AddDivisionEquality. You also have to scale some variables up as CP-SAT works with integers.
scaling = 1000
x = model.NewIntVar(0, 10, 'x')
y = model.NewIntVar(0, 10, 'y')
z = model.NewIntVar(0, 10, 'z')

scaled_z = model.NewIntVar(0, 10 * scaling, 'z_scaled')
denom = model.NewIntVar(1, 3 * 10, 'x+y+z')
division = model.NewIntVar(0, 10 * scaling, 'z/(x+y+z)')

model.Add(scaled_z == z * scaling)
model.Add(denom == x + y + z)
model.AddDivisionEquality(division, scaled_z, denom)
model.Add(division <= int(0.25 * scaling))
model.Maximize(x + y + z)

solver.Solve(model)

print('x =', solver.Value(x))
print('y =', solver.Value(y))
print('z =', solver.Value(z))
print('z/(x+y+z) =', solver.Value(division) / scaling)


text:
Q: Carmen Gem giving special characters I am using Carmen gem to get countries and respective states.but, when I use Carmen::Country.named("Sri Lanka").subregions.collect{|p| p.name}, I am getting this array:
["Basnāhira paḷāta",
 "Madhyama paḷāta",
 "Dakuṇu paḷāta",
 "Uturu paḷāta",
 "Næ̆gĕnahira paḷāta",
 "Vayamba paḷāta",
 "Uturumæ̆da paḷāta",
 "Ūva paḷāta",
 "Sabaragamuva paḷāta"]

and after using I18n, I am getting:
["Basnahira pa?ata",
 "Daku?u pa?ata",
 "Madhyama pa?ata",
 "Nae?genahira pa?ata",
 "Sabaragamuva pa?ata",
 "Uturu pa?ata",
 "Uturumae?da pa?ata",
 "Uva pa?ata",
 "Vayamba pa?ata"]

With ? replacing a special characters.

A: transliterate changes non ascii characters to ascii characters approximations, any characters for which there are no approximations are replaced with ?. this is explained in the docs. If this is not what you want to do, you do not want to use the transliterate method.
If you want to write your own transliteration approximations do it like so (from the docs I linked to):
i18n:
  transliterate:
    rule:
      ü: "ue"
      ö: "oe"


text:
Q: Show ajax response in a div according to the value of a selection I have two selections. The second selection values depend on the first ones.
When the user select a value in the first select, an Action is called to fill the second select.
It works only if the user submits the form and there are validation errors.
how could I reload the div when the user selects a value in the first select?
My jquery is:
$('select[name=select1]').change(function () {
            var cod=$(this).val();
            if (cod>0) {
                $.ajax({
                    url:"Load.do",
                    data: "cod="+cod,
                    });
            }
        });

In the struts-config.xml, I have:
<action path="/Load" scope="request" type="mypackage.Load">
    <forward name="Success" path="/jsp/myForm.jsp"/>
 </action>

The class Load is an Action:
public class Load extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
{
    // TODO Auto-generated method stub

    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
        // get the connection
        stmt = (Statement) con.createStatement();

        String cod = request.getParameter("cod");

        String select = new String("Select firstCode, name from mytable where secondCode = '");
        select = select.concat(cod);
        select = select.concat("';");
        rs = stmt.executeQuery(select);
        ArrayList<LabelValueBean> arr = new ArrayList<LabelValueBean>();
        while (rs.next()) {
            arr.add(new LabelValueBean(rs.getString("name"),rs.getString("firstCode")));
        }

        request.getSession().setAttribute("arr", arr);

        return mapping.findForward("Success");
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }  catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (rs != null) {
              try { rs.close(); } catch (SQLException e) {}
              rs = null;
        }
        if (stmt != null) {
              try { stmt.close(); } catch (SQLException e) {}
              stmt = null;
        }
        if (con != null) {
              try { con.close(); } catch (SQLException e) {}
              con = null;
        }
    }

    return mapping.findForward("Failure");
}
 }

In my myForm.jsp page, the select which I want fill is:
 <html:select property="prop1">
 <html:option value="0">Choose:</html:option>
 <% if (request.getSession().getAttribute("arr") != null) { %>
<html:optionsCollection name="arr" label="label" value="value"/>
<% } %>
</html:select>

A: If the response data contains exactly the html you want, i.e. the correct <select> with all the options you can simply replace the 2nd select with the response data:
$('select[name=select1]').change(function () {
    var cod=$(this).val();
    if (cod>0) {
        $.ajax({
            url:"Load.do",
            data: "cod="+cod,
            success: function(result) {
                $('select[name=select2]').replaceWith(result); //guessing the name
            }
        });
    }
});


text:
Q: Check if a string from a column in a dataframe exists in a column in a different dataframe I have two dataframes.

and a second one as shown below

I would like to combine them to one dataframe like this one

A: You can do:
df = pd.DataFrame([[1, 'select from [mary_flowers]'], [2, 'select from [esther_pots]'], [3, 'select from [somthing]']], columns=['item_id', 'Column_x'])
df['view_name'] = df['Column_x'].str.extract(r'\[(\w*)\]', expand=True)[0]
df.loc[~df['view_name'].isin(list(df2['view_name'])), 'view_name'] = np.nan
df

Output:
   item_id    Column_x                    view_name
0   1        select from [mary_flowers]   mary_flowers
1   2        select from [esther_pots]    esther_pots
2   3        select from [somthing]       NaN

Explaination: This extracts the table_name from the [], and than checks if it's in you second df, changing it to np.nan if not.
EDIT:
If you can have more than one table name in 'Column_x' use:
df = pd.DataFrame([[1, 'select from [mary_flowers] join [tom_trucks]'], [2, 'select from [esther_pots]'], [3, 'select from [somthing]']], columns=['item_id', 'Column_x'])
names = ['mary_flowers', 'esther_pots', 'tom_trucks']
df['view_name'] = df['Column_x'].str.findall(r'\[(\w*)\]')
df['view_name'] = df['view_name'].map(lambda views: [v for v in views if v in list(df2['view_name'])])
df

Output:
  item_id   Column_x                                     view_name
0       1   select from [mary_flowers] join [tom_trucks] [mary_flowers, tom_trucks]
1       2   select from [esther_pots]                    [esther_pots]
2       3   select from [somthing]                       []


text:
Q: Binding a guava supplier using guice I want do a binding like this,
bind(Supplier<TestClass>).toProvider(Provider<Supplier<TestClass>>).in(Singleton.class);

The provider is returned by an external function so, inside the toProvider(), I call that function and it returns Provider<Supplier<TestClass>>.
The supplier is from guava, the reason to do this kind of thing is, there is a file associated with the TestClass and I need to read that file and assign those values to the respective fields of TestClass.
And that file change at run time, So I need a way to refresh the values stored in TestClass. To-Do that guava supplier I used. Guava supplier has a get method and when that get method is called, if I used memoizeWithExpiration() to create the instance then it checks the TTL value and if it passed, then I can specify a lambda function to read the file and assign values.
So I need to inject Supplier<TestClass> like this
@Inject
Supplier<TestClass> someClassSupplier;

But For doing that binding with Guice is confusing for me.

A: You can use the following kind of code to do what you want:
class ServiceModule extends AbstractModule {
  private TestClass readTestClassFromFile() {
    return new TestClass();
  }

  // Cache an instance for 5 seconds.
  private final Supplier<TestClass> testClassSupplier = Suppliers.memoizeWithExpiration(this::readTestClassFromFile, 5, SECONDS);

  @Provides TestClass provideTestClass() { // Don't declare as singleton
    return testClassSupplier.get();
  }
}

Then, in your class:
class Service {

  @Inject
  Provider<TestClass> testClassProvider; // Inject the provider, not the instance itself, or any supplier.

  void doSomething() throws Exception {
    TestClass a = testClassProvider.get();
    TestClass b = testClassProvider.get();

    Thread.sleep(6000); // Sleep for 6 seconds

    TestClass c = testClassProvider.get();

    System.out.println(a == b); // Prints true
    System.out.println(a == c); // Prints false
  }
}

You requested for a generic way of doing this, so here it is, check the bindSupplier method:
import static com.google.common.base.Suppliers.memoizeWithExpiration;

import com.google.inject.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class Main {

  public static void main(String[] args) throws Exception {
    Guice.createInjector(new ServiceModule())
        .getInstance(Service.class)
        .doSomething();
  }

  static class ServiceModule extends AbstractModule {
    Dependency createDependency() { return new Dependency(); }

    // For Java 8+
    private <T> void bindSupplier(Class<T> type, Supplier<? extends T> supplier) {
      // Definitely avoid .in(Singleton.class) because you want the scope to be defined by the Supplier.
      bind(type).toProvider(supplier::get);
    }

// For Java 7 and less
//    private <T> void bindSupplier(Class<T> type, final Supplier<? extends T> supplier) {
//      bind(type).toProvider(new Provider<T>() {
//          @Override public T get() { return supplier.get(); }
//        });
//    }

    @Override protected void configure() {
      bindSupplier(Dependency.class,
          memoizeWithExpiration(this::createDependency, 3, TimeUnit.SECONDS));
    }

  }

  static class Dependency {}

  static class Service {

    @Inject Provider<Dependency> dependencyProvider;

    void doSomething() throws InterruptedException {
      Dependency a = dependencyProvider.get();
      Dependency b = dependencyProvider.get();
      Thread.sleep(4000);
      Dependency c = dependencyProvider.get();
      System.out.printf("a == b ? %s%n", a == b); // true
      System.out.printf("a == c ? %s%n", a == c); // false
    }
  }
}


text:
Q: PostgreSQL: Intersection entre polygons retorna linhas e pontos Estou trabalhando em uma consulta espacial e tenho duas tabelas com feições de GeometryType APENAS Polygon ou MultiPolygon:
TABELA ZONEAMENTO:
select ST_GeometryType (geom), count (*)
    from
        legislacao_urbanistica_municipal.prod_lu_zon_zoneamento
group by ST_GeometryType (geom)

Essa consulta me retorna:

"ST_MultiPolygon"  "13"
"ST_Polygon"   "606"

TABELA QUADRA
select ST_GeometryType (geom), count (*)
    from
        cadastro_tecnico_municipal.prod_ct_ctm_quadra_ctm
group by ST_GeometryType (geom)

Essa consulta me retorna:

"ST_MultiPolygon"  "110"
"ST_Polygon"   "17661"

Observem que só há Polygon ou MultiPolygon.
No entanto, quando dou um ST_Intersection, o meu retorno contém pontos, linhas e polígonos e multis.... De tudo! E isso está me atrapalhando num consulta posterior:
Essa é a consulta que faz a interseção:
create materialized view legislacao_urbanistica_municipal.lu_lei_7166_zoneamento_quadra_vw as
select  row_number() over (order by id_tipo_zoneamento) as id,
        ST_Intersection(ST_Multi(quadra.geom),ST_Multi(z_7166.geom)) as geom,
        z_7166.id_tipo_zoneamento
    from    legislacao_urbanistica_municipal.prod_lu_zon_zoneamento as z_7166,
            cadastro_tecnico_municipal.prod_ct_ctm_quadra_ctm as quadra
    where ST_Intersects (z_7166.geom , quadra.geom)

E o retorno dos Geometry Types dela:
select ST_GeometryType (geom), count (*)
    from
        legislacao_urbanistica_municipal.lu_lei_7166_zoneamento_quadra_vw
group by ST_GeometryType (geom)

"ST_GeometryCollection"    "195"
"ST_LineString"    "3"
"ST_MultiLineString"   "41"
"ST_MultiPoint"    "2"
"ST_MultiPolygon"  "783"
"ST_Point" "13"
"ST_Polygon"   "18782"

O problema é que dessa tabela eu faço uma outra consulta de Intersection e, como ela tem GeometryCollection nela, o PGAdmin me dá erro:
SELECT  h.id_zona_homogenea_tgc,
        z.id_tipo_zoneamento,
        z.sigla_zoneamento
    FROM    tributario.prod_tr_lim_zona_homogenea_tgc as h,
            (
                select  a.id_tipo_zoneamento,
                        b.sigla_zoneamento,
                        a.geom
                    from    legislacao_urbanistica_municipal.lu_lei_7166_zoneamento_quadra_vw a,
                            legislacao_urbanistica_municipal.prod_lu_zon_tipo_zoneamento b
                    where a.id_tipo_zoneamento = b.id_tipo_zoneamento
            ) as z
    where   ST_Intersects(h.geom,z.geom)
    group by h.id_zona_homogenea_tgc, z.id_tipo_zoneamento, z.sigla_zoneamento
    ORDER BY id_zona_homogenea_tgc

ERROR:  ERRO:  Relate Operation called with a LWGEOMCOLLECTION type.  This is unsupported.
  HINT:  Change argument 2: 'GEOMETRYCOLLECTION(POINT(612590.299990058 7794557.73136217),POLYGON((612588.6...
  SQL state: XX000

Já tentei algumas soluções (Dump, cast, Multi), mas não tá rolando. Alguém sabe o motivo e alguma solução?


text:
Q: Is there a way to iterate through certain types of objects on a canvas in python tkinter? For example, I've got a bunch of text objects of varying font families on a canvas, can I make some kind of call to iterate through these text objects and alter them?

A: You can get a list of all items on a canvas with the find_all() method and then just list them:
def get_canvas_items(canvas):
    item_list = canvas.find_all()
    for item in item_list:
        item_type = canvas.type(item)   # e.g. "text", "line", etc.
        item_keys = canvas.itemconfig(item).keys()  # item options
        # Do stuff...

Have a look at effbot: The Tkinter Canvas Widget for additional info on canvas.


text:
Q: Using CSS to make sections that extend full width of screen I'm sure this is real simple but it's been a few yeasr since I've worked in CSS and need some help jogging my brain. I simply want to create a number of sections (i.e., ) where each one will have a different background color and each section will stretch to the edge of the browser window. I've provided a basic scheme as follows:

        Header content.

List

List

List

…content…

...content...

        Footer content.

the CSS:
* { margin: 0; padding: 0; }

body { background: yellow; }

div.header { background: orange; color: white; }

div.nav { background: pink; }

div.content-blue { background: blue; color: white; }

div.content-red { background: red; color: white; }

div.footer { background: gray; color: white; }

And yes, I did take a look through the forums and look around but I couldn't find anything particularly related. Maybe my question's too simple. :)

A: Just add a
min-width: 100%;

to the relevant divs

* { margin: 0; padding: 0; }

body { background: yellow; }

.header, .nav, .content-blue, .content-red, .footer {
min-width: 100%;
}

div.header { background: orange; color: white; }

div.nav { background: pink; }

div.content-blue { background: blue; color: white; }

div.content-red { background: red; color: white; }

div.footer { background: gray; color: white; }

        Header content.

List

List

List

…content…

...content...

        Footer content.

A: You don't need to do anything apart from removing the padding on the body, which you already did.
You just need to remove the padding from the body.
There is need to set the width of the divs, since they are block elements so they will automatically use the width available.
If I make a code snippet with your code in it, it works perfectly (at least in Chrome):

* { margin: 0; padding: 0; }

body { background: yellow; }

div.header { background: orange; color: white; }

div.nav { background: pink; }

div.content-blue { background: blue; color: white; }

div.content-red { background: red; color: white; }

div.footer { background: gray; color: white; }

        Header content.

List

List

List

…content…

...content...

        Footer content.


text:
Q: component is not defined while opened on web I have a component that work fine on android but it shows an error when I try to open it on the web using expo

Uncaught ReferenceError: TextInputMask is not defined
at ./src/components/atoms/TextInputMask.js (TextInputMask.js:6:1)

Here is TextInputMask code that gives an error
import React, { useEffect, useState } from "react";
import { View, StyleSheet } from "react-native";
import { TextInput, Text } from "react-native-paper";
import { TextInputMask as TextInputMaskDefault } from "react-native-masked-text";

export default TextInputMask = React.forwardRef(
  (
    {
      label,
      placeholder,
      style,
      mode = "outlined",
      onChangeValue = () => {},
      type = "custom",
      options = {},
      value,
      icon,
      disabled,
      error,
      ...props
    },
    ref
  ) => {
    const [data, setData] = useState();
    const [maskValue, setMaskValue] = useState();
    useEffect(() => {
      if (value === null || value === undefined) {
        setMaskValue("");
        return;
      }
      if (value) {
        value = String(value);
        setMaskValue(value);
      }
    }, [value]);
    useEffect(() => {
      let rawValue = data?.getRawValue();
      onChangeValue(rawValue, maskValue);
    }, [maskValue]);
    return (
      <View style={style}>
        <View style={styles.viewInput}>
          <TextInput
            style={styles.textInput}
            label={label}
            placeholder={placeholder}
            mode={mode}
            autoCapitalize="none"
            autoCorrect={false}
            autoCompleteType="off"
            ref={ref}
            disabled={disabled}
            value={maskValue}
            error={error}
            render={(inputProps) => {
              return (
                <TextInputMaskDefault
                  {...inputProps}
                  type={type}
                  options={options}
                  onChangeText={(text) => setMaskValue(text)}
                  ref={(ref) => setData(ref)}
                />
              );
            }}
            {...props}
          />
          {icon ? (
            <Text style={styles.textInputIcon}>
              <TextInput.Icon
                name={icon}
                onPress={onPress}
                size={30}
                color={error ? Colors.red800 : null}
                disabled={disabled}
              />
            </Text>
          ) : null}
        </View>
      </View>
    );
  }
);

Any idea where the error might be? I wonder if there is a difference in creating component for android and web?


text:
Q: Pass two set of rules for rows to xtable Please consider the following MWE (variation from this answer)
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{booktabs}
\usepackage{colortbl, xcolor}

\begin{document}

<<do_table, results = "asis">>=
library(xtable)
mydf <- data.frame(id = 1:10, var1 = rnorm(10), var2 = runif(10))
rws <- c(1,3,5,6,7)
col <- rep("\\rowcolor[gray]{0.95}", length(rws))
print(xtable(mydf), booktabs = TRUE,
   add.to.row = list(pos = as.list(rws), command = col))
@

\end{document}

With this I have set a rule for the rows 1,3,5,6,7. Now let's say I would like also to set a different colour [green] for different rows (2,4). Is it possible?

A: Yes, you just need to construct a col vector that contains all corresponding colors for each position in the table. Your example with two differently colored rows:
<<do_table, results = "asis">>=
library(xtable)
mydf <- data.frame(id = 1:10, var1 = rnorm(10), var2 = runif(10))
rws <- c(1,4)
col <- c("\\rowcolor[gray]{0.95}", "\\rowcolor[gray]{0.7}")
print(xtable(mydf), booktabs = TRUE,
   add.to.row = list(pos = as.list(rws), command = col))
@


text:
Q: Get user Access Token from Twitter in Angular 2+ app Hi I want to get a twitter user access token/refresh token so that My application can post/read tweets on behalf of the user..
I have a button in my app.. on clicking of the button, I need to show something like below image -
user should be able to provide his/her credential and if it is already logged in to twitter then he/she should only see authorize app button..
I created a new app in my developer twitter account.. but little clueless on how to get user's access token to post/read behalf of him...

A: Twitter uses OAuth1.0a unlike Facebook which uses OAuth2.0. The difference between OAuth1.0a and OAuth2.0 is that OAuth1.0a is more secure and you should use a server-based authentication flow because it involves api keys and secrets which we shouldn't be sharing with angular app.
On server side (NodeJS/Django, etc) you should use a client library for OAuth1.0 which will help you in complicated process of signing requests befores sending it to twitter.
Here is a useful link (which I also used) for you to implement the server flow:
https://github.com/requests/requests-oauthlib/blob/master/docs/oauth1_workflow.rst
Basically, the OAuth flow for twitter is as follows:

*

*Send a POST request to oauth / request_token

*You will get the authroization url from Step 1 like this https://api.twitter.com/oauth/authorize?oauth_token=XXX which you will redirect the user to so that they can authorize your app

*Twitter redirects the user to your redirect url (which you sent with the request in previous step) with access_token and verifier.

*You need to exchange the access_token and verifier for the actual usable user access token by sending a POST to oauth/access_token.

You can find more details for 3-legged OAuth flow here: https://developer.twitter.com/en/docs/basics/authentication/overview/3-legged-oauth


text:
Q: GridBagLayout not lining up I have 5 JPanels lined up vertically. Each JPanel is filled with the same elements, but different values (JPanel, JButton, JLabel). I want them to look like this:
Panel   Button   Label
Panel   Button   Label

Buts it's turning out like this
Panel   Button   Label
Panel Button     Label

The spacing is a little off, but the code is exactly the same for each container. How can I fix this?
public class AnswerChoice extends JPanel {
    private static final long serialVersionUID = 1L;

    private AnswerButton button;
    private JLabel answerLabel;

    public AnswerChoice(String imageURL) {
        setBackground(Color.RED);
        setLayout(new GridBagLayout());
        button = new AnswerButton(imageURL);
        answerLabel = new JLabel();
        answerLabel.setFont(new Font("Times New Roman", Font.PLAIN, 32));

        GridBagConstraints gbc = new GridBagConstraints();

        JPanel panel = new JPanel();
        panel.setBackground(Color.ORANGE);
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 1;
        gbc.weightx = 0.2;
        add(panel, gbc);

        gbc.fill = GridBagConstraints.NONE;
        gbc.gridx = 2;
        gbc.weightx = 0.0;
        gbc.insets = new Insets(0, 0, 0, 30);
        add(button, gbc);

        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 3;
        gbc.weightx = 0.8;
        add(answerLabel, gbc);
    }

}

The JLabel does have text in it but I set it somewhere else.

A:
but the code is exactly the same for each container.

The layout is done independently for each container based on the components added to the containter. So the size of each component on the container matters. Each container doesn't know that you have 4 other containers.

I have 5 JPanels lined up vertically.

So then you need to create a single panel using a GridBagLayout and add all 15 components to that panel. Then all 3 columns will be sized based on the components in each of the 5 rows.
Or I see in your logic that you try to assign relative sizes to each of the 3 components as .2, 0, .8. In this case you could use the Relative Layout on each of the panels. Using the Relative Layout you would display the button at its preferred size and then use 0.2f and 0.8f as the contraints for the panel and label respectively.


text:
Q: Query for Case Owner returns 0 results? I have a trigger passing cases to a class, excerpted below.
The query for User matching caseowner.id returns zero results, though the query for user matching Salesperson__C (a custom lookup to a user) works.
Is it b/c an owner can be a queue?
for (Case OP: Cases){

            List <User> UsersToSub = new List <user>();
            List <User> CaseSalesperson = [select id from User where  id =: op.Salesperson__c ];
            List <User> CaseOwner = [select id from User where  id =: op.CreatedBy.id ];
            system.debug('owner=================== '+CaseOwner);

            UsersToSub.addAll(CaseOwner);
            UsersToSub.addAll(CaseSalesperson);

Note that this also returns zero results:
List <User> CaseOwner = [select id from User where  id =: op.CreatedBy.id ];

A: Use the CreatedById field instead of CreatedBy.Id.
See the Default System Fields.


text:
Q: OCAML Depth-First Search I've been doing a tutorial in OCaml (don't ask me why, I just decided to expand my knowledge of languages, I guess) and I've gotten to the point where I'm working with graphs. The tutorial taught me how to do a breadth-first search on a graph, which I can implement fine. However, I've been struggling with an algorithm for a depth-first search, which is one of those things where the tutorial goes, "We suggest you try this on a depth-first method, but we won't tell you how to do it."
I'm trying to implement it like so: let rec dfs graph start end. Which is to say, I've been trying to do it where I take in a list of edges (graph), a starting node (start), and an ending node (end).
I've created my graph using a list of edges...
let edges = [
  ("a", "b"); ("a", "c");
  ("a", "d"); ("b", "e");
  ("c", "f"); ("d", "e");
  ("e", "f"); ("e", "g")
];;

However, I'm totally lost about where to go from here. Any advice on how to get me going? Thanks.

A: So, I did it but I find it strange that you represent a graph as a list if you have to search in it. A map would be much better. Anyway, here's how it's done :
let edges = [
  ("a", "b"); ("a", "c");
  ("a", "d"); ("b", "e");
  ("c", "f"); ("d", "e");
  ("e", "f"); ("e", "g")
];;

let successors n e =
  List.map (fun (_, v) -> v) (List.filter (fun (u, _) -> n = u) e)

let dfs graph start f =
  let rec rdfs visited node =
    if not (List.mem node visited) then
      begin
        f node;
        let s = successors node graph in
        List.fold_left rdfs (node::visited) s
      end
    else visited
  in rdfs [] start

 let () = let _ = dfs edges "a" print_string in ()

First thing, define a successors functions which will give you every direct successor of a node (the List.filter part gets you the edges, the List.map part split the resulting edges in two parts and keep only the second one (the first one is naturally the node for which you are searching the successors).
The dfs function defines an internal function that do two things, checking if the node we are working on was already visited or not.

*

*If yes, nothing changes, we just return the same list of visited nodes (and maybe some other things depending on what you want to do with your search).

*If no, then

*We apply the function we gave to dfs to the current node,

*We add this node to the visited nodes,

*We take his successors,

*We apply the function to each one, (here, there's a small trick, since we have
List.fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
and
rdfs : string list -> string -> string list
instead of writing
List.fold_left (fun visited node -> rdfs visited node) ...
we can write
List.fold_left rdfs ...
(something to do with this strange thing called Lambda Calculus and some rule called eta conversion which states that :
λ x · ux    η    u      (x ∉ fv(u)) (fv(u) being the free variables of u) :-p) (what it means is that in OCaml, if you write fun x -> f x you could have written f instead, it is strictly equivalent.)

*We return the visited nodes list in which all the visited nodes have been added
Hope I helped.


text:
Q: InputTextarea of prime faces not applying the maxlength I am using <p:InputTextarea /> tag like this
<p:inputTextarea id="description" required="false"
    label="description" maxlength="255" tabindex="3"
    rendered="#{basicSetupController.description}" validatorMessage="Maximum allowable length for description is 255"
    value="#{basicSetupController.basicSetupBean.description}">
    <f:validateLength minimum="0" maximum="255" />
</p:inputTextarea>

I am facing problems that prime faces is not limiting the user after having entered 255 characters.  The user enters as many characters as he/she wants.  Although the validateLength tag works fine but the demand of the client is that the user should not be able to enter more than 255 characters.
Any idea please ?

A: Try:
<script type="text/javascript">
     function validate()
     {
       var x=document.getElementById("form:text").value;
       if(x.length > 255) {
          document.getElementById("form:text").value=x.substring(0,255);
       }

     }
</script>

 <h:form id="form">

         <h:inputText id="text" onkeyup="validate()" />

 </h:form>

A: Well, the issue has been resolved by the primefaces in the later releases. No need for  <f:validateLength>. Primefaces itself restricts the user to type more than the maxLength set
<p:inputTextarea id="details" maxlength="20">
            </p:inputTextarea>

works pretty well now.


text:
Q: Sending JSON to Flask, request.args vs request.form My understanding is that request.args in Flask contains the URL encoded parameters from a GET request while request.form contains POST data. What I'm having a hard time grasping is why when sending a POST request, trying to access the data with request.form returns a 400 error but when I try to access it with request.args it seems to work fine.
I have tried sending the request with both Postman and curl and the results are identical.
curl -X POST -d {"name":"Joe"} http://127.0.0.1:8080/testpoint --header "Content-Type:application/json"

Code:
@app.route('/testpoint', methods = ['POST'])
def testpoint():
    name = request.args.get('name', '')
    return jsonify(name = name)

A: You are POST-ing JSON, neither request.args nor request.form will work.
request.form works only if you POST data with the right content types; form data is either POSTed with the application/x-www-form-urlencoded or multipart/form-data encodings.
When you use application/json, you are no longer POSTing form data. Use request.get_json() to access JSON POST data instead:
@app.route('/testpoint', methods = ['POST'])
def testpoint():
    name = request.get_json().get('name', '')
    return jsonify(name = name)

As you state, request.args only ever contains values included in the request query string, the optional part of a URL after the ? question mark. Since it's part of the URL, it is independent from the POST request body.

A: Your json data in curl is wrong, so Flask does not parse data to form.
Send data like this: '{"name":"Joe"}'
curl -X POST -d '{"name":"Joe"}' http://example.com:8080/testpoint --header "Content-Type:application/json"

A: just change args for form and it will work
@app.route('/testpoint', methods = ['POST'])
def testpoint():
    name = request.form.get('name', '')`enter code here`
    return jsonify(name = name)


text:
Q: Why is this function not returning any values? Each sub-list always has three elements in the following order:

*

*Type of membership: a string that is one of 'Student', 'Faculty' or 'Visitor'.

*Type of car: a string that is one of 'Coupe', 'Sedan', 'SUV' or 'Hybrid'.

*Duration: the number of hours the car was borrowed for
The cars provide free service for up to certain number of hours based on the type of membership:

*'Student': first three hours are free

*'Faculty': first two hours are free

*'Visitor': first hour is free

After free service is over, the members are charged based on the type of car they have rented:

*

*Sedan: $10 per hour

*Coupe: $12 per hour

*SUV: $13 per hour

*Hybrid: $15 per hour

At index 0 store the total income generated by Sedans. At index 1 store the total income generated by Coupes. At index 2 store the total income generated by SUVs. At index 3 store the total income generated by Hybrids.
def car_rental(rentals):
    car_type = [0, 0, 0, 0]
    for rental in rentals:
        if rental == 'Student' and car_type == "Sedan" and hours > 3:
            income = 10 * (hours - 3)
            car_type[0] += income
    for rental in rentals:
        if rental == 'Faculty' and car_type == "Sedan" and hours > 2:
           income = 10 * (hours - 2)
           car_type[0] += income
    for rental in rentals:
        if rental == 'Visitor' and car_type == "Sedan" and hours > 1:
            income = 10 * (hours - 1)
            car_type[0] += income
    for rental in rentals:
        if rental == 'Student' and car_type == "Coupe" and hours > 3:
           income = 12 * (hours - 3)
           car_type[1] += income
    for rental in rentals:
        if rental == 'Faculty' and car_type == "Coupe" and hours > 2:
           income = 12 * (hours - 2)
           car_type[1] += income
    for rental in rentals:
        if rental == 'Visitor' and car_type == "Coupe" and hours > 1:
           income = 12 * (hours - 1)
           car_type[1] += income
    for rental in rentals:
        if rental == 'Student' and car_type == "SUV" and hours > 3:
           income = 13 * (hours - 3)
           car_type[2] += income
    for rental in rentals:
        if rental == 'Faculty' and car_type == "SUV" and hours > 2:
           income = 13 * (hours - 2)
           car_type[2] += income
    for rental in rentals:
        if rental == 'Visitor' and car_type == "SUV" and hours > 1:
           income = 13 * (hours - 1)
           car_type[2] += income
    for rental in rentals:
        if rental == 'Student' and car_type == "Hybrid" and hours > 3:
           income = 15 * (hours - 3)
           car_type[3] += income
    for rental in rentals:
        if rental == 'Faculty' and car_type == "Hybrid" and hours > 2:
           income = 15 * (hours - 2)
           car_type[3] += income
    for rental in rentals:
        if rental == 'Visitor' and car_type == "Hybrid" and hours > 1:
           income = 15 * (hours - 1)
           car_type[3] += income

    return car_type

Tested with:
print("Testing car_rental() with rentals = [['Student','Coupe',4],['Faculty','Coupe',4],['Visitor','Coupe',4]]: " +
      str(car_rental([['Student', 'Coupe', 4], ['Faculty', 'Coupe', 4], ['Visitor', 'Coupe', 4]])))
print("Testing car_rental() with rentals = [['Student','Coupe',4],['Faculty','SUV',4],['Visitor','Hybrid',4],['Visitor','Sedan',4]]: " +
      str(car_rental([['Student', 'Coupe', 4], ['Faculty', 'SUV', 4], ['Visitor', 'Hybrid', 4], ['Visitor', 'Sedan', 4]])))
print("Testing car_rental() with rentals = [['Student','Coupe',3],['Faculty','SUV',2],['Visitor','Hybrid',1],['Visitor','Sedan',4]]: " +
      str(car_rental([['Student', 'Coupe', 3], ['Faculty', 'SUV', 2], ['Visitor', 'Hybrid', 1], ['Visitor', 'Sedan', 4]])))
print()

A: The problem is the way you're referencing the elements of the rentals argument passed to the function. Specifically in each of the for rental in rentals: loops, the rental variable itself is also a list and you need to reference its contents with the [] indexing notation.
Here's a fixed version of your code:
def car_rental(rentals):
    car_type = [0, 0, 0, 0]
    for rental in rentals:
        if rental[0] == 'Student' and rental[1] == "Sedan" and rental[2] > 3:
            income = 10 * (rental[2] - 3)
            car_type[0] += income
    for rental in rentals:
        if rental[0] == 'Faculty' and rental[1] == "Sedan" and rental[2] > 2:
           income = 10 * (rental[2] - 2)
           car_type[0] += income
    for rental in rentals:
        if rental[0] == 'Visitor' and rental[1] == "Sedan" and rental[2] > 1:
            income = 10 * (rental[2] - 1)
            car_type[0] += income
    for rental in rentals:
        if rental[0] == 'Student' and rental[1] == "Coupe" and rental[2] > 3:
           income = 12 * (rental[2] - 3)
           car_type[1] += income
    for rental in rentals:
        if rental[0] == 'Faculty' and rental[1] == "Coupe" and rental[2] > 2:
           income = 12 * (rental[2] - 2)
           car_type[1] += income
    for rental in rentals:
        if rental[0] == 'Visitor' and rental[1] == "Coupe" and rental[2] > 1:
           income = 12 * (rental[2] - 1)
           car_type[1] += income
    for rental in rentals:
        if rental[0] == 'Student' and rental[1] == "SUV" and rental[2] > 3:
           income = 13 * (rental[2] - 3)
           car_type[2] += income
    for rental in rentals:
        if rental[0] == 'Faculty' and rental[1] == "SUV" and rental[2] > 2:
           income = 13 * (rental[2] - 2)
           car_type[2] += income
    for rental in rentals:
        if rental[0] == 'Visitor' and rental[1] == "SUV" and rental[2] > 1:
           income = 13 * (rental[2] - 1)
           car_type[2] += income
    for rental in rentals:
        if rental[0] == 'Student' and rental[1] == "Hybrid" and rental[2] > 3:
           income = 15 * (rental[2] - 3)
           car_type[3] += income
    for rental in rentals:
        if rental[0] == 'Faculty' and rental[1] == "Hybrid" and rental[2] > 2:
           income = 15 * (rental[2] - 2)
           car_type[3] += income
    for rental in rentals:
        if rental[0] == 'Visitor' and rental[1] == "Hybrid" and rental[2] > 1:
           income = 15 * (rental[2] - 1)
           car_type[3] += income

    return car_type

print("Testing car_rental() with rentals = "
      "[['Student','Coupe',4], ['Faculty','Coupe',4], ['Visitor','Coupe',4]]: " +
      str(car_rental([['Student', 'Coupe', 4], ['Faculty', 'Coupe', 4], ['Visitor', 'Coupe', 4]])))

print("Testing car_rental() with rentals = "
      "[['Student','Coupe',4], ['Faculty','SUV',4], ['Visitor','Hybrid',4], ['Visitor','Sedan',4]]: " +
      str(car_rental([['Student', 'Coupe', 4], ['Faculty', 'SUV', 4], ['Visitor', 'Hybrid', 4], ['Visitor', 'Sedan', 4]])))

print("Testing car_rental() with rentals = "
      "[['Student','Coupe',3],['Faculty','SUV',2],['Visitor','Hybrid',1],['Visitor','Sedan',4]]: " +
      str(car_rental([['Student', 'Coupe', 3], ['Faculty', 'SUV', 2], ['Visitor', 'Hybrid', 1], ['Visitor', 'Sedan', 4]])))

Output:
Testing car_rental() with rentals = [['Student','Coupe',4], ['Faculty','Coupe',4], ['Visitor','Coupe',4]]: [0, 72, 0, 0]
Testing car_rental() with rentals = [['Student','Coupe',4], ['Faculty','SUV',4], ['Visitor','Hybrid',4], ['Visitor','Sedan',4]]: [30, 12, 26, 45]
Testing car_rental() with rentals = [['Student','Coupe',3],['Faculty','SUV',2],['Visitor','Hybrid',1],['Visitor','Sedan',4]]: [30, 0, 0, 0]
A better way to fix it would be to give readable names to each of the elements of the rental sublists at the beginning of each nested for loop. Something along these lines:
def car_rental(rentals):
    car_type = [0, 0, 0, 0]
    for customer, style, hours in rentals:
        if customer == 'Student' and style == "Sedan" and hours > 3:
            income = 10 * (hours - 3)
            car_type[0] += income
    for customer, style, hours in rentals:
        if customer == 'Faculty' and style == "Sedan" and hours > 2:
           income = 10 * (hours - 2)
           car_type[0] += income
    etc ...

Beyond that you could also put all the if statements inside one big for rental in rentals: loop. This would be faster and shorten the amount of code needed slightly:
def car_rental(rentals):
    car_type = [0, 0, 0, 0]
    for customer, style, hours in rentals:
        if customer == 'Student' and style == "Sedan" and hours > 3:
            income = 10 * (hours - 3)
            car_type[0] += income

        if customer == 'Faculty' and style == "Sedan" and hours > 2:
           income = 10 * (hours - 2)
           car_type[0] += income

        etc ...


text:
Q: Accessing website with urllib returns error, retrieving information from Results Page I created a code in python so I could access a reverse phone lookup site and determine if a phone is a cell phone or land line. The website I am using is whitepages, whose results page will only include the phrase "VoIP" if the phone is a land line (which I have determined after looking at many results). However, I am getting an error at the website accessing stage. So far my code looks like:
import urllib

def Phone_Checker(number):
     url = 'http://www.whitepages.com/reverse_phone'
     enter = {'e.g. 206-867-5309': number}
     door= urllib.parse.urlencode(enter)
     open=door.encode('UTF-8')
     fight= urllib.request.urlopen(url, open)
     d = fight.read()
     v="VoIP"
     vv=v.encode("UTF-8")
     if vv in d:  #if VoIP  it is landline
          return False
     else:
          return True

I changed my strings into bytes because it was required for my variable "open" to be in bytes for urlopen. In a version of the code I made to access a different site it required a few other string conversion into bytes but I cannot quite remember which information required this conversion (just a heads up if the code after introducing the variable fight looks incorrect because I have not been able to debug the code which follows because of my difficulty with my urlopen. Whenever I run my code I receive this error
File "C:\Users\aa364\Anaconda3\lib\urllib\request.py", line 589, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)

HTTPError: Requested Range Not Satisfiable

I was wondering how I could circumvent this error and if there is any possible alternative to creating a program to verify if a phone is mobile or a landline for DOMESTIC (USA) phone numbers. Thank you in advance!

A: Based on the stuff I'm reading and experimenting with to try to find an answer on this, I think this is likely whitepages' doing. I have 3 reasons:

*

*the error seems to be a result of whitepages only accepting requests from certain browsers ('User-Agents')

*Upon changing the 'User-Agent' I get kicked to robots.txt (which is basically a response meaning "don't automate this")

*Both of these things are likely the result of whitepages having a paid/premium-access API: obviously, they'll do whatever they can to stop people from accessing their information for free if they're trying to charge for it

So, I think the answer in this case is, unfortunately, find another phonenumber lookup.


text:
Q: Spring mvc controller handling all request and should not do that I have two controllers:
UserController and AdminController.
The AdminController is handling all requests that have not created. Also handle the request to access to my resources.
Also I'm using spring-security and maven to compile all.
Examples:
Request: .../appName/login --> return login view.
Request: .../appName/home --> return home view.
Request: .../appName/fahsjhgasghdjfg --> return admin view.
Request: .../appName/dasjdha/fhfashjfs --> return admin view.
Request: .../appName/resources/css/one.css --> return admin view.

If I remove the AdminController and create a new controller with name ExamplefasjkasController it happens the same.
Code:
Controllers:
@Controller
public class AdminController {

    @RequestMapping(name = "/panel")
    public ModelAndView adminPanel() {
        return new ModelAndView("admin");
    }

}

@Controller
public class UserController extends GenericController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = { "/", "/home" })
    public ModelAndView home(HttpServletRequest request, Principal principal) {

        ModelAndView model = new ModelAndView(Name.VIEW_HOME);
        model.setViewName(Name.VIEW_HOME);

        return model;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(HttpServletRequest request,
            @RequestParam(value = Name.PARAM_ERROR, required = false) String error,
            @RequestParam(value = Name.PARAM_LOGOUT, required = false) String logout) {

        ModelAndView model = new ModelAndView();
        model.setViewName(Name.VIEW_LOGIN);

        if (error != null) {
            addError(model, getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
        }

        if (logout != null) {
            addInfo(model, Message.INFO_USER_LOGOUT);
        }

        return model;
    }
}

In the AdminController I try to get Request with
@Controller
@RequestMapping(name = "/admin"}
public class AdminController {

    @RequestMapping(name = "/panel")
    ...

}

But I get an exception:
javax.servlet.ServletException: No adapter for handler [com.base.controller.AdminController@3f114da7]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler

XMLs:
web.xml
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/spring-mvc-dispatcher.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/spring-database.xml,
        /WEB-INF/spring/spring-security.xml
    </param-value>
</context-param>
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

spring-mvc-dispatcher.xml
    <mvc:resources mapping="/web_resources/bower_components/**" location="classpath:/web_resources/bower_components/" />
    <mvc:resources mapping="/web_resources/layouts/**" location="classpath:/web_resources/layouts/" />
    <mvc:resources mapping="/web_resources/elements/**" location="classpath:/web_resources/elements/" />

    <context:component-scan base-package="com.base.*" />

    <mvc:annotation-driven />

    <context:annotation-config />

    <import resource="spring-messages.xml" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

I could share the entire application if someone request.
Thanks in advance and best regards.

A: You have to fix your request mapping as below:
@Controller
@RequestMapping(value = "/admin"}
public class AdminController {

    @RequestMapping(value = "/panel")
    ...

}


text:
Q: Spring boot docker application end-to-end Testing with chrome driver I already have Unit and Integration tests with maven but I'm trying to move end-to-end testing with angular(frontend) to maven so I can have every layer of the testing pyramid connected within the same maven build but i'm having trouble doing so.
My spring boot application has some dependencies like postgres and keycloak. I was trying to "mock" does dependencies (in unit and integration tests i use postgres with testcontainers) so i can have an isolated environment without depending on external services are running or not.
I managed to open chrome and do some clicks with selenium and chrome driver but all of this is running on my local database and frontend application which i need to have it up and running. I want something that i can integrate with jenkins later on so i need something to work isolated.
I searched on the internet but i could't find any scenario like this. Anyone could help?

A: You can have Jenkins flow as
+--------------+          +-----------------+       +-----------+
|              |          | Setup Phase     |       |           |
| Trigger Test | -------->| DB setup and    |------>| Run Tests |
|              |          | Any other setup |       |           |
+--------------+          +-----------------+       +-----------+

Your entire end to end tests would be divided into two phases. In the first phase, you would have to configure all the required services like database, caching layer, test credentials for any third-party services like Keycloak. For example,
you need to use a running Postgresql or any other databases as required by the service(s). For other third-party services, you can use their sandbox if available otherwise use a different configuration for each test run (also you can have multiple configurations and pick of them based on the other running tests). Some of the third party services would require you to have public domain/URL in such cases, you need to configure your services behind public URL.
Once you have configured entire systems, then you can start hitting API to gather the response using test scripts. There could be some time, where API might not provide you the exact data you're looking in, in such cases you can add new APIs to the code or use some other technique to gather the data, like DB query, running some manual/automated scripts using FTP, etc.


text:
Q: How add elements to the JList parameterized by my own Type I have created a JList but it(and its' model) lacks addElement method. How to add instance of my class Pacjent to that JList?
Pacjent p = new Pacjent("Blosom", "Polo");
ListModel<Pacjent> model = new DefaultListModel<Pacjent>();
pList = new JList<Pacjent>(model);

public class Pacjent extends Osoba {

    private String imie;
    private String nazwisko;
    public ArrayList<Ubezpieczenie> ubezpieczenia = new ArrayList<Ubezpieczenie>();

...}

A: You add element to the model. Instead of writing
ListModel<Pacjent> model = new DefaultListModel<Pacjent>();

write
DefaultListModel<Pacjent> model = new DefaultListModel<Pacjent>();

and just call its model.addElement(element) method.


text:
Q: How to get current NSDate in current timezone? I need to get current time in NSDate, not swift. I tried to do this like on screenshot, but the final nsdate is in wrong timezone.

A: An NSDate does not have a time zone. It records an instant in time on planet Earth. It is DISPLAYED in a particular time zone.
An NSDateFormatter will convert between NSDate objects and date strings (in either direction).
If you install a time zone into your date formatter then it will convert dates to/from strings using that time zone. If you don't specify a time zone it will use the user's current time zone.
If you try to display an NSDate using the Swift print statement or NSLog then it will be displayed in UTC. Always.
The code you've posted that prints strDate, your date string you created using a date formatter, is correct. The line `print(localDate!) is meaningless.
To repeat: NSDate objects do not have a time zone. When you log them to the console, they will always be displayed in UTC. If you want to see them in your local time zone then you need to use date formatter like you are doing.


text:
Q: Kivy window management I'm writing  gstreamer application and Iam using kivy as GUI framework.
Working with kivy I found out that it has poor window management so I wrote a module for window management using Xlib.
Now the thing is when I get ID of window and when I send it to gstreamer set_window_handle() function I don't get video rendered in kivy window nor there is a default gstreamer window.
I created a test GTK+ HelloWorld application which prints XID in the terminal and when I run it with my test script in which I call function from Xlib module in which I print ID of window I got 2 different values.
For example I get:
Gtk+ xid - 67108880
Xlib - 67108871 or I don't know some other random number as ID
Here is my code :
Xlib module
class WManager:
    def __init__(self):
        self.display=Display()
        self.WinIDs=self.display.screen().root.get_full_property(self.display.intern_atom('_NET_CLIENT_LIST'),X.AnyPropertyType).value

    def getWinID(self,name):
        for winID in self.WinIDs:
            wind=self.display.create_resource_object("window",winID)
            NAME = wind.get_wm_name()
            print(wind.get_wm_name(),":",winID)
            if name in NAME:
                return winID

Functions where I call this module to get XID
  def on_sync_message(self, bus, msg):
    if msg.get_structure().get_name()=='prepare-window-handle':
        print('rendering area set')
        msg.src.set_window_handle(self.wid)

def on_play(self):
    X11Man=WManager()
    self.wid=X11Man.getWinID('main')
    self.pipeline.set_state(Gst.State.PLAYING)

The thing I want to do is to get same ID with Xlib as GTK+ gets with get_xid() function
EDIT:
Okey I realized that problem is not in window ID I can render video in any other window except that of kivy. What's the catch? How can I render it to kivy window? Which widget should I use?


text:
Q: from origin 'http://localhost:4200' has been blocked by CORS policy I am calling a web service in Angular 8 and the two URLs are not the same.

Error -> Access to XMLHttpRequest at
  'http://localhost:51891/api/Admin/Login' from origin
  'http://localhost:4200'enter code here has been blocked by CORS
  policy: Response to preflight request doesn't pass access control
  check: The 'Access-Control-Allow-Origin' header contains multiple
  values 'http://localhost:4200, *', but only one is allowed.

I put this code in my startup file:
services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
                .WithOrigins(http://localhost:4200, http://localhost:51891/api)
                .AllowAnyMethod()
                .AllowAnyHeader()
        );

});
app.UseCors("CorsPolicy");


text:
Q: Estimating ATT with a linear regression model Suppose there is a binary treatment such as taking a drug or not.
Let $D_i=1$ if an individual $i$ took the drug and $D_i=0$ if she did not.
Let $Y^1_i$ is the potential outcome (e.g. blood pressure) when she took the drug.
Let $Y^0_i$ is the potential untreated outcome.
In this setup, we can estimate the average treatment effect (ATE) using a linear regression like below:

$$Y_i=D_i Y_i^1+(1-D_i)Y^0_i \\
=Y_i^0+(Y_i^1-Y_i^0)D_i$$
where $Y_i$ is the observed outcome.
Then, rewriting $Y_i^0$ and $Y_i^1-Y_i^0$ as
$$Y_i^0=\mathbb{E}[Y_i^0]+\{Y_i^0-\mathbb{E}[Y_i^0]\} \\
Y_i^1-Y_i^0=\mathbb{E}[Y_i^1-Y_i^0]+\{(Y_i^1-Y_i^0)-\mathbb{E}[Y_i^1-Y_i^0]\},$$
the observed outcome is
$$Y_i=\mathbb{E}[Y_i^0]+\mathbb{E}[Y_i^1-Y_i^0]D_i+U_i$$
where $U_i=\{Y_i^0-\mathbb{E}[Y_i^0]\}+\{(Y_i^1-Y_i^0)-\mathbb{E}[Y_i^1-Y_i^0]\}D_i$.

Therefore, we can estimate the ATE=$\mathbb{E}[Y_i^1-Y_i^0]$ by regressing $Y_i$ on $[1,\;D_i]$ with pretty strong assumptions.
Here, I am wondering whether we can also estimate the ATT=$\mathbb{E}[Y_i^1-Y_i^0|D_i=1]$ using a linear regression like above case.

A: If you have a randomized trial, then ATE = ATT because $E[Y^d|D=1, X] = E[Y^d|D=0, X]$ for all $d \in \{0,1\}$ and pretreatment covariates $X$, so $E[Y^1 - Y^0|D=1] = E[Y^1 - Y^0]$. Thus, a simple difference in means is sufficient to estimate either.
In an observational study with no unmeasured confounding, you can estimate the ATE and ATT using g-computation. This involves first fitting a model for $Y$ given $X$ and the observed $D$; this should ideally include interactions between the treatment and covariates or can be fit separately for each treatment group. To estimate the ATE, generate predicted values $\hat{Y}_1$ and $\hat{Y}_0$ for each individual as the predicted values from this model after setting all units' treatment values to 1 and then to 0, respectively. The estimate of the ATE is $n^{-1}\sum{\hat{Y}_1} - n^{-1}\sum{\hat{Y}_0}$. To estimate the ATT, generate predicted values $\hat{Y}_0$ for each treated individual after setting their treatment values to 0. The estimate of the ATT is $n_1^{-1}\sum_{i:D_i=1}{Y} - n_1^{-1}\sum_{i:D_i=1}{\hat{Y}_0}$ where $n_1$ is the number of treated units.
There is an equivalent way to get these estimates as coefficients in a regression model, which will only be unbiased when the potential outcomes are linear in the covariates. For both estimands, you will fit a regression of $Y$ on $X$, $D$, and the interaction between $D$ and each $X$ and use the coefficient on $D$ as the treatment effect estimate. For the ATE, you must first center the $X$ at their mean in the full sample. For the ATT, you must first center the $X$ at their mean in the treated group.
Note that the coefficient on $D$ on a regression of $Y$ on $X$ and $D$ but without their interaction corresponds to the ATE only when there is no effect modification by the covariates or the distributions of covariates are the same in both groups (i.e., as the result of a randomized trial), in which cases the ATE and ATT are equal.


text:
Q: Are webhooks retried if my server is down? I have setup a webhook for install event. I would like to know what will happen if my site is down. Will the webhooks get retried incase of non 200 response codes.

A: That's a good question! Branch does not automatically retry webhooks in the case of a non 2xx response. However, Branch does allow you to go through and see every single time they have tried to fire a webhook. In the case of a non-2xx response, you would see a red 'X' next to the record. From there you can manually re-send said webhook to your server.
If this post does not resolve your issue(s) please ask more!


text:
Q: In the model adding new Bilstm layer return error "bidirectional_1" is incompatible with the layer and the model is not working expected ndim=3, i am trying to add new Bilstm layer to
model.add(Conv1D(500,9,strides=1,input_shape=(7680,1),activation='tanh'))
model.add(Conv1D(300, 3, activation='relu'))
model.add(Conv1D(300, 3, activation='relu'))
model.add(MaxPooling1D(pool_size=2,strides=2))
model.add(Conv1D(200, 3, activation='relu'))
model.add(Conv1D(200, 3, activation='relu'))
model.add(Bidirectional(LSTM(300),input_shape=(7680,1)))
model.add(Bidirectional(LSTM(300)))
model.add(Dense(9, activation='softmax'))

Input 0 of layer "bidirectional_1" is incompatible with the layer:
expected ndim=3, found ndim=2. Full shape received: (None, 600)


text:
Q: OpenSSL & C - Hash Passwords w/ SHA256 or SHA512 I've tried my best reading over the docs but they seem very sparing in information (maybe I'm looking in the wrong place?)
I'm trying to create a password hasher in C using OpenSSL lib in which the program can be called and passed arguments such as the ending length of the hashed password, salt length, and the HMAC used (SHA256 or 512). There just isn't a lot of info on how to utilize the API to do this.
The biggest problem I see is that there is a function called PKCS5_PBKDF2_HMAC_SHA1, but I can't find one similar for 256 or 512.. Is only SHA1 available via OpenSSL API?
Any guidance is much appreciated.

A: You can use PKCS5_PBKDF2_HMAC, which allows you to target a specific digest algorithm.
int PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
    const unsigned char *salt, int saltlen,
    int iter, const EVP_MD *digest, // <<==== HERE
    int keylen, unsigned char *out);

A simple example appears below, which generates a random salt, then creates a PBK from "password", the generated salt, and EVP_sha256()
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/bio.h>

int main(int argc, char *argv[])
{
    int iter = 1007;

    unsigned char salt[32] = {0};
    RAND_bytes(salt, sizeof(salt));

    unsigned char key[32] = {0};
    PKCS5_PBKDF2_HMAC("password", 8,
        salt, sizeof(salt),
        iter, EVP_sha256(),
        sizeof(key), key);

    BIO *bio = BIO_new_fp(stdout, BIO_NOCLOSE);
    BIO_dump(bio, (const char*)salt, sizeof(salt));
    BIO_dump(bio, (const char*)key, sizeof(key));
    BIO_free(bio);
}

Output (varies)
0000 - a7 ca ac f4 43 b0 2d 48-2b f6 d5 67 7e d2 5c b4   ....C.-H+..g~.\.
0010 - c5 82 1d 4d b1 00 cd 1e-85 91 77 4c 32 3e f3 c8   ...M......wL2>..
0000 - 48 8f be 5a e9 1c 9e 11-d8 95 cb ed 6d 6f 36 a2   H..Z........mo6.
0010 - 38 e6 db 95 e1 d7 a6 c0-8a 2f 3a f6 e1 74 e9 b9   8......../:..t..


text:
Q: G-Sheet Function support to Match Date, name and Other Point Its Pleasurer if you can support me to write function to preform google sheet.
https://docs.google.com/spreadsheets/d/1uwbFcdkN3VHkzpHyx73LSTbPwltZrH5R_n7jsLe-iuU/edit?usp=sharing
Solution starting from cell D7 (D7:AH14)
Need to Factors
For Sheet Working Indika -
Date row 6,
Facility Column C
Plan or Actual - Cell F3 (F3:J3)
Need to Capture Information from Sheet Facility Schedule
Date - Row 2
Facility Column B
Plan or Actual - Column C

Best regard
Indika

A: let me know if this is useful:
In D7 use this formula and copy then to the entire range:
=index('Facility Schedule'!$1:$962,match($C7,'Facility Schedule'!$B$1:$B$18,0)+if($F$3="Actual",1,0),match(D$6,'Facility Schedule'!$2:$2,0))

Here I upload a picture of your own spreadsheet with Plan and Actual displayed:

Look how Facility A changes (which is the only one different by now)


text:
Q: What is the Gensim word2vec output I want to use gensim word2vec as input for neural network. I have 2 questions:
1) gensim.models.Word2Vec get as parameter the size. How this parameter is used? and size of what?
2) Once trained what is the output of gensim word2vec? As i could see this is not a probability values (not between 0 and 1). It seems to me for each word vector we get a distance (cosinus) between this word and some other words (but which words exactly?)
Thanks for your response.

A: Ans to 1 -> The size parameter is the dimension of the word vectors i.e. each vector will be having 100 dimensions if size=100
Ans to 2 -> You can save the word vectors using this function save_word2vec_format(fname="vectors.txt", fvocab=None, binary=False) ref. This will save a file "vectors.txt" which will have first line as <size of the vocabulary> <dimensions> and rest of the lines will be of the form <word> <vector of size dimension>.
Sample for "vectors.txt":
297820 100
the -0.18542234751 0.138813291635 0.0392148854213 0.0238721499736 -0.0443151295365 0.03226302388 -0.168626211895 -0.17397777844 -0.0547546409461 0.166621666046 0.0534506882806 0.0774947957067 -0.180520283779 -0.0938140452702 -0.0354599008902 -0.0533488133527 -0.0667684564816 -0.0210904306995 -0.103069115604 -0.138712344952 -0.035142440978 -0.125067138202 0.0514192233164 -0.142052171747 0.0795726729387 0.0310433094806 -0.00666224898992 0.047268806263 0.0339849190176 -0.181107631029 0.0477396587205 0.0483130822899 -0.090229393762 0.0224528628225 0.190814060668 -0.179506639849 0.00034066604609 0.0639057478 0.156444383949 -0.0366888977431 -0.170674385275 -0.053907152935 0.106572313582 0.0724497821903 -0.00848717936216 0.124053494271 -0.0420715605081 0.0460277422205 -0.0514693485657 0.132215091575 -0.0429308836475 -0.111784875385 -0.0543172053216 0.0849476776796 -0.015301892652 0.00992711997251 -0.00566113637219 0.00136359242972 -0.0382116842516 0.0681229985191 0.0685156463052 0.0759072640845 -0.0238136705161 0.168710450161 0.00879930186352 -0.179756801973 -0.210286559709 -0.161832152064 -0.0212640125813 -0.0115905356526 -0.0949562511822 0.126493155131 0.0215821686774 -0.164276918273 -0.0573806470616 -0.0147266125919 0.0566350339785 -0.0276969849679 0.0178970346094 0.0599163813161 0.0919867942845 0.172071394538 0.0714226787026 0.109037733251 0.00403647493576 0.044853743905 -0.0915639785243 -0.0242494817113 0.0705554654776 0.255584701079 0.001309754199 0.0872413719572 -0.0376289782286 0.158184379871 0.109245196088 -0.0727554069742 0.168820215174 0.0454895919746 0.0741726055733 -0.134467710995
...
...

A:
Dimension Size in word2vec**

*

*Word2vec is used to create a vector space that represents words based on the trained corpus.

*The vector is a mathematical representation of the word compared to other words in the given corpus. The dimensions size is the vector length.

*Performing mathematical operations on the vectors represent the relationship between words.

*as the vector of "man" and "king" will be close and same for the vector of "Faris" and "France".

*If the size is too small like two or three dimensions, the information representation will be very limited.

*The dimensions can be simplified as a linkage between different words. Words can be linked to each other in different dimensions based on how the words are positioned to each other in the corpus.

How to use the vectors

*

*The vector by itself is useless and the numbers represent the position of the word with relations to all other words in the corpus

*The vector can be meaningful when measured against another vector

*cosine similarity is one of the common methods to measure the similarity between different words.

Good luck


text:
Q: Differential of a map in polar coordinates. I read in a book:
Consider the map $f:\mathbb{R}^2\to\mathbb{R}^2$ with $f(r,\theta)=(r',\theta')=(r^m,k\theta)$, where $k$ and $m$ natural numbers. The differential of this map sends the orthogonal frame $\frac{\partial}{\partial r}$ , $\frac{1}{r}\frac{\partial}{\partial \theta}$ to the frame $mr^{m-1}\frac{\partial}{\partial r'}$ and $kr^{m-1}\frac{1}{r'}\frac{\partial}{\partial \theta'}$.
My guess about what the differential(or the total derivative) looks like is that is the map induced by the matrix $\pmatrix{mr^{m-1}&0\\0&k/r}$ but probably that is not expressed in the correct base.
Can someone explain the correct way to do this?
By what the book says the matrix of the differential should look like $\pmatrix{mr^{m-1}& 0\\0 & kr^{m-1}}$.

A: The differential of $f$ in the polar coordinate basis $\{\partial_r, \partial_\theta\}$ is obtained by calculating the partial derivatives:
$$
J_{\{\partial_r, \partial_\theta\}\mapsto \{\partial_r, \partial_\theta\}}(r, \theta) = \begin{pmatrix}
mr^{m - 1}& 0 \\
0 & k
\end{pmatrix}.
$$
If we want to express it relative to the basis $B = \{\partial_r, r^{-1}\partial_\theta\}$ in the domain and $B' = \{\partial_{r}, (r')^{-1}\partial_{\theta}\}$ in the codomain, we need a different matrix. Note that we maintain orthogonality and don't change the first basis vector so the only entry that will change is the bottom right entry. Also, we have:
$$
df_{(r, \theta)}(r^{-1}\partial_{\theta}) = r^{-1}df_{(r, \theta)}(\partial_\theta) = r^{-1}k\partial_\theta = r^{-1}r' \frac{1}{r'}\partial_\theta = r^{m - 1}\cdot \frac{1}{r'}\partial_\theta.
$$
So, this takes the second basis element of $B_1$ to $r^{m - 1}$ times the second basis element of $B_2$. This is what you wrote in your first paragraph. Thus the matrix with respect to these bases is
$$
J_{B_1 \mapsto B_2}(r, \theta) = \begin{pmatrix}
mr^{m - 1} & 0 \\
0 & kr^{m - 1}
\end{pmatrix}.
$$
I believe the difference between your proposed matrix and the one the book gives is that you are using the same basis for the domain and the codomain, whereas the one in the book uses $\{\partial_r, r^{-1}\partial_\theta\}$ in the domain and $\{\partial_r, (r')^{-1}\partial_{\theta}\}$ in the codomain.


text:
Q: Finding number of unique values (quickly) across a large data.table I have a 1.5Mx7 data.table that I need to process through. The code I have written is running very slowly (.18s per row, estimated 75 hours to complete), and I'm hoping I can optimize it.
I'll put the pseudo-example code at the end, because it's long.
str(review)

Classes 'data.table' and 'data.frame':  1500000 obs. of  7 variables:
 $ user_id     : Factor w/ 375000 levels "aA1aJ9lJ1lB5yH5uR6jR7",..: 275929 313114 99332 277686 57473 31780 236964 44371 210127 217770 ...
 $ stars       : int  2 1 3 3 1 1 2 1 2 2 ...
 $ business_id : Factor w/ 60000 levels "aA1kR2bK6nH8yQ9gU2uI9",..: 40806 29885 43018 58297 58444 31626 26018 2493 37883 34204 ...
 $ votes.funny : int  3 0 0 7 2 9 6 8 2 7 ...
 $ votes.useful: int  4 1 0 5 9 2 4 7 4 9 ...
 $ votes.cool  : int  5 3 6 8 3 2 0 8 10 9 ...
 $ IDate       : IDate, format: "2012-01-01" "2012-01-01" "2012-01-01" ...
 - attr(*, ".internal.selfref")=<externalptr>
 - attr(*, "sorted")= chr "IDate"

I need to subset the dataset by date, and then compute several columns by business_id.
setkey(review, IDate)

system.time(
  review[
    #(IDate >= window.start) & (IDate <= window.end),
    1:10,
    .SD,
    keyby = business_id
  ][
    ,
    list(
      review.num = .N,
      review.users = length(unique(user_id)),
      review.stars = mean(stars),
      review.votes.funny = sum(votes.funny),
      review.votes.useful = sum(votes.useful),
      review.votes.cool = sum(votes.cool)
    ),
    by = business_id
  ]
)

   user  system elapsed
  1.534   0.000   1.534

Timing for smaller versions of the example dataset is
# 1% of original size - 15000 rows
   user  system elapsed
   0.02    0.00    0.02

# 10% of original size - 150000 rows
   user  system elapsed
   0.25    0.00    0.25

So, even though I'm only processing 10 rows, the time increases with the size of the original dataset.
I tried commenting out the review.users variable above, and the computation time on the original dataset fell tremendously:
   user  system elapsed
      0       0       0

So, my challenge is making unique() work more quickly.
I need to count the unique values in user_id for each grouping of business_id.
Not sure what else to specify, but I'm happy to answer questions.

Here is some code to create a pseudo-example dataset. I'm not sure exactly what is the cause of the slowdown, so I've tried to recreate the data as specifically as possible, but because the processing time for the random variables is so long I've reduced the size by ~90%.
z <- c()
x <- c()

for (i in 1:6000) {
  z <<- c(z, paste0(
    letters[floor(runif(7, min = 1, max = 26))],
    LETTERS[floor(runif(7, min = 1, max = 26))],
    floor(runif(7, min = 1, max = 10)),
    collapse = ""
  ))
}

z <- rep(z, 25)

for (i in 1:37500) {
  x <<- c(x, paste0(
    letters[floor(runif(7, min = 1, max = 26))],
    LETTERS[floor(runif(7, min = 1, max = 26))],
    floor(runif(7, min = 1, max = 10)),
    collapse = ""
  ))
}

x <- rep(x, 4)

review2 <- data.table(
  user_id = factor(x),
  stars = as.integer(round(runif(150000) * 5, digits = 0)),
  business_id = factor(z),
  votes.funny = as.integer(round(runif(150000) * 10, digits = 0)),
  votes.useful = as.integer(round(runif(150000) * 10, digits = 0)),
  votes.cool = as.integer(round(runif(150000) * 10, digits = 0)),
  IDate = rep(as.IDate("2012-01-01"), 150000)
)

setkey(review2, IDate)

A: It seems that length(unique()) is inefficient in calculating the length of factor variables as levels become very large.
Using uniqueN() instead (thanks @Frank):
   user  system elapsed
   0.12    0.00    0.12

Using set(review, NULL, "user_id", as.character(review$user_id)) and length(unique)):
   user  system elapsed
   0.11    0.00    0.11

A: How about this - an alternative to unique using an extra data.table within an anonymous function:
review2[,{

  uid <- data.table(user_id)
  rev_user <- uid[, .N, by = user_id][, .N]

  #browser()
  list(
    review.num = .N,
    review.users = rev_user,
    review.stars = mean(stars),
    review.votes.funny = sum(votes.funny),
    review.votes.useful = sum(votes.useful),
    review.votes.cool = sum(votes.cool)
)}, by = business_id]


text:
Q: Javascript strange behaviour Can anyone explain this code to me
var ParentClass = function(){
}

var ChildClass = function(){
}

//ChildClass.prototype = new ParentClass();

var child = new ChildClass();
alert(child.constructor === ChildClass); // alert true

But
var ParentClass = function(){
}

var ChildClass = function(){
}

ChildClass.prototype = new ParentClass();

var child = new ChildClass();
alert(child.constructor === ChildClass); // alert false

A: constructor is a property of the prototype object:
var ChildClass = function(){
}

alert(ChildClass.prototype.constructor == ChildClass); // alert true

The relationship is now like this:
  +-------------------+           +--------------------+
  |                   |           |                    |
  |ChildClass instance|---------->|ChildClass protoype |
  |                   |           |  constructor prop  |
  +-------------------+           +--------------------+

This property points indeed to the ChildClass function.
If you override ChildClass.prototype, then child.constructor will be looked up in the prototype chain and will refer to:
ParentClass.prototype.constructor

as ChildClass.prototype is now an instance of ParentClass which inherits from ParentClass.prototype:
  +-------------------+      +--------------------+      +---------------------+
  |                   |      |                    |      |                     |
  |ChildClass instance| ---> |ParentClass instance| ---> |ParentClass prototype|
  |                   |      |                    |      |   constructor  prop |
  +-------------------+      +--------------------+      +---------------------+

ParentClass.prototype.constructor will of course point to ParentClass.

A: Well because in that case you borrow the constructor form ParentClass! It's a pattern i'v read of in the book "javascript patterns" (very good book on javascript).
In fact:
var ParentClass = function(){
}

var ChildClass = function(){
}

ChildClass.prototype = new ParentClass();

var child = new ChildClass();
alert(child.constructor === ParentClass)

Alerts true!

A: The behavior here isn't strange at all.  Normally you see people do things like this:
var ChildClass = function () {

}

ChildClass.prototype.OftUsedMethod = function () {
  // Something you'll want to be able to do here for every instance of
  // ChildClass, but that you don't want separate instances of the function
  // for.
}

But because you've assigned directly to ChildClass.prototype instead of assigning to a member attribute you've effectively overwritten the base prototype for ChildClass.

A: When you overwrite an object's prototype, it overwrites the constructor as well. You can set it back to the original, however. This is done is various libraries and snippets such John Resig's Simple Inheritance.
var ParentClass = function(){
}

var ChildClass = function(){
}

ChildClass.prototype = new ParentClass();
ChildClass.prototype.constructor = ChildClass;

var child = new ChildClass();
alert(child.constructor === ChildClass); // alert true


text:
Q: MongoDB check types of attributes before insert I'm using mongoose to define the following schema:
var toySchema = new Schema({
    id: {type: String, required: true, unique: true},
    name: {type: String, required: true},
    price: Number
});

I believed that when I inserted into the collection using db.toys.insert(), mongo would check to see that the type of each attribute matched the types in the schema, but it seems that it does not. For example, id should be a string, but I was able to insert a document with an integer id. How can I enforce the schema onto these inserts?

A: Actually it does work, but not as you might expect. If you specify a field in your model that is of type Date and you try to save a boolean value (e.g. true) then you will get an error like
Error [ValidationError]: MySchema validation failed: expireAt: Cast to Date failed for value "true" at path ...

The reason for your particular problem can be found in the documentation

If you pass an element that has a toString() function, Mongoose will call it, unless the element is an array or the toString() function is strictly equal to Object.prototype.toString().

You could add a custom validator


text:
Q: Python: problems with csvwriter I am attempting to write data (mostly dates, booleans and float data types) into a CSV file format. Here is a snippet of my code:
# Write data to file
with open(OUTPUT_DIR + output_filename,'w') as outputfile:
    wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')

    for x, y in datarows.items():
        a,b,c,d,e,f,g = (somedate.strft('%Y-%m-%d'),0,6058.7,False,1913736200,0,False)
        rowstr = "{0},{1},{2},{3},{4},{5},{6}".format(a,b,c,d,e,f,g)
        wrtr.writerow(rowstr)

    outputfile.close()

File contents look like this:

2,0,0,7,-,10,-,03,",",0,",",6,0,5,8,.,7,",",F,a,l,s,e,",",1,9,1,3,7,3,6,2,0,0,",",0,",",F,a,l,s,e

I am currently using the raw file object to write to file - but I would prefer to use the csvwrite - since that is what its supposed to be used for

A: Try wrtr.writerow([a,b,c,d,e,f,g]) instead.
writerow() parameter must be a list of values, not a text line. The idea of csv.writer is that it will format row values according to CSV rules.
The result you have is due to the fact that writerow() interpreted your rowstr string as a list of characters.

A: look at this example maybe it can help you:
import datetime

with open('file.csv','w') as outputfile:
    wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')
    a = (datetime.datetime.now().strftime('%Y-%m-%d'),0,6058.7,False,1913736200,0,False)
    wrtr.writerow(a)  # pass an iterable here

    # outputfile.close() you don't have to call close() because you use with

file.csv
2010-11-01,0,6058.7,False,1913736200,0,False

hope this can help you


text:
Q: Is there a way of getting authenticated user ID and use it on navigation.blade? I'm building a new Laravel app, using Breeze.
What i'm trying to do is get the authenticated user id to redirect it to the profile route, which is:
Route::group([
    'prefix' => 'profile',
    'as' => 'profile.',
    'middleware' => ['auth']
], function () {
    Route::get('/{id}',  [ProfileController::class, 'show'])->name('profile');
}
);

But, on the layout of navigation, as shown below, i can't manage to get it on the :href.
I already tried some approaches, like:
:href="{{ route('profile', [Auth::user()->id]) }}"
:href="{{ route('profile',/([Auth::user()->id])) }}"

But none of them seems to work.
The navigation.blade.php dropdown part:
   <x-slot name="content">
                    <x-dropdown-link :href="route('admin.aprovar')">
                                {{ __('Aprovações') }}
                            </x-dropdown-link>
                            <x-dropdown-link>
                                {{ __('Perfil') }}
                            </x-dropdown-link>
                        <!-- Authentication -->
                        <form method="POST" action="{{ route('logout') }}">
                            @csrf

                            <x-dropdown-link :href="route('logout')"
                                    onclick="event.preventDefault();
                                                this.closest('form').submit();">
                                {{ __('Log Out') }}
                            </x-dropdown-link>
                        </form>
                    </x-slot>

Any help or hint would be appreciated.
Thanks for your time!

A: Credits to @aynber to answering, what i needed to do was:
{{ route('profile', ['id' => Auth::user()->id]) }}


text:
Q: Get mysql column of a clicked item I have searched endlessly for an answer but have found none. I am trying to get the id of a clicked item. The item that I am clicking is from mysql database and has been displayed through a for loop. When the item is clicked I am taken to another page. In this page I want to utilize the id from the clicked item to get other information from that row in mysql database; this much I can do. The problem is getting the id from the clicked item and sending it.
This is the most recent way that I tried:
First I displayed the items from mysql.
<?php
   $query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
   $result = mysql_query($query);
   if($result = mysql_query($query))
    {
       for($i = 0; $i < mysql_num_rows($result); $i++)
          {
              $id = $i;
              $code = "
<h7 class=\"challenge_preview_item\"
                        id=\"challenge_preview_name\"></h7>
                        <video
                        class=\"challenge_preview_item\" id=\"challenge_video\"
                        src=\"".mysql_result($result, $i)."\"></video>
";
               echo $code;
          }
         }
    else
     {
       die('Couldn\'t connect'. mysql_error());
      }
?>

Than I put the id in a hidden form so that I could attempt to POST it to the other page:
<form action="<?php echo $current_file; ?>" method="POST">
                    <input type="hidden" name="id" value="14">
                </form>

On the script.php file that is included in both pages, I put
$(#challenge_video).click(function(){ <?php $id = $_POST['id']; ?> ;});

And on the page that the id is being posted to I put
<?php
   include 'script.php';
   echo getChallengeData('name', 'id', $id)
?>

Please help, Thank you
These are the edits

                <?php
                    $query   =   "SELECT `video` FROM `challenge_name` ORDER BY `id`";
                    $result  =   mysql_query($query);
                    if($result = mysql_query($query))
                    {
                        for($i = 0; $i < mysql_num_rows($result); $i++)
                        {
                            $id = $i;
                            echo "
<video class=\"challenge_preview_item challenge_video\" src=\"".mysql_result($result, $i)."\"></video>
";
                        }
                    }
                    else
                    {
                        die('Couldn\'t connect'. mysql_error());
                    }
                    ?>
                    <form action="<?php echo $current_file; ?>" method="GET">
                        <input type="hidden" name="id" value="14">
                    </form>

This is the code for page 2

                    <?php
                        $id = substr(base64_decode($_GET['id']),6);
                        echo getChallengeData('name', 'id', $id);
                    ?>

This is the code for the getChallengeData method in the core.inc.php
function getChallengeData($field1, $field2, $field3)
{
    $query = "SELECT `$field1` FROM `challenge_name` WHERE `$field2` = '$field3'";
    if($query_run = mysql_query($query))
    {
        if($query_result = mysql_result($query_run, 0, $field1))
        {
            return $query_result;
        }
    }
}

That error that I'm getting has to do with the implementation of the getChallengeData method on page 2. The error says

Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 10 in C:\xampp\htdocs\ChallengeNetworkWebsite\core.inc.php on line 42


text:
Q: swapon fails on boot, Ubuntu 17.04 I have the following in my /etc/fstab, and /dev/sdb1 is correctly formatted as a swap space. swapon -a works without problems.
/dev/sdb1 none swap sw 0 0

However, every time I reboot the system, swapping is off. /var/log/syslog contains the following:
Sep  5 09:17:59 puffin systemd[1]: Activating swap /dev/sdb1...
Sep  5 09:17:59 puffin swapon[757]: /sbin/swapon: invalid option -- 'o'
Sep  5 09:17:59 puffin swapon[757]: Usage:
Sep  5 09:17:59 puffin swapon[757]:  swapon -a [-e] [-v] [-f]             enable all swaps from /etc/fstab
Sep  5 09:17:59 puffin swapon[757]:  swapon [-p priority] [-v] [-f] <special>  enable given swap
Sep  5 09:17:59 puffin swapon[757]:  swapon -s                            display swap usage summary
Sep  5 09:17:59 puffin swapon[757]:  swapon -h                            display help
Sep  5 09:17:59 puffin swapon[757]:  swapon -V                            display version
Sep  5 09:17:59 puffin swapon[757]: The <special> parameter:
Sep  5 09:17:59 puffin swapon[757]:  {-L label | LABEL=label}             LABEL of device to be used
Sep  5 09:17:59 puffin swapon[757]:  {-U uuid  | UUID=uuid}               UUID of device to be used
Sep  5 09:17:59 puffin swapon[757]:  <device>                             name of device to be used
Sep  5 09:17:59 puffin swapon[757]:  <file>                               name of file to be used
Sep  5 09:17:59 puffin systemd[1]: dev-sdb1.swap: Swap process exited, code=exited status=1

It seems that systemd is calling swapon with the -o option, which swapon does not recognize. I noticed that there exist some other versions of swapon that do support an -o option, for example here:
http://man7.org/linux/man-pages/man8/swapon.8.html. However, the version of swapon that comes with Ubuntu 17.04 does not have an -o option.
Question: how can I fix this? In particular, where is systemd configured to use the swapon -o command? I cannot find the corresponding unit file; there are no files under /etc/systemd ending in .swap or containing the word swap.
Additional information: the command systemctl start dev-sdb1.swap also does not work. It fails, and journalctl -xe shows an error similar to the above.
Most answers to similar questions are for people who forgot to format their swap partitions. Note that this is a different problem. Thanks!


text:
Q: net beans 8.1 not running only until reading modules I have this in my terminal for checking
martin@martin:~$ sudo update-alternatives --config java
There is 1 choice for the alternative java (providing /usr/bin/java).

  Selection    Path                                     Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-8-oracle/jre/bin/java   1081      auto mode
* 1            /usr/lib/jvm/java-8-oracle/jre/bin/java   1081      manual mode

Press <enter> to keep the current choice[*], or type selection number:
martin@martin:~$ java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

Still my netbeans 8.1 is not starting up it is only starting up until reading modules and I dont know what is the error.
Also I added
netbeans_jdkhome="/usr/lib/jvm/java-8-oracle"
In netbeans.conf As it was an accepted in a post but it didnt work for me.
I already tried uninstalling and installing a couple of times but it still didnt work.
I am out of idea right now and I hope some one will point me to the right direction
UPDATE
martin@martin:~$ javac -version
javac 1.8.0_131

tried to run
martin@martin:~$ sudo chown -R martin:martin ~/.cache/netbeans
[sudo] password for martin:
martin@martin:~$

from this this still didnt work
paste bin of messages.log


text:
Q: Java ByteArrayOutputStream into a different container Can ByteArrayOutputStream be stored into some other container like say HashMap?
If not how do I merge all my streams and then zip archive by entries into 1 file.
public class CFr {

  private static HashMap<String, Object> fileEntries;

  public static void setFileEntries(String fileNameEntry, Object fileEntry) {
    CFr.fileEntries.put(fileNameEntry, fileEntry);
  }

}

public void addDocx(CDb cd) {
  CFr.setFileEntries((String)entryName, (ByteArrayOutputStream)bos);
}

And I get NullPointer on that setFileEntries line. Doesn't seem right, I was just assuming it is possible.

A: Yes, it can be stored, but you will need to initialize your HashMap for that purpose. In your case this
  private static HashMap<String, Object> fileEntries;

is never initialized. You will need to do something like this:
private static HashMap<String, Object> fileEntries = new HashMap<String, Object>();

instead. This will fix your current issue.


text:
Q: function with several variables $C^1$ on the open unit ball Consider $\Omega$ is the open ball centered at $(0,0)$ with radius $R$ in $R^2$. I would like to show that the function $f : \overline{\Omega}\mapsto R$ is $C^1(\Omega)$ but not $C^1(\overline{\Omega})$. I don't know how to deal with this :
$$f(x,y)=\sqrt{R^2-x^2-y^2}$$


text:
Q: Jquery login scrollDown I'm using JQuery version 1.4.2.
My goal is to let the user click the voice 'login' in the top menu to scroll Down the login form (as twitter).
Everything works fine, the insertAfter jQuery show the form as I want, but when the login button is clicked, it change its horizontally position by some pixels.
How is possible to let the 'login' button fixed after insertAfter (excuse me for the pun) ?

A: Make insertAfter insert after the login button's container and make sure you set a width on the login button's container.  OR you could set the position of the login button to absolute and then it won't move at all

A: You're going to need to either edit your markup or css. I can't tell you more without seeing both.
-Bill

A: There could be a few reasons for this. One that possibly comes to mind is that the position is being set before scroll bars appear on the screen and changes it's position. One of my much loved tools is jQuery position, it allows you to absolutely attach the element on the page - perhaps try giving that a go? Otherwise, perhaps hide the element after all the content has loaded using document.load instead of .ready? And lastly, perhaps show some code? :-)


text:
Q: Is it possible to use an OR statement within WebDriverWait? Is it possible to use an OR statement with WebDriverWait?  Basically I want the code to look for a UPC product code OR a Not Found statement.  Only one or the other will show up on the website, so as soon as it finds either I want to to do something.   If it finds the UPC I want it to click on it.  If it finds the Not Found statement, I want it to append the UPC that wasn't found to a list.  Below is the snippet of code from my larger For Loop.  I'd prefer not to wait for the 10 with an else statement, but sometimes the search function on the website does load slower, so it's nice to have that larger 10 timer.
WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH,'//*[@id="'+upc+'"]' OR '/html/body/app-root/div/crf-report-route-entry/crf-report-page/div/div[2]/crf-data-selector-panel/crf-navigation-list/div[2]/p')))

A: There is any_of expected_condition.
As per documentation:
An expectation that any of multiple expected conditions is true.
Equivalent to a logical 'OR'.
Returns results of the first matching condition, or False if none do.

The example of use of it looks like:
WebDriverWait(driver, 20).until(
    EC.any_of(
        EC.visibility_of_element_located((By.ID, "id1")),
        EC.visibility_of_element_located((By.ID, "id2"))
    )
)

UPD
Alternatively you can try using a python's lambda expression, using the find_elements methods glued together with an or operator as following:
wait.until(lambda x: x.find_elements(By.ID, "id1") or x.find_elements(By.ID, "#id2"))

Read this answer for more details


text:
Q: Cocos2D in UIKit app? Right now I am properly and completely implemented Cocos2D and FontLabel (Cocos2D needed file), into my project. I need to use Cocos2D in only one of my UIViews. Does anyone have any tutorials or tips they can give me so I can use Cocos2d like I usually would but just in my UIView in my UIKit app?

A: The second edition of my book Learn iPhone and iPad Cocos2D Game Development has a chapter on Cocos2D with UIKit integration, both for adding UIKit views to Cocos2D as well as adding Cocos2D to an existing UIKit app.
If you're looking for example code try the UIKit template project provided by Kobold2D, although it doesn't contain the "UIKit app with Cocos2D" example.


text:
Q: Can't install older version 1.8.27 of Geth on Ubuntu 16.04 I have tried
sudo apt-get install ethereum

sudo apt-get install ethereum=VERSION

And
sudo apt-get upgrade ethereum

To install a specific version of Geth but I can't.

A: An older version of Geth can be installed using tar file, here I am using version 1.8.16. To download the required Geth file, we need to check the OS version using the following command.
> dpkg --print-architecture
amd64

Once you have your OS information, download (amd64 tar in our case) file from the Geth website.
Upload downloaded tar file on a server and extract using the following command:
sudo tar -xvf <filename>

In our case,
sudo tar -xvf  geth-linux-amd64-1.8.16-477eb093.tar.gz

Step into extracted folder
cd geth-linux-amd64-1.8.16-477eb093

It should contain the geth file, make it executable with the below command.
sudo chmod +x geth

Copy file to the user bin.
sudo cp geth /usr/local/bin/

Check the Geth version with the following command
> geth version
Version: 1.8.16-stable

Geth is now installed successfully on the system
Ref: How To Install Geth On A Linux Machine

A: You can get the older versions from here:
https://github.com/ethereum/go-ethereum/releases
To install ethereum on Ubuntu type the following commands into your CLI:
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt update

Once this is done type:
sudo apt install ethereum


text:
Q: Correlation between gravity and time dilation If gravity field increases logarithmically, should time dilation increase proportionately? say gravity increases to $g=10$, $g=100$, $g=1000$, or even $g=10,000$; what should the time difference be at a given at those distances.
Singularities have infinite gravity and as you approach, the gravity field increases.
How strong would the gravity field be to create a  time dilation of say a $10:1$, or $100:1$ second difference?
10 or 100 seconds on earth = 1 second in the gravity field?
What would the escape velocity have to be at those spots.
What would a hyperbolic orbit to drop into and out of the gravity field to end up with the time difference look like with all the parameters?
What would be the relativistic speeds be?

A: Can not give you a simple relation but here is what I could get.
$$ T_1 = T {\sqrt{1 - \frac{2GM}{rc^2}}} \tag{1}$$
$$g = {{\frac{GM}{r^2}}} \tag{2}$$
Substituting $g$ in $(1)$, you get
$$ T_1 = T {\sqrt{1 - \frac{2gr}{c^2}}} \tag{3}$$
$$ T_1' = T {\sqrt{1 - \frac{2g'r}{c^2}}} \tag{4}$$
You can see how $\frac{T_1'}{T_1}$ depends on $g$ and $g'$ from $(3)$ and $(4)$.
Note that $r$ appears in the equation which is the distance from the center of mass which is providing the gravitation.