text:
Q: dynamic parametrized queries using Spring data mongodb I am looking for a way to dynamically create parametrized queries. In essence, I want to decouple the queries from the application and make them configurable.
For instance, I want to create a query with parameters, such as
{ firstName: ?0 }

As you probably know, this is perfectly feasable in Spring data mongodb using an interface:
interface MyQuery {

  @Query("{firstName: ?0}")
  public Person getByFirstName(final String name);
}

But this couples my query at compile time, while I want to change them at runtime.

I can't however find a way to use this mechanism dynamically. The particular class that is used under the hood is StringBasedMongoQuery, and uses heavy reflection utilities in order to determine the query, the parameters, the returntype, etc. You can manage most of it using Groovy I think, however Annotations seem to be a pickle.
This makes me think I chose the wrong way to approach this problem.

I myself only see a few options left:

*

*Reimplement Spring's fancy query parsing for mongo myself (seems a lot of work)

*Implement poor man's query parameter replacement myself. (this will not be flexible, will not yield correct result on null parameters...)

I'm at loss here, it's too bad that I can't seem to use StringBasedMongoQuery standalone, it seems to be coupled to reflection.

Update:
My suggestions seem pointless here, as I noticed also Spring data mongodb's StringBasedMongoQuery does not support 'dynamic' queries with nullable parameters; in fact this is quite logical, it is quite hard to cut parts out of your query when a parameter is null, and quite impossible to do it right.
The following sheds some light on the issue: https://jira.spring.io/browse/DATAJPA-209
So it seems my possible options have shifted to:

*

*We make different queries and the query used depends on the parameters that are available. This creates a possible nightmare for maintanance.

*We expose a groovy or other JVM script that allows us to use one of the available Criteria-esque API's of Spring or the mongodb Java driver, that will then build the query for us. The disadvantage of this is that someone that wants to configure the queries now has to know Java in the very least.

*We make our queries null-safe where needed at the expense of readability.

A: This method takes a map of parameters with their values and forms a query based on it. Obvious minus for this solution is that formed query is based on ANDs. So, if you need a dynamic query which consists only of logical ANDs this is the way to go. I'm still working on a fully dynamic query with all logical operations. Written in Groovy:
Query buildSearchQuery(Map searchParams, List resultFields, int limit) {
Query query = new Query()
searchParams.each {
    if (it.getValue() != null && it.getValue() != '') {
        query.addCriteria(Criteria.where(it.getKey()).regex('^'+ it.getValue(), 'i'))
        }
    }

    resultFields.each {
        query.fields().include(it)
    }
    query.limit(limit)

    query
}

A: I found a better and easier solution to this problem than the suggestions I already made myself here in this post. I'll tell you how I will solve this problem for future reference for other.
While mongodb has nothing like query parameters or anything like that, we can make stuff a lot easier by using some other rather unique constructs mongodb offers, together with a strict structure. We can adhere to this structure because it concerns dynamic configurable queries for users.
Our structure is simple, and as follows. We have a basic query structure that looks as follows:
{ $and: []}

We define one basic query that will always be filled in. This can be as simple as the empty JS object. Like this, our query becomes
{ $and: [{}] }

So, this just queries everything. Now we can define a subquery for each condition that can be dynamic. We can choose to add this query to the $and if it meets the conditions. Since we eadhere to put everything in an and construct, we know how the query will look, and we don't need very fancy parameter substitution to get something very flexible to work easily.
A query can become for instance:
{ $and: [{}, {active: true}, {started: false}]}

And we can add those little subqueries for added and started whenever we want.

A: Another way that you could solve this is to use the Example object... I'm leveraging spring-data-mongodb btw so not sure if that applies for you or not...
public interface PetRepository extends MongoRepository<Pet, String>{
}

...
@Service
public class PetService {

private Logger logger = LogManager.getLogger(PetService.class);

@Autowired
PetRepository petRepository;

public List<Pet> findPetsByExample(String name, String sex, String color, Integer age){
    //Guard clauses omitted...
    Example<Pet> example = Example.of(new Pet(name, sex, color, age));
    return Lists.newArrayList(petRepository.findAll(example));
}

Now what this is doing is leveraging the QueryByExampleExecutorclass that's extended within the MongoRepository to under the hood do a comparison of the supplied example pet with the contents of your documents. This will only look at fields on our example pet that have supplied values and will ignore Nulls in it's comparison. You can also include custom matchers as well to perform further filtering. Here's a link to some example documentation: https://github.com/spring-projects/spring-data-examples/tree/master/mongodb/query-by-example


text:
Q: What is the best method of getting Int32 from first four bytes of GUID? I'm just wondering if it exists better solution for this.
BitConverter.ToInt32(sample_guid.ToByteArray(), 0)

A: I don't think there's a better solution than this.

A: I don't know if it's better, but it is easier to read:
Int32.Parse(sample_guid.ToString().SubString(0,1));
I'm a junior developer, admittedly, but the above reads easier to me than a byte conversion, and on a modern computer it would run indistinguishably quickly.

A: Dunno about a better solution, but I hope you don't intend to use that Int32 as a random (or unique) value.
You cannot depend on any sub part of a Guid to be unique. Guid is assumed to be unique, only in its entirety.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Easily make a copy of my android application I have an android application for one client, and he wants to make a 99% similar app for different country.
Almost everything is the same, only a few bitmaps would need to be replaced, address of API server will change, language file will change, but the code should stay the same, BUT I will need a different package name.
What is a simple way to make a clone of the app that will allow me to make code changes to one version, merge them with the new version (or versions), but keep the package name?
Or should I have everything in one project folder and then write and run some script that will change package names and swap content files? My iOS friend will probably need a few different #defines, but what should I do here, so I can maintain both versions in the future?

A: declare your original project as library, then create 2 new projects each for one language and let them include original project as library
then you can go ahead and just override bitmaps and constants you need.
this way, if you need any changes in core functionality, you just change your library project, and changes will propagate to both of extending projects
read more about library projects here:
https://developer.android.com/tools/projects/index.html#LibraryProjects


text:
Q: set column values in octave dataframe I have two sets of data as follows;
file a:
 1476356687
 1476356689
 1476356690

file b:
 "2016-10-13 12:04:47.706193",1000,516130
 "2016-10-13 12:04:49.225305",2000,516130
 "2016-10-13 12:04:50.439240",3000,516130

 new_col=dataframe("file_a")
 df=dataframe("file_b")

>> size(new_col)
ans =

   3     1

>> size(df)
ans =

   3     3

>> new_col(1:3,:)
ans = dataframe with 3 rows and 1 columns
_1    new_col
Nr     double
 1 1476356687
 2 1476356689
 3 1476356690
>> df(1:3,:)
ans = dataframe with 3 rows and 3 columns
Src: import_nbu_op
_1                         X1     X2     X3
Nr                       char double double
 1 2016-10-13 12:04:47.706193   1000 516130
 2 2016-10-13 12:04:49.225305   2000 516130
 3 2016-10-13 12:04:50.439240   3000 516130

I am trying to either set column 1 of df to be new_col, or construct a new dataframe of new_col and columns 2:end of df
I have tried a bunch of things, but can't figure out the magic incantation to get it to work.... coming from something like python, this is driving be bonkers ;)
I have tried,
>> df=dataframe(new_col,df)
error: Concatenating dataframes: use cat instead
error: called from
    dataframe at line 568 column 5
>> df=cat(new_col,df)
error: Incorrect call to cat
error: called from
    cat at line 197 column 7
>> df=cat(1,new_col,df)
error: Different number of columns in dataframes
error: called from
    cat at line 50 column 11
>> df=cat(2,new_col,df)
df(1): out of bound 0
error: called from
    display at line 66 column 7
>> df=cat(0,new_col,df)
error: Incorrect call to cat
error: called from
    cat at line 197 column 7
    display at line 66 column 7
>> cat(2,1,new_col,df)
error: Different number of rows in dataframes
error: called from
    cat at line 109 column 11
>> cat(2,2,new_col,df)
error: Different number of rows in dataframes
error: called from
    cat at line 109 column 11
>> horzcat(new_col,df)
error: df(2): out of bound 1
error: called from
    display at line 66 column 7
>> df(:,1)=new_col
error: cast: TYPE must be a string
error: called from
    cast at line 67 column 5
    df_matassign at line 452 column 31
    subsasgn at line 217 column 10
>> dataframe(df,new_col)
error: Concatenating dataframes: use cat instead
error: called from
    dataframe at line 568 column 5

Then, Eureka I thought! Almost there! at least I can add the col to the frame now...
>> dataframe(df,new_col.array(:,:))
ans = dataframe with 3 rows and 4 columns
Src: import_nbu_op
 _1                         X1     X2     X3          X
 Nr                       char double double     double
  1 2016-10-13 12:04:47.706193   1000 516130 1476356687
  2 2016-10-13 12:04:49.225305   2000 516130 1476356689
  3 2016-10-13 12:04:50.439240   3000 516130 1476356690

Excellent. So I just need to swap df and new_col around to create the frame  I (almost) want! just a couple of steps away :)
>> dataframe(new_col.array(:,:),df)
error: Concatenating dataframes: use cat instead
error: called from
    dataframe at line 568 column 5

Argh! How the what why?
>> cat(1,new_col,df(:,2:end))
error: Different number of columns in dataframes
error: called from
    cat at line 50 column 11
>> cat(2,new_col,df(:,2:end))
error: df(2): out of bound 1
error: called from
    display at line 66 column 7
>> horzcat(new_col,df(:,2:end))
error: df(2): out of bound 1

Help! - I've tried more permutations of various things than this, but it all ends the same way :(

A: I got it to work using its .cell property as opposed to .array you tried:
>> concatenated = dataframe(cat(2, new_col.cell, df.cell))
concatenated = dataframe with 3 rows and 7 columns
_1 unnamed          X unnamed1 unnamed2                         X1     X2     X3
Nr    char     double   double     char                       char double double
 1         1.4764e+09        1          2016-10-13 12:04:47.706193   1000 516130
 2         1.4764e+09        2          2016-10-13 12:04:49.225305   2000 516130
 3         1.4764e+09        3          2016-10-13 12:04:50.439240   3000 516130

However, this results in columns 1,3 and 4 as artefacts (presumably 1 and 4 is from an empty space character, and 3 is the previous 'ascending index' numbers). So I had to remove these to get my dataframe:
>> concatenated(:,[1,3,4]) = []
concatenated = dataframe with 3 rows and 4 columns
_1          X                         X1     X2     X3
Nr     double                       char double double
 1 1.4764e+09 2016-10-13 12:04:47.706193   1000 516130
 2 1.4764e+09 2016-10-13 12:04:49.225305   2000 516130
 3 1.4764e+09 2016-10-13 12:04:50.439240   3000 516130

I agree though, this package does seem pretty broken.
PS. The dataframe pkg is specific to octave. This question is not matlab-related. Matlab offers dataset and table classes (and I've also seen a datamatrix class, and a dataframe fileexchange one).


text:
Q: MySQL Select multiple columns group by sorted columns values I have this table columns structure:
id - n1 - n2 - n3

And here it is with some dummy data:
id - n1 - n2 - n3
1 - 3 - 2 - 1
2 - 6 - 5 - 7
3 - 2 - 3 - 1
4 - 1 - 6 - 5
5 - 5 - 6 - 7
6 - 3 - 5 - 6

And the idea is to Select and count each unique distinct group of n1, n2 and n3 in sequence.
So, for example, we could get this result:
total - n1s - n2s - n3s
2 - 1 - 2 - 3
2 - 5 - 6 - 7
1 - 1 - 5 - 6
1 - 3 - 5 - 6

Can you help me set the state to achieve that??
I am trying to attempt that without multiple selects and PHP array sorting...
Thanks.

A: Consider the following - a normalised dataset...
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL
,n INT NOT NULL
,val INT NOT NULL
,PRIMARY KEY(id,n)
);

INSERT INTO my_table VALUES
(1, 1, 3),
(1, 2, 2),
(1, 3, 1),
(2, 1, 6),
(2, 2, 5),
(2, 3, 7),
(3, 1, 2),
(3, 2, 3),
(3, 3, 1),
(4, 1, 1),
(4, 2, 6),
(4, 3, 5),
(5, 1, 5),
(5, 2, 6),
(5, 3, 7),
(6, 1, 3),
(6, 2, 5),
(6, 3, 6);

Here's a quick (to write) and dirty solution. Faster / more elegant solutions are available...
SELECT vals
     , COUNT(*) total
  FROM
     ( SELECT id
            , GROUP_CONCAT(val ORDER BY val) vals
         FROM my_table
        GROUP
           BY id
     ) x
 GROUP
    BY vals;
+-------+-------+
| vals  | total |
+-------+-------+
| 1,2,3 |     2 |
| 1,5,6 |     1 |
| 3,5,6 |     1 |
| 5,6,7 |     2 |
+-------+-------+

A: We just need expressions to "sort" the values in columns n1, n2 and n3.  If we have that, then we can do a simple GROUP BY and COUNT.
SELECT COUNT(1) AS total
     , IF(t.n1<=t.n2,IF(t.n1<=t.n3,t.n1,t.n3),IF(t.n2<=t.n3,t.n2,t.n3)) AS n1s
     , IF(t.n1<=t.n2,IF(t.n2<=t.n3,t.n2,IF(t.n1<=t.n3,t.n3,t.n1)),IF(t.n1<=t.n3,t.n1,IF(t.n2<=t.n3,t.n3,t.n2 ))) AS n2s
     , IF(t.n1<=t.n2,IF(t.n2<=t.n3,t.n3,t.n2),IF(t.n1<=t.n3,t.n3,t.n1)) AS n3s
  FROM this_table_column_structure t
 GROUP BY n1s,n2s,n3s
 ORDER BY total DESC, n1s, n2s, n3s

will return
total   n1s   n2s   n3s
-----  ----  ----  ----
    2     1     2     3
    2     5     6     7
    1     1     5     6
    1     3     5     6

A: As a first approach (if time permits), you should really consider normalizing your table, as suggested in @Strawberry's answer
However, a second approach allowing any number of columns (although inefficient due to String operations and Bubble Sorting) is possible, utilizing User Defined Functions.
We basically need to create a function, which can sort the values inside a comma separated string. I found a working function, which can do the sorting. Reproducing code from here:
-- sort comma separated substrings with unoptimized bubble sort
DROP FUNCTION IF EXISTS sortString;
DELIMITER |
CREATE FUNCTION sortString(inString TEXT) RETURNS TEXT
BEGIN
  DECLARE delim CHAR(1) DEFAULT ','; -- delimiter
  DECLARE strings INT DEFAULT 0;     -- number of substrings
  DECLARE forward INT DEFAULT 1;     -- index for traverse forward thru substrings
  DECLARE backward INT;   -- index for traverse backward thru substrings, position in calc. substrings
  DECLARE remain TEXT;               -- work area for calc. no of substrings
-- swap areas TEXT for string compare, INT for numeric compare
  DECLARE swap1 TEXT;                 -- left substring to swap
  DECLARE swap2 TEXT;                 -- right substring to swap
  SET remain = inString;
  SET backward = LOCATE(delim, remain);
  WHILE backward != 0 DO
    SET strings = strings + 1;
    SET backward = LOCATE(delim, remain);
    SET remain = SUBSTRING(remain, backward+1);
  END WHILE;
  IF strings < 2 THEN RETURN inString; END IF;
  REPEAT
    SET backward = strings;
    REPEAT
      SET swap1 = SUBSTRING_INDEX(SUBSTRING_INDEX(inString,delim,backward-1),delim,-1);
      SET swap2 = SUBSTRING_INDEX(SUBSTRING_INDEX(inString,delim,backward),delim,-1);
      IF  swap1 > swap2 THEN
        SET inString = TRIM(BOTH delim FROM CONCAT_WS(delim
        ,SUBSTRING_INDEX(inString,delim,backward-2)
        ,swap2,swap1
        ,SUBSTRING_INDEX(inString,delim,(backward-strings))));
      END IF;
      SET backward = backward - 1;
    UNTIL backward < 2 END REPEAT;
    SET forward = forward +1;
  UNTIL forward + 1 > strings
  END REPEAT;
RETURN inString;
END |
DELIMITER ;

You will need to run this code on your MySQL server, so that this function is available within a query, just like native built-in MySQL functions. Now, the querying part becomes simple. All you need to do is Concat_ws() all the number columns using comma. And, then apply sortString() function on the concatenated string. Eventually, use the "ordered" string in Group By clause, to get the desired result.
Try:
SELECT sortString(CONCAT_WS(',', n1, n2, n3)) AS n_sequence -- add more columns here
       COUNT(id) AS total
FROM your_table
GROUP BY n_sequence
ORDER BY total DESC

Now I suggest that you can use your application code to change comma separated n_sequence back to tabular column display.


text:
Q: ggplot2: italicising only certain x axis columns In my box plot, I'm trying to keep the x axis column label "WT" plain, whilst converting the other 7 column labels into italic text. I used element_text, but this caused all of the labels to turn italic. Is there some way to isolate the "WT" column label to be able to change it to plain text?
ggplot(edtct2)+
  geom_boxplot(aes(x=Mutant, y=Chlorophyll))+
  labs(title = "Total Chlorophyll levels across SP2 Mutants",
       y = "Chlorophyll (nmol/mg tissue)")+
  theme(axis.text.x = element_text(angle = 45, hjust = 1, face = "italic"))+
  theme(plot.title = element_text(hjust = 0.5))

The data that I used is from a cvs file that I inputted and modified, and so is in the following format.
       Mutant Chlorophyll
1          WT        1.14
2          WT        1.33
3          WT        1.29
4          WT        1.65
5        ppi1        0.59
6        ppi1        0.80
7        ppi1        0.61
8        ppi1        0.67
9       sp2-4        1.15
10      sp2-4        1.08
11      sp2-4        1.00
12      sp2-4        1.01
13   sp2 ppi1        1.02
14   sp2 ppi1        0.82
15   sp2 ppi1        0.65
16   sp2 ppi1        0.84
17 sp2-3 ppi1        0.91
18 sp2-3 ppi1        0.77
19 sp2-3 ppi1        0.78
20 sp2-3 ppi1        0.85
21 sp2-5 ppi1        0.78
22 sp2-5 ppi1        1.04
23 sp2-5 ppi1        0.90
24 sp2-5 ppi1        0.97
25 sp2-6 ppi1        0.74
26 sp2-6 ppi1        0.84
27 sp2-6 ppi1        0.86
28 sp2-6 ppi1        0.88
29 sp2-8 ppi1        1.25
30 sp2-8 ppi1        1.25
31 sp2-8 ppi1        1.30
32 sp2-8 ppi1        1.34

A: You can define the face with a vector.
library(ggplot2)
ggplot(edtct2)+
  geom_boxplot(aes(x=Mutant, y=Chlorophyll))+
  labs(title="Total Chlorophyll levels across SP2 Mutants",
       y="Chlorophyll (nmol/mg tissue)")+
  theme(axis.text.x=element_text(angle=45, hjust=1, face=c(rep("italic", 7), "plain")),
        plot.title=element_text(hjust=0.5))

Result

Data:
edtct2 <- structure(list(Mutant = c("WT", "WT", "WT", "WT", "ppi1", "ppi1",
"ppi1", "ppi1", "sp2-4", "sp2-4", "sp2-4", "sp2-4", "sp2 ppi1",
"sp2 ppi1", "sp2 ppi1", "sp2 ppi1", "sp2-3 ppi1", "sp2-3 ppi1",
"sp2-3 ppi1", "sp2-3 ppi1", "sp2-5 ppi1", "sp2-5 ppi1", "sp2-5 ppi1",
"sp2-5 ppi1", "sp2-6 ppi1", "sp2-6 ppi1", "sp2-6 ppi1", "sp2-6 ppi1",
"sp2-8 ppi1", "sp2-8 ppi1", "sp2-8 ppi1", "sp2-8 ppi1"), Chlorophyll = c(1.14,
1.33, 1.29, 1.65, 0.59, 0.8, 0.61, 0.67, 1.15, 1.08, 1, 1.01,
1.02, 0.82, 0.65, 0.84, 0.91, 0.77, 0.78, 0.85, 0.78, 1.04, 0.9,
0.97, 0.74, 0.84, 0.86, 0.88, 1.25, 1.25, 1.3, 1.34)), row.names = c(NA,
-32L), class = "data.frame")


text:
Q: Split disorganized arrays with numpy I am using the below code to read arrays from csv files.
x,y = np.loadtxt(filename, delimiter=';', unpack=True, skiprows=1, usecols=(1,2))

Being x and array that goes like this [5,5,5,0,1,1,2,3,3,4,5,5,5]
and y [111.0,111.1,111.2,111.3,111.4,111.5...]
I want to split both arrays accordingly using x.
So my expected output would be something like this:
[1,1,1,1,1..][111.4,111.5,111.6...]
[2,2,2,2,..][111.10,111.11,111.12...]
[5,5,5,5,5,...][111.0,111.1,111.2...111.20,111.21,111.22]
...

So that I can choose between the x values and it would return its respective y values
I've tried using np.split np.split(x,[21,1,2,3...]) but It doesn't seem to be working for me.

A: Despite the fact that my solution is probably not the most efficient one performance-wise, you can use it as a starting point for future investigations
import numpy as np

# some dummy data
x = np.array([5,5,5,0,1,1,2,3,3,4,5,5,5])
y = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12])

def split_by_ids(data: np.array, ids: np.array):
    splits = []  # result storage
    # get unique indicies with their counts from ids array
    elems, counts = np.unique(ids, return_counts=True)
    # go through each index and its count
    for index, count in zip(elems, counts):
        # create array of same index and grab corresponding values from data
        splits.append((np.repeat(index, count), data[ids == index]))

    return splits

split_result = split_by_ids(y, x)
for ids, values in split_result:
    print(f'Ids: {ids}, Values: {values}')

Above code resulted in
Ids: [0], Values: [3]
Ids: [1 1], Values: [4 5]
Ids: [2], Values: [6]
Ids: [3 3], Values: [7 8]
Ids: [4], Values: [9]
Ids: [5 5 5 5 5 5], Values: [ 0  1  2 10 11 12]


text:
Q: Dealing with separation characters within quotes when using componentsSeparatedByCharactersInSet I'm trying to separate a string by the use of a comma. However I do not want to include commas that are within quoted areas. What is the best way of going about this in Objective-C?
An example of what I am dealing with is:
["someRandomNumber","Some Other Info","This quotes area, has a comma",...]

Any help would be greatly appreciated.

A: Regular expressions might work well for this, depending on your requirements. For example, if you're always trying to match items that are enclosed in double quotes, then the it might be easier to look for the quotes rather than worrying about the commas.
For example, you could do something like this:
NSString *pattern = @"\"[^\"]*\"";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
  options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];

for (NSTextCheckingResult *match in matches) {
   NSRange matchRange = [match range];
   NString *substring = [string substringWithRange:matchRange];
   // do whatever you need to do with the substring
}

This code looks for a sequence of characters enclosed in quotes (the regex pattern "[^"]*"). Then for each match it extracts the matched range as a substring.
If that doesn't exactly match your requirements, it shouldn't be too difficult to adapt it to use a different regex pattern.
I'm not in a position to test this code at the moment, so my apologies if there are any errors. Hopefully the basic concept should be clear.


text:
Q: While running "npm run prod" getting this "CssSyntaxError: /css/style.css:118:18: Missed semicolon" in Laravel reactjs I am using Laravel and reactjs and when I am using npm run dev everything works fine but when I run npm run prod command I get errors in my console as follows:

CssSyntaxError: /css/style.css:118:18: Missed semicolon
      at Input.error (/home/iron/Documents/reactify/reactify-dev/reactify-laravel/reactify-redux-thunk/node_modules/postcss/lib/input.js:130:16)
      at Parser.checkMissedSemicolon (/home/react/Documents/react/react-dev/react-laravel/react-thunk/node_modules/postcss/lib/parser.js:603:22)
      at Parser.decl (/home/iron/Documents/react/react-dev/react-laravel/reactify-thunk/node_modules/postcss/lib/parser.js:286:46)

If you need any files let me know.

A: Error already is self explanatory, CssSyntaxError: /css/style.css:118:18: Missed semicolon
it tells you to look in /css/style.css file for missing semicolon on line 118


text:
Q: javascript: send myself message when a user press button I'm looking for a way to send myself a message(email) when a user submit a form on my website.
Is there any service for that?

A: There is a service that can do this.  https://formspree.io/  You setup your form action to point to their url with your email address appended to the end.

A: You need to call a server side file (where you should write your email trigger logic) in your <form> tag's "action" attribute with it's "method" attribute is set to "post"
Alternately you may also try this too,
<form action="mailto:emailaddress@domain.tld" method="GET">
   <input name="subjectText" type="text" />
   <textarea name="message"></textarea>
   <input type="submit" value="Send" />
</form>


text:
Q: Rotate a 2D square about the Y axis and display it in perspective projection using neither DirectX nor openGL I want to have a 2D square rotated about the Y axis and I want to display it in perspective projection using neither DirectX nor openGL.
If you look at the code below you'll notice I am using direct X matrix and vectors stuff - that's just to make things simple here...
Anyways, after you run the drawSquare method you'll see some kind of rotation, especially if you animate the rotation angle, but the projection does not look right.
Can anybody help me and tell me what I am doing wrong?
Thx guys.
As I said before: DX stuff is just to make things simple:
void set3Dto2D( D3DXVECTOR3* a, D3DXVECTOR3& b )
{
    b.x = a->x / ( a->z * .01 ) + 357.f;
    b.y = a->y / ( a->z * .01 ) + 357.f;
}
void drawSquare( HDC dc )
{
    D3DXMATRIX proj, rot;

    // corners of my square
    D3DXVECTOR3 pt1( 1, -1, 1 ), pt2( -1, -1, 1 ), pt3( -1, 1, 1 ), pt4( 1, 1, 1 );

    // rotation matrix
    D3DXMatrixRotationY( &rot, 1.5708f );
    // projection matrix
    D3DXMatrixPerspectiveFovLH( &proj, 45.0f / 180.0f * D3DX_PI, 1.f, 1.f, 100.0f );

    // multiply corners by rotation matrix
    D3DXVec3TransformCoord( &pt1, &pt1, &rot );
    D3DXVec3TransformCoord( &pt2, &pt2, &rot );
    D3DXVec3TransformCoord( &pt3, &pt3, &rot );
    D3DXVec3TransformCoord( &pt4, &pt4, &rot );

    // multiply rotated corners by projection matrix
    D3DXVec3TransformCoord( &pt1, &pt1, &proj );
    D3DXVec3TransformCoord( &pt2, &pt2, &proj );
    D3DXVec3TransformCoord( &pt3, &pt3, &proj );
    D3DXVec3TransformCoord( &pt4, &pt4, &proj );

    // transform 3D points into 2D ones
    set3Dto2D( &pt1, pt1 ); set3Dto2D( &pt2, pt2 );
    set3Dto2D( &pt3, pt3 ); set3Dto2D( &pt4, pt4 );

    // draw the lines
    MoveToEx( dc, pt1.x, pt1.y, NULL );
    LineTo( dc, pt2.x, pt2.y ); LineTo( dc, pt3.x, pt3.y );
    LineTo( dc, pt4.x, pt4.y ); LineTo( dc, pt1.x, pt1.y );
}

A: It looks like you are rotating around the Y axis, which will rotate your cube around the "up" vector. You need to rotate around the Z axis.
Also, a transform is an absolute operation so you'll need to increment the rotation angle to start rotating your square.
(after spending some time to reproduce your problem)
First off, you don't need to perspective correct for what you are trying to do so you can go without the line:
D3DXMatrixPerspectiveFovLH( &proj, 45.0f / 180.0f * D3DX_PI, 1.f, 1.f, 100.0f );

The problem lies in your 3Dto2D code. If you change your code from:
void set3Dto2D( D3DXVECTOR3* a, D3DXVECTOR3& b )
{
    b.x = a->x / ( a->z * .01 ) + 357.f;
    b.y = a->y / ( a->z * .01 ) + 357.f;
}

to
void set3Dto2D( D3DXVECTOR3* a, D3DXVECTOR3& b )
{
    b.x = a->x * 100 + 357.f;
    b.y = a->y * 100 + 357.f;
}

it should work.
The problem is that you are assuming that the Z component of your vectors remains unchanged after the transform application. This is not the case and therefore your 3Dto2D function yields unexpected behavior. If you replace the devision by the a.z component with multiply by 100 (every z component in your square equals 1 and X/(1*.01) = X*100). You eliminate the dependence on the z component and your function should behave as expected.


text:
Q: Node INTL locale Collation I'm working on a side project that involves sorting Japanese and Thai strings.  When I was testing the sorting in client-side Javascript, I was able to use a.localeCompare(b, "languageCode") which worked.  When I tried this same logic in Node, it did not work, because the Node INTL object is restricted to English as the default.
I want to customize my node build as described in the above link, and came across the ICU4C-data Node Module, which I understand contains a full set of ICU data. I've been playing around with different build flags, like the one specified by the (sparse) README: --icu-data-dir=node_modules/icu4c-data, to no avail - no matter which flags I set I cannot get the INTL Collator's compare function to give the expected results.  Is there an obvious flag that I'm missing, or key assumption I have wrong?
Here are a few things important notes/resources:

*

*The end goal is Thai & Japanese collation - if there's another approach using Node to implement this, I'm open to suggestions.

*Collation must be done in Node

*I'm going to be relying on Array.prototype.sort() - mainly looking for a comparator

*Using Node 0.12, with ECMA support

*My first time customizing a Node build (~1 month experience)

A: Install the full-icu package instead. It will give instructions on how to load the rest of the data.
Also note that future node versions should not require any configuration to pick up the new data, you can see #3460 if interested.
I need to fix the icu4c-data's readme to reflect this.


text:
Q: Setting the maxlength of text in an element that is displayed I have an element with an id of templateDescription that receives values arriving through a database. I would like to set a maximumlength of the text that is displayed in the view for each entry on the home page because I have a "read more" button that is responsible for opening up a modal that will contain more information about the page. How would be the best approach for this?

A: HTML5 introduces a new maxlength attribute for input elements.
It looks like this
<input type="text" maxlength="10" />

This will limit the length of a text field to 10 characters.
For other elements, it might be best to set a width and then use the text-overflow property. You'll also want to add the overflow and white-space properties. It looks like this

div {
      width: 100px;
      white-space: nowrap;
      border: 1px solid black;
      text-overflow: ellipsis;
      overflow: hidden;
    }

This is a really really long sentence


text:
Q: flash send request to another server hi i am sending a flash reqesut to a url when i make request from local computer its working but when i upload on my server its not working i think flash is not sending request from my server to another server
//it working
myvars.sendAndLoad("http://mywebsite.com",myvars,"GET");
gotoAndPlay("thankYou");

//its not working
myvars.sendAndLoad("http://anotherwebsite.com",myvars,"GET");
gotoAndPlay("thankYou");

any ideas thanks

A: You need a crossdomain file on your server
http://kb2.adobe.com/cps/142/tn_14213.html


text:
Q: How to get my current position with GPS using python flask? I have a project that developed using Python-Flask which can find all nearby clothes shop places using Google Maps.
so far i can do that with my code, but my current position i got from my IP Address, which that IP from the Internet Service Provider, so.. i dont want it.. because the internet service provider not too close to my location, i want more accurate position that can get current user GPS..
but so far.. i din't get the tutorial or source to get that using python flask..
so my questions.. Can flask to do that..? , if not..what's the others solution to do that..?
Here's my code to get my current ISP location and find all nearby places:
import googlemaps
import geocoder
from googleplaces import GooglePlaces, types

# you can get the API KEY here:
# https://developers.google.com/console
API_KEY = 'MY_API_KEY'

gmaps = googlemaps.Client(key=API_KEY)
locations = gmaps.geolocate()

latitude = locations['location']['lat']
longitude = locations['location']['lng']

g = geocoder.google([latitude, longitude], method='reverse')

get_json_values = g.json

my_current_position = get_json_values['address']

google_places = GooglePlaces(API_KEY)

query_result = google_places.nearby_search(
    location=my_current_position,
    keyword='baju', radius=3200)

for place in query_result.places:
    print(place.name)
    place.get_details()
    print(place.url)


text:
Q: SQL: Check existence of a file on local machine when i'm connected to another database server I have two test Machines. i don't know if this is possible but here is what im trying to do

*

*Machine1: has DBServer setup
where i am currently logged in
where the file C:\test_IDNumber1.txt is located
where i use SSMS. i connect to Machine2\SQLServer

*Machine2: has DBServer setup
where the dbserver for DBTest is located
DBTest is where the Filename records are stored

*First i need to do some select script from DBTest to get the IDNumber for the Filename
SELECT FileName FROM tblFiles where...... (results to "IDNumber1")

*Then i'll check the existence of the file with the same IDNumber (e.g: "C:\test_IDNumber1.txt") using this script
EXEC xp_fileexist 'C:\test_IDNumber1.txt', @exists OUTPUT

*If the file exists, i need to delete the record from DBtest on Machine2 and the file from Machine1
DELETE FROM tblFiles where Filename = 'IDNumber1'
EXEC master.dbo.xp_cmdshell 'del ''C:\test_IDNumber1.txt'''

but the result for existence is always 0 because it is checking the C drive of Machine2 where the DBTest is located.
Is there a way to use a select script from a db from Machine2 and check the existence of a file from Machine1?
thank you very much

A: Several possible solutions can exist. One of the least expensive is:

*

*Make file storage on Machine1 shared, visible to Machine2 and mapped there as network drive (e.g. Z:) with read+delete permissions.
Machine1: C:\Shared\   (mapping)→   Machine2: Z:\

*Then you can use SQL commands similar to what you already show in steps 4 and 5 in order to test the existence of Z:\test_IDNumber1.txt and delete the file.


text:
Q: Underscorejs : can template call itself Following is underscore template:
template name is navItems.html. i am using text plugin to load templates

     <%=data.title%>

<%=data.attr%>

which i am calling like this from backbone view
<%=_.template(navItemTpl,{'data':data})%>

is it possible to call template itself from inside template like
can i do?
 <%=_.template(navItemTpl,{'data':data})%>

inside navItem.html?

A: Yes its possible.Added example code below:
HTML:

JS:
$(function() {
    var compiled = _.template($("#templ").html());
    $("#here").html(compiled());
});


text:
Q: 8bit shift left register with serial in, serial out implementation in verilog I took an example from website that describes 8bit serial in serial out shift left register.
module shift (clk, si, so);
input        clk,si;
output       so;
reg    [7:0] tmp;
always @(posedge clk)
begin
   tmp    <= tmp << 1;
   tmp[0] <= si;
end
   assign so = tmp[7];
    endmodule

from above example, I think that this is strange implementation. This is because, inside always, when tmp[0] <= si; is executed first, then we will take unexpected output.
For example, let's assume si is 1, and when tmp is:
1010 1010
and, when tmp[0] <= si; is executed first(which will make an unexpected output), the output is:
0101 0110
But, if always statements are executed sequentially as it is written in above example, the output is
0101 0101
As a result, we cannot guarantee that the output could be what we expected.
Am I right? So, the correct implementation should be:
tmp <= (tmp << 1) + {7'b0000_000, si};

Or, can we prove that the above example is always executed sequentially?

A: HDL languages do not work like other computer languages. They all have what is called 'concurrent' assignments. Which means all assignments take place 'at the same time'.
Thus tmp[0] gets the value si at the same time as tmp[7:1] get the value from tmp[6:0].

Am I right?

No, I strongly suggest you study Verilog and VHDL in more detail.

I think I see where you are coming from.
In Verilog when there are multiple concurrent assignments, the last one wins.
Thus tmp[0] gets assigned a zero: tmp <= tmp << 1;
Next it gets assigned si: tmp[0] <= si;
The last one overrides the previous.
I agree it is sloppy coding here.
However there are cases where using that technique greatly improves code readability. I always add a comment like this:
...
... // big complex FSM
...
// Overrides all previous assignments above!
if (emergency_stop)
   state <= FSM_IDLE;


text: Q: Approximate medoid using matrix approximation The medoid of a set of $n$ points is defined as the point that minimizes the average distance to all the other points. If there is a matrix containing rows in which each row is the set of all metric distances between a point and the rest of the points, we are looking for the row with the smallest sum. Finding this row by brute force is of $O(n^2)$ complexity. Is it possible to approximate the matrix first by some approach like Nystrom Method, which is of complexity $O(nmr+r^3)$, where $m$ is the number of anchor points chosen and $r$ is the rank for the approximation. Such an approximation is of the form $UV^T$, where $U$, $V$ are $n \times r$ matrices. Then, with the matrix-vector product $UV^T\mathbb{1}$, it will be possible to compute row sums in $O(nr+mr)$ operations. I understand that the medoid will be approximate. Nevertheless, is this a good approach to get a reasonable point which is somewhere close to the medoid?


text:
Q: Get the subsection using \eqref if the equation isnt't in the current subsection As the title says, I want to define an eqref command such that if the equation is in the current subsection then it produces the usual (1) and that if the equation is in another subsection then the cite looks like ¶2.3 Equation (4). It is similar to my previous question Include the subsection number in cross-reference to a theorem-like environment (the solution given by @egreg).
I have tried to copy the code with some changes. Here it is:
\let\eqref\relax
\makeatletter
\renewcommand*{\c@equation}{\perhapssubsection{\thesubsection}}
\newcommand{\eqref}[1]{\textsc{Equation}~\textup{(\ref{#1})}}
\makeatother

However, it does not work. Can you help me, please?
Here is my MWE:
\documentclass[a4paper,12pt]{article}

\usepackage{mathtools}
\usepackage{xparse}
\usepackage{amsthm}
\usepackage{thmtools}

\declaretheoremstyle[%
spaceabove=\topsep,
spacebelow=\topsep,
headfont=\scshape,
bodyfont=\itshape,
notefont=\normalfont,
notebraces={}{.},
headpunct={},
postheadspace=1em,
headformat=\NAME\space\NUMBER.---\NOTE,
headindent=\parindent
%   qed=$\qedsymbol$%
]{theorem}

\declaretheorem[style=theorem,name=Theorem,numberwithin=subsection]{theorem}

\makeatletter
\@addtoreset{equation}{subsection}% Reset equation at \section
\makeatother
\makeatletter
\def\gobblesomething#1\csname thesection\endcsname{\begingroup\normalfont\S\thesection\endgroup}
\def\gobblesomethingother#1\csname thesubsection\endcsname{\begingroup\normalfont\P\thesubsection\endgroup}
\renewcommand*{\p@section}{\gobblesomething}
\renewcommand*{\p@subsection}{\gobblesomethingother}
\makeatother

\renewcommand{\thetheorem}{\arabic{theorem}}

\makeatletter
\def\gobblesomethinga#1\csname thetheorem\endcsname{\begingroup\normalfont\textsc{Theorem}~\thetheorem\endgroup}
\renewcommand*{\p@theorem}{\perhapssubsection{\thesubsection}\gobblesomethinga}
\makeatother

\ExplSyntaxOn
\NewDocumentCommand{\perhapssubsection}{m}
 {
  \str_if_eq_x:nnF { #1 }{\thesubsection}{\P\textup{#1}~}
 }
\ExplSyntaxOff

\begin{document}

\section{One}

\subsection{A}

\begin{theorem}
\label{th:E}
Bla bla bla
\begin{equation}
E=mc^2
\label{eq:E}
\end{equation}
\end{theorem}

\subsection{B}

In \ref{th:E} and \eqref{eq:E}

\end{document}

A: I wouldn't do like this: a reference "Theorem 1.1.1" is much clearer than "¶1.1 Theorem 1".
Anyway, some more juggling can do what you want.
\documentclass[a4paper,12pt]{article}

\usepackage{mathtools}
\usepackage{xparse}
\usepackage{amsthm}
\usepackage{thmtools}

\declaretheoremstyle[
  spaceabove=\topsep,
  spacebelow=\topsep,
  headfont=\scshape,
  bodyfont=\itshape,
  notefont=\normalfont,
  notebraces={}{.},
  headpunct={},
  postheadspace=1em,
  headformat=\NAME\space\NUMBER.---\NOTE,
  headindent=\parindent,
%   qed=$\qedsymbol$,
]{theorem}

\declaretheorem[style=theorem,name=Theorem,numberwithin=subsection]{theorem}

\counterwithin{equation}{subsection}

\renewcommand{\thetheorem}{\arabic{theorem}}
\renewcommand{\theequation}{\perhapsbrackets{\arabic{equation}}}

\makeatletter
\renewcommand*{\p@theorem}{\perhapssubsection{Theorem}{\thesubsection}}
\renewcommand*{\p@equation}{\perhapssubsection{Equation}{\thesubsection}}
\makeatother

\ExplSyntaxOn
\RenewDocumentCommand{\eqref}{m}
 {
  \group_begin:
  \bool_set_true:N \l_dog_brackets_bool
  \ref{#1}
  \group_end:
 }
\bool_new:N \l_dog_brackets_bool

\NewDocumentCommand{\perhapsbrackets}{m}
 {
  \bool_if:NTF \l_dog_brackets_bool { \textup{(#1)} } { \textup{#1} }
 }

\NewDocumentCommand{\perhapssubsection}{mm}
 {
  \str_if_eq:eeF { #2 }{\thesubsection}
   {
    \P\textup{#2}\nobreakspace
   }
  \str_case:nn { #1 }
   {
    {Theorem}{\textsc{Theorem}\nobreakspace}
    {Equation}{\textsc{Equation}\nobreakspace}
   }
 }
\ExplSyntaxOff

\begin{document}

\section{One}

\subsection{A}

\begin{theorem}
\label{th:E}
Bla bla bla
\begin{equation}
E=mc^2
\label{eq:E}
\end{equation}
\end{theorem}

In \ref{th:E} and \eqref{eq:E}

\subsection{B}

In \ref{th:E} and \eqref{eq:E}

\end{document}


text:
Q: Deploy a MDE - auto update & Trusted Source enquiry My backend is on a cloud server and my frontend will be a MDE file.  My company now uses Access2013 but when the database was being designed and coded, we were still on XP.
I am hoping to be able to email all the users a file which will enable auto-updating of the MDE.  The examples I have seen require access to the backend.  While I do not wish to reinvent the wheel, especially as my only programming knowledge is some VBA, I am hoping to create a file that will:

*

*Check if the path C:\Program Files\myDatabaseFolder exists

*If not then create it and copy the MDE from my department server (not the
cloud).
(Possibly also copy a self-certificate to get past the
Trusted Source warning)

*If Path exists then check the date modified of the current version
against the version on the department server and retain the latest.

*Then Open the Database

There are a few things I'm not too clear on - this file I would email to users and get them to put it on their desktop.  When they wanted to access the database, they would just run this - but should this be a batch file or some other form of executable?
Also, when I created the MDE and tried to open it, I got a warning:- "not possible to determine that this content came from a trustworthy source".  I do not want the users to see that on opening the file/database, so would a self-certificate be adequate or is there a way to create a trusted location?  I am hoping for as little user interaction as possible - not all are able to follow simple instructions.
Any advice or comments welcomed.

A: I have set this up in a Citrix environment but it should work with normal desktops as well. It is described in detail here:
FE Deploy Method
The script, I used, happened to be VB Script and can be found here:
FE Deploy Script
I didn't have to charge a consulting fee for this.
PS: If you meet a request for signing up at EE, you should be able to just browse past it.
Link to script:
Download script


text:
Q: jQuery - css() not working properly in firefox I am using .css() to get style from a element.
But in firefox .css() is not getting value of margin and padding from element.
Please see the fiddle:
http://jsfiddle.net/howtoplease/fMTsW/
This is my jquery code:
$(document).ready(function(){
    $('input').each(function(){
        this.value = $('h3').css(this.name);
    });
});

My html code
<h3 style="margin:20px;padding:20px;font-size:30px;font-family:'open sans';">
    I am heading 3
</h3>

<input name="margin" />
<input name="padding" />
<input name="font-size" />
<input name="font-family" />

A: This is happening because properties like margin and padding are short hand property and jQuery cannot give you these values you have use independant values such as margin-top and margin-right.
Moreover, properties with multiple words like margin-top should be accessed using marginTop i.e First letter of second word should be capital.
For a full set of values:
<input name="marginTop" />
<input name="marginRight" />
<input name="paddingTop" />
<input name="paddingRight" />
<input name="fontSize" />
<input name="fontFamily" />

A: The CSS tag 'margin & padding' is actually a shorthand for the four separate margin/padding values, top/left/bottom/right. Use css('marginTop'), etc. - note they will have 'px' on the end if you have specified them that way.
Use parseInt() around the result to turn it in to the number value.
<input name="margin-top" />
<input name="padding-top" />

OR
<input name="marginTop" />
<input name="paddingTop" />

This will give you the value. Using this technique you can get the value of margin and padding.

A: In your code in fiddle i tried changing the HTML.
From
<input name="margin"/>
<input name="padding"/>

To
<input name="margin-left"/>
<input name="padding-left"/>

and the values were set in the inputs value field correctly. This is because the margin in css is a keyword which set value of attributes like margin-right, margin-left,margin-top,margin-bottom to a value but it by itself is not a attribute.


text:
Q: Estimation of the difference of two integrals My goal is to find an estimate for the following difference of integrals.
$$\frac{1}{x}\int_0^x\frac{(\sinh t)^{(2n)}}{(2n-1)!}(x-t)^{2n-1}dt-\int_0^{\alpha x}\frac{(\cosh t)^{(2n-1)}}{(2n-2)!}(\alpha x-t)^{2n-2}dt$$
with $0\leq\alpha\leq1$ (real parameter) and $x\in \mathbb R$. The difference is in reality a difference of integrals remains in the Taylor series, but I do not think this is very important.
I thought that, for $0\leq\alpha x\leq x$ we have
$$\int_0^{\alpha x} \left( \frac{1}{x}\frac{(\sinh t)^{(2n)}}{(2n-1)!}(x-t)^{2n-1}-\frac{(\cosh t)^{(2n-1)}}{(2n-2)!}(\alpha x-t)^{2n-2}\right)dt+\\
\frac{1}{x}\int_{\alpha x}^x\frac{(\sinh t)^{(2n)}}{(2n-1)!}(x-t)^{2n-1}dt$$
but I can not go on. Can anyone help me please?

A: You haven't really specified what kind of estimate you want, or what quality/precision you need. I'll provide a rough, non-rigourous, estimate (suitable for putting up shelves, not for putting a man on the moon). I'm going to assume $ x > 0$ otherwise repeat the below with symmetry arguments.
Firstly, $\sinh$ is odd, but to an even power, it is also monotone on $[0, \infty)$. Therefore maximum of $(\sinh t)^{2n}$ is $(\sinh x)^{2n}$. The term $(x-t)^{2n-1}$ is monotone decreasing in $t$ hence it's maximum value is $x^{2n-1}$.
Therefore,
$\frac{1}{x} \int_0^x \frac{(\sinh t)^{2n}}{(2n-1)!}(x-t)^{2n-1}dt \leq \frac{1}{x} \cdot x \cdot \sup_{t \in [0,x]} \frac{(\sinh t)^{2n}}{(2n-1)!}(x-t)^{2n-1} = \frac{(\sinh x)^{2n}}{(2n-1)!}x^{2n-1}$
To estimate the cosine term,
$\int_0^{\alpha x} \frac{(\cosh t)^{2n-1}}{(2n-2)!}(x-t)^{2n-2}dt \geq  {\alpha x} \cdot \inf_{t \in [0,\alpha x]} \frac{(\cosh t)^{2n-1}}{(2n-2)!}(x-t)^{2n-2} = \frac{(\cosh 0)^{2n-1}}{(2n-2)!}x^{2n-2} = \frac{1}{(2n-2)!}x^{2n-2}$
using similar monotonicity considerations. Therefore,
$\frac{1}{x} \int_0^x \frac{(\sinh t)^{2n}}{(2n-1)!}(x-t)^{2n-1}dt - \int_0^{\alpha x} \frac{(\cosh t)^{2n-1}}{(2n-2)!}(x-t)^{2n-2}dt \leq \frac{(\sinh x)^{2n}}{(2n-1)!}x^{2n-1} - \frac{1}{(2n-2)!}x^{2n-2}$.
An estimate below can be derived similarly.

A: Right dcs24. Mark, you may take a look for some research papers about this subject:
http://dx.doi.org/10.1016/S0898-1221(03)90037-X
http://rgmia.org/papers/v16/v16a11.pdf
and others (google it)


text:
Q: PHP Soap server slow on different computers Any reason why a soap server can be slow on different computers and networks? For me its working very good but for other people in different networks is very slow, like minutes.
Any reason for that?
Thanks

A: I don't use the SOAP stuff much with PHP, so the only PHP configuration thing I can think of is caching:
ini_set("soap.wsdl_cache_enabled", 1);

Or see the parameters to:
SoapClient::SoapClient($wsdl, $options)
SoapServer::SoapServer($wsdl, $options)

Otherwise it's likely to be networking issues or configuration outside the realm of PHP and a stackoverflow question.


text:
Q: Backing Services as attached resources I was looking at 12 factor app principle and saw this statement. I believe this statement states that the application must respond to any backing service such database or message broker and connect to them irrespective of what they are. How does it differ from traditional way of connecting? For eg: in my microservice , I was defined database and kafka broker as user provided service in cloud foundry. It just provides the connection parameters as vcap service variables. I still have code to connect to a database and kafka broker which are entirely different. What does this statement signify and how does it differ from what we do in non-cloud environment?

A: As stated in the below article:
https://12factor.net/backing-services
It states that :

A backing service is any service the app consumes over the network as part of its normal operation. Examples include datastores (such as MySQL or CouchDB), messaging/queueing systems (such as RabbitMQ or Beanstalkd), SMTP services for outbound email (such as Postfix), and caching systems (such as Memcached).

Microservice can connect to any backing service irrespective of the platform. In PCF, you are binding services to your microservices to connect. In other cloud environment, you can point to any backing service like AWS RDS or other services provided by the Platform.
The real difference is this :

Backing services like the database are traditionally managed by the same systems administrators as the app's runtime deploy. In addition to these locally-managed services, the app may also have services provided and managed by third parties. Resources can be attached and detached to deploys at will. For example, if the app's database is misbehaving due to a hardware issue, the app's administrator might spin up a new database server restored from a recent backup. The current production database could be detached, and the new database attached – all without any code changes.


text:
Q: CheckList Box Delphi como pegar a String do Item que esta com o checked Estou tendo um problema de como pegar a string do CheckListBox que está selecionado. como posso resolver o problem
var
 setores : array of string

    for I := 0 to auditoriaDeEPIFrm.lckCheck.Items.Count - 1 do
    begin
      if auditoriaDeEPIFrm.lckCheck.Checked then
        setores[i] := recebe a string do que esta selecionado;

    end;

A: var
  iCont: Integer;
  sValor: string;
begin
  for iCont := 0 to CheckListBox1.Count-1 do
  begin
    if CheckListBox1.Checked[iCont] then
      sValor := CheckListBox1.Items[iCont].Trim;
  end;
end;

Espero ter ajudado


text:
Q: Parametrized CTE Let's say I have a table-function that I'm currently doing with a CTE, for example:
WITH info AS (
    SELECT * FROM sales WHERE website='Google'
) SELECT * FROM info JOIN other USING (id)

Is there a way to parametrize the CTE such that I can do something like:
WITH table_function_info($var1) AS (
    SELECT * FROM sales WHERE website=$var1
)

And then I could call it as:
WITH info AS
    table_function_info('Yahoo')
SELECT * FROM info JOIN other USING (id)

Or what is the proper way to parametrize a table function in a postgres (CTE?) Note that I don't necessarily know the output columns, and they may potentially change (for example, if a user adds/removes a column in the sales table).

A: Create a function that returns a set of rows of the type sales, e.g.
create or replace function select_from_sales(arg text)
returns setof sales language sql as $$
    select * from sales where website = arg
$$;

The output format of the function will adapt to possible modifications to the table structure, test it in Db<>fiddle. Postgres automatically creates a corresponding type for every created/altered table in a database. This allows a user to declare the return type of a function in an easy way.


text:
Q: Error inflating class  in RecyclerView Adapter i am beginner in android programing
i get online data from web and save images in sd card
after i show them in recyclerview.
app crash in genymotion samsung android 6.0.0
thats my item xml:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="4dp"
    card_view:cardUseCompatPadding="true">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/image_book"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"
                android:adjustViewBounds="true"
                android:padding="10dp"
                android:scaleType="fitXY"
                android:src="@drawable/exam" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"

                android:paddingLeft="10dp"
                android:paddingRight="10dp">

                <ImageView
                    android:id="@+id/three_dots"
                    android:layout_width="15dp"
                    android:layout_height="wrap_content"

                    android:src="@drawable/dots" />

                <TextView

                    android:id="@+id/name"
                    android:layout_width="match_parent"
                    android:layout_height="40sp"
                    android:text=""
                    android:lineSpacingExtra="-5dp"
                    android:textColor="@color/black" />

            </LinearLayout>

            <View
                android:id="@+id/title22"
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:layout_marginBottom="2dp"
                android:layout_marginTop="2dp"
                android:background="#cfcfcf"
                android:gravity="center" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingRight="10dp"
                android:paddingTop="3dp"
                android:paddingBottom="3dp"
                android:paddingLeft="10dp"
                android:text="نحو" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true">

            <ImageView
                android:id="@+id/free_tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:src="@drawable/free" />

            <ImageView
                android:id="@+id/des_tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:src="@drawable/des_tag" />

            <ImageView
                android:id="@+id/music_tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:src="@drawable/music_tag" />

        </LinearLayout>
    </RelativeLayout>
</android.support.v7.widget.CardView>

and my method in recycleview adapter :
    @Override
    public RecyclerViewHolderMain onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        // This method will inflate the custom layout and return as viewholder
        LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());

        ViewGroup mainGroup = (ViewGroup) mInflater.inflate(
                R.layout.item_main_row, viewGroup, false);
        RecyclerViewHolderMain listHolder = new RecyclerViewHolderMain(mainGroup);
        return listHolder;

    }

this my crash logs:
FATAL EXCEPTION: main
  Process: com.rohamweb.hozebook, PID: 6006
  android.view.InflateException: Binary XML file line #20: Binary XML file line #20: Error inflating class <unknown>
        at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
        at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at com.rohamweb.hozebook.RecyclerViewAdapterMain.onCreateViewHolder(RecyclerViewAdapterMain.java:144)
        at com.rohamweb.hozebook.RecyclerViewAdapterMain.onCreateViewHolder(RecyclerViewAdapterMain.java:22)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6078)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5248)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5158)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2061)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1445)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1408)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:555)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3379)
        at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2906)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
        at android.view.View.measure(View.java:18788)
        at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1283)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.widget.ScrollView.onMeasure(ScrollView.java:340)
        at android.view.View.measure(View.java:18788)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1662)
        at android.view.View.measure(View.java:18788)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:703)
        at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:770)
        at android.view.View.measure(View.java:18788)
        at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
        at android.view.View.measure(View.java:18788)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.

i used picaso for show image:
   File f = new File(arrayList.get(position).getImagepath());
Picasso.with(context)
        .load(f)
        .resize(sizeX, sizeY)
        .centerCrop()
        .error(R.drawable.logo).placeholder(R.drawable.logo)
        .into(mainHolder.bookImage);


text:
Q: Weak p-summability of Schauder basis It is know that in a Hilbert space $H$, an orthonormal basis $(e_i)_{i\in \mathbb{N}}$ is weakly 2-summable, that is, $\sup_{h\in B_H}\sum_{i=1}^\infty \langle h,e_i\rangle^2<\infty$.
I was wondering if we have an analogous statement in a Banach space $B$ with a Schauder basis $(b_i)_{i\in \mathbb{N}}$. More precisely, is it true for some $p>0$ that $\sup_{b^*\in B_{B^*}}\sum_{i=1}^\infty \vert\langle b_i,b^*\rangle\vert^p<\infty$?


text:
Q: How to create custom notification messages? I have to do a notifications section in my project using SharePoint 2013. There is a set of notifications created and assigned to different users. I want to show these notifications (one or many), when the user logs in to the application as a popup message. Also, it should be able to show the message which is triggered automatically on a hourly/daily/weekly basis depending on a custom setting. One or many messages should be there in a single notification message.
I'm new to sharepoint, hence could you please suggest how to do this ?

A: I used sharepoint ui notifications long back. You can find a quick reference here http://msdn.microsoft.com/en-us/library/office/ff408137(v=office.14).aspx
It is one of the easiest way to show notifications.


text:
Q: Insertion of text between List of data in android I have no idea of how would be this done in android. The image is provided Its a ux created in html and wanted the same in android. The thing is I thought it can be attached in recycler view and coded it in this way:
public class FourFragment extends Fragment {

    RecyclerView rv_notify;
    MyAdapter adapter;
    ArrayList<Player> players=new ArrayList<>();
    TextView notify_count_tv;
    Context c;

    public FourFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_four, container, false);
        c=v.getContext();
        notify_count_tv=(TextView) v.findViewById(R.id.profile_notification_count);
        ImageView imageView = (ImageView) v.findViewById(R.id.profile_imageview);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_bank);
        Bitmap blurredBitmap = blur(bitmap);
        imageView.setImageBitmap(blurredBitmap);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);

        rv_notify= (RecyclerView) v.findViewById(R.id.profile_recyclerView);
        rv_notify.setLayoutManager(new LinearLayoutManager(getContext()));
        rv_notify.setItemAnimator(new DefaultItemAnimator());

        adapter=new MyAdapter(getContext(),players);

        players.clear();
        for(int i=0;i<=6;i++){
            int id=i;
            if(i!=5) {
                String notify = "Your appointment for UI design has been accepted by Subajeeth Mukerjeee";
                String time = "" + i;
                String date = "17 Oct 2016";
                Player p = new Player(id, notify, time, date, R.mipmap.ic_bank);
                players.add(p);
            }else {
                rv_notify.setAdapter(adapter);
                players.clear();
                TextView textView = new TextView(c);
                textView.setText("123");
                String notify = "Your appointment for UI design has been accepted by Subajeeth Mukerjeee";
                String time = "" + i;
                String date = "17 Oct 2016";
                Player p = new Player(id, notify, time, date, R.mipmap.ic_bank);
                players.add(p);
            }
        }

        if(!(players.size()<1)){
            notify_count_tv.setText(""+players.size());
            rv_notify.setAdapter(adapter);
        }

        return v;
    }

    public Bitmap blur(Bitmap image) {
        float BLUR_RADIUS = 23.3f;
        if (null == image) return null;

        Bitmap outputBitmap = Bitmap.createBitmap(image);
        final RenderScript renderScript = RenderScript.create(getContext());
        Allocation tmpIn = Allocation.createFromBitmap(renderScript, image);
        Allocation tmpOut = Allocation.createFromBitmap(renderScript, outputBitmap);

        //Intrinsic Gausian blur filter
        ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        theIntrinsic.setRadius(BLUR_RADIUS);
        theIntrinsic.setInput(tmpIn);
        theIntrinsic.forEach(tmpOut);
        tmpOut.copyTo(outputBitmap);
        return outputBitmap;
    }

}

but the view only print the last remaining data left replacing the other.
I also tried to insert a textview in middle to get result of the image but dat too failed. Can you help me make the same as the image provided in android?

A: You want to use sticky-headers-recyclerview for section headers with list.


text:
Q: svn checkout most recent date and prune empty directories In CVS i can be specific with the type of checkout i need to acquire... For expample:
cvs -q checkout -d CMS -P CMS
Which means, checkout somewhat quite and create a directory called CMS and Prune empty directories and place it in CMS folder.
I need to create the same directory structure using SVN checkout... Here is what i have so far.
svn checkout http://svn/project/CMS/trunk CMS -q

There are some empty folders that i have in my repository that i need to keep but not checkout during a checkout.  I know SVN uses --depth and --empty but i don't think that will take care of my request.
Basically i need to checkout my repository but exclude empty folders during checkout... Any one know what the command would be for that? To bad i couldn't use the -P like i can in CVS.
Thanks for you help.

A: I think you misunderstand how CVS works with empty folders.
In CVS, only files are versioned and not directories (we'll use that term instead of folders). When you do a checkout in CVS, CVS will create directories as needed. However, since directories weren't versioned, directories that contained no files are never created. It's why you'll see files like .keep in otherwise empty directories. It's the only way you could get CVS to create a required empty directory.
Things are different if you do a cvs update. In that case, a directory might become empty. Passing a -P to the cvs update command would remove those folders.
Unlike CVS, Subversion versions directories as well as files. If you create an empty directory in Subversion, it will be checked out as an empty directory. If there's a directory you no longer want, you should remove it like you would remove a file that's no longer needed via the svn delete command.
Therefore, there's no equivalent to the CVS -P command line parameter.


text:
Q: How to find difference, compare and get each field values in NSDate variables? How can i do the following operations on NSDate variables?

*

*How to compare two NSDate variables?

*How to find difference between two NSDate variables?

*How to get each separate value of minute, hours and days from NSDate variable?
We can get the current date by
NSDate *currentDate=[NSDate date];

But it will give the result of
    yyyy-mm-dd hh:mm:ss GMT
From this, can i get hour field alone? or month value only?

A: From NSDate class reference, you have instance methods to do these -

*

*How to compare two NSDate variables? Ans: isEqualToDate:

*How to find difference between two NSDate variables? Ans: timeIntervalSinceDate:

*How to get each separate value of minute, hours and days from NSDate variable? links
PS: Use Google to the maximum.


text:
Q: Function to get the index of the combinations produced by itertools.product's combination/matrix representation in python? For example:
alist=[['a','b'],[1,2]]

and the combination
('a',1)

Is there a way to get the index of this combination i.e. (0,0) because both are at the 0-th position in their respective list or a matrix like
[[1,1],[0,0]]

where the 1s indicate the position get selected to form the combination?

A: Well you can just create the indices as ruaridhw pointed out. You can do it like so:
from itertools import product

alist = [['a','b'],[1,2]]
print [a for a in product(*alist)]
print [list(a) for a in product(*[range(len(x)) for x in alist])]

Output:
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
[[0, 0], [0, 1], [1, 0], [1, 1]]

A: Since each element of given combination c is to be found in the corresponding row of alist, the following returns the tuple of their indices:
alist = [['a','b'],[1,2]]
c = ('a',1)
ix = tuple(row.index(elem) for row, elem in zip(alist, c))

Here ix becomes (0, 0)


text:
Q: Mozilla not getting SAML context I am using  below code to get my credential, it is woking fine in IE,
Why it is not working in mozilla.
SecurityContextImpl obj = (SecurityContextImpl) session
            .getAttribute("SPRING_SECURITY_CONTEXT");
SAMLCredential credential = (SAMLCredential) obj.getAuthentication()
            .getCredentials();

if any body has encounter situation like this.
I am using Spring SAML

A: Resolved as responseSkew was I am using the default 60 below change helped
<bean id="webSSOprofileConsumer" class="org.springframework.security.saml.websso.WebSSOProfileConsumerImpl"> <property name="responseSkew" value="600"/> <!-- 10 minutes --> </bean>


text:
Q: Magento: Canonical Link disappeared I have modified the _prepareLayout() function in Mage_Catalog_Block_Category_View class to have a customized canonical url. After modifying the URL, the canonical code does not display in the html source code anymore.
Here are my codes:
    protected function _prepareLayout() {

    Mage_Core_Block_Template::_prepareLayout();

    $this->getLayout()->createBlock('catalog/breadcrumbs');

    if ($headBlock = $this->getLayout()->getBlock('head')) {
        $category = $this->getCurrentCategory();
        if ($title = $category->getMetaTitle()) {
            $headBlock->setTitle($title);
        }
        if ($description = $category->getMetaDescription()) {
            $headBlock->setDescription($description);
        }
        if ($keywords = $category->getMetaKeywords()) {
            $headBlock->setKeywords($keywords);
        }
        if ($this->helper('catalog/category')->canUseCanonicalTag()) {
            //$headBlock->addLinkRel('canonical', $category->getUrl());
            if ($category->getCategoryUrlAlias()) {
                $url = Mage::getBaseUrl() . $category->getCategoryUrlAlias();
            } else {
                $key = $this->helper('my_package/category')->getIsTitleCategoryKey($category);
                $url = $category->getUrl();
                $url = $this->_removeKeyFromUrl($url, $key);
            }
            $headBlock->addLinkRel('canonical', $url);
        }
        /*
          want to show rss feed in the url
         */
        if ($this->IsRssCatalogEnable() && $this->IsTopCategory()) {
            $title = $this->helper('rss')->__('%s RSS Feed', $this->getCurrentCategory()->getName());
            $headBlock->addItem('rss', $this->getRssLink(), 'title="' . $title . '"');
        }
    }

    return $this;
}

I have verified that the $url variable always have the customized url value that I want. I'm wondering if there is any validation function that's preventing me to have a customized canonical URL?
Any help will be greatly appreciated. Thanks!


text:
Q: Subscribe Orion without receive old entities There is some way to subscribe to Orion (e.g. Car entity), without receive the old entities?
Example:
Orion has -> Car A, Car B.
I do onchange subscription and Orion sends me at same time:
Car A notification and Car B notification.
We need the following:
Orion has -> Car A, Car B.
I do onchange subscription but don't receive nothing at this moment. If in a future Orion receives Car B, or changes some attribute of Car A or Car B, then send the notification.
Is that possible?

A: The behaviour is explained in the the user manual:

You may wonder why accumulator-server.py is getting this message if you don't actually do any update. This is because the Orion Context Broker considers the transition from "non existing subscription" to "subscribed" as a change.

We understand that for some uses cases this is not convenient. However, behaving in the opossite way ruins another uses cases which need to know the "inicial state" before starting getting notifications corresponding to actual changes. The best solution to make everybody happy is to make this configurable, so each client can chose what it prefers. This feature is currently in our roadmap (see this issue in github.com).
While this gets implemented in Orion, in your case maybe a possible workaround is just ignore the first received nofitication belonging to a subscription (you can identify the subscription to which one notification belongs by the subscriptionId field in the notification payload). All the following notifications beloning to that subscription will correspond to actual changes.
EDIT: the posibility of avoiding initial notification has been finally implemented at Orion. Details are at this section of the documentation. It is now in the master branch (so if you use fiware/orion:latest docker you will get it) and will be include in next Orion version (2.2.0).


text:
Q: Naming Convention for SQL AD Group Logins (Potential Bug) My team is attempting to come up with a new naming standard for our Active Directory groups within SQL Server to help manage permissions.
DOMAIN\ENVIRONMENT_DATABASE_FUNCTION
EXAMPLES:
TEST\STAGE_StackOverflow_RW
TEST\STAGE_StackOverflow_RO
TEST\STAGE_StackOverflow_EX
However, before implementing this convention we decided to look up character limitations of both active directory and SQL Server Logins and while the character limit itself doesn't appear to be a direct issue, we did stumble upon this article from 2014: Max Length of AD Names for Security
Tl;dr of that forum post:

My team and I used one of our dev servers to attempt to recreate this potential issue, but realized that it was very difficult to test as the permissions on AD groups sometimes don't propagate for hours even if you restart the server (tested this last night and proved it).  I am wondering if anybody knows if this issue has been resolved on SQL Server 2016/2017.  Is it safe to use the naming convention I posted at the very top where the first 20 characters are the same or do we have to come up with a way of abbreviating all of our objects so that the first 20 characters of a login are NEVER the same.


text:
Q: convert audio to wav/mp3 using pure JavaScript I'm trying to convert an audio file directly recorded from the browser in a friendly format, such as wav or mp3, using only pure JavaScript, I've tried several things but nothing worked so far.
The only thing I managed to do is to record audio from the browser.
Here's my code :
navigator.mediaDevices.getUserMedia({ audio: true })
  .then(stream => {
    const mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();
    const audioChunks = [];
    mediaRecorder.addEventListener("dataavailable", event => {
      audioChunks.push(event.data);
    });
    mediaRecorder.addEventListener("stop", () => {
      const audioBlob = new Blob(audioChunks);
      const audioUrl = URL.createObjectURL(audioBlob);
      const audio = new Audio(audioUrl);
    });
    setTimeout(() => {
      mediaRecorder.stop();
    }, 3000);
  });


text:
Q: Confusion about ordinals in Devlin "The Joy of Sets" Theorem 1.7.7 I'm working through Devlin's "The Joy of Sets". Theorem 1.7.7 states: Let $X$ be an ordinal. Let $Y\subset X$. If $Y$ is an ordinal, then $Y=X_{a}=\{x\in X\vert x \lt a\}$ for some $a \in X$.
Now, I know this theorem to be true but the first line of his proof seems wrong to me. I'm sure the misunderstanding is mine, but might you help me understand where I'm confused? He begins by letting $a$ be the smallest member of $X-Y$ and then simply states "Thus $X_{a}\subseteq Y$". I don't see how this follows. It seems to me that if $a$ is the smallest member of $X-Y$ then $Y \subseteq X_{a}$. I know that these two aren't mutually exclusive, but I don't get Devlin's intuition that $X_{a} \subseteq Y$.
To show you where I'm coming from, it seems to me that if $a$ is the smallest member of $X-Y$ then $a \notin Y$. However, $a\in X$ and so we know that $X_{a}$ is an ordinal and $X_{a} \subset X$. Thus both $Y$ and $X_{a}$ are ordinals that are subsets of $X$. Since $X_{a}=a$ and $a\notin Y$ we know that $X_{a}\notin Y$. This can only happen if $X_{a} = Y$ or if $Y \subset X_{a}$, thus we conclude $Y \subseteq X_{a}$.
Can someone explain to me where I've gone wrong so that I can understand why Devlin states "Thus $X_{a}\subseteq Y$". Thanks!

A: If $b<a$, then $b\not\in X-Y$ since $a$ is defined to be the smallest element of $X-Y$.
But if $b\not\in X-Y$ then necessarily $b\in Y$, and since $b$ was an arbitrary element of $X_a$ we obtain $X_a\subseteq Y$.


text:
Q: Font awesome ttf files not working in android font family I am working on android app, I downloaded font awesome ttf files and added to android studio project. It is not working but if I try with icoomon working fine. Can anyone please help me.
code:
<TextView
            android:text="aws"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView2" android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toTopOf="@+id/button" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"
            app:fontFamily="@font/fa_brands_400"/>

A: First of all make sure you place your .ttf dowloaded file in your Asset folder.
Then create a class called FontAwesome that extends TextView like this
  public class FontAwesome extends TextView {

public FontAwesome(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public FontAwesome(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public FontAwesome(Context context) {
    super(context);
    init();
}

private void init() {

//Font name should not contain "/".
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
            "fontawesome.ttf");
    setTypeface(tf);
}

}
Finally you create your TextView as follow
<PACKAGE_NAME.Fontawesome
android:id="@+id/userLogin"
android:text="  Login Now"
android:clickable="true"
android:onClick="login"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

I hope this helps you.


text:
Q: Converting 4 dimensional tensors into list of lists of lists (Python) I have 6 tensors of shape (batch_size, S, S, 1) and I want to combine them in one python list of size (batch_size, S*S, 6) - so every element of tensor should be inside the inner list.
Can this be achieved without using loops? What's the efficient way to solve it?

A: Let batch_size=10 and S=4 for the purpose of this example:
 >>> x = [torch.rand(10, 4, 4, 1) for _ in range(6)]

Indeed the first step is to concatenate the tensor on the last dimension axis=3:
>>> y = torch.cat(x, -1)
>>> y.shape
torch.Size([10, 4, 4, 6])

Then reshape to flatten axis=1 and axis=2, you can do so with torch.flatten here since the two axes as adjacent:
>>> y = torch.cat(x, -1).flatten(1, 2)
>>> y.shape
torch.Size([10, 16, 6])


text:
Q: How to get the location coordinate based on nickname I am using the uber sdk for iOS. And i see I have to specify the
button.setProductID("abc123-productID")
button.setPickupLocation(latitude: "37.770", longitude: "-122.466", nickname: "California Academy of Sciences")
button.setDropoffLocation(latitude: "37.791", longitude: "-122.405", nickname: "Pier 39")

How can I get the coordinate information based on the location's nickname.

A: The iOS Uber SDK doesn't provide this functionality. However, Apple's CoreLocation framework has the CLGeocoder class that provides both forward-geocoding and reverse-geocoding. To convert an address into coordinates to pass to the request button, you can use the function geocodeAddressString:completionHandler:.


text:
Q: redirect url exact match with htaccess like case sensitive redirect url exact match with htaccess not redirect if query string or anything after index.php
Redirect This Page: https://example.com/demo/index.php
To Page: https://example.com/ (home page)

But Do Not redirect: https://example.com/demo/index.php/*

 Do NOT redirect: https://example.com/demo/index.php/password

 Do NOT redirect https://example.com/demo/index.php?m=page
  not redirect if any other combination

only redirect https://example.com/demo/index.php to https://example.com/

this script not working
RewriteEngine On
RewriteBase /
RewriteRule ^demo/index.php /demo/index.php?m=page[L,NC,END]
RewriteRule ^demo/index.php$ https://example.com/ [L,R=301]

A:
only redirect https://example.com/demo/index.php to https://example.com/

If you only want to redirect that exact URL, without a query string then you need to reverse your existing rules and include an additional condition that checks that the QUERY_STRING is empty. The RewriteRule only matches against the URL-path, which excludes the query string.
You are also missing a space before the flags argument in the first rule.
For example:
# Redirect exact URL to home page
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^demo/index\.php$ / [R=302,L]

# Redirect other URLs with query string OR path-info
RewriteRule ^demo/index\.php /demo/index.php?m=page [NC,L]

You don't need L and END.
Test with 302, and change to 301 only once you have confirmed it works OK. To avoid caching issues.

A: You may use these rules in site root .htaccess:
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+demo/index\.php\s [NC]
RewriteRule ^ / [L,R=301]

RewriteRule ^demo/index\.php$ $0?m=page [QSA,NC,L]

A: This was created by htaccess redirect generator I use very often.
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^demo/index\.php$ https://example.com/? [R=301,L]

Maybe "?" sign is redundant because of empty query string match.
Not sure, but You also can try to add
RewriteCond %{REQUEST_METHOD} !=POST

in case You can't log in. All together:
RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^demo/index\.php$ https://example.com/? [R=301,L]


text:
Q: Java Set Bigdecimal abbreviation Does Java have a BigDecimal set abbreviation?
This is for float. What is for BigDecimal?
import java.math.BigDecimal;

data.setPaymentAmount(25F);

A: tl;dr
Replace your float numeric literal with passing text to a constructor.
data.setPaymentAmount( new BigDecimal( "25" ) );

Details
The first word in the Javadoc for BigDecimal is "immutable". So you cannot change the number content of such an object. Calling methods such as add, subtract, multiply, and divide result in a new separate BigDecimal object being instantiated.
Never use a float/Float or double/Double as seen in your code, not if you care about accuracy. Those floating point types trade away accuracy for speed of performance. The BigDecimal class does the opposite, trading away speed for accuracy.
Your example code uses a float literal: 25F. Passing a float to the constructor of BigDecimal defeats the purpose of using a BigDecimal if your purpose is accuracy.
 To maintain accuracy, use String inputs.
BigDecimal x ;                 // Null object reference. No number involved.
x = new BigDecimal( "25" ) ;   // Representing *exactly* twenty-five in a new object of type `BigDecimal`.

In your code, if your set… method is meant to install a BigDecimal object, pass a BigDecimal object.
data.setPaymentAmount( new BigDecimal( "25" ) ) ;


text:
Q: Proof verification : A weird identity involving sums I recently managed to solve a question that I asked a few days ago, but that was unfortunately closed, probably because it wasn't clear enough. Here is the question :
Let $ n $ be a positive integer, prove the following identity : $$ \sum_{k=0}^{n}{\frac{1}{2k+1}\binom{n}{k}}=\left(\sum_{k=0}^{n}{\frac{1}{2^{k}}\binom{2k}{k}}\right)\left(\sum_{k=0}^{n}{\frac{\left(-1\right)^{k}}{2k+1}\binom{n}{k}}\right) $$
What I'm asking you for is to verify the following solution for me.
First of all : $$ \sum_{k=0}^{n}{\frac{1}{2k+1}\binom{n}{k}}=\sum_{k=0}^{n}{\binom{n}{k}\int_{0}^{1}{x^{2k}\,\mathrm{d}x}}=\int_{0}^{1}{\left(1+x^{2}\right)^{n}\,\mathrm{d}x}\overset{\mathrm{denoted}}{=}I_{n}$$
Then :\begin{aligned} I_{n}=\int_{0}^{1}{\left(1+x^{2}\right)^{n}\,\mathrm{d}x}&=\left[x\left(1+x^{2}\right)^{n}\right]_{0}^{1}-2n\int_{0}^{1}{x^{2}\left(1+x^{2}\right)^{n}\,\mathrm{d}x}\\ &=2^{n}-2n\int_{0}^{1}{\left(\left(1+x^{2}\right)^{n}-\left(1+x^{2}\right)^{n-1}\right)\mathrm{d}x} \\ I_{n}&=2^{n}-2n\left(I_{n}-I_{n-1}\right)\\ \iff I_{n}&=\frac{2^{n}}{2n+1}+\frac{2n}{2n+1}I_{n-1}\end{aligned}
In order to solve this recurrence relation, we'll multiply everything by $ \prod\limits_{k=1}^{n}{\frac{2k+1}{2k}} $, so that we could have telescopic cancelling between the consecutive terms. Meaning, $$ \prod_{k=1}^{n}{\frac{2k+1}{2k}}I_{n}=\frac{2^{n}}{2n+1}\prod_{k=1}^{n}{\frac{2k+1}{2k}}+\prod_{k=1}^{n-1}{\frac{2k+1}{2k}}I_{n-1} $$
Since : $$ \frac{2^{n}}{2n+1}\prod_{k=1}^{n}{\frac{2k+1}{2k}}=\frac{2^{n}\prod\limits_{k=0}^{n-1}{\left(2k+1\right)}}{\prod\limits_{k=1}^{n}{\left(2k\right)}}=\frac{\left(2n\right)!}{2^{n}\left(n!\right)^{2}}=\frac{1}{2^{n}}\binom{2n}{n} $$
We get that for any $ k\geq 1 $ : \begin{aligned} \prod_{j=1}^{k}{\frac{2j+1}{2j}}I_{k}-\prod_{j=1}^{k-1}{\frac{2j+1}{2j}}I_{k-1}&=\frac{1}{2^{k}}\binom{2k}{k}\\ \Longrightarrow\sum_{k=1}^{n}{\left(\prod_{j=1}^{k}{\frac{2j+1}{2j}}I_{k}-\prod_{j=1}^{k-1}{\frac{2j+1}{2j}}I_{k-1}\right)}&=\sum_{k=1}^{n}{\frac{1}{2^{k}}\binom{2k}{k}}\\ \iff \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \prod_{k=1}^{n}{\frac{2k+1}{2k}}I_{n}-1&=\sum_{k=1}^{n}{\frac{1}{2^{k}}\binom{2k}{k}}\\ \iff \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ I_{n}&=\left(\prod_{k=1}^{n}{\frac{2k}{2k+1}}\right)\left(\sum_{k=0}^{n}{\frac{1}{2^{k}}\binom{2k}{k}}\right)\end{aligned}
Secondly : $$ \sum_{k=0}^{n}{\frac{\left(-1\right)^{k}}{2k+1}\binom{n}{k}}=\sum_{k=0}^{n}{\left(-1\right)^{k}\binom{n}{k}\int_{0}^{1}{x^{2k}\,\mathrm{d}x}}=\int_{0}^{1}{\left(1-x^{2}\right)^{n}\,\mathrm{d}x}\overset{\mathrm{denoted}}{=}J_{n} $$
Then :\begin{aligned} J_{n}=\int_{0}^{1}{\left(1-x^{2}\right)^{n}\,\mathrm{d}x}&=\left[x\left(1-x^{2}\right)^{n}\right]_{0}^{1}+2n\int_{0}^{1}{x^{2}\left(1-x^{2}\right)^{n}\,\mathrm{d}x}\\&=2n\int_{0}^{1}{\left(\left(1-x^{2}\right)^{n-1}-\left(1-x^{2}\right)^{n}\right)\mathrm{d}x} \\ J_{n}&=2n\left(J_{n-1}-J_{n}\right)\\ \iff \ \ \ \ \ \ \ \ \ J_{n}&=\frac{2n}{2n+1}J_{n-1}\\ \Longrightarrow \prod_{k=1}^{n}{\frac{J_{k}}{J_{k-1}}}&=\prod_{k=1}^{n}{\frac{2k}{2k+1}}\\ \iff \ \ \ \ \ \ \ \ \ J_{n}&=\prod_{k=1}^{n}{\frac{2k}{2k+1}}\end{aligned}
Thus, $$ \sum_{k=0}^{n}{\frac{1}{2k+1}\binom{n}{k}}=\left(\sum_{k=0}^{n}{\frac{\left(-1\right)^{k}}{2k+1}\binom{n}{k}}\right)\left(\sum_{k=0}^{n}{\frac{1}{2^{k}}\binom{2k}{k}}\right) $$
What do you guys think ?


text:
Q: Excel changes dates where the day is lower than the month (e.g 2nd april) to the reverse (e.g 4th feb) I am having some toruble with excel and dates. The situation is as follows:
We have a monthly report with a number of tabs which the macro imports into a central spreadsheet, it has about 120 columns. After importing, I need to add some formulas in the final few columns that are relevant to the data but not included in the data, and one of these is the period number (we work for a client with the year starting on April 1st and 13 periods of 4 weeks in the year). To acomplish this, I have a seperate sheet with all of the dates in column A, then periods and other data in the following columns. A simple Vlookup looks up the date and returns the period.
However, some of the dates come stored as text (and so the vlookup has #N/A), simple fix, paste special - add a blank cell and voila it works. And this does work if I do it manually. But this is meant to do all the work for the user so I tried to do it programatically as per the code below:
'Sheets("dates and Periods").Activate
'Range("P1").Copy
'Sheets("Data").Activate
'Range(Cells(2, 5), Cells(lastrow, 5)).PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd
'Range(Cells(2, 5), Cells(lastrow, 5)).NumberFormat = "dd/mm/yyyy"

I get the blank cell from "Dates and Periods" because I know it will definitely be blank.
Now when I run this code, it works for most values. However for all dates in column E where the day is smaller than the month, e.g 1st April, 4th May etc, it switches the day and month around, and this is not formatting, by changing to long date I can see it has changed the data around.
Is there a way around this? I have looked for a solution but all of the problems I could find when searching were to do with the 1904 date system or with formatting.
Any help would be appreciated.
Solution: [breaking it into parts and putting it back together]
For Each cell In Range(Cells(2, 5), Cells(lastrow, 5))

cell.Value = Mid(cell, 4, 2) & "/" & Left(cell, 2) & "/" & Right(cell, 4)

Next cell

A: i have had this problem many times. the answer is usually specific to the solution, but you can try converting the date to a string in dd-mmm-yyyy format, then back again.

A: When you enter something that looks like a date into an Excel cell, it will parse it according to the Windows Regional Settings.  Strings that don't fit get entered as text, strings that do get turned into Excel dates.  This latter will usually not be the same as the intended date.
I would suggest correcting this during the import process.  Exactly how to do this depends on specifics you have not included, but the process is to use the Data/Import process and go through the Text Import Wizard.  That wizard will allow you to specify the format for each column; including the date format for E.  That will ensure that all of your dates are properly understood by Excel as being dates.  So if the incoming date format is MDY, you would specify MDY; and Excel would properly store it, and then display it either in your default setting, or in whatever way you format that column.
Another option, if feasible, would be to alter the report generator so that it generates dates that are in the same format as the short date format of your Windows Regional Settings

A: I import a large number of files emailed to me into data bases and this is consistently a problem.  The issue isn't caused by incorrect data, bad formatting or any such thing, but simply an error in excel (I believe Microsoft call it a feature), where it tries to understand dates in the American format and automatically 'corrects' anything in finds.  It is made worse because if a date doesn't work in the American format then it converts it into a text file leaving you with some dates formatted one way, some another.
The only solution I have found is to alter the data on the source sheet so that Excel cannot understand it as a date in any way, then import it, then convert it back, a huge phaff.  Microsoft please sort this out, it's wasting so much time programming workarounds!


text:
Q: Does WPF DataGrid Implicitly Convert IEnumerable to List When Binding? Most of my question is in the title: Does WPF DataGrid Implicitly Convert IEnumerable<X> ItemsSource to List<x>?
I have a WPF, using MVVM, etc. ViewModel property is defined as ...
    private IEnumerable<Plan> _PlanListItems;
    public IEnumerable<Plan> PlanListItems
    {
        get { return _PlanListItems; }
        protected set { RaiseAndSetIfChanged(ref _PlanListItems, value); }
    }

    // ...
    // in some method
    OpenPlanItems = await service.GetAllPlansAsync();

In service ...
    public IEnumerable<Plan> GetAllPlans()
    {
        using (MyEntities ent = new MyEntities())
        {
            return (from a in ent.DbPlans select a)
                .AsEnumerable()
                .Select(o => o.Convert());   // Does some stuff to convert DbPlan entity into Plan class
        }
    }

    public async Task<IEnumerable<Plan>> GetAllPlansAsync()
    {
        return await Task.Run(() => GetAllPlans());
    }

In XAML ...
    <DataGrid ItemsSource="{Binding PlanListItems}"  ...>

This throws an exception: The operation cannot be completed because the DbContext has been disposed error. Another question indicates a cause could be due to late execution on the IEnumerable object (i.e. trying to enumerate after the context has been disposed).
Additionally, I have similar code that has a .ToList() conversion inside a method similar to GetAllPlans(). Something like this, but not the actual code:
    public List<Plan> GetAllPlans()
    {
        using (MyEntities ent = new MyEntities())
        {
            return (from a in ent.DbPlans select a)
                .AsEnumerable()
                .Select(o => o.Convert()).ToList();   // Does some stuff to convert ...
        }
    }

It turned out to be a slow method (>5 seconds). When I removed the .ToList() conversion, it dropped the time to <0.2 seconds, but the inefficiency returned (and almost the exact same duration) when I bind the result to a DataGrid.
This leads me to believe that WPF DataGrid implicitly converts IEnumerable bound items to a List as part of the binding process. Is that true? And if so, is there a way to avoid the implicit conversion?

A: The reason your IEnumerable<T> service takes < 0.2 seconds to return is because it isn't actually returning data: it is returning more of 'how to get the data, when you're actually interested in it'. It will only actually give you the data when you iterate over it or otherwise access it. This will give you the DbContext has been disposed of error you had, if the client code tries to make use of that 'how to get the data' outside of the scope of the context.
This is why when you have .ToList() on your service it takes longer: because it is actually returning data. Real data you can really use on the client without worrying about the scope of the context.
The DataGrid just needs its ItemsSource collection to implement the IEnumerable interface, so it can enumerate over the items as and when it needs to. It isn't "converting things to a list" per se, it is just enumerating the collection.


text:
Q: How to find distance from emitter using TDOA? I have the three receivers set up: $A (0.5, 0)$ $ B (-0.5, 0)$ $ C (0, 1)$
I know that the signal arrives at $C$ first. It then arrives at $B$  $2.63464*10^{-4}$ later. It finally arrives at $A$ last $7.07023 * 10^{-4}$ seconds after it arrives at $C$.
How would I use this information to find the point of emission? I know it has to do with trilateration. (Note, please do not link a Wikipedia page. I've already tried that as well as intensive googling.)

A: I think you can only approximate the position of the emitter
Let's call the emitter E and the speed of the signal s
then we have $ EB-EC = 2.6364 *10^{-4} s$
and  $EA-EC= 7.07023 * 10^{-4} s$
and s is the same in each formula
I (using geometers sketchpad) played around with it a bit and found that E is around (-1 , 1.3) but be aware this is just a very rough guess where E is (it can be much further away).
the proper way is to plot some hyperbolics and then E on the intersection of some of them and so but that is abit beyond my knowledge.
still a wikipedia link (sorry :)
https://en.wikipedia.org/wiki/Hyperbolic_navigation
https://en.wikipedia.org/wiki/Multilateration
sadly did not find a good geometry reference for this