text:
Q: Converting multiple UTC timestamps columns to US/Pacific in pandas dataframe I have a dataset containing 2 timestamp columns with string format YYYY-mm-dd HH:mm:ss. The timezone of these timestamps is not included in the string, but they are in UTC and I want to convert them to US/Pacific.
My dataset is in a csv file, so I'm parsing those 2 timestamp columns using
df = pd.read_csv("my_dataset.csv", parse_dates=['timestamp_col1', 'timestamp_col2'])
After reading some posts here it seems the below (example for one column only) could be a possible solution
pd.to_datetime(df.timestamp_col1, utc=True).astimezone(timezone('US/Pacific'))
However, I'm getting the error below. Any insights into how to fix this or is there a better way to do this?
'Series' object has no attribute 'astimezone'

A: It seems you are looking for dt.tz_convert:
pd.to_datetime(df.timestamp_col, utc=True)
#0   2022-10-10 10:10:00+00:00
#Name: timestamp_col, dtype: datetime64[ns, UTC]

pd.to_datetime(df.timestamp_col, utc=True).dt.tz_convert(tz="US/Pacific")
#0   2022-10-10 03:10:00-07:00
#Name: timestamp_col, dtype: datetime64[ns, US/Pacific]

Data:
df = pd.read_csv(StringIO("""timestamp_col
2022-10-10 10:10:00
"""), parse_dates=['timestamp_col'])

df
        timestamp_col
0 2022-10-10 10:10:00

A: The pandas.Timestamp object has its native timezone feature. Localize it with the tz argument and convert it simply with the tz_convert() method. So no need to mingle packages
pd.Timestamp.now(tz='UTC').tz_convert('US/Pacific')

This post covered it also.
You can also convert all timestamps of a series by using apply
sr = pd.Series([pd.Timestamp.now(tz='UTC'), pd.Timestamp.now(tz='UTC')])
sr.apply(lambda x: x.tz_convert('US/Pacific'))

One needs to use this workaround since pandas.Series.tz_conver() expects a pandas.DatetimeIndex so that it converts the index and not the values.


text:
Q: If $f \colon [-1,1] \to \mathbb R$ satisfies $\vert f'' \vert \le k$ then $\vert f \vert \le \frac{k}{2}$
Let $f \colon [-1,1] \to \mathbb R$ be a twice differentiable function s.t. $f(-1)=f(1)=0$ and there exists $k>0$ s.t. $\vert f''(x) \vert \le k$ for every $x \in [-1,1]$.
  Show that
  $$
\max_{[-1,1]}\vert f \vert \le \frac{k}{2}.
$$

The book suggests: take $x_0\in (-1,1)$ such that $\vert f(x_0)\vert$ is maximum and use Taylor.
Following this hint, I write:
$$
f(x_0+h)=f(x_0) + \frac{f''(\xi)}{2}h^2
$$
The linear term, $f'(x_0)=0$ (since the point is in the interior of $[-1,1]$ and is a maximum or a minimum for $f$).
Now how can I conclude? I can't see how to use the hypotesis $f(-1)=f(1)=0$.

A: Take $x_0$ such that $|f(x_0)$ is maximized, and note that $f'(x_0)=0$. Using Taylor, we have
$$f(x_0+h)=f(x_0)+f'(x_0)h+R(h)\text{ where } |R(h)|\leq \left|\frac{\max_{x\in [-1,1]}|f''(x)|}{2}h^2\right|$$
and since $f'(x_0)=0$ this simplifies to $f(x_0+h)=f(x_0)+R(h)$. If we take $h$ such that $|h|\leq 1$ and $x_0+h=\pm 1$ (which is always possible), we get $0=f(x_0)+R(h)$ so
$$|f(x_0)|=|R(h)|\leq\left|\frac{\max_{x\in [-1,1]}|f''(x)|}{2}h^2\right|\leq \frac{k}{2}|h|^2\leq \frac{k}{2}$$
which completes the proof.

A: Try choosing $h$ so that $x_0+h$ is either $-1$ or $1$ (whichever results in the smaller $h$).

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Cómo puedo transformar los datos de entrada en AWS Glue? Tengo un bucket S3 con carpetas en cuales tenemos archivos. Quiero hacer un base de datos para pueder consultar este documentos sobre pocas claves con une API basado sobre Lambda. Pero por eso necesito normalizar los datos. Por ejemplo necesito transformar todos los de la carpeta /jomalone/ como el siguiente:
{
  "data": {
    "products": {
      "items": [
        {
          "default_category": {
            "id": "25956",
            "value": "Bath & Body"
          },
          "description": "London's Covent Garden early morning market.  Succulent nectarine, peach and cassis and delicate spring flowers melt into the note of acacia honey.  Sweet and delightfully playful.  Our luxuriously rich Body Crème with its conditioning oils of jojoba seed, cocoa seed and sweet almond, help to hydrate, nourish and protect the skin, while delicious signature fragrances leave your body scented all over.",
          "display_name": "Nectarine Blossom & Honey Body Crème",
          "is_hazmat": false,
          "meta": {
            "description": "The Jo Malone™ Nectarine Blossom & Honey Body Crème leaves skin beautifully scented with fruity notes of nectarine and peach sweetened with acacia honey."
          },
          "product_badge": null,
          "product_id": "10024",
          "product_url": "/product/25956/10024/bath-body/nectarine-blossom-honey-body-creme",
          "short_description": "A caring Body Crème infused with the succulent scent of Nectarine Blossom & Honey.",
          "tags": {
            "total": 2,
            "items": [
              {
                "id": "25956",
                "value": "Bath & Body",
                "key": "bath-body"
              },
              {
                "id": "26087",
                "value": "Nectarine Blossom & Honey Scent",
                "key": "nectarine-blossom-honey-scent"
              }
            ]
          },
          "cross_sell": [
            {
              "sku_id": "L0Y401",
              "sort_key": 1
            },
            {
              "sku_id": "L0YF01",
              "sort_key": 2
            },
            {
              "sku_id": "L01G01",
              "sort_key": 3
            },
            {
              "sku_id": "L8CC01",
              "sort_key": 4
            },
            {
              "sku_id": "L8CA01",
              "sort_key": 5
            },
            {
              "sku_id": "L7XW01",
              "sort_key": 6
            }
          ],
          "maincat": [
            {
              "key": "bathbody-maincat",
              "value": "bathbody_maincat"
            }
          ],
          "subcat": [
            {
              "key": "bodycare-subcat",
              "value": "bodycare_subcat"
            }
          ],
          "media": null,
          "reviews": {
            "average_rating": null,
            "number_of_reviews": null
          },
          "usage": [
            {
              "content": "Take a generous amount of our luxurious Body Crème and massage into skin.",
              "label": "HOW DOES IT WORK",
              "type": "how_does_it_work"
            }
          ],
          "fragrance_family": [
            {
              "key": "fruity-fragrance",
              "value": "fruity_fragrance"
            }
          ],
          "style": [
            {
              "key": "decadent-style",
              "value": "decadent_style"
            }
          ],
          "mood": [
            {
              "key": "cosy-mood",
              "value": "cosy_mood"
            }
          ],
          "skus": {
            "total": 1,
            "items": [
              {
                "is_default_sku": false,
                "is_discountable": true,
                "is_giftwrap": false,
                "is_under_weight_hazmat": false,
                "iln_listing": "Ingredients: Water\\Aqua\\Eau, Glycerin, Cetearyl Alcohol, Simmondsia Chinensis (Jojoba) Seed Oil, Fragrance (Parfum), Glyceryl Stearate, Stearic Acid, Triethanolamine, Theobroma Cacao (Cocoa) Seed Butter, Prunus Amygdalus Dulcis (Sweet Almond) Oil, Isopropyl Palmitate, Dimethicone, Aloe Barbadensis Leaf Juice, Bisabolol, Caffeine, Cocamidopropyl Pg-Dimonium Chloride Phosphate, Glyceryl Laurate, Hexylene Glycol, Caprylyl Glycol, Disodium Edta, Citral, Limonene, Citronellol, Linalool, Phenoxyethanol <ILN47239>",
                "iln_version_number": "ILN47239",
                "inventory_status": "Active",
                "material_code": "L4P8010000",
                "prices": [
                  {
                    "currency": "EUR",
                    "is_discounted": false,
                    "include_tax": {
                      "price": 68,
                      "original_price": 68,
                      "price_per_unit": 38.86,
                      "price_formatted": "€68.00",
                      "original_price_formatted": "€68.00",
                      "price_per_unit_formatted": "€38.86 / 100ML"
                    }
                  }
                ],
                "sizes": [
                  {
                    "value": "175ML",
                    "key": 1
                  }
                ],
                "shades": [
                  {
                    "name": "",
                    "description": "",
                    "hex_val": ""
                  }
                ],
                "sku_id": "L4P801",
                "sku_badge": null,
                "unit_size_formatted": "100ML",
                "upc": "690251040254",
                "is_engravable": null,
                "perlgem": {
                  "SKU_BASE_ID": 63584
                },
                "media": {
                  "large": [
                    {
                      "src": "/media/export/cms/products/1000x1000/jo_sku_L4P801_1000x1000_0.png",
                      "alt": "Nectarine Blossom & Honey Body Crème",
                      "height": 1000,
                      "width": 1000
                    },
                    {
                      "src": "/media/export/cms/products/1000x1000/jo_sku_L4P801_1000x1000_1.png",
                      "alt": "Nectarine Blossom & Honey Body Crème",
                      "height": 1000,
                      "width": 1000
                    }
                  ],
                  "medium": [
                    {
                      "src": "/media/export/cms/products/670x670/jo_sku_L4P801_670x670_0.png",
                      "alt": "Nectarine Blossom & Honey Body Crème",
                      "height": 670,
                      "width": 670
                    }
                  ],
                  "small": [
                    {
                      "src": "/media/export/cms/products/100x100/jo_sku_L4P801_100x100_0.png",
                      "alt": "Nectarine Blossom & Honey Body Crème",
                      "height": 100,
                      "width": 100
                    }
                  ]
                },
                "collection": null,
                "recipient": [
                  {
                    "key": "mom-recipient",
                    "value": "mom_recipient"
                  },
                  {
                    "key": "bride-recipient",
                    "value": "bride_recipient"
                  },
                  {
                    "key": "host-recipient",
                    "value": "host_recipient"
                  },
                  {
                    "key": "me-recipient",
                    "value": "me_recipient"
                  },
                  {
                    "key": "her-recipient",
                    "value": "her_recipient"
                  }
                ],
                "occasion": [
                  {
                    "key": "thankyou-occasion",
                    "value": "thankyou_occasion"
                  },
                  {
                    "key": "birthday-occasion",
                    "value": "birthday_occasion"
                  },
                  {
                    "key": "treat-occasion",
                    "value": "treat_occasion"
                  }
                ],
                "location": [
                  {
                    "key": "bathroom-location",
                    "value": "bathroom_location"
                  }
                ]
              }
            ]
          }
        }
      ]
    }
  }
}

En un json con el schema siguiente:
brandName     String
productName   String
productLink   String
productType   ?
maleFemale    Male/Female
price         float
unitPrice     String
size          float
ingredients   String
notes         String
numReviews    Int
userIDs       float
locations     float
dates         Date
ages          int
sexes         M/F
ratings       Int
reviews       Array of String
sources       String
characteristics  String
specificRatings  String

Entonces he probado AWS Glue pero no sé como deshacerme con los datos anidados como las claves al principo:
  "data": {
    "products": {
      "items": [
          ...

En efecto solé probé las modificaciones sobre los nombres:

Pero no parece tener ninguna de las consecuencias que buscaba si he de creer a la pestaña Preview:

En efecto habia borrado el primero y el ultimo campos soubrayados y modificado los otros pero nada de esto parece haberse tenido en cuenta en el Preview.
En efecto no parece habe al menos los mappings en el relatado script que esta producido a lo largo de esta creacion visual:
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

args = getResolvedOptions(sys.argv, ["JOB_NAME"])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args["JOB_NAME"], args)

# Script generated for node S3 bucket
S3bucket_node1 = glueContext.create_dynamic_frame.from_options(
    format_options={"multiline": False},
    connection_type="s3",
    format="json",
    connection_options={"paths": ["s3://datahubpredicity/JoMalone/"], "recurse": True},
    transformation_ctx="S3bucket_node1",
)

# Script generated for node ApplyMapping
ApplyMapping_node2 = ApplyMapping.apply(
    frame=S3bucket_node1,
    mappings=[("data.products.items", "array", "data.products.items", "array")],
    transformation_ctx="ApplyMapping_node2",
)

# Script generated for node S3 bucket
S3bucket_node3 = glueContext.write_dynamic_frame.from_options(
    frame=ApplyMapping_node2,
    connection_type="s3",
    format="json",
    connection_options={"path": "s3://datahubpredicity/merged/", "partitionKeys": []},
    transformation_ctx="S3bucket_node3",
)

job.commit()


text:
Q: UIView animationWithDuration not working second when called twice I have created a category on UITextField which allows to animate between red and white color as shown below:
@implementation UITextField (Additions)

-(void) flash
{
    [UIView animateWithDuration:2.0 animations:^{

        [self setBackgroundColor:[UIColor redColor]];

    } completion:^(BOOL finished) {

        [self setBackgroundColor:[UIColor whiteColor]];
    }];

}

@end

I call it like this:
[self.paymentTextField flash];

First time it works and it shows the red background and then switches back to white color. But on second call it does not do anything.

A: I'm not sure why that doesn't work. I tried it and got the same thing. However, since the color doesn't really animate, you can do it like this instead:
self.backgroundColor = [UIColor redColor];
[self performSelector:@selector(setBackgroundColor:) withObject:[UIColor whiteColor] afterDelay:2];

This should give you the same look.


text:
Q: SQL conditional Pivot Yes, this is another Pivot question... I've read through nearly all the previous questions and I can't seem to hack together a query that does what I need.
Here is what my table looks like:
FirmName    Account Balance Pmt Revolving   Installment     Mortgage
Amex    12345   10000   2000    1   0   0
Discover    54321   20000   4000    1   0   0
Chase   13579   100000  1500    0   0   1
Wells Fargo 2468    40000   900 0   1   0

The last three bit columns (Revolving, Installment, & Mortgage) dictate how the columns should be rolled up into a type. Each result requires three columns based on the type and its row count. The outcome should be one row with many columns. Here is what the result should look like:
Revolving1_Firm Revolving1_Balance  Revolving1_Pmt  Revolving2_Firm    Revolving2_Balance   Revolving2_Pmt  Realestate1_Firm    Realestate1_Balance     Realestate1_Pmt Vehicle1_Firm   Vehicle1_Balance    Vehicle1_Pmt

Amex        10000   2000    Discover    20000   4000    Chase   100000  1500    Wells Fargo 40000   900

How do you pivot based on the bit fields (Revolving, Installment, & Mortgage) and retain the proper count so that that each column gets count # appended to it?

A: This would have to be done with dynamic SQL.  First you would need to determine the maximum number of each type (and probably also convert the 3 bit columns into a single LOAN_TYPE column since that's your partition) over your whole population and then use a ROW_NUMBER() OVER (PARTITION BY LOAN_TYPE ORDER BY FirmName) over the normalized data correlated with that in order to put things in their right column.
I'd have to ask how important it is to do this in the database - because the schema is not fixed, it's pretty difficult to see the utility of doing it this way.
Still, only a little more complex than most dynamic pivots, so if the hints above don't get you there, and you still want me to take a stab at it, I'll try to post some actual working code later.
SET NOCOUNT ON

DECLARE @t AS TABLE
    (
     FirmName varchar(50) NOT NULL
    ,Account varchar(50) NOT NULL
    ,Balance money NOT NULL
    ,Pmt money NOT NULL
    ,Revolving bit NOT NULL
    ,Installment bit NOT NULL
    ,Mortgage bit NOT NULL
    ) ;
INSERT  INTO @t
VALUES  ('Amex', '12345', 10000, 2000, 1, 0, 0) ;
INSERT  INTO @t
VALUES  ('Discover', '54321', 20000, 4000, 1, 0, 0) ;
INSERT  INTO @t
VALUES  ('Chase', '13579', 100000, 1500, 0, 0, 1) ;
INSERT  INTO @t
VALUES  ('Wells Fargo', '2468', 40000, 900, 0, 1, 0) ;

WITH    n1
          AS (
              SELECT    FirmName
                       ,Account
                       ,Balance
                       ,Pmt
                       ,LoanType
                       ,LoanTypeFlag
              FROM      @t UNPIVOT ( LoanTypeFlag FOR LoanType IN ([Revolving], [Installment], [Mortgage]) ) AS unpvt
             ),
        n2
          AS (
              SELECT    FirmName
                       ,Balance
                       ,Pmt
                       ,LoanType
              FROM      n1
              WHERE     LoanTypeFlag = 1
             ),
        n3
          AS (
              SELECT    FirmName
                       ,Balance
                       ,Pmt
                       ,LoanType
                       ,ROW_NUMBER() OVER (PARTITION BY LoanType ORDER BY FirmName) AS SequenceNumber
              FROM      n2
             ),
        n4
          AS (
              SELECT    LoanType + CONVERT(varchar, SequenceNumber) AS Column_Prefix
                       ,FirmName AS Firm
                       ,CONVERT(varchar(50), Balance) AS Balance
                       ,CONVERT(varchar(50), Pmt) AS Pmt
              FROM      n3
             ),
        n5
          AS (
              SELECT    Column_Prefix + '_' + Col AS Col_Nm
                       ,Val
              FROM      n4 UNPIVOT ( Val FOR Col IN ([Firm], [Balance], [Pmt]) ) AS unpvt
             )
    SELECT  *
    FROM    n5 PIVOT ( MAX(Val) FOR Col_Nm IN ([Installment1_Firm], [Installment1_Balance], [Installment1_Pmt],
                                               [Mortgage1_Firm], [Mortgage1_Balance], [Mortgage1_Pmt], [Revolving1_Firm],
                                               [Revolving1_Balance], [Revolving1_Pmt], [Revolving2_Firm],
                                               [Revolving2_Balance], [Revolving2_Pmt]) ) AS pvt

Your main remaining problem is the final PIVOT list (you could generate this dynamically as I mentioned) and the type-safety because everything is conformed to varchar(50) in the entity-value stage before the final PIVOT.
Also, if the bit flags are not mutually exclusive, you will have some duplicates...
I would think if you are using a form generation system that the final PIVOT list is relatively fixed, so you could leave off the dynamic SQL to generate that list, but it would make the system slightly non-future-proof.
This will generate the pivot_list (could be simplified):
WITH    n1
          AS (
              SELECT    FirmName
                       ,Account
                       ,Balance
                       ,Pmt
                       ,LoanType
                       ,LoanTypeFlag
              FROM      @t UNPIVOT ( LoanTypeFlag FOR LoanType IN ([Revolving], [Installment], [Mortgage]) ) AS unpvt
             ),
        n2
          AS (
              SELECT    FirmName
                       ,Balance
                       ,Pmt
                       ,LoanType
              FROM      n1
              WHERE     LoanTypeFlag = 1
             ),
        n3
          AS (
              SELECT    FirmName
                       ,Balance
                       ,Pmt
                       ,LoanType
                       ,ROW_NUMBER() OVER (PARTITION BY LoanType ORDER BY FirmName) AS SequenceNumber
              FROM      n2
             ),
        n4
          AS (
              SELECT    LoanType + CONVERT(varchar, SequenceNumber) AS Column_Prefix
                       ,FirmName AS Firm
                       ,CONVERT(varchar(50), Balance) AS Balance
                       ,CONVERT(varchar(50), Pmt) AS Pmt
              FROM      n3
             ),
        n5
          AS (
              SELECT    Column_Prefix + '_' + Col AS Col_Nm
                       ,Val
              FROM      n4 UNPIVOT ( Val FOR Col IN ([Firm], [Balance], [Pmt]) ) AS unpvt
             ),
        pivot_list(pivot_list)
          AS (
              SELECT    ',' + QUOTENAME(Col_Nm)
              FROM      n5
              FOR       XML PATH('')
             )
    SELECT  STUFF(pivot_list, 1, 1, '') AS pivot_list
    FROM    pivot_list


text:
Q: JEXL with TalendDate.isDate Using tScriptRule component in Talend DI 4.2.1. Using the jexl expression to evaluate the date pattern results to false for all the conditions. The snippet derived from job for testing is as :
public class Script {

static class Row {

    public String EFFECTIVEDATE;

    public String getEFFECTIVEDATE() {
        return this.EFFECTIVEDATE;
    }
}

public static void main(String[] args) {
    Row row1 = new Row();
    row1.EFFECTIVEDATE = "10-01-2012";
    com.bekwam.tscriptrules.JexlRowEvaluator e_tScriptRules_2 = new com.bekwam.tscriptrules.JexlRowEvaluator();
    boolean ruleTest_tScriptRules_2_1 = e_tScriptRules_2
    .evalTrue("'${TalendDate.isDate(row1.EFFECTIVEDATE, \"dd-mm-yyyy\")}' == true", "row1", row1);
    System.out.println(ruleTest_tScriptRules_2_1);
}
}

The libraries/component are from tScriptRules

A: Talend functions are not evaluated by the jexl expression processor.
You can only use field (in your input row) in a jexl expression.
As you can see in the generated java code, the only parameter passed to the method is the row and all its fields
com.bekwam.talend.component.scriptrules.Result result_tScriptRules_1 = rulesBean_tScriptRules_1.process(row1, row2, row3, counter_tScriptRules_1);

*

*row1 : the input rows

*row2 : the filtered rows

*row3 : the rejected rows

You can modify the tscriptrules-2.0.1.jar library if you want to add Talend method evaluation in the jexl expression processor.
Instead, I would suggest to use a tmap to do this kind of data quality check
tMap Design : http://imageshack.us/a/img842/879/talendtmap.jpg
tMap Result : http://imageshack.us/a/img541/5950/talendtmapresult.jpg
talend jexl


text:
Q: Retrofit + rxandroid causes stackoverflow error on kitkat I am working with Retrofit 2 + RxAndroid, this code works pefect on Marshmallow and Lollipop devices, but fails with kitkat devices.
@OnClick(R.id.login_btn)
public void onLoginClicked() {
    loginBtn.setEnabled(false);
    AuthenticationAPI authApi = ServiceCreator.createService(AuthenticationAPI.class, null);
    authApi.login(new LoginUserRequest(emailEditText.getText().toString(), passwordEditText.getText().toString()))
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(verifyEmailResponse -> Log.i("TEST", "onNext: " + verifyEmailResponse.success),
             throwable -> {
             handleError(throwable);
             loginBtn.setEnabled(true);
             });
}

ServiceCreator.java
public class ServiceCreator {

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    private static final int DEFAULT_TIMEOUT = 30; //seconds

    private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    private static RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());

    private static Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(BuildConfig.REST_BASE_ENDPOINT)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(rxAdapter);

    public static <RESTService> RESTService createService(Class<RESTService> service, String userToken) {

        if (BuildConfig.REST_DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.addInterceptor(logging);
        }

        if (StringUtils.isNotBlank(userToken)) {
            httpClient.addInterceptor(chain -> {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .header(Constants.AUTHORIZATION_HEADER, userToken)
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            });
        }

        httpClient.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClient.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClient.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(service);
    }

    public static Retrofit retrofit() {
        return builder.client(httpClient.build()).build();
    }
}

The error:
FATAL EXCEPTION: RxNewThreadScheduler-1 java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
   at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:59)
   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
   at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.StackOverflowError
   at org.apache.harmony.security.asn1.ASN1StringType.getDecodedObject(ASN1StringType.java:99)
   at org.apache.harmony.security.asn1.ASN1StringType.decode(ASN1StringType.java:90)
   at org.apache.harmony.security.asn1.ASN1Choice.decode(ASN1Choice.java:308)
   at org.apache.harmony.security.x501.AttributeTypeAndValue$1.decode(AttributeTypeAndValue.java:339)
   at org.apache.harmony.security.asn1.BerInputStream.readSequence(BerInputStream.java:554)
   at org.apache.harmony.security.asn1.DerInputStream.readSequence(DerInputStream.java:105)
   at org.apache.harmony.security.asn1.ASN1Sequence.decode(ASN1Sequence.java:40)
   at org.apache.harmony.security.asn1.BerInputStream.decodeValueCollection(BerInputStream.java:626)
   at org.apache.harmony.security.asn1.BerInputStream.readSetOf(BerInputStream.java:606)
   at org.apache.harmony.security.asn1.DerInputStream.readSetOf(DerInputStream.java:115)
   at org.apache.harmony.security.asn1.ASN1SetOf.decode(ASN1SetOf.java:40)
   at org.apache.harmony.security.asn1.BerInputStream.decodeValueCollection(BerInputStream.java:626)
   at org.apache.harmony.security.asn1.BerInputStream.readSequenceOf(BerInputStream.java:584)
   at org.apache.harmony.security.asn1.ASN1SequenceOf.decode(ASN1SequenceOf.java:40)
   at org.apache.harmony.security.asn1.ASN1Type.decode(ASN1Type.java:82)
   at javax.security.auth.x500.X500Principal.<init>(X500Principal.java:78)
   at com.android.org.conscrypt.OpenSSLX509Certificate.getIssuerX500Principal(OpenSSLX509Certificate.java:422)
   at com.android.org.conscrypt.OpenSSLX509Certificate.getIssuerDN(OpenSSLX509Certificate.java:236)
   at com.android.org.conscrypt.TrustManagerImpl.cleanupCertChainAndFindTrustAnchors(TrustManagerImpl.java:340)
   at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:225)
   at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:202)
   at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:611)
   at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
   at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)
   at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:241)
   at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:198)
   at okhttp3.internal.connection.RealConnection.buildConnection(RealConnection.java:174)
   at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:114)
   at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:193)
   at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:129)
   at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:98)
   at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
   at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:109)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)

Thanks!
//UPDATE: I have discovered which cause the error but not the solution, I have created an issue in https://github.com/square/okhttp/issues/2962

A: The error happens because I was adding the same interceptor over and over, a new version could be.
public class ServiceCreator {

    private OkHttpClient.Builder httpClient;
    private static final int DEFAULT_TIMEOUT = 30; //seconds

    private Gson gson;
    private RxJavaCallAdapterFactory rxAdapter;
    private Retrofit.Builder builder;

    private static ServiceCreator mInstance = null;

    private ServiceCreator() {
        httpClient = new OkHttpClient.Builder();
        gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
        rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
        builder = new Retrofit.Builder()
                .baseUrl(BuildConfig.REST_BASE_ENDPOINT)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(rxAdapter);

        if (BuildConfig.REST_DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.addInterceptor(logging);
        }
    }

    public static ServiceCreator getInstance() {
        if (mInstance == null) {
            mInstance = new ServiceCreator();
        }
        return mInstance;
    }

    public <RESTService> RESTService createService(Class<RESTService> service, String userToken) {

        if (StringUtils.isNotBlank(userToken)) {
            httpClient.addInterceptor(chain -> {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .header(Constants.AUTHORIZATION_HEADER, userToken)
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            });
        }

        httpClient.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClient.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClient.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(service);
    }

    public Retrofit retrofit() {
        return getInstance().builder.client(getInstance().httpClient.build()).build();
    }
}

A: This is one of most trivial problems dealing with on OkHttp and retrofit. Actually, I, too, was struggling for a solution for a long time until I foudn the error caused because of following block of code.
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);

So once you remove the lines it should work back normally.


text:
Q: How to split a report page in two I am trying to divide my page in containers like in the above image

In the left side will be an image and in the right side will be a table. I need a nice way to display this image. I tried to use \Block to solve this problem but didn't work.
I have 4 tables with 12 columns and only 3 images, so the last container should only contain the table.
I don't really know how to divide this page in order to divide the page and to fit in tables in my container.
If someone can help me with this it will be just great.
Thanks

A: Is that you want ?
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,matrix,calc,positioning}

\begin{document}

\begin{center}

Title
\end{center}

\tikzset{mymatrix/.style={ampersand replacement=\&,nodes in empty cells, matrix of nodes,
    nodes = { gray, draw, align=center,  minimum height=4cm,
        anchor=center,
        minimum width=5cm,
        inner sep=0pt,}}}

\begin{tikzpicture}

\matrix (a) [mymatrix]{ sized image\\};
\matrix (b) [mymatrix,right=of a,node distance=3cm]{  \node (){ \begin{tabular}{llllllllllll}
1 & 2 & 3 &4  & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\
1 &  &  &  &  &  &  &  &  &  &  &  \\
1 &  &  &  &  &  &  &  &  &  &  &
\end{tabular} };\\};
\end{tikzpicture}

\end{document}

You can adjust the distance between title and the  environment, and the node distance.


text:
Q: Pass value to function that gets called later I have a variable that I'd like to use in a function that will be called at a later time. Here's the situation:
var a = 'something';

var mapFun = {
    map: function (doc) {
        if(doc.a === a) {
            emit(doc, doc);
        }
    }
};

So map() is a function that gets called later on in a different context. So a is undefined when the function is called. This makes sense, but I'm wondering how I can access the value of a within the function. For instance:
if(doc.a === a) should be if(doc.a === 'something') when the function is called.
EDIT: I understand the way I've set the example up makes it seem as though a is a global variable. This is not the case. The map() method inside mapFun gets called inside a function which does not have access to a

A: Putting variables in global scope so you'll have access to it later is an anti pattern in any language. I'm surprised all 4 answers from JavaScript programmers would suggest to do such a thing.
Let's say you need to pass mapFun.map to someLib.callBack, at the time you pass map you know the value of a therefor you can use a closure:
var a = 22;
someLib.callBack = function(doc){
  mapFun.map(doc,a);
};

It'll look as though someLib would pass "a" but it will only pass "doc". If you have to change the value of "a" later then it depends on the scope. If a is passed around then re assigning it won't change it so you'll need to pass an object that can be mutated.
var someLib = {
  callBack : function(fn){
    setTimeout(function(){
      fn("hello");
    },100);
  }
};
var mapFun = {
  map : function(doc,a){
    console.log("doc passed when called:",doc);
    console.log("variable a is:",a);
  }
};
(function(){
  var a = 22;
  someLib.callBack(function(doc){
    mapFun.map(doc,a);
  });
  a=44;//this is fine, same scope

  a=22;
  someLib.callBack(function(doc){
    mapFun.map(doc,a);
  });
  (function(a){
    a = "not changed";
  }(a));//doesn't change a because you assign it in a different scope

  var obj={};
  obj.a=22;
  someLib.callBack(function(doc){
    mapFun.map(doc,obj.a);
  });
  (function(obj){
    obj.a = "Hello World";
  }(obj));//changed a because you mutated the object
    //diffeerent scope doesn't matter here.
}());

If closures were not an option you could have myMap remember the value of a as suggested by Trendy.

A: If a is no longer in scope when this function is called in different context, try making a a global by putting it in the window. Instead of var a = 'something'; do window.a = 'something';

A: Try, instead of doing var a = "something";, try doing window.a = "something"; and then referencing it within your code by doing if(doc.a == window.a).

If that doesn't work, I don't know what will.

Good luck!

A: If you're trying to access a variable defined within another function's scope you'll need to lift the variable from the scope, either by storing it inside the global scope or adding it to the prototype of an object in the global scope (I.E. the object you're trying to pass "a" to).
For instance:
var mapFun = {
    map: function(){
        //do something here
        alert(this.a);
    }
};

mapFun.a = "something";

See how this works: http://jsfiddle.net/z8Uvr/

A: Variables a and mapFun are in the same scope, so they should generally always be available for each other.
Even though the .map() function is being called within another function, where the function was declared still has access to a
When you create a new scope, all variables and functions you create in that scope are accessible the functions and objects created in the same scope.
If you are having an issue with accessing a you could make is available to the window (global) object by saying window.a = 'something';
Be careful when adding a to the global scope as it could cause conflict.
Thanks to @HMR for pointing that out


text:
Q: On Mac OS X (10.6.4) is there a keyboard shortcut to close all other windows On Mac OS X (10.6.4) is there a keyboard shortcut to close all other windows except the one with focus?

A: Not that I know of.
You can however hide all other applications with Option+Command+H.

A: You can create an applescript to close all but the frontmost window of the current application. In snow leopard, you can put it in an automator service and give it a keyboard shortcut. Alternatively, you can use Fastscripts to give it a shortcut.
Edit: I've added hiding other applications to the applescript.
Edit #2: OK, after testing I found the repeat while  window 2 exists actually didn't stop looping, causing nasty autoclose behaviour when opening new windows. The new code should be more robust.
with timeout of 2 seconds
  try
    tell application "System Events"
        set app_name to name of the first process whose frontmost is true
        set visible of (every process) to false -- hide everything
    end tell

    tell application app_name
        activate -- show frontmost application
        repeat with aWindow in (get every window)
            if index of aWindow > 1 then close aWindow
        end repeat
    end tell
  on error error_message number error_number
    display alert ("Something went wrong:") ¬
        message error_message ¬
        & (" Error number ") & error_number & "."
  end try
end timeout


text:
Q: Set of pairs, with and without repetitions I have two sets:
X = {a, b}
Y = {1, 2, 3}

I would like to generate the following set of sets of pairs:
{<<a, 1>>, <<a, 2>>, <<a, 3>>}
{<<a, 1>>, <<a, 2>>, <<b, 3>>}
{<<a, 1>>, <<b, 2>>, <<a, 3>>}
{<<a, 1>>, <<b, 2>>, <<b, 3>>}
...
{<<b, 1>>, <<b, 2>>, <<b, 3>>}

In each set the first element is from X and the second is from Y. X can be repeated, Y cannot. How to do it?

A: Using the \X operator gives us the set of all pairs: X \X Y = {<<a, 1>>, <<a, 2>>, ... <<b, 3>>}. SUBSET (X \X Y) gives us all possible sets. {s \in SUBSET (X \X Y): Cardinality(s) = 3} (from the FiniteSets module) gives us all 3-element sets.
We want to make this unique on the second element of each pair. Let's define a new operator:
UniqueBy(set, Op(_)) == Cardinality(set) = Cardinality({Op(s): s \in set})

If we do {x[2] : x \in {<<a, 1>>, <<a, 2>>, <<a, 2>>}}, we get {1, 2}, which has a smaller cardinality and will be filtered out. So our final expression is
{s \in SUBSET (X \X Y) : UniqueBy(s, LAMBDA x: x[2]) /\ Cardinality(s) = 3}

Note that without the cardinality check {<<a, 1>>} would be part of the set of sets, which isn't what you're looking for.

A: EXTENDS Functions, FiniteSets, Naturals

CONSTANTS a, b

X == {a, b}
Y == {1, 2, 3}

Dom == 1..Cardinality(Y)

Slice == {{<< xt[n], yt[n] >>:  n \in Dom}:
              << xt, yt >> \in [Dom -> X] \X Bijection(Dom, Y)}

The TLAPS distribution includes the module Functions. The modules FiniteSets and Naturals are part of the standard library of TLA+.


text:
Q: iPhone UIDatePicker style is there any way/trick to change the size, font, background color etc. of a uiDatePicker?? even the backgroundcolor attribute does not work and the default style of the picker is sooo irrelevant with the design of my application :(

A: Perhaps you can use a UIPickerView instead?  I've seen people use images as backgrounds using this.  You'll have to code up all the date logic though.

A: I don't believe there is a way.  Even if there is, your app will likely get rejected for doing it.


text:
Q: first() not working on the existing RDD I am trying to import a csv file into the RDD format. When i use .first() command to get the first row of the rdd, it gives the error as mentioned below.
It seems the .map function makes the RDD into the pipelined RDD on which a command like .first() and .count() does not work. Is there any other way to work on this ?
import csv
import StringIO

def loadRecord(line):
    input = StringIO.StringIO(line)
    reader = csv.DictReader(input, fieldnames=["PassengerId","Survived","Pclass","Name","Sex","Age","SibSp","Parch","Ticket","Fare","Cabin","Embarked"])
    return reader.next()
input = sc.textFile("C:\Users\rohit.guglani\Documents/train.csv",4).map(loadRecord)

type(input)

pyspark.rdd.PipelinedRDD

input.first()

gives this error:
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-9-d93d15081c08> in <module>()
----> 1 input.first()

C:\spark-1.6.1\python\pyspark\rdd.pyc in first(self)
   1313         ValueError: RDD is empty
   1314         """
-> 1315         rs = self.take(1)
   1316         if rs:
   1317             return rs[0]

C:\spark-1.6.1\python\pyspark\rdd.pyc in take(self, num)
   1265         """
   1266         items = []
-> 1267         totalParts = self.getNumPartitions()
   1268         partsScanned = 0
   1269

C:\spark-1.6.1\python\pyspark\rdd.pyc in getNumPartitions(self)
   2361
   2362     def getNumPartitions(self):
-> 2363         return self._prev_jrdd.partitions().size()
   2364
   2365     @property

C:\spark-1.6.1\python\lib\py4j-0.9-src.zip\py4j\java_gateway.py in __call__(self, *args)
    811         answer = self.gateway_client.send_command(command)
    812         return_value = get_return_value(
--> 813             answer, self.gateway_client, self.target_id, self.name)
    814
    815         for temp_arg in temp_args:

C:\spark-1.6.1\python\pyspark\sql\utils.pyc in deco(*a, **kw)
     43     def deco(*a, **kw):
     44         try:
---> 45             return f(*a, **kw)
     46         except py4j.protocol.Py4JJavaError as e:
     47             s = e.java_exception.toString()

C:\spark-1.6.1\python\lib\py4j-0.9-src.zip\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name)
    306                 raise Py4JJavaError(
    307                     "An error occurred while calling {0}{1}{2}.\n".
--> 308                     format(target_id, ".", name), value)
    309             else:
    310                 raise Py4JError(

Py4JJavaError: An error occurred while calling o50.partitions.
ohit.guglani/Documents/train.csv
    at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:285)
    at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:228)
    at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:313)
    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:199)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)
    at org.apache.spark.api.java.JavaRDDLike$class.partitions(JavaRDDLike.scala:64)
    at org.apache.spark.api.java.AbstractJavaRDDLike.partitions(JavaRDDLike.scala:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
    at py4j.Gateway.invoke(Gateway.java:259)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:209)
    at java.lang.Thread.run(Unknown Source)

A: when working on Windows you should be careful while using /instead of \
input = sc.textFile("C:\Users\rohit.guglani\Documents\train.csv",4).map(loadRecord)


text:
Q: Anylogic: duplicate basic model I have created a basic model in Anylogic (model name: Basic & java package: basic). This basic model represents our current production. Now I want to simulate different optimization concepts and adjust the basic model accordingly. In order to keep my basic model, I have saved the basic model in a new file. For this I changed the model name to basic1 and also the java package to basic1. However, Anylogic crashes every time during this saving process. Does anyone know what the reason is and how I can manage to save my basic model in a new (independent) file?

A: If your problem is really related to saving files, here is the method I am sure that works (it might be that your problem is somewhere else). I always do it as following:

*

*Copy paste the whole folder.

2.Change the AnyLogic file name.

*Open the model and change the package name.

This will create an independent model for you.


text:
Q: Ruby Ecosystem (rake, capistrano, mongrel, etc.?) basics So I am diving into Ruby (and Rails) and back-end web development in general, and it seems to me there is a huge ecosystem of Ruby projects that seem to be totally essential.
I am thinking of projects like Rake, Rack, Mongrel, Gems, Capistrano specifically.
Besides these apps' own documentation on their respective project websites, can you recommend a good place to start diving into more information about creating a good Ruby environment?
I have tons of questions about running Mongrel, deploying with capistrano, and rather than list each individual question that pops into my head, is there a good repository of information that addresses the "Ruby world"?

A: The Pragmatic Programmers have a Deploying Rails book that covers some of this.  One tool I would add to your list is Phusion Passenger (aka mod_rails).
Also, see my answer to Ethan's question for Rails resources.

A: I just posted a similar question, but it was specifically about Rails learning resources, not Ruby.
If you're just diving in I recommend putting Rails to the side for the moment and focusing on Ruby exclusively. Get comfortable with Ruby before you start trying to learn Rails.
An awesome Ruby book is David Black's Ruby for Rails. But note that the Rails chapters in that book are outdated. It's worth owning just for the Ruby chapters though.
If you don't want to buy a book, try _why's poignant guide to Ruby.

A: I've just used the Howtos on the wiki. Most of these pieces you don't need to learn too much about at first. You'll just naturally use them if you follow the install instructions and basic tutorials.
Capistrano is an example of one you really do have to dig into a bit more - I read this article when I set it up the first time just recently and it helped me a lot; it was really pretty easy.

A: A new series of Rails Guides have just been launched.
Provides a very in-depth look at the fundamentals.
I would suggest concentrating on Rake and Capistrano. There is not much to say about Gems really, at it's most basic it is just a way of managing code packages for Ruby and can be approached as a black box as you get started.

A: You probably want to learn simple Ruby basics that can help you understand rails better such as gems, databases, or third-party resources. I know TeamTreehouse is really good at teaching around the Ruby ecosystem and HackCasts is very similar for a cheaper cost. TeamTreehouse can teach you everything from Rails API's to simple SQL to MongoDB databases. Hackcasts can teach you how to use those skills to create robust web applications. It really depends on your need. Thanks, hope this helped!


text:
Q: Error Json in swift 3 this code JSON not work on swift 3 and i got err in swift 3 how to fix it ?
func dataJsonFromURL(url:String) -> NSArray {

    if let data = NSData(contentsOfURL: NSURL(string: url)! as URL) {
        return ((try! JSONSerialization.JSONObjectWithData(data, options: [])) as! NSArray)
    }
    else {
        return data
    }
}

how to fix it to work in swift 3

A: You're trying to use NSData in Swift 3. It has been changed to Data. How to convert NSData to Data in Swift 3?

A: func dataJsonFromURL(url:String) -> [String: Any]? {
    if let realUrl = URL(string: url) {
        do {
            let data = try Data(contentsOf: realUrl)
            if let json = try JSONSerialization.jsonObject(with: data, options:[]) as? [String: Any] {
                return json
            }
        } catch {
            //error
        }
    }
    return nil
}


text:
Q: How to make the most relevant search with MySQL? I want to do a search based on its relevance to MySQL. Whatever I tried, I could not succeed. I did a Fulltext search, I did a search with Like, again I can not do the following order.
Search word for example this: "first second"
First Second Keyword ->  (full word) will begin with
Keyword First Second Keyword -> (full word) in between or at the end
Firstsecond Keyword ->  (adjacent word) will begin with
Keyword Firstsecond Keyword ->  (adjacent word) in between or at the end
First Keyword ->  (only the first word) will begin with
Keyword First Keyword ->  (only the first word)  in between or at the end
Second Keyword ->  (only the second word) will begin with
Keyword Second Keyword ->  (only the second word)  in between or at the end

Then I want it to continue as below; (all of them)
Firstasdasd Keyword
Keyword asdasdfirst Keyword
Keyword asdasdfirstasdasd Keyword
Secondasdasd Keyword
Keyword asdasdsecond Keyword
Keyword asdasdsecondasdasd Keyword

A: Yeah, FULLTEXT won't do this kind of search. It's word-oriented.
What you want isn't really simple SQL. I think you want something like this to hit the first keyword.
SET @match := 'first'
SELECT MIN(priority) priority, value
  FROM (
      SELECT 1 priority, value FROM tbl WHERE value LIKE CONCAT(@match, ' %')
       UNION ALL
      SELECT 2 priority, value FROM tbl WHERE value LIKE CONCAT('% ', @match, ' %')
       UNION ALL
      SELECT 3 priority, value FROM tbl WHERE value LIKE CONCAT('%', @match, '%')
  ) results
 GROUP BY value
 ORDER BY MIN(priority), value;

Generally, you use a UNIONed series of SELECTs with priorities for the full-word and embedded word matches, and take the lowest priority match you get for each row.
You'll need to elaborate on that general kind of pattern to handle both keywords. This looks like it could turn into a real pain in the xxx neck to get right. And the LIKE '%something' search terms mean it won't be very fast.
If you're going to large scale with this, it might be worth investigating Sphinx.


text:
Q: Simple preg expression to strip name into 2 parts based on the space I have a form field called 'Name' - but I'd like to save the submission into the DB as First Name & Last Name using a preg expression.
Can some illustrate how if I entered the name 'John Smith' into the field a regexp would strip this into First Name - John Surname - Smith
Thanks in advance

A: For simple cases, you might just want to split the name by blanks:
$name = "John Smith";
$nameParts = explode(' ',$name);
var_dump($nameParts);

More complex cases (e.g. titles/middle names) might force you to use multiple input fields.

A: $names = explode(" ", $POST['name']);
$firstName = $name[0];
$lastName = $name[1];

This is however an absolutely brutal idea. Just make a first name and last name form field. I guarantee at some point someone is going to put something like Alfred E Newman and you're going to end up with their initial or middle name as a last name.

A: Prefer use split (version php < 5.3.0) or explode which is an alias of split function, in your case, you just have to split you fullname with space character ' '
var $fullname = "John Smith";
var $splitfullname = $fullname.split(' ');

var $firstname = $splitfullname[0];
var $lastname = $splitfullname[1];

-
var $fullname = "John Smith";
var $splitfullname = explode(' ', $fullname);

var $firstname = $splitfullname[0];
var $lastname = $splitfullname[1];

if you build the form that catch firstname and fullname, I will suggest you to split your fullname input field into two input field (firstname and lastname).

A: Use explode:
<?php
$fullname='John Smith';

list ($firstName,$lastName)=explode(' ',$fullname);

echo 'First name: '.$firstName.PHP_EOL;
echo 'Last name: '.$lastName.PHP_EOL;

A: Just created this function just in case someone else has a similar problem - thanks for all of the advice guys!
http://ideone.com/gxvi9


text:
Q: Get value from checkbox array through filter_input(INPUT_POST, 'check_list') My HTML code following:
<form action="test.php" method="post">
<input type="checkbox" name="check_list[]" value="value 1">
<input type="checkbox" name="check_list[]" value="value 2">
<input type="checkbox" name="check_list[]" value="value 3">
<input type="checkbox" name="check_list[]" value="value 4">
<input type="checkbox" name="check_list[]" value="value 5">
<input type="submit" />
</form>

and my PHP code test.php
$check_list = filter_input(INPUT_POST, 'check_list');
var_dump($check_list);

php code mention top return false,
but if i am use : $check_list = $_POST['check_list'] then its work fine. how can i solve my code through filter_input

A: Try
    filter_input_array
instead, see ref


text:
Q: How to restrict submit action on JSP based on a user role? I have a some.jsp There is an action button, for example delete. I have users and their roles. Tomcat 8 provides security. Let's say user made some actions and clicked the button send
The url with parameters goes to servlet. Let's take an example of servlet mapping:
<servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>servlets.myServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>sName</servlet-name>
    <url-pattern>/action1</url-pattern>
</servlet-mapping>
<security-constraint>
    <display-name>administrators</display-name>
    <web-resource-collection>
        <web-resource-name>action1</web-resource-name>
        <description>action1</description>
        <url-pattern>/action1</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <description>allowed for administrator</description>
        <role-name>administratorRole</role-name>
    </auth-constraint>
</security-constraint>

Based on above all that comes with <url-pattern>/action1</url-pattern> is allowed only for administrator.
But I want to restrict only delete button. Everything else on that some.jsp shall be allowed for other users. How to implement it?
JSP part:
<form name="frm" action="action1">
    <input type="hidden" name="prm1" value="${prm1}"/>
    <input type="hidden" name="prm2" value="${prm2}"/>
    <input id="btnid" type="submit" value="send" name="btn"/>
</form>

<form name="frm" action="action1">
    <input type="hidden" name="prm1" value="${prm1}"/>
    <input type="hidden" name="prm2" value="${prm2}"/>
    <input id="btnid" type="submit" value="delete" name="btn"/>
</form>

Servlet part:
String actionType=request.getParameter("btn");
if(actionType.equals("send")) doSend();
if(actionType.equals("delete")) doDel();

The expected outcome:

*

*URL like: http://localhost:8084/action1?prm1=111&prm2=221&btn=send is OK to perform by anyone.

*URL like: http://localhost:8084/action1?prm1=111&prm2=221&btn=delete is OK to perform only for administrators.


text:
Q: geopandas spatial join with conditions / additional columns I have two DataFrames with Lat, Long columns and other additional columns. For example,
import pandas as pd
import geopandas as gpd

df1 = pd.DataFrame({
                    'id': [0, 1, 2],
                    'dt': [01-01-2022, 02-01-2022, 03-01-2022],
                    'Lat': [33.155480, 33.155480, 33.155480],
                    'Long': [-96.731630, -96.731630, -96.731630]
                  })

df2 = pd.DataFrame({
                    'val': ['a', 'b', 'c'],
                    'dt': [01-01-2022, 02-01-2022, 03-01-2022],
                    'Lat': [33.155480, 33.155480, 33.155480],
                    'Long': [-96.731630, -96.731630, -96.731630]
                  })

I'd like to do a spatial join not just on lat, long but also on date column. Expected output:
id   dt           lat         long         val

0    01-01-2022   33.155480   -96.731630   a
1    02-01-2022   33.155480   -96.731630   b
2    03-01-2022   33.155480   -96.731630   c


text:
Q: Removing object from the display list I have an application that uses a main class to control other MovieClips, adding and removing them as needed, most of them are separate screens or sub menus.
When I leave the main menu and come back to it later from another screen, certain animations and roll over buttons still play, which I don't want, I basically need the main menu screen to reset every time it is seen.
I read up on this and found out that removing the child doesn't necessarily remove it from the memory.
I tried setting the mainmenu to null before moving onto a different screen but this threw up an error, stating that the parameter child must be none null.
Could anyone shed some light on how to completely kill my mainmenu when it is not needed.
public function confSubMenuOneScreen():void {
        subMenuOneScreen = new SubMenuOne();
        mainmenu = null;
        removeChild(mainmenu)
        addChild(subMenuOneScreen)
        currentScreen = subMenuOneScreen;
    }

This is the example of code that removes the menu and adds another screen, with the mainmenu = null code that throws up the error.

A: The error you're getting is because you're setting the object to null - then attempting to remove the object (which is now null). Reversing the two lines will probably fix the error.
However, this won't free the object from memory until garbage collection removes it (assuming there are no other references to "mainmenu" in your application).
Rather than trying to delete the object and create new objects each time you need it, I would suggest creating one instance of "mainmenu" and reuse it. Then, just remove it from the display list and add it back when you need it again.


text:
Q: How can i check if a param exists with jstl? I need a JSTL expression or a tag which checks that the availability of param in request.

A: You could use c:if tag to test if variable or say ${param["xyz"]} exists or not like:
 <c:if test="${empty parameter}">
     parameter is empty or null.
 </c:if>

A: <s:if test="%{#parameters.itemId == null}">
    <fmt:message key="Add" />
</s:if>
<s:else>
    <fmt:message key="Edit"/>
</s:else>


text:
Q: Using Exchange Web Services(EWS) how I can determine admin user? I am using EWS OAuth for authentication Office 365 users, but sometime I need to verify provided office 365 user is admin or not. I checked Microsoft Graph API for the same but I need to validate user is admin or not using EWS.
Thanks in advance!

A: I referred many Microsoft documents and asked same question on Microsoft community. I get below answer from the Microsoft expert.
There's nothing in EWS that covers that, use the Graph API


text:
Q: Wordpress - Migrate Theme In New Wordpress I wondering how to migrate custom theme from another wordpress to another without copying the whole wordpress...
I already tried copy the folder theme to new wordpress, but it has a lot of problem, because in the new wordpress, there is no Page as in origin wordpress.

A: Create some pages and see if it works.
Some themes uses plugins also, you must copy them too.
By the way, there's a dedicated stackexchange site for wordpress : https://wordpress.stackexchange.com/

A: You can never expect the 100% same experience on another install since there may not be the same plugins, pages, images, server settings and so on and so on. You can not even be sure your theme work on the new wordpress if the WP version is diffrent from the one you made the theme on.


text:
Q: How can one imagine an arrow from the empty set to an arbitrary set in the category of sets? My question may seem very elementary because I'm learning category theory from the very basics. I can understand there's a unique terminal object (the one-element object) and that there's a unique arrow from any other object to it. But the initial object is hard to imagine. Let's consider the example of the category of sets. Obviously, the one-element set cannot be the initial object because one can imagine more than one function, each matching the one element of the domain with a specific element of the arbitrary codomain.
It is said that in the example above, the empty set is the unique initial object. But how is it posibble to define a unique function FROM THE EMPTY SET (to any other set in the category Set)?


text:
Q: Why doesn't snippets in Sublime text do anything? I tried using snippets in Sublime Text - I created a document hello.sublime-snippet in /Users/davidfaux/Library/Application Support/Sublime Text 2/Packages/User:
<snippet>
  <content><![CDATA[
  alert("hello {$1}");
]]></content>
  <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
  <!-- <tabTrigger>hello</tabTrigger> -->
  <!-- Optional: Set a scope to limit where the snippet will trigger -->
  <!-- <scope>source.js</scope> -->
</snippet>

Then, I created a new file called hello.js on my Desktop:
document.onload = function() {
  hello
}

However, when I press tab after hello, nothing happens. Why not? I tried setting "auto_complete_commit_on_tab": true in my User settings, and this attribute seems to be working for autocomplete.
Any advice on directions for debugging appreciated!

A: You are using a template to create this snippet. So you need to uncomment the lines that actually define the snippet.
The quick way to do this in ST2 is to select the entire line and press ctrl+shift+/ to remove the comment markings.
The lines you need to uncomment are the <tabTrigger>hello</tabTrigger> line and the <scope>source.js</scope> line. Then this snippet should work fine as long as you are putting it in a .js file.
Also, I prefer using Enter to auto-complete as Tab is also used in ST2 for navigation.

A: As others have mentioned, the parts of the snippet that determine its tab trigger are currently commented. XML comments look like this:
<!-- ...commented content... -->
You've left both the tabTrigger tag line and the scope tag line commented, so hello will not expand to the snippet content—the only way to activate the snippet now is via the Command Palette—nor is the snippet's scope actually restricted to Javascript files. You'll have to remove the commenting from those lines (Ctrl+/ is the default single-line comment toggle on Windows) for them to have any effect, like this:
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>hello</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>source.js</scope>

You can read more about snippets at the Unofficial Docs Snippets page.

A: Uncomment <tabTrigger> and it will work when you press tab after hello


text:
Q: How to move the scrollbar to inside the text widget I have this code
from tkinter import *

   root = Tk()
   root.geometry("1200x1000+30+30")
   # width x height + x_offset + y_offset:
   T = Text(root, height=10, width=100)
   T.place(x=20, y=30)
   for i in range(40):
      T.insert(END, "This is line %d\n" % i)

   yscroll = Scrollbar(command=T.yview, orient=VERTICAL)
   T.configure(yscrollcommand=yscroll.set)
   yscroll.pack(side="right", fill="y", expand=False)

   root.mainloop()

The srollbar is on the window frame, is there a way I can move it inside and to the right edge of text area?

A: There might be another way, but I would use the ScrolledText widget contained in tkinter.scrolledtext.
from tkinter import *
import tkinter.scrolledText

root = Tk()
root.geometry("1200x1000+30+30")
# width x height + x_offset + y_offset:
T = ScrolledText(root, height=10, width=100)
T.place(x=20, y=30)
for i in range(40):
    T.insert(END, "This is line %d\n" % i)

root.mainloop()

This automatically puts the scrollbar inside of the textbox.
From this answer I also got that you could use place instead of pack to position the scrollbar and then use in_=T:
from tkinter import *

root = Tk()
root.geometry("1200x1000+30+30")
# width x height + x_offset + y_offset:
T = Text(root, height=10, width=100)
T.place(x=20, y=30)
for i in range(40):
    T.insert(END, "This is line %d\n" % i)

yscroll = Scrollbar(command=T.yview, orient=VERTICAL)
yscroll.place(in_=T, relx=1.0, relheight=1.0, bordermode="outside")
T.configure(yscrollcommand=yscroll.set)

root.mainloop()


text:
Q: How to capture live audio via RTMP using xuggler? I am trying to live microphone stream (SPEEX codec) using xuggler but I am getting warning that codec as null. What is fix for this issue?
public void audioCapture(String streamName, String sessionId) {
        IContainer readContainer = IContainer.make();
        readContainer.setInputBufferLength(4096);
        String url = "rtmp://127.0.0.1:1935/live/Session_"
                + sessionId + "/" + streamName + " live=1";
        if (readContainer.open(url, IContainer.Type.READ, null, true, false) < 0) {
            // if(readContainer.open(url, IContainer.Type.READ, null) < 0){
            throw new RuntimeException("unable to open read container");
        }
        int numStreamAudio = readContainer.getNumStreams();
        System.out.println("Numer of audio stream: " + numStreamAudio);
        IStream stream = readContainer.getStream(0);
        audioCoder = readContainer.getStream(0).getStreamCoder();
        int st = audioCoder.open(null, null);
        // if(st<0) throw new RuntimeException("cant open audio coder");
        // if(audioCoder.open() <0) throw new
        // RuntimeException("cant open audio coder");
        System.out.println(" audio coder prop channels"
                + audioCoder.getChannels() + "  sample rate "
                + audioCoder.getSampleRate() + " bit rate "
                + audioCoder.getBitRate() + " codec type  "
                + audioCoder.getCodecType().toString() + " codec tag "
                + audioCoder.getCodecTag() + " audio frame size "
                + audioCoder.getAudioFrameSize() + " codec id "
                + audioCoder.getCodecID().toString() + " num properties "
                + audioCoder.getNumProperties());

        writer.addAudioStream(1, 1, 1, 16000);
        IPacket packet = IPacket.make();
        while (readContainer.readNextPacket(packet) >= 0) {
            IAudioSamples samples = IAudioSamples.make(1024, 1);
            int offset = 0;
            while (offset < packet.getSize()) {
                int bytesDecoded = audioCoder.decodeAudio(samples, packet,
                        offset);

                // if(bytesDecoded < 0) throw new
                // RuntimeException("got error decoding audio in: " );
                offset += bytesDecoded;
            }
        }

        // IAudioSamples samples = IAudioSamples.make(numSamples, numChannels)
    }

Errror:
20:24:25,569 INFO  [stdout] (http-0.0.0.0-0.0.0.0-8081-2) 20:24:25.568 [http-0.0.0.0-0.0.0.0-8081-2] WARN  com.xuggle.xuggler - Attempting to decode when not ready; codec not opened (../../../../../../../csrc/com/xuggle/xuggler/StreamCoder.cpp:873)

20:25:41,517 INFO  [stdout] (http-0.0.0.0-0.0.0.0-8081-2) 20:25:41.517 [http-0.0.0.0-0.0.0.0-8081-2] WARN  com.xuggle.xuggler - Attempting to decode when not ready; codec not opened (../../../../../../../csrc/com/xuggle/xuggler/StreamCoder.cpp:873)

20:25:42,621 INFO  [stdout] (http-0.0.0.0-0.0.0.0-8081-2) 20:25:42.621 [http-0.0.0.0-0.0.0.0-8081-2] WARN  com.xuggle.xuggler - Attempting to decode when not ready; codec not opened (../../../../../../../csrc/com/xuggle/xuggler/StreamCoder.cpp:873)

20:25:43,485 INFO  [stdout] (http-0.0.0.0-0.0.0.0-8081-2) 20:25:43.485 [http-0.0.0.0-0.0.0.0-8081-2] WARN  com.xuggle.xuggler - Attempting to decode when not ready; codec not opened (../../../../../../../csrc/com/xuggle/xuggler/StreamCoder.cpp:873)

A: Have u set audioCoder as IStreamCoder??
and an IStreamCoder open() doesn't need arguments, jus give audioCoder.open() , and this is only if audioCoder is an IStreamCoder object.


text:
Q: How to logout shell in dialog script? I tried logout, exit, TMOUT.
If I use logout, it prompts logout: not login shell: use 'exit'.
If I use exit, it just exit the dialog, not the shell.
If I set TMOUT=1, TMOUT will remain no changed.
Can I logout shell in dialog script?
#!/bin/bash

HEIGHT=15
WIDTH=40
CHOICE_HEIGHT=4
OPTIONS=(1 "Logout")

CHOICE=$(dialog --clear \
                --backtitle "back" \
                --title "title" \
                --menu "menu" \
                $HEIGHT $WIDTH $CHOICE_HEIGHT \
                "${OPTIONS[@]}" \
                2>&1 >/dev/tty)

clear
case $CHOICE in
        1)
            logout
            TMOUT=1
            exit
            ;;
esac

Edit 1:
This is also not working
//menu.sh
case $CHOICE in
        1)
            exit 99
            ;;
esac

./menu.sh
#!/bin/bash
if [ $? -eq 99 ]
then
    logout
fi

A: Bash script is executed in a subshell when you call it directly. You need to source it if you'd like to run it in the current shell.
source Script.sh

Or simply
. Script.sh

A: In your script you could set the exit value (e.g. exit 99) then check for it in the way you call the script:
./Script.sh; if [ $? -eq 99 ] ;then exit fi

You can set up the terminal session to close on it's own:
Terminal.app > Preferences > Profiles > Shell
    - "When the shell exists:"
        > Close if the shell exited cleanly
    - "Ask before closing:"
        (•) Never
        -- OR --
        (•) Only if there are....

You can kill terminals from the script :
killall Terminal


text:
Q: Graphics Device initialization failed for : es2, sw I'm using the next release of Java:
 openjdk version "1.8.0_111"
 OpenJDK Runtime Environment (build 1.8.0_111-8u111-b14-2ubuntu0.16.04.2-b14)
 OpenJDK 64-Bit Server VM (build 25.111-b14, mixed mode)

My system is ubuntu 16.04 Lts, I tried to execute a shell script file, using the terminal, I get the next error message
Graphics Device initialization failed for :  es2, sw
Error initializing QuantumRenderer: no suitable pipeline found
java.lang.RuntimeException: java.lang.RuntimeException: Error    initializing QuantumRenderer: no suitable pipeline found
 at com.sun.javafx.tk.quantum.QuantumRenderer.getInstance(QuantumRenderer.java:280)
at com.sun.javafx.tk.quantum.QuantumToolkit.init(QuantumToolkit.java:227)
at com.sun.javafx.tk.Toolkit.getToolkit(Toolkit.java:173)
at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:209)
at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:675)
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:695)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$152(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
 Caused by: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found
at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.init(QuantumRenderer.java:94)
at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:124)
... 1 more
Exception in thread "main" java.lang.RuntimeException: No toolkit found
at com.sun.javafx.tk.Toolkit.getToolkit(Toolkit.java:185)
at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:209)
at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:675)
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:695)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$152(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)

Could you tell me please what would the cause of thsi message.

A: At present, I can provide the exact instructions for Ubuntu 18.x. They may also work on other Debian-based systems. If you're using another OS, perhaps the package names listed below will lead you in the right direction.
First, you need to discover which versions of OpenJFX are available on your distribution. Run this from the command line:
$ apt-cache policy openjfx

In the Version table section, you'll likely see two choices. I currently see 11.0.2+1-1~18.04.2 and 8u161-b12-1ubuntu2 . The version beginning with 11 is the default, even though you've (presumably) installed openjdk-8-jdk. You'll want the version beginning with the number 8. At the time of writing, this is 8u161-b12-1ubuntu2.
To install OpenJFX and the related packages (assuming you're doing development work), first make sure you've uninstalled any Java 11-based packages, because they'll (un)happily coexist with JDK 8, and cause you lots of problems.
$ sudo apt remove openjfx openjfx-source libopenjfx-java libopenjfx-jni

Next, install the correct versions (substituting whatever version you saw listed in the policy query for 8u161-b12-1ubuntu2):
$ sudo apt install openjfx=8u161-b12-1ubuntu2 openjfx-source=8u161-b12-1ubuntu2 libopenjfx-java=8u161-b12-1ubuntu2 libopenjfx-jni=8u161-b12-1ubuntu2

Update: I noticed the next day that sudo apt upgrade (or automatic system updates) would "upgrade" the jfx packages I'd so carefully chosen the version for. Here's how to prevent that from happening:
$ sudo apt-mark hold openjfx openjfx-source libopenjfx-java libopenjfx-jni
 openjfx set on hold.
 openjfx-source set on hold.
 libopenjfx-java set on hold.
 libopenjfx-jni set on hold.

You can run sudo apt showhold any time to list the packages that are being held back.
Having those old-but-good packages installed resolved all the problems for me. I hope they can help you as well.


text:
Q: Why the R script provide by site pubmed is not executing ? Is it possible to make it run? If possible, I need help to understand why the code below is not working. This code I was found on the page: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3817376/. Would it be possible for any expert member to adapt it to work?
library(ggplot2)
library(nlme)
head(Theoph)

ggplot(data=Theoph, aes(x=Time, y=conc, group=Subject)) + geom_line() + labs(x="Time (hr)", y="Concentration (mg/L)")

p <- ggplot(data=Theoph, aes(x=Time, y=conc, group=Subject)) + geom_line() + labs(x="Time (hr)", y="Concentration (mg/L)") + stat_summary(fun.y=median, geom="line",aes(x=ntpd, y=conc, group=1), color="red", size=1)

print(p) # "p" is a ggplot object

# create a flag for body weight

Theoph$WT <- ifelse(Theoph$Wt<70, "WT < 70kg", "WT >= 70kg")
p + facet_grid(.~WT)""t>

A: There are a couple things to help you run this.
First, you have curly/smart quotes " in your code, and should just use plain quotes ". Sometimes we get this excess formatting when we copy/paste code from other sources like this.
Second, you need to use the supplementary materials to calculate ntpd, add to the Theoph dataset.
Below is code that seemed to work at my end to reproduce the spaghetti plots.
library(ggplot2)
library(nlme)

# Reference:
# https://ascpt.onlinelibrary.wiley.com/doi/10.1038/psp.2013.56

head(Theoph)

ggplot(data = Theoph, aes(x = Time, y = conc, group = Subject)) +
  geom_line() +
  labs(x = "Time (hr)", y = "Concentration (mg/L)")

##################################################################################
## we need some data manipulation for Figure 1(e) and Figure (f)
## below code is how to calculate approximate ntpd (nominal post time dose)
## "ntpd" is used for summarizing conc data (calculate mean at each time point)
## create body weight category for <70 kg or >=70 kg
##################################################################################

#--create a cut (time intervals)
Theoph$cut <- cut(Theoph$Time, breaks=c(-0.1,0,1,1.5, 2,3,4,6,8,12,16,20,24))

#--make sure each time point has reasonable data
table(Theoph$cut)

#--calcuate approximate ntpd
library(plyr)
tab <- ddply(Theoph, .(cut), summarize, ntpd=round(mean(Time, na.rm=T),2))

#--merge ntpd into Theoph data
Theoph <- merge(Theoph, tab, by=c("cut"), all.x=T)

#--sort the data by Subject and Time, select only nessesary columns
Theoph <- Theoph[order(Theoph$Subject, Theoph$Time),c("Subject","Wt","Dose","Time","conc","ntpd")]

#--create body weight category for <70 kg or >=70 kg for Figure 1(f)
Theoph$WT <- ifelse(Theoph$Wt<70, "WT < 70kg", "WT >= 70kg")

#--end of data manipulation
##################################################################################

p <- ggplot(data = Theoph, aes(x=Time, y=conc, group=Subject)) +
  geom_line() +
  labs(x="Time (hr)", y="Concentration (mg/L)") +
  stat_summary(fun = median, geom = "line", aes(x = ntpd, y = conc, group = 1), color = "red", size=1)

print(p)

p + facet_grid(. ~ WT)


text:
Q: Angular 6 - Router can't navigate to next page I have a method for authentification user before he opens any component.
When I receive isAuthorized from service, I simply need to forward a user to component he requested. In my case, I stay on the same page, the app works normally no errors, no logs to trace this problem, it simply stays on the page. Can anyone tell me what I do wrong?
 AuthUser() {
    let auth = new Authorize();
    auth.Credentials.CredentialsData1 = this.email;
    auth.Credentials.CredentialsData2 = this.password;
    auth.ResourceId = this.authGard.requestedComponentID;

    this.http.post(this.appGlobal.BASE_SERVER_ADDRESS + 'api/AppServer/Authorize', auth).subscribe((res) => {
      if (res['IsAuthorized'] == true)
        this.router.navigate([this.authGard.requestedComponent]);
      else this.router.navigate(['auth/unauthorized']);
    });
  }

A: I have recently helped out someone on my team with a similar issue.
I'm assuming that the component in "FuelDashboard" is protected via an authentication check.
However, I'm not seeing you saving the res['IsAuthorized'] response.
Q) Does the component in "FuelDashboard" check for authentication?
Q) Does an unauthorized request return the user to the login page?
Possible answer-  You will have to save the response ( res['IsAuthorized'] ) into a persistent location so that FuelDashboard can check if the user is authenticated.

A: Is your route FuelDashboard? I believe you are getting the component name and not the route name from the this.authGuard.requestedComponent and not the route you created at your app.routing.module.ts or whatever routing you opted in.


text:
Q: Does Excel does not recognize SQL Server Variable syntax? I have a query that builds a table in excel. My job is to parameterize it with date variables. My boss wants to be able to change the year of a query that is built-in .xls without having to copy/paste the query in SQL Server to ctrl + F and replace years and dates, etc.
So, I parameterized this with the declaration and initialization of the date params on the top, however, when I leave them as set Year1 = '', I thought Excel would recognize the empty variable and interface a dialog box for the user to enter instead it errors out until I directly type 2017 on the query itself.
My question, is there a way to enter that data on the .xls spreadsheet before the query is refreshed as a user input pop up or dialog box?
declare @Year1 varchar(8)
set @Year1 = '2018'

select * from table A

A: If I correctly understand your question, you need to create a stored procedure with your query and then set some cells in excel to enter the parameters (like dates) for example. Excel will send the values in those cells to the stored procedure in the SQL Server.
Please follow the steps in this tutorial:
Getting Data from SQL Server in Excel using parameters


text:
Q: Count of messages in rabbitMQ queue using spring boot i wanted help regarding how to save the count of messages in a RabbitMQ queue to an object. so this data can be used by some other functionality. I found some answers but not for Spring boot. Please help!

A: The AMQP protocol in the Spring Boot application is based on the Spring AMQP project.
For your task to reach as high API level as possible you can do like this:
@Autowired
private RabbitTemplate rabbitTemplate;
...

AMQP.Queue.DeclareOk declareOk = this.rabbitTemplate.execute(channel ->
                        channel.queueDeclare(QUEUE_NAME, true, false, false, queueArgs));

declareOk.getMessageCount();

And apply appropriate queue options for that queueDeclare().


text:
Q: How to "control" when Firestore.getAll(...promises) stops by reject Context:
I 'm doing a cloud function to send pushes to multiple users. I need to recover the info of each user to know some data like, name, country..etc..
Problem:
Actually I recover the list of user Id's and when I got it, then I create an array of promisesto recover all the info:
var usersPromises = []
for (var i = 0; i < usersInRange.length; i++) {
   usersPromises[i] = firestore.collection("users").doc(usersInRange[i])
}

Then I recover and send the push using firestore.getAll():
firestore.getAll(...usersPromises).then(results => {
   for(snapshot in results){
      if(snapshot.exists){
         ......
         var user = snapshot.data()
         ......
      }else{
         ......
      }
   }
})

This solution is actually working "fine" almost all the time. But at this moment the Firestore db has some users that do not exist or something is wrong, because the method getAll()stops before finishing all the promises. I know it because no push is sent, and in the console, just say that the method has finished.
Reading in SO and documentation, I saw, that getAll stops if some promise is "broken". (all or nothing)
And here is where I'm lost. How can I "force" or do in another way, to just "jump" this promises that can't be completed?
P.S:
I tried to do with a "for" but It seems to omit some promises:
for (var i = 0; i < usersPromises.length; i++) {
   usersPromises[i]
      .get()
      .then(snapshot => {
        if(snapshot.exists){
           ......
           var user = snapshot.data()
           ......
        }else{
           ......
        }
      })
}

A: I think its not a problem of getAll. I have tested like this:
const firestore = new Firestore();

let doc = []
doc[0] = firestore.doc('test/test');
doc[1] = firestore.doc('test/test1');
doc[2] = firestore.doc('test/doc');

firestore.getAll(...doc)
.then(result=> result.forEach(doc => console.log(doc._fieldsProto)))
.catch(err=>console.log(err));

In my database I have 'test/test' and 'test/doc' document, but I do not have  'test/test1' and results look like this:

So we just get undefined on document that is not exist and that's all. I suggest to add catch and see if there is any exception. When I have been writing the test the function was interrupted by typo mistake in inner function.
I hope this will help!


text:
Q: Read clipboard from text editor vs spreadsheet in R I have following text (indented by tabs) on a text editor (Geany) and also in Libreoffice spreadsheet in Debian Stable Linux:
Aorta
    coronary
    brachio cephalic
    left common
        external carotid
        internal carotid
            ophthalmic
    left subclavian
        vertebral
        brachial
    left iliac
    right iliac

I copy it and use following command to paste it in R:
library(psych)
dat = read.table(text = readClipboard(), sep="\t", header=FALSE, fill=TRUE, strip.white=TRUE, stringsAsFactors=FALSE)

It works well when it is copied from spreadsheet:
dat
      V1               V2               V3         V4
1  Aorta
2                coronary
3        brachio cephalic
4             left common
5                         external carotid
6                         internal carotid
7                                          ophthalmic
8         left subclavian
9                                vertebral
10                                brachial
11             left iliac
12            right iliac

But when copied from text editor there is an error. Note empty line 7 and 'ophthalmic' coming in first variable:
dat
           V1               V2               V3
1       Aorta
2                     coronary
3             brachio cephalic
4                  left common
5                              external carotid
6                              internal carotid
7
8  ophthalmic
9              left subclavian
10                                    vertebral
11                                     brachial
12                  left iliac
13                 right iliac

What could be the cause and how can this be corrected?

A: Here's a demo reading directly from a tempfile:
x <- tempfile()

cat("1\t2", "1\t2", "1\t2", "1\t2", "1\t2",
    "1\t2", "1\t2", "1\t2\t3", "1\t2", "1\t2",
    file=x, sep="\n")

## readClipboard() or readLines(textConnection(readClipboard()))
infile <- readLines(x)
fields <- max(count.fields(textConnection(infile), sep = "\t"))

## Will demonstrate the behavior you describe
read.table(text = infile,
           sep = "\t",
           header = FALSE,
           fill = TRUE)

## Will do what you expect
read.table(text = infile,
           col.names = paste0("V", sequence(fields)),
           sep = "\t",
           header = FALSE,
           fill = TRUE)

Thus, try replacing readLines with readClipboard() directly, or wrap readClipboard() in textConnection().


text:
Q: What's an example of Ruby code that's "too clever"? I was having a discussion with some programmer friends who said that they see Ruby programmers (in particular) producing a lot of code that's "too clever". So I'm wondering what would that look like? I'm referring to the unnecessary use of an obscure language feature in a context in which something straightforward would have worked just as well or better. Know any good Ruby examples of this?

A: class Tree
  def initialize*d;@d,=d;end
  def to_s;@l||@r?"<#{@d},<#{@l}>,<#{@r}>>":@d;end
  def total;(@d.is_a?(Numeric)?@d:0)+(@l?@l.total: 0)+(@r?@r.total: 0);end
  def insert d
    alias g instance_variable_get
    p=lambda{|s,o|d.to_s.send(o,@d.to_s)&&
      (g(s).nil??instance_variable_set(s,Tree.new(d)):g(s).insert(d))}
    @d?p[:@l,:<]||p[:@r,:>]:@d=d
  end
end

A: The double-bang: !!something
I'm not gonna write what it does. Forget that you ever saw this syntax.

A: Any use of metaprogramming without having thought damn hard about whether there's a better way to acheive this using the normal, non-'meta' idioms of the language, I tend to find annoying.
An obsession with "DRY" (don't repeat yourself) where some fiendish piece of metaprogramming spaghetti is invoked to avoid repeating yourself, say, twice in a simple and actually-more-straightforward-and-readable-than-the-alternative fashion.
Any use of 'eval' in particular. As metaprogramming goes, this one should be your absolute last resort after trying everything else. eg a lot of rubyists appear not to have heard of Class#define_method.

A: The output phase of yaml.rb; that's why I co-authored zaml.rb.  The standard yaml version does all sorts of metaprogramming (it was originally written by why-the-lucky-stiff, who I generally admire) but by replacing it with a straight forward hierarchical version that directly maps to the class tree we were able to eliminate several O(n^3) cases, resulting in a factor of ten speedup for cases of interest, fix several bugs, and do so in a fraction of the code.
Plus, even people who aren't ruby gurus can see what it does.

A: Many of the examples in this article would seem to qualify:
21 Ruby Tricks You Should Be Using In Your Own Code.
The title of the article was a bit of a giveaway, given that it reads "Should" instead of "Should Not". Code "should" be transparent. Code "should not" be tricky.

A: After giving a straight answer to your question, I'd like to also dispute the premise; whenever a group of programmers characterizes the users of another language in this way, the odds are that they are telling you more about themselves than about the community they are describing.
You could, for example, accuse c programmers of being too obsessed with low level details, or haskell programmers with being blinded by their desire for functional purity; perl mongers for brevity, etc.  But you would, IMHO, by getting the causality backwards when you do so.
When I want to write a program that is best expressed in a certain style, I try to choose a language that supports that style.  Sometimes you want a tool that lets you do unusual things, and for such a task having a language such as ruby is as valuable as having mathematica for math or javascript for browser manipulation in your toolkit.  If I want to play with typography I hop into postscript because that's what it's best at.
It's like saying "Have you ever noticed that people who use power drills are always poking holes in things?"  It's true, but it kind of misses the point.

A: I'm not sure if this qualifies as "too clever," but I have seen code that made me wonder if the author was either a genius or an idiot.  One developer seemed to have a rule that no method should have more than two lines of code.  That pushed the call stack very deep and made debugging rather difficult.  The upside is that his overall design was very abstract and even elegant from a distance.

A: Cucumber (or RSpec Stories)
Quoted from the above RSpec Stories link:

Based around plain text descriptions
  of application behaviour, it lets you
  write integration tests with good
  reuse and good diagnostic reporting.
For example, here's a story I wrote to
  check the login process.
Story: login as an existing user
    As an unauthenticated user
    I want to log in to Expectnation
    So I can see my account details

    Scenario: login details are correct
            Given an event provider
            And my test@example.org account
            When I log in with email test@example.org and password foofoo
            Then I will be logged in
            And I will be shown the account page

The words such as "Given", "When" and
  "Then" are cues to the story runner to
  execute some code. Behind the story
  sits a collection of steps. Here's a
  couple of steps from this test:
  Given "my $email account" do |email|
    @user = find_or_create_user_by_email({:email => email,
      :password => 'foofoo',
      :password_confirmation => 'foofoo'})
  end

  When "I log in with email $email and password $password" do |email, password|
    post '/user/account/authenticate',
      :user => {:email => email, :password => password}
  end

Notice how a clever bit of string
  matching allows you to pass parameters
  from the story prose.
With a small bit of bolting together, the prose stories are then run as code and the tests executed.

A: It depends. (I love "it depends" questions)
It depends on the knowledge of the writer and reader. I used to think the use of Symbol#to_proc in Rails was unnecessarily arcane, for example, preferring
a.map { |e| e.downcase }

to
a.map(&:downcase)

Now I'm happy when I read it, although I still don't think to write it.
There are areas of libraries (Rails and others) where I have felt excessive and self-indulgent metaprogramming may have occurred but again the division between "too clever" and "really very clever indeed" is often paper-thin. DSLs are a good area: the ways in which "macros" are made available within classes (think of all that declarative goodness in things like ActiveRecord::Base or ActionController::Base) is very hard for a relative novice to understand and would probably seem like over-cleverness. It did to me. Now I find myself referencing the same code for guidance as I implement similar capabilities.

A: method_missing can be abused and it's one of those things that may cause you to pull your hair out when you have to fix a bug 3 months after you've written code.

A: Take a look at the source of Markaby. Insanity.

A: You shouldn't have to go from method to method to method to try to figure out what in the hell something is doing, for the sole purpose of not repeating a few lines of code. Being too focused on the LOC count and ultra-skinny methods might feel cool at the time but is time-consuming for someone else trying to debug or follow the code (and that someone may be you months later).

A: compare:
if MODELS.keys.inject(true) {|b, klass| b and klass.constantize.columns.map(&:name).include? association.options [:foreign_key]} then
  # ...
end

1 line (if), 132 chars, 132 avg len, 22.9 flog
vs
fk = association.options[:foreign_key]
columns = MODELS.keys.map { |key| key.constantize.columns.map { |c| c.name } }
if columns.all? {|column| column.include? fk} then
  # ...
end

4 lines, 172 chars, 43 avg chars, 15.9 flog
much faster too.
Original author actually argued maintainability for the first version.

A: Recently uncovered this monster:
def id
  unless defined?(@id)
    @id = if id = local_body.to_s[/(?:#\s*|@[[:punct:]]?)#{URL_REGEX}/,1]
            id.to_i
          end
  end
  @id
end

Not that I disagree with caching a calculation, it could just be far more clear.


text:
Q: Wordpress blog page title font not appropriate [Link for blog][1]
In the above Blog page how can i increase font for title of every post?

A: Add following in style.css. Appearance->Editor->style.css
.entry-title
{
font-size:30px;
}

A: Find Class/ID of element you want to change with tool like Element Inspector of firefox/chrome then add appropriate styling to your element.


text:
Q: Passing an array as a parameter with default values into int main() I am having difficulty passing an array as an argument into int main() with default values.
For example:
int main(int a){}

works wonderfully. As does
int main(int a = 1){}

Passing int main() an array also works wonderfully:
int main(int a[3])

However, combining these two concepts seems break:
int main(int a[1] = {0,1})

After a significant amount of googleing, I haven't found a solution.
please help me SO, you're my only hope!
EDIT
The purpose of this, in short, is to make my code as little lines as possible, for a challenge my professor recently issued (not for points -- just for learning). The assignment is to create a recursive "12-days-of-chirstmas" program
This is my current program
#include <iostream>
#include <string>
void p(std::string v){std::cout<<v;}
std::string v[13] = {"A Partridge in a Pear Tree.\n\n","2 Turtle Doves\n","3 French Hens\n","4 Colly Birds\n","5 Gold Rings\n","6 Geese-a-Laying\n","7 Swans-a-Swimming\n","8 Maids-a-Milking\n","9 Ladies Dancing\n","10 Lords-a-Leaping\n","11 Pipers Piping\n","12 Drummers Drumming\n",""};
int main(){
    switch(v[12].length()){
        case 12:system("pause"); return 0;
        case 11:p(v[11]);
        case 10:p(v[10]);
        case 9: p(v[9]);
        case 8: p(v[8]);
        case 7: p(v[7]);
        case 6: p(v[6]);
        case 5: p(v[5]);
        case 4: p(v[4]);
        case 3: p(v[3]);
        case 2: p(v[2]);
        case 1: p(v[1]);
        case 0: p(v[0]);
    }v[12] += "0";
    main();
}

I would like to pass in the array of verses as an argument to main instead of declaring it above the function.  I know, not the most memory/stack conscious. But it would eliminate a line :)

A: Addressing the array passing rather than the unlikely use of main(), due to the array really being passed as a pointer, you can do it like this:
int defaultInit[2] = {0,1}; // {0,1} means 2 elements for the array.

int f(int arg[2] = defaultInit)
{
    return 0;
}

A: The main() function should only receive none or two parameters the quantity of command line arguments and the arguments itself.
int main(int argc, char* argv[]) {
}

Where argc is the quantity of arguments and argv is one array of C-strings containing the arguments.
EDIT:
He changed the focus.
You can reduce the number of lines doing this:
void loop(int i) {
    if (i < 0) { v[12] += "0"; return; }
    p(v[i]);
    loop(i-1);
}
int main() {
    if (v[12].size() == 12) return;
    loop(v[12].size());
    main();
}

A: This link explains it best:

In C++ it is not possible to pass a
  complete block of memory by value as a
  parameter to a function, but we are
  allowed to pass its address.

That's why you can declare a function with
void foo (int bar[]);

but you can't declare
void foo (int bar[] = {0 ,1});

It has nothing to do with main().

A: #include <stdio.h>
int go(int);
int main( int argc, char*argv[]) {
go(0);
}
int go(int argc) {
const char* lyrics[] = {...};
printf("On the %d%s day of Christmas\nmy true love gave to me\n",argc,
  argc==1?"st":argc==2?"nd":argc==3?"rd":"th" );
for(int i=argc-1;i>0;--i) { printf("%d %s\n",i+1,lyrics[i]); }
printf("%s\n\n",lyrics[0]);

if( argc < 12 ) go(argc+1);
return 0;
}