text:
Q: How to plot this in MATLAB This is what I'm trying to do: I have the following diagram (called the phase space plot):
Phase space diagram http://www.thestudentroom.co.uk/attachment.php?attachmentid=185627&d=1354917185
The paper which i'm following says :

The phase space plots of the signals were divided
into a grid of 20x20 squares and the number of points c(i,j)
within a square was computed to form the phase space
density matrix c.

I tried the following code in order to do the above :
    %%matrix(1,:) Is the first row and all columns. This row has the actual signal of
    %interest and corresponds to the x axis of the above graph.
    and is the x axis of the above graph.
    %matrix(2,:) Is the second row and all columns and comprises of the y axis of the
    above graph.

    for i=1:180:size(matrix,2)
        for j=1: 180 : size(matrix,2)
            if isnan(matrix(1,i))
            else
                c(1,i)=matrix(1,i);
            end

            if isnan(matrix(2,i))
            else
                c(2,i)=matrix(2,j);
            end
        end
    end

    figure,plot(c)

The output is :

I am meant to get something like this :
paper http://www.thestudentroom.co.uk/attachment.php?attachmentid=185629&d=1354918102
The LHS is the phase space diagrams and the RHS corresponds to the respective plots which I am trying to get to.
Help plz!!!
Would be very grateful.
Thanks!

A: You can use function hist3.
For example
x = randn(100, 2);
hist3(x, [20 20]);

A: Maybe you probably want some kind of 2d histogram?
Look here for help: http://blogs.mathworks.com/videos/2010/01/22/advanced-making-a-2d-or-3d-histogram-to-visualize-data-density/
You can also look at the file exchange for some 2D hist functions(my first search gave me this: http://www.mathworks.com/matlabcentral/fileexchange/1487)
EDIT: @3lectrologos has the right function


text:
Q: Azure Devops query - Group by month I'd like to create a query which shows the bugs created during the last 12 weeks grouped by each month, but I can't manage.
I have created a query that shows the number of bugs created each day (by date) but can't find a way aggregate them for each month.
Also tried doing it by the chart (Dashboard) but didn't manage as well.
The goal is to show whether the number of bugs gets lower or higher across the last 12 weeks.
Thanks

A: There's no built-in feature that an help group by month in query.
In Dashboard, you could choose to use Burndown/Burnup chart in Dashboard that may meet your requirment. In the configuration, you can add field criteria to limit the work items that appear in the chart. You can set Plot interval to Months. If you select Months, then burndown/burnup is calculated based on the last day of each month.

You could refer to the official page: Configure a Burndown or Burnup widget for more details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Yii2 application default event handler attach in application configuraiton How can I add an event handler in a yii2 application configuration file. In the guide it is specified, but not clearly explained. I don't want to create a component then bootstrap, and attach a handler in the component.
I just simply want to alter configuration params with the help of the Yii::$app->basePath parameter.
Now I can't use Yii::$app on params.php, because the application is still not bootstrapped.

A: Sorry. I just misunderstood the guide. It is very simple as yii2 itself.
Just need to attach the 'on beforeRequest' => function( $event) {...} , in the configuration file at first level. IN doc there is [ 'on beforeRequest'...] . This syntax just make me confused.


text:
Q: How do I check if a Twitter OAuth access_token is still valid? I'm writing a Django app and I want users to be able to supply their Twitter username and connect their Twitter account with their User in my app. (I'm not using Twitter to log them into my site; I just want them to connect their Twitter account with their account on my site, and give permissions for certain actions.)
Assuming I do that successfully, and I get back and store an access_token for the user, what's the best way to subsequently check that the access_token is still valid? i.e., if the user has later revokes access to my service on their Twitter account, I want to be able to check the access_token and, if it's invalid, delete it and prompt the user to re-authenticate.
The Flickr API has flickr.auth.checkToken and I guess I'm looking for the equivalent functionality with the Twitter API.

A: using python-twitter, you can verify if the credentials are ok using:
if api.VerifyCredentials() is not None:


text:
Q: Best practice (GRPC communication) architecture Microservice (List vs Loop) I want to know what do you think about this two ways to get user :
I have a Grpc service "GetUser" and "GetUsers"
Model of User
{
userName : string
email: string
firstName: string
LastName: string
}

I have userIds list (between 1 to 5000 Ids).
What is the more efficient :
Call Grpc => GetUsers(ids[])
Or loop Call Grpc => GetUser(id)

NOTE : anyway i will have one access to the DB by user

A: If you do a unary GetUser RPC in a loop, there will be additional framing per call, meaning more bytes on the wire. So, viewed from the perspective bytes transmitted/received, GetUsers is more "efficient".
However, a GetUsers RPC requires you to hold the whole dataset in memory at once. Since you apparently only need 5000 IDs, this may not be an issue for you. But for larger datasets, this can become a real issue.
If both the memory and the additional framing are unacceptable to you, you can look at a streaming RPC like:
rpc GetUser(stream GetUserRequest) returns (stream GetUserResponse);


text:
Q: Read MS SQL Server View to Pandas Dataframe I am trying to read a MS SQL Server view to a pandas dataframe.  At first I thought it was a table, so I wrote the following code (tables/views, server, database, ID and password have been changed to remove proprietary information):
import sqlalchemy as sa
import urllib
from datetime import date

today = date.today().isformat()

params = urllib.parse.quote_plus('DRIVER={ODBC Driver 17 for SQL Server};'
                                 + 'SERVER=mssql_server;DATABASE=database;UID='
                                 + 'user_id;PWD=password')
engine = sa.create_engine(f'mssql+pyodbc:///?odbc_connect={params}')

with engine.connect() as conn, conn.begin():
    # Read data and store in pandas dataframe.
    df1 = pd.read_sql_table('dbo.view1', conn)
    df2 = pd.read_sql_table('dbo.view2', conn)
    df3 = pd.read_sql_query('SELECT * FROM dbo.view3 WHERE date=' + today, conn)

but it resulted in the following errors:
Traceback (most recent call last):

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\sql.py", line 243, in read_sql_table
    meta.reflect(only=[table_name], views=True)

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 4261, in reflect
    "in %r%s: (%s)" % (bind.engine, s, ", ".join(missing))

InvalidRequestError: Could not reflect: requested table(s) not available in Engine(mssql+pyodbc:///?odbc_connect=DRIVER={ODBC Driver 17 for SQL Server};SERVER=mssql_server;DATABASE=database;UID=user_id;PWD=password): (dbo.view1)

During handling of the above exception, another exception occurred:
Traceback (most recent call last):

  File "<ipython-input-89-bbb0170e1399>", line 1, in <module>
    df1 = pd.read_sql_table('dbo.view1', engine)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\sql.py", line 245, in read_sql_table
    raise ValueError("Table {name} not found".format(name=table_name))

ValueError: Table dbo.view1 not found

That was when I found out I was trying to load a view and not a table, so I changed the code to:
import sqlalchemy as sa
import urllib
from datetime import date

today = date.today().isformat()

params = urllib.parse.quote_plus('DRIVER={ODBC Driver 17 for SQL Server};'
                                 + 'SERVER=mssql_server;DATABASE=database;UID='
                                 + 'user_id;PWD=password')
engine = sa.create_engine(f'mssql+pyodbc:///?odbc_connect={params}')

with engine.connect() as conn, conn.begin():
    # Read data and store in pandas dataframe.
    df1 = pd.read_sql('dbo.view1', conn)
    df2 = pd.read_sql('dbo.view2', conn)
    df3 = pd.read_sql('SELECT * FROM dbo.view3 WHERE date=' + today, conn)

Which resulted in the following errors:
Traceback (most recent call last):

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
    cursor, statement, parameters, context

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 581, in do_execute
    cursor.execute(statement, parameters)

ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The request for procedure 'view1' failed because 'view1' is a view object. (2809) (SQLExecDirectW)")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

  File "<ipython-input-76-6b8d4a0d911d>", line 1, in <module>
    df1 = pd.read_sql('dbo.view1', engine)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\sql.py", line 436, in read_sql
    chunksize=chunksize,

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1218, in read_query
    result = self.execute(*args)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\sql.py", line 1087, in execute
    return self.connectable.execute(*args, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 2182, in execute
    return connection.execute(statement, *multiparams, **params)

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 976, in execute
    return self._execute_text(object_, multiparams, params)

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1149, in _execute_text
    parameters,

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1250, in _execute_context
    e, statement, parameters, cursor, context

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1476, in _handle_dbapi_exception
    util.raise_from_cause(sqlalchemy_exception, exc_info)

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 398, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 152, in reraise
    raise value.with_traceback(tb)

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
    cursor, statement, parameters, context

  File "C:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\engine\default.py", line 581, in do_execute
    cursor.execute(statement, parameters)

ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The request for procedure 'view1' failed because 'view1' is a view object. (2809) (SQLExecDirectW)")
[SQL: dbo.view1]

I've tried searching for the answer but either haven't found it, or am looking in the wrong place.  Can reading a view to a pandas dataframe be done?  If so, what am I doing wrong?  Thanks in advance!

A: How about doing it this way?
import pypyodbc
cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
                        "Server=LAPTOP-CEDUMII6;"
                        "Database=TestDB;"
                        "Trusted_Connection=yes;")

cursor = cnxn.cursor()
dfObj = pd.DataFrame(cursor.execute('SELECT * FROM myTable1'))


text:
Q: converting nested tbl_df into tibble or data frame I'm running a function in the 'rnoaa' package that finds the 5 nearest weather stations to a data frame that contains nest box locations. This produces a nested tbl_df, a tibble for each nest box ID. I'd like to convert the tbl_df into a tibble or data frame that retains the corresponding nest box ID, but I'm not sure how to do it. Here's my code and an example of the data.
Import the data:
 nests<-structure(list(id = structure(1:5, .Label = c("29", "36", "39",
    "41", "42", "43", "45", "47", "48", "50", "51", "52", "53", "54",
    "55", "57", "58", "59", "60", "61", "62", "64", "65", "67", "69",
    "70", "71", "72", "73", "75", "77", "78", "79", "80", "81", "82",
    "84", "87", "88", "89", "90", "91", "92", "93", "95", "97", "99",
    "100", "102", "106", "108", "109", "110", "118", "123", "124",
    "125", "126", "127", "129", "130", "131", "133", "134", "136",
    "138", "140", "141", "144", "147", "149", "151", "155", "157",
    "158", "160", "161", "162", "163", "165", "167", "168", "169",
    "172", "174", "175", "177", "178", "179", "180", "181", "182",
    "186", "189", "190", "193", "195", "202", "205", "207", "208",
    "215", "217", "218", "225", "229", "230", "236", "240", "241",
    "243", "244", "246", "247", "248", "249", "251", "253", "254",
    "255", "257", "258", "259", "260", "261", "262", "263", "269",
    "270", "276", "292", "294", "295", "296", "297", "298", "300",
    "301", "302", "303", "305", "306", "307", "308", "309", "311",
    "316", "317", "318", "322", "323", "324", "326", "329", "330",
    "331", "332", "333", "334", "335", "336", "337", "338", "339",
    "342", "345", "346", "350", "351", "353", "358", "362", "363",
    "365", "366", "368", "369", "372", "379", "380", "381", "382",
    "384", "386", "387", "388", "390", "391", "392", "393", "394",
    "395", "396", "397", "398", "400", "401", "403", "404", "406",
    "410", "411", "414", "415", "416", "418", "420", "424", "425",
    "426", "428", "429", "430", "432", "433", "435", "436", "440",
    "441", "442", "445", "446", "447", "448", "449", "450", "451",
    "453", "458", "459", "461", "462", "463", "464", "465", "466",
    "469", "470", "471", "478", "479", "488", "490", "497", "503",
    "504", "506", "507", "508", "509", "512", "513", "514", "515",
    "516", "517", "518", "519", "520", "521", "527", "528", "529",
    "530", "531", "534", "540", "542", "545", "552", "553", "554",
    "556", "558", "561", "562", "563", "565", "566", "568", "569",
    "570", "571", "572", "573", "574", "575", "576", "577", "578",
    "580", "583", "584", "585", "591", "592", "595", "606", "608",
    "610", "612", "614", "615", "616", "617", "620", "621", "627",
    "628", "634", "635", "636", "637", "638", "639", "643", "647",
    "648", "651", "652", "653", "654", "656", "661", "662", "663",
    "664", "665", "667", "669", "670", "673", "674", "676", "677",
    "679", "680", "681", "684", "685", "690", "693", "694", "695",
    "706", "708", "716", "717", "719", "720", "728", "757", "759",
    "761", "777", "798", "801", "803", "818", "838", "839", "855",
    "856", "864", "865", "867", "868", "880", "890", "899", "901",
    "914", "915", "924", "985", "998", "999", "1002", "1003", "1004",
    "1019", "1020", "1021", "1022", "1058", "1059", "1116", "1139",
    "1146", "1164", "1169", "1170", "1178", "1183", "1186", "1188",
    "1193", "1211", "1233", "1235", "1236", "1237", "1251", "1263",
    "1285", "1288", "1289", "1294", "1296", "1298", "1299", "1300",
    "1302", "1303", "1305", "1307", "1310", "1311", "1328", "1331",
    "1332", "1333", "1334", "1335", "1455", "1456", "1459", "1461",
    "1462", "1463", "1466", "1467", "1469", "1473", "1474", "1475",
    "1476", "1478", "1479", "1480", "1482", "1485", "1487", "1503",
    "1506", "1520", "1534", "1564", "1572", "1575", "1582", "1587",
    "1588", "1592", "1593", "1594", "1597", "1602", "1607", "1611",
    "1612", "1613", "1615", "1616", "1617", "1619", "1633", "1656",
    "1657", "1658", "1660", "1663", "1664", "1667", "1668", "1669",
    "1676", "1677", "1679", "1691", "1704", "1716", "1734", "1735",
    "1736", "1766", "1771", "1772", "1773", "1775", "1777", "1783",
    "1801", "1814", "1818", "1834", "1835", "1836", "1837", "1838",
    "1840", "1843", "1845", "1846", "1847", "1850", "1852", "1856",
    "1857", "1858", "1859", "1860", "1882", "1883", "1890", "1891",
    "1897", "1899", "1901", "1902", "1909", "1910", "1912", "1914",
    "1923", "1926", "1928", "1929", "1935", "1941", "1956", "1958",
    "1960", "1968", "1991", "1994", "1998", "2002", "2010", "2012",
    "2016", "2019", "2024", "2026", "2029", "2030", "2032", "2033",
    "2034", "2035", "2036", "2039", "2042", "2046", "2049", "2053",
    "2055", "2056", "2057", "2059", "2093", "2101", "2103", "2121",
    "2134", "2146", "2147", "2152", "2184", "2185", "2186", "2187",
    "2188", "2190", "2197", "2201", "2239", "2240", "2249", "2250",
    "2291", "2313", "2322", "2347", "2351", "2353", "2354", "2355",
    "2360", "2361", "2369", "2370", "2372", "2373", "2374", "2375",
    "2376", "2402", "2426", "2427", "2445", "2447", "2449", "2459",
    "2460", "2462", "2467", "2468", "2469", "2471", "2484", "2485",
    "2486", "2488", "2490", "2494", "2496", "2517", "2613", "2623",
    "2624", "2625", "2641", "2696", "2697", "2709", "2711", "2712",
    "2713", "2714", "2997", "3000", "3004"), class = "factor"), latitude = c(43.29515222,
    44.02074565, 44.44193, 44.146666, 43.98897), longitude = c(-89.29077182,
    -92.04753707, -121.40635, -121.347223, -121.18639)), .Names = c("id",
    "latitude", "longitude"), row.names = c(NA, -5L), class = c("tbl_df",
    "tbl", "data.frame"))

This grabs the 5 nearest weather stations and produces a tbl_df:
nearest_station<-meteo_nearby_stations(lat_lon_df = nests, station_data = station_data,
                      limit = 5, var = c("TAVG"),
                      year_min = 2011, year_max = 2016)
nearest_station

Finally, I used do.call to produce a single data frame:
ns <- do.call(rbind, lapply(nearest_station, data.frame, stringsAsFactors=FALSE))
head(ns)

While the resulting data table shows the nest box ID next to the weather station ID (under id), the first column really only contains the weather station ID:
 id                     name latitude longitude  distance
29.1 USW00014837     MADISON DANE RGNL AP  43.1406  -89.3453  17.74438
29.2 USR0000WDDG     DODGEVILLE WISCONSIN  43.1000  -90.0000  61.44939
29.3 USW00014839    MILWAUKEE MITCHELL AP  42.9550  -87.9044 118.69939
29.4 USW00094822 ROCKFORD GTR ROCKFORD AP  42.1928  -89.0931 123.63416
29.5 USW00094908          DUBUQUE RGNL AP  42.3978  -90.7036 152.38709
36.1 USW00014925        ROCHESTER INTL AP  43.9042  -92.4917  37.83807

ns[,1]

USW00014837
Is there a way to keep the nest box information in the weather station data frame?

A: (sorry for late reply)
If you use something like dplyr::bind_rows, you can do:
dplyr::bind_rows(nearest_station, .id = "nest_box_id")

to get
#> # A tibble: 25 x 6
#>    nest_box_id id          name                        latitude longitude distance
#>    <chr>       <chr>       <chr>                          <dbl>     <dbl>    <dbl>
#>    29          USW00014837 MADISON DANE RGNL AP            43.1     -89.3     17.7
#>    29          USR0000WDDG DODGEVILLE WISCONSIN            43.1     -90.0     61.4
#>    29          USW00014839 MILWAUKEE MITCHELL AP           43.0     -87.9    119.
#>    29          USW00094822 ROCKFORD GTR ROCKFORD AP        42.2     -89.1    124.
#>    29          USW00094908 DUBUQUE RGNL AP                 42.4     -90.7    152.
#>    36          USW00014925 ROCHESTER INTL AP               43.9     -92.5     37.8
#>    36          USW00014920 LA CROSSE MUNI AP               43.9     -91.3     65.5
#>    36          USR0000WBRF BLACK RIVER FALLS WISCONSIN     44.3     -90.8    102.
#>    36          USR0000WAUG AUGUSTA WISCONSIN               44.7     -91.1    105.
#>    36          USW00014922 MINNEAPOLIS/ST PAUL AP          44.9     -93.2    134.
#> # ... with 15 more rows


text:
Q: How to split a string containing non ascii characters based on the byte size limit? How to split a string containing non ascii characters based on the byte size limit?
I want to split the below string and add to a List and the split is based on the size limit (e.g) 3 bytes.
The problem here is extended ascii char takes 2 characters and after split the data become junk as shown in the actual output.
what I want is the expected output as given below, its ok to write only 2 bytes, if we come across non-ascii char. Please let me know how to resolve it.
Problem:
String words = "Hello woræd  æåéøòôóâ";
        List<String> payloads = new ArrayList<>();
        try( ByteArrayOutputStream outStream = new ByteArrayOutputStream();) {
            byte[] chars = words.getBytes(StandardCharsets.UTF_8);
             for (byte ch: chars) {
                 outStream.write(ch);
                 if (outStream.size() >= 3) {
                     String s = outStream.toString("UTF-8");
                     payloads.add(s);
                     outStream.flush();
                     outStream.reset();
                 }
             }
            payloads.add(outStream.toString("UTF-8"));
            outStream.flush();
            System.out.println(payloads);
        } catch (IOException e) {
            e.printStackTrace();
        }

Actual Output: [Hel, lo , wor, æd,   �, �å, é�, �ò, ô�, �â, ]
Expected output: [Hel, lo , wor, æd,  ,æ, å, é, ø, ò, ô, ó, â]  ]

A: It's UTF-8.  UTF-8 is designed so that you can easlly detect character boundaries.
So: convert String to UTF-8 bytes.
Then backtrack until the first excluded byte is a legitimate 'first byte', i.e. not 10xxxxxx.  You are now positioned at a character boundary.


text:
Q: Run private strong-named assemblies side-by-side I have an application depending on version 1.0 of Assembly A (which is strongly named and deployed privately in bin folder).  The application also loads Assembly B via reflection.  The complication is that Assembly B depends on version 2.0 of Assembly A, which is also strongly named and to be deployed privately.
Now I could configure the CLR to load 2.0 whenever 1.0 is requested and thus only have to deploy version 2.0.  However, this means later when Assembly B is updated to depend on another version of Assembly A, I have to reconfigure the redirection.  Therefore, I'd prefer to have both versions of Assembly A run side-by-side in the my application.
Is there a way to do this?


text:
Q: java.lang.NullPointerException what I'm doing wrong? I'm working on a project in which my intention is to run a Corn job and send mail to my friends to wishing them on their birthday, I was able to get email from MySQL DB and compared it to the current date but when it comes to sending an email I'm getting NullPointerException.
I'm sure there is no problem with application properties I used them with other projects as well and they are function properly
//Imports
package dev.teja.happybirthday;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.persistence.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.Email;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;

//Main
@SpringBootApplication
public class HappybirthdayApplication {
    public static void main(String[] args) {
        SpringApplication.run(HappybirthdayApplication.class, args);
    }
    @Autowired
    MyFriendsRepository myFriendsRepository ;
    @Scheduled(cron = "*/30 * * * * *")
    void WishMyFriends() {
        List<MyFriends> myFriendsList = myFriendsRepository.findAll();
        myFriendsList.forEach(friend -> {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
            String CurrentDate= formatter.format(date);
            String GivenDate = formatter.format(friend.dob);
            if (GivenDate.equals(CurrentDate)){
                Job job = new Job();
                Map<String, Object> model = new HashMap<>();
                model.put("Name",friend.name);
                job.sendWish(friend.email,model);
            }
        });
    }
}
@Configuration
@ConditionalOnProperty(name = "scheduling.enabled", matchIfMissing = true)
@EnableScheduling
class Tasks {
}
//Model
@Data
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
class MyFriends {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    String name;
    @Email
    @Column(unique = true)
    String email;
    @JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
    Date dob;
    Long phoneNumber;
}
//Repository
interface MyFriendsRepository extends JpaRepository<MyFriends, Long> {
}
@RestController
@RequestMapping("/")
class FriendsController {
    @Autowired
    MyFriendsRepository myFriendsRepository;
    @PostMapping("/friends")
    ResponseEntity<MyFriends> createFriend(@RequestBody MyFriends myFriend) {
        myFriendsRepository.save(myFriend);
        return new ResponseEntity<MyFriends>(myFriend, HttpStatus.CREATED);
    }
    @GetMapping("/friends")
    List<MyFriends> getFriends() {
        return myFriendsRepository.findAll();
    }
}
//Interface
interface wisher{
    void sendWish(String email, Map<String, Object> model);
}
//Implementation
@Service
class Job implements wisher{
    @Autowired
    private JavaMailSender sender;
    @Autowired
    private freemarker.template.Configuration config;
    @Override
    public void sendWish(String email,Map<String, Object> model) {
        System.out.println("wishes sent to "+ email);
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                    StandardCharsets.UTF_8.name());
            Template template = config.getTemplate("new-template.ftl");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            helper.setTo(email);
            helper.setFrom("kondasaitej@gmail.com");
            helper.setSubject("Happy Birthday");
            helper.setText(html,true);
            sender.send(message);
        } catch (MessagingException | IOException | TemplateException e) {
            e.printStackTrace();
        }
    }
}

FreeMaker file in ./resources/Templates
/**
 * FREEMAKER new-template.ftl
 *
 *
 *     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 *     <title>Comment Alert Mail</title>
 *
 *
 *
happy birthday ${Name}

 *
 */

This is the error I'm getting this following

Hibernate: select myfriends0_.id as id1_0_, myfriends0_.dob as dob2_0_, myfriends0_.email as email3_0_, myfriends0_.name as name4_0_, myfriends0_.phone_number as phone_nu5_0_ from my_friends myfriends0_
wishes sent to kondasaitej@protonmail.com
2020-09-26 21:01:52.012 ERROR 84242 --- [   scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task

java.lang.NullPointerException: null
    at dev.teja.happybirthday.Job.sendWish(HappybirthdayApplication.java:115) ~[classes/:na]
    at dev.teja.happybirthday.HappybirthdayApplication.lambda$WishMyFriends$0(HappybirthdayApplication.java:53) ~[classes/:na]
    at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_251]
    at dev.teja.happybirthday.HappybirthdayApplication.WishMyFriends(HappybirthdayApplication.java:44) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_251]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_251]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_251]
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) [spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_251]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_251]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_251]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.8.0_251]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_251]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_251]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_251]

A: Try add getting in the @Autowired private JavaMailSender sender;

A: I think you have not implemented your JavaMailSender bean. Define a bean like below. Then your  @Autowire  annotation will work.
@Bean
public JavaMailSender getJavaMailSender()
{
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(25);

    mailSender.setUsername("admin@gmail.com");
    mailSender.setPassword("password");

    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");

    return mailSender;
}


text:
Q: How can I run latest version of node on Openshift? I have a node app which got a lot of ES6 code and wouldn't run below node version 5.0.0. I have to deploy it on Openshift but its node-cartridge has a very old version of node. Is there a way to deploy my code on Openshift without re-writing it in ES5?

A: This is the link in OpenShift that allows you to use the latest Node.JS versions. It is available up to 5.11 at this time, as is specified at https://semver.io/node/stable.
https://hub.openshift.com/quickstarts/243-node-js-latest

A: If you would like to upgrade the version of nodejs there is already a topic on this here Can Node.JS on OpenShift be upgraded?. We have shared a few custom cartridges that may work in your case.

A: Try ramr's nodejs-custom-version-openshift repo: https://github.com/ramr/nodejs-custom-version-openshift
It includes some scripts for installing nodejs locally during the build process.


text:
Q: Put date conversion in where clause db2 sql I have the following query. And I am calculating on MYDATE column which is a DECIMAL(8, 0) data type which stores datea in numeric form in YYYYMMDD format like this 20191107.
SELECT DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0) FROM PDF_TABLE;

It works fine. However, when I use the above conversion in a WHERE clause like below, query does not return anything.
SELECT * FROM PDF_TABLE WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0);

Example

Above is the data as is. Now I pass the date 20200601 as parameter in the WHERE clause of the following query, it should return the following row after subtracting 3 months from 20200601.

SELECT * FROM PDF_TABLE WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS, 'yyyymmdd')), 8, 0);

A: Try this as is:
WITH MYTAB (PDF_VOLUME, MYDATE) AS
(
VALUES
  ('110 GB', DEC(20200101, 8))
, ('120 GB', DEC(20200301, 8))
, ('390 GB', DEC(20200601, 8))
)
SELECT *
FROM MYTAB
WHERE MYDATE = DEC(TO_CHAR(TO_DATE(CHAR(CAST(? AS DEC(8))), 'YYYYMMDD') - 3 MONTH, 'YYYYMMDD'), 8);

A: How could it possibly return anything?
WHERE MYDATE = DECIMAL((TO_CHAR(TO_DATE(CAST(CAST(MYDATE AS INT) AS VARCHAR(8)), 'yyyymmdd') - 3 MONTHS
Dropping the conversions, you're asking WHERE MYDATE = MYDATE - 3 months
That's never going to be equal... Perhaps you forgot to change the inner MYDATE to CURRENT_DATE or something?  That would also require the conversion to change..
Personally, I use a user defined function for this type of conversion; either write it yourself or download Alan Campin's free iDate source
WHERE MYDATE = ConvertToIDate(CCURRENT_DATE - 3 months, '*CCYMD');


text:
Q: Laravel get all from with belongTo value In my Laravel 8 project I have two tables A and B:
| A     |
---------
| ID    |
| B_ID  |
| VALUE |

| B       |
-----------
| ID      |
| VALUE   |
| Private |

In my models I have:
A{
    public function b()
    {
        return $this->belongsTo(B::class);
    }
}

B{
    public function as()
    {
        return $this->hasMany(A::class);
    }
}

In my controller I have:
public function index()
{
    $a = A::join('bs', 'as.b_id', '=', 'b.id')->get(['as.value', 'bs.value']);

    return $a;
}

Is'nt there a more elegant Laravel way to do this?
I would like to get all records from table A with the value from table B but without the private value from B. (There could be a lot of entries in Table A, Table B only has some values (<20) ).

A: When building a query, you may specify which relationships should be eager loaded using the with method. In your case you could write:
A::with('b:value')->('value')

In the with you can precise a specific relationship by its name or a list of column you want : https://laravel.com/docs/8.x/eloquent-relationships
The code I have provided as an example as not been tested and may need some changes but you have the general idea


text:
Q: In swift, how do I scale and position an SKSpriteNode to fit each iPhone? I'm having trouble understanding how I make my SKSpriteNode fit each iPhone. I have a background image and a separate chair image that needs to be in the same position and scalling for each iPhone. When I get it to look good on say the 6+ if I swap to a 5s its not in the correct position and isn't scaled for that iPhone. This is how I am currently scaling and positioning my SKSpriteNode.
chair.position = CGPointMake(self.size.width * 0.50, self.size.height * 0.35)
chair.setScale(0.50)
chair.zPosition = 1.0
self.addChild(Chair)

A: I guess you have a problem of screen scale factors which are different from iPhone 5s (x2) to iPhone 6+ (x3). Simply multiply with screen factor you may solve the problem. The code (Swift) looks like bellow:
let screenScaleFactor = UIScreen.mainScreen().scale
chair.position = CGPointMake(self.size.width * 0.50 * screenScaleFactor, self.size.height * 0.35 * screenScaleFactor)
chair.setScale(0.50 * screenScaleFactor)
chair.zPosition = 1.0
self.addChild(Chair)


text:
Q: Which custom search engine? I have a website running on Apache with PHP and MySQL.
I wish to implement a custom search engine on text that is stored in the MySQL table and on .pdf and .docx documents.
I am not sure which API to go for.
I have looked at Google's Custom Search Engine (CSE) and Elastic Search. Elastic, I have learnt, can only be run on a Java-based server and so I am unable to go down that route.
I know Elastic can handle my requirements through its REST api. Is Google CSE able to do the same, i.e. search through text stored in Database tables and PDFs? Any other custom search APIs out there that are possible?

A: Solutions such as Google Custom Search Engine (in your case Google Site Search) or even any other web robot (such as Nutch) will only read the web-side of things: what is accessible by a browser (not being logged in) and classify this by URL displaying web-pages (with a title and text content's extract).
If all PDFs, docx and web-pages are accessible without login, it works extremely well. The web-app creator should enable that. It does not mean that the normal user has access to all, just the robot (e.g. the Springer publisher invites the Google bot to just about all content but not a normal browser).
If you want a search server to access only the fields of your database, it needs to talk to your database. Google Site Search (a form of Google Custom Search) does not allow for that. ElasticSearch and Apache Solr allow that. However, most web hosting services do not make the database ports accessible from outside for security reasons. Thus, you see another requirement for you to run a search server on premises probably.
The requirement to run java or Google CSE seems unavoidable. I know of no solutions of the same quality in other languages (e.g. Drupal can offer a MySQL-based text search but it has a far lower tolerance). Nowadays, many cloud nodes can run java.


text:
Q: Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your I'm really confused right now, keep getting this MySQL error:

Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'condition='-78' WHERE id='2'' at line 1

While I KNOW that condition is correct, when I remove the condition='".$data['condition']."' from the update record, the update is being processed but when I add that, it fails.
The field in the database is VARCHAR (6), just like all the other fields.
What could be the issue?

A: condition is a MySQL keyword. You need to enclose it with backticks if you're using it as a column name.
`condition`='-78' WHERE id='2'

Take care: This is the backtick symbol, not the single quote.

A: condition is a reserved word in MySQL.
You can see the full reserved word list here
You need to wrap condition in backticks;
"UPDATE ..... WHERE `condition`= '".$data['condition']."'";

A note for next time: Please include as much code as is sensible next time. Otherwise it is trickier for people to help you.


text:
Q: Can we integrate chatbase with other chatbots? After chatbase became part of the Dialogflow, can we still integrate other chatbots with chatbase?
I'm looking at how to use the chatbase analytics for other chatbots.
We had a connector built earlier.
Thanks!


text:
Q: Android ICS and MJPEG using AsyncTask I modified the MJPEG viewer code from Android and MJPEG to work using an AsyncTask (and thus work on Ice Cream Sandwich (ICS), 4.0.4) and here is my code.
If anyone has any suggestions on how to optimize, cleanup, or do something more proper with the code please let me know. Two issues I'd appreciate help addressing:

*

*If you have the device on a stream then lock the screen
and unlock the screen it does not resume playing until you either
kill and resume the app or rotate the screen. All my attempts at using OnResume() to do something or other resulted in app crashes.

*In particular I'd like to get the AsyncTask back in
MjpegInputStream.java but was not able to get that to work.
MjpegActivity.java:
package com.demo.mjpeg;

import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.demo.mjpeg.MjpegView.MjpegInputStream;
import com.demo.mjpeg.MjpegView.MjpegView;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class MjpegActivity extends Activity {
    private static final String TAG = "MjpegActivity";

    private MjpegView mv;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //sample public cam
        String URL = "http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg/video.cgi?resolution=800x600&amp%3bdummy=1333689998337";

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mv = new MjpegView(this);
        setContentView(mv);

        new DoRead().execute(URL);
    }

    public void onPause() {
        super.onPause();
        mv.stopPlayback();
    }

    public class DoRead extends AsyncTask<String, Void, MjpegInputStream> {
        protected MjpegInputStream doInBackground(String... url) {
            //TODO: if camera has authentication deal with it and don't just not work
            HttpResponse res = null;
            DefaultHttpClient httpclient = new DefaultHttpClient();
            Log.d(TAG, "1. Sending http request");
            try {
                res = httpclient.execute(new HttpGet(URI.create(url[0])));
                Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode());
                if(res.getStatusLine().getStatusCode()==401){
                    //You must turn off camera User Access Control before this will work
                    return null;
                }
                return new MjpegInputStream(res.getEntity().getContent());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                Log.d(TAG, "Request failed-ClientProtocolException", e);
                //Error connecting to camera
            } catch (IOException e) {
                e.printStackTrace();
                Log.d(TAG, "Request failed-IOException", e);
                //Error connecting to camera
            }

            return null;
        }

        protected void onPostExecute(MjpegInputStream result) {
            mv.setSource(result);
            mv.setDisplayMode(MjpegView.SIZE_BEST_FIT);
            mv.showFps(true);
        }
    }
}

MjpegInputStream.java:
package com.demo.mjpeg.MjpegView;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class MjpegInputStream extends DataInputStream {
    private static final String TAG = "MjpegInputStream";

    private final byte[] SOI_MARKER = { (byte) 0xFF, (byte) 0xD8 };
    private final byte[] EOF_MARKER = { (byte) 0xFF, (byte) 0xD9 };
    private final String CONTENT_LENGTH = "Content-Length";
    private final static int HEADER_MAX_LENGTH = 100;
    private final static int FRAME_MAX_LENGTH = 40000 + HEADER_MAX_LENGTH;
    private int mContentLength = -1;

    public MjpegInputStream(InputStream in) {
        super(new BufferedInputStream(in, FRAME_MAX_LENGTH));
    }

    private int getEndOfSeqeunce(DataInputStream in, byte[] sequence) throws IOException {
        int seqIndex = 0;
        byte c;
        for(int i=0; i < FRAME_MAX_LENGTH; i++) {
            c = (byte) in.readUnsignedByte();
            if(c == sequence[seqIndex]) {
                seqIndex++;
                if(seqIndex == sequence.length) {
                    return i + 1;
                }
            } else {
                seqIndex = 0;
            }
        }
        return -1;
    }

    private int getStartOfSequence(DataInputStream in, byte[] sequence) throws IOException {
        int end = getEndOfSeqeunce(in, sequence);
        return (end < 0) ? (-1) : (end - sequence.length);
    }

    private int parseContentLength(byte[] headerBytes) throws IOException, NumberFormatException {
        ByteArrayInputStream headerIn = new ByteArrayInputStream(headerBytes);
        Properties props = new Properties();
        props.load(headerIn);
        return Integer.parseInt(props.getProperty(CONTENT_LENGTH));
    }

    public Bitmap readMjpegFrame() throws IOException {
        mark(FRAME_MAX_LENGTH);
        int headerLen = getStartOfSequence(this, SOI_MARKER);
        reset();
        byte[] header = new byte[headerLen];
        readFully(header);
        try {
            mContentLength = parseContentLength(header);
        } catch (NumberFormatException nfe) {
            nfe.getStackTrace();
            Log.d(TAG, "catch NumberFormatException hit", nfe);
            mContentLength = getEndOfSeqeunce(this, EOF_MARKER);
        }
        reset();
        byte[] frameData = new byte[mContentLength];
        skipBytes(headerLen);
        readFully(frameData);
        return BitmapFactory.decodeStream(new ByteArrayInputStream(frameData));
    }
}

MjpegView.java:
package com.demo.mjpeg.MjpegView;

import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MjpegView extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "MjpegView";

    public final static int POSITION_UPPER_LEFT  = 9;
    public final static int POSITION_UPPER_RIGHT = 3;
    public final static int POSITION_LOWER_LEFT  = 12;
    public final static int POSITION_LOWER_RIGHT = 6;

    public final static int SIZE_STANDARD   = 1;
    public final static int SIZE_BEST_FIT   = 4;
    public final static int SIZE_FULLSCREEN = 8;

    private MjpegViewThread thread;
    private MjpegInputStream mIn = null;
    private boolean showFps = false;
    private boolean mRun = false;
    private boolean surfaceDone = false;
    private Paint overlayPaint;
    private int overlayTextColor;
    private int overlayBackgroundColor;
    private int ovlPos;
    private int dispWidth;
    private int dispHeight;
    private int displayMode;

    public class MjpegViewThread extends Thread {
        private SurfaceHolder mSurfaceHolder;
        private int frameCounter = 0;
        private long start;
        private Bitmap ovl;

        public MjpegViewThread(SurfaceHolder surfaceHolder, Context context) {
            mSurfaceHolder = surfaceHolder;
        }

        private Rect destRect(int bmw, int bmh) {
            int tempx;
            int tempy;
            if (displayMode == MjpegView.SIZE_STANDARD) {
                tempx = (dispWidth / 2) - (bmw / 2);
                tempy = (dispHeight / 2) - (bmh / 2);
                return new Rect(tempx, tempy, bmw + tempx, bmh + tempy);
            }
            if (displayMode == MjpegView.SIZE_BEST_FIT) {
                float bmasp = (float) bmw / (float) bmh;
                bmw = dispWidth;
                bmh = (int) (dispWidth / bmasp);
                if (bmh > dispHeight) {
                    bmh = dispHeight;
                    bmw = (int) (dispHeight * bmasp);
                }
                tempx = (dispWidth / 2) - (bmw / 2);
                tempy = (dispHeight / 2) - (bmh / 2);
                return new Rect(tempx, tempy, bmw + tempx, bmh + tempy);
            }
            if (displayMode == MjpegView.SIZE_FULLSCREEN){
                return new Rect(0, 0, dispWidth, dispHeight);
            }
            return null;
        }

        public void setSurfaceSize(int width, int height) {
            synchronized(mSurfaceHolder) {
                dispWidth = width;
                dispHeight = height;
            }
        }

        private Bitmap makeFpsOverlay(Paint p, String text) {
            Rect b = new Rect();
            p.getTextBounds(text, 0, text.length(), b);
            int bwidth  = b.width()+2;
            int bheight = b.height()+2;
            Bitmap bm = Bitmap.createBitmap(bwidth, bheight, Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(bm);
            p.setColor(overlayBackgroundColor);
            c.drawRect(0, 0, bwidth, bheight, p);
            p.setColor(overlayTextColor);
            c.drawText(text, -b.left+1, (bheight/2)-((p.ascent()+p.descent())/2)+1, p);
            return bm;
        }

        public void run() {
            start = System.currentTimeMillis();
            PorterDuffXfermode mode = new PorterDuffXfermode(PorterDuff.Mode.DST_OVER);
            Bitmap bm;
            int width;
            int height;
            Rect destRect;
            Canvas c = null;
            Paint p = new Paint();
            String fps;
            while (mRun) {
                if(surfaceDone) {
                    try {
                        c = mSurfaceHolder.lockCanvas();
                        synchronized (mSurfaceHolder) {
                            try {
                                bm = mIn.readMjpegFrame();
                                destRect = destRect(bm.getWidth(),bm.getHeight());
                                c.drawColor(Color.BLACK);
                                c.drawBitmap(bm, null, destRect, p);
                                if(showFps) {
                                    p.setXfermode(mode);
                                    if(ovl != null) {
                                        height = ((ovlPos & 1) == 1) ? destRect.top : destRect.bottom-ovl.getHeight();
                                        width  = ((ovlPos & 8) == 8) ? destRect.left : destRect.right -ovl.getWidth();
                                        c.drawBitmap(ovl, width, height, null);
                                    }
                                    p.setXfermode(null);
                                    frameCounter++;
                                    if((System.currentTimeMillis() - start) >= 1000) {
                                        fps = String.valueOf(frameCounter)+" fps";
                                        frameCounter = 0;
                                        start = System.currentTimeMillis();
                                        ovl = makeFpsOverlay(overlayPaint, fps);
                                    }
                                }
                            } catch (IOException e) {
                                e.getStackTrace();
                                Log.d(TAG, "catch IOException hit in run", e);
                            }
                        }
                    } finally {
                        if (c != null) {
                            mSurfaceHolder.unlockCanvasAndPost(c);
                        }
                    }
                }
            }
        }
    }

    private void init(Context context) {
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);
        thread = new MjpegViewThread(holder, context);
        setFocusable(true);
        overlayPaint = new Paint();
        overlayPaint.setTextAlign(Paint.Align.LEFT);
        overlayPaint.setTextSize(12);
        overlayPaint.setTypeface(Typeface.DEFAULT);
        overlayTextColor = Color.WHITE;
        overlayBackgroundColor = Color.BLACK;
        ovlPos = MjpegView.POSITION_LOWER_RIGHT;
        displayMode = MjpegView.SIZE_STANDARD;
        dispWidth = getWidth();
        dispHeight = getHeight();
    }

    public void startPlayback() {
        if(mIn != null) {
            mRun = true;
            thread.start();
        }
    }

    public void stopPlayback() {
        mRun = false;
        boolean retry = true;
        while(retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
                e.getStackTrace();
                Log.d(TAG, "catch IOException hit in stopPlayback", e);
            }
        }
    }

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

    public void surfaceChanged(SurfaceHolder holder, int f, int w, int h) {
        thread.setSurfaceSize(w, h);
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        surfaceDone = false;
        stopPlayback();
    }

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

    public void surfaceCreated(SurfaceHolder holder) {
        surfaceDone = true;
    }

    public void showFps(boolean b) {
        showFps = b;
    }

    public void setSource(MjpegInputStream source) {
        mIn = source;
        startPlayback();
    }

    public void setOverlayPaint(Paint p) {
        overlayPaint = p;
    }

    public void setOverlayTextColor(int c) {
        overlayTextColor = c;
    }

    public void setOverlayBackgroundColor(int c) {
        overlayBackgroundColor = c;
    }

    public void setOverlayPosition(int p) {
        ovlPos = p;
    }

    public void setDisplayMode(int s) {
        displayMode = s;
    }
}

A: nice work!
For your problem with onResume(), isn't it enough when you move the following code from onCreate() to onResume()?
    //sample public cam
    String URL = "http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg/video.cgi?resolution=800x600&amp%3bdummy=1333689998337";

    mv = new MjpegView(this);
    setContentView(mv);

    new DoRead().execute(URL);

Then you simply recreate the View and new instance of the AsyncTask... I tried it and it works for me...

A: It'll be helpful for the newbies that if you want to access your ip camera having a username or password , you might want to add this to your DefaultHttpClient and the above code will work for cameras that require authentication
 CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("yourusername", "yourpassword");
            provider.setCredentials(AuthScope.ANY, credentials);
            DefaultHttpClient httpclient = new DefaultHttpClient();
            httpclient.setCredentialsProvider(provider);

A: thanks for the code, it's very helpful
I want to suggest few optimization tips, which are already used in my code, overall performance can be easily increased by a few times.

*

*I removed memory allocations during frame reading, where possible
private final static int HEADER_MAX_LENGTH = 100;
private final static int FRAME_MAX_LENGTH = 200000 + HEADER_MAX_LENGTH;
private final String CONTENT_LENGTH = "Content-Length:";
private final String CONTENT_END = "\r\n";
private final static byte[] gFrameData = new byte[FRAME_MAX_LENGTH];
private final static byte[] gHeader = new byte[HEADER_MAX_LENGTH];
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

public Bitmap readMjpegFrame() throws IOException {

    mark(FRAME_MAX_LENGTH);
    int headerLen = getStartOfSequence(SOI_MARKER);

    if(headerLen < 0)
        return false;

    reset();
    readFully(gHeader, 0, headerLen);

    int contentLen;

    try
    {
        contentLen = parseContentLength(gHeader, headerLen);
    } catch (NumberFormatException nfe)
    {
        nfe.getStackTrace();
        Log.d(TAG, "catch NumberFormatException hit", nfe);
        contentLen = getEndOfSequence(EOF_MARKER);
    }

    readFully(gFrameData, 0, contentLen);

    Bitmap bm = BitmapFactory.decodeByteArray(gFrameData, 0, contentLen, bitmapOptions);
    bitmapOptions.inBitmap = bm;

    return bm;
}

*Optimizing parseContentLength, removing String operations as much as possible
byte[] CONTENT_LENGTH_BYTES;
byte[] CONTENT_END_BYTES;

public MjpegInputStream(InputStream in)
{
    super(new BufferedInputStream(in, FRAME_MAX_LENGTH));

    bitmapOptions.inSampleSize = 1;
    bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
    bitmapOptions.inPreferQualityOverSpeed = false;
    bitmapOptions.inPurgeable = true;
    try
    {
        CONTENT_LENGTH_BYTES = CONTENT_LENGTH.getBytes("UTF-8");
        CONTENT_END_BYTES = CONTENT_END.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
}

private int findPattern(byte[] buffer, int bufferLen, byte[] pattern, int offset)
{
    int seqIndex = 0;
    for(int i=offset; i < bufferLen; ++i)
    {
        if(buffer[i] == pattern[seqIndex])
        {
            ++seqIndex;
            if(seqIndex == pattern.length)
            {
                return i + 1;
            }
        } else
        {
            seqIndex = 0;
        }
    }

    return -1;
}

private int parseContentLength(byte[] headerBytes, int length) throws IOException, NumberFormatException
{
    int begin = findPattern(headerBytes, length, CONTENT_LENGTH_BYTES, 0);
    int end = findPattern(headerBytes, length, CONTENT_END_BYTES, begin) - CONTENT_END_BYTES.length;

    // converting string to int
    int number = 0;
    int radix = 1;
    for(int i = end - 1; i >= begin; --i)
    {
        if(headerBytes[i] > 47 && headerBytes[i] < 58)
        {
            number += (headerBytes[i] - 48) * radix;
            radix *= 10;
        }
    }

    return number;
}

There could be mistakes in the code since I was rewriting it for stackoverflow, originally I'm using 2 threads, one is reading frames and another is rendering.
I hope it will help for someone.


text:
Q: Web Scrape/Crawl Google Play Store/iTunes I would like to find the most downloaded apps from the previous month in Google Play store(or I can make do with itunes too actually), and perform further exploratory data analysis with the data on these apps.
Python is familiar to me. But I don't know what approach is used to achieve this.

A: There is another alternative package which works for scraping google play store data, below is the link
https://pypi.org/project/google-play-scraper/
In case, your looking straight for sample code follow the below steps
from google_play_scraper import app

result = app(
'com.nianticlabs.pokemongo',
lang='en', # defaults to 'en'
country='us' # defaults to 'us'
)
print(result)

A: In the new Google Play UI most downloaded apps are likely displayed on the home page, or in the Top Charts section.
The main difference is that it is a faster approach than using for example selenium or playwright web driver. The  API will bypass blocks by Google, and you don't have to create a parser from scratch and maintain it if certain HTML elements will be changed in the fututre.
Retrieving data from multiple devices (phone, tablet, etc.) using the device parameter (this will be a list of devices that we need to iterate over and assign dynamically before making a request to API):
devices = ['phone', 'tablet']

for device in devices:
    params = {
      "api_key": os.getenv("API_KEY"),    # serpapi key, https://serpapi.com/manage-api-key
      "device": device,                   # Parameter defines the device for sorting results
      "engine": "google_play",            # serpapi parser engine
      "hl": "en",                         # language
      "store": "apps",                    # Apps store
      "gl": "us"                          # country of the search, US -> USA
    }

Pagination is integrated into the code with a while loop, which is infinite and will run until the loop exit condition is met. This will happen if there is no next page to load:
# if next page is there, grab it and pass to GoogleSearch()
# otherwise, stop.
if "next" in results.get("serpapi_pagination", {}):
    search.params_dict.update(dict(parse_qsl(urlsplit(results.get("serpapi_pagination").get("next")).query)))
else:
    apps_is_present = False

You can check code in online IDE.
from serpapi import GoogleSearch
from urllib.parse import urlsplit, parse_qsl
import json, os

devices = ['phone', 'tablet']

apps_data = []

for device in devices:
    params = {
      "api_key": os.getenv("API_KEY"),    # serpapi key, https://serpapi.com/manage-api-key
      "device": device,                   # Parameter defines the device for sorting results
      "engine": "google_play",            # serpapi parser engine
      "hl": "en",                         # language
      "store": "apps",                    # Apps store
      "gl": "us"                          # country of the search, US -> USA
    }

    search = GoogleSearch(params)   # where data extraction happens

    index = 0
    apps_is_present = True
    while apps_is_present:
        results = search.get_dict()  # JSON -> Python dict

        index += 1

        for result in results.get("organic_results", []):
            for app in result["items"]:

                apps_data.append({
                    "page": index,
                    "title": app.get("title"),
                    "link": app.get("link"),
                    "product_id": app.get("product_id"),
                    "description": app.get("description"),
                    "rating": app.get("rating")
                })

    # if next page is there, grab it and pass to GoogleSearch()
    # otherwise, stop.
        if "next" in results.get("serpapi_pagination", {}):
            search.params_dict.update(dict(parse_qsl(urlsplit(results.get("serpapi_pagination").get("next")).query)))
        else:
            apps_is_present = False

print(json.dumps(apps_data[:2], indent=2, ensure_ascii=False)) # prints first two elements from a list

Example output:
[
  {
    "page": 1,
    "title": "Google Photos",
    "link": "https://play.google.com/store/apps/details?id=com.google.android.apps.photos",
    "product_id": "com.google.android.apps.photos",
    "description": null,
    "rating": 4.5
  },
  {
    "page": 1,
    "title": "Gmail",
    "link": "https://play.google.com/store/apps/details?id=com.google.android.gm",
    "product_id": "com.google.android.gm",
    "description": null,
    "rating": 4.2
  }
]

There's a Scrape Google Play Search Apps in Python blog post if you need a little bit more code explanation.

Disclaimer, I work for SerpApi.


text:
Q: Component is not rendering the if block inside the function - React JS I am working on a task where I need to pass the data to the table. The table has its own data type and prop. I need to follow the same when I am applying the logic. Now I am trying to pass the data dynamically. For the header of the table values are populating as expected. But when I am trying to pass the data to table body I am not getting any values. Anyone can guide how to achieve this. I need to follow the Table props format when I am working with the table component. I have written down the table props, code and sample data. When I am seeing the console I am getting an error stating that check the render method of the table component.
My Code
const Table = ({mockData}) => {

function getHeadings(mockData) {
    return mockData[0].cells.map(heading => {
        return <HeaderCell key={heading.key}>{heading.headername}</HeaderCell> // this part is working fine
    })
}

function getRow(cells) {
    return cells.map(cell => {
        const {headername} = cell;
        if(Array.isArray(cell[headername])){
            return (
                <Cell key={cell.toString()}>
                    {
                        cell[headername].map(element => {
                            console.log("ELEMENT", element)----> This value is not coming(this if block is not working)
                            return <Badge intent={element} text="Primary" />
                        })
                    }
                </Cell>
            )
        }
        return <Cell>{cell[headername]}</Cell>
    })
}

function getRows(mockData) {
    // console.log("GETROWS ROW", mockData)
    return mockData.map(row => {
        // console.log("GETROWS ROW", row.cells)
        return <Row key={row}>{getRow(row.cells)}</Row>
    })
return (
<>
<Table paddingStyle="compact">
  <Header>
    {getHeadings(mockData)}
  </Header>
  <Body>
    {getRows(mockData)}
  </Body>
</Table>

JSON Data
 [
    {
      "key": "row-0",
      "cells": [
        { "key": "cell-0", "headername":"Name", "CName": "Patient One" },
        { "key": "cell-1", "headername":"Reg ID","CID": "C- 001" },
        { "key": "cell-2", "headername":"Label","CLabel": ["In", "Out"] }

      ]
    }

]
Table Props:
1. Table PROPS- Prop: Children Type: Node default:[] (Desc: the child
    content for table consisting of eithera Table Header or Body)

 2. Table Header Props- Prop: Children Type: node default:[]

 3. Table Header Cell props - prop:children type:node default:[](Desc:
    content to display for column header)

 4. Table Row Props - Prop: Children Type: node default:[] (Desc: child
    table cells to be placed within the tr)

 5. Table Cell Props - Prop: Children Type: node default:[] (Desc:
    content to be displayed for row cell)

A: As all your cells contain only key, headername, and one other property, here's a janky way of fixing your issue without too much work
However ... key={cell.toString()} is not right either, as that will result in [object Object]
Perhaps you want key={key} instead
function getRow(cells) {
    return cells.map(cell => {
        const {key, headername, ...rest} = cell;
        const data = Object.values(rest)[0];
        if(Array.isArray(data)){
            return (
                <Cell key={cell.toString()}>
                    {
                        data.map(element => {
                            return <Badge intent={element} text="Primary" />
                        })
                    }
                </Cell>
            )
        }
        return <Cell>{data}</Cell>
    })
}


text:
Q: Joining mysql tables vs updating multiple tables Lets say i got two tables in mysql.
1. person (id, name, lastname) - Image
2. someothertable (id, name, lastname, action, quantity) - image
I wanted to ask, if its really bad practice, to update both tables at once? For example if someone updates the last name of Robert Jackson to "Smith" then do 2 queries:
mysql_query("UPDATE person SET lastname = '$lastname' WHERE id = '$id'");
mysql_query("UPDATE someothertable SET lastname = '$lastname' WHERE name = '$name' AND lastname = '$oldlastname'");

Assuming for now, you wont meet 2 same names and surnames (its just an example).
Is it strongly recommended, to join those two tables when displaying data from tables, and change last name only in person table?
I didn't have need to use join before (never had databases big enough), and I just started to wonder if there is another way to do this (than 2 queries). Using join will require some code changing, but i am ready to do it, if its right thing to do.

A: Using a join is not a function of how big your databases are, it's about normalization and data integrity.  The reason you would have lastname in only one table is so that there's no need to worry about keeping values in sync.  In your example, if those calls are in a single transaction, then they should stay in sync.  Unless one of them is changed somewhere else, or manually in the database.
So an option for you would be to have these tables:
person (id, name, lastname)
someothertable (id, person_id, action, quantity)

A: One option would be to make someothertable have a foreign key constraint on the lastname field in Person. You could apply an update trigger so it would automatically cascade.
Here is an example below:
Alter table someothertable add constraint foreign key (lastname) references Person (lastname) on delete cascade on update cascade;

A generic version of that can be seen below:
Alter table [table-name] add constraint foreign key (field-in-current-table) references [other-table-name] (field-in-other-table) on delete cascade on update cascade;

This can be applied to any field in any table. You can then set the triggers to be appropriate for you. Here is a reference link.
Have you considered normalization?
Another option would be to assign each person in the Person table a uniqueID (i.e. PersonID). Now in all your other tables you where you reference a person you reference them by the unique id. This adds many advantages:
1) It keeps the data normalized
2) It maintains data integrity
3) No need for updates, triggers, or cascades
4) A change would only be required in one place
Hope this helps. Best of luck!

A: Instead of using 2 update, you can use trigger : Tutorial here


text:
Q: C# how to repeat function I am reading directories and adding .ini files to listbox1 or lisbox2 depending what is inside.
    private void Form1_Load(object sender, EventArgs e)
    {
        string rootdir = @"C:\Users\isaced1\Desktop\test";   //root directory of all projects
        string[] files = Directory.GetFiles(rootdir, "*.ini", SearchOption.AllDirectories);  //searches for specific .ini files in all directories whithin rood directory

        //cycles through all .ini files and adds it to lsitbox1 or listbox2
        foreach (string item in files)
           {
            string fileContents = File.ReadAllText(item); //reads all .ini files
            const string PATTERN = @"OTPM              = true"; //search pattern in .ini files
            Match match = Regex.Match(fileContents, PATTERN, RegexOptions.IgnoreCase); //matches pattern with content in .ini file

                if (match.Success)
                {
                    listBox1.Items.Add(item); //if match is successfull places file in lisbox1
                    listBox1.ForeColor = Color.Green;
                }
                else
                {
                    listBox2.Items.Add(item); //if match is unsuccessfull places file in lisbox2
                    listBox2.ForeColor = Color.Red;
                }
           }
    }

Now I want to to continuously repeat the process. I tried to do timer, but I keep getting error "error CS0120: An object reference is required for the non-static field, method, or property". I understand that my private void Form1_Load has to be static, but I just dont know way around it.
My timer code
    private static System.Timers.Timer aTimer;

    public static void Main1()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 1000;
        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(Form1_Load);

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;
    }

Any suggestions, thanks.

A: Don't poll for new files (using a timer is inefficient), use events from the OS to tell you when files are created/updated/deleted etc.
https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=net-6.0
    static void Main()
    {
        using var watcher = new FileSystemWatcher(@"C:\path\to\folder");

        watcher.NotifyFilter = NotifyFilters.Attributes
                             | NotifyFilters.CreationTime
                             | NotifyFilters.DirectoryName
                             | NotifyFilters.FileName
                             | NotifyFilters.LastAccess
                             | NotifyFilters.LastWrite
                             | NotifyFilters.Security
                             | NotifyFilters.Size;

        watcher.Changed += OnChanged;
        watcher.Created += OnCreated;
        watcher.Deleted += OnDeleted;
        watcher.Renamed += OnRenamed;
        watcher.Error += OnError;

        watcher.Filter = "*.txt";
        watcher.IncludeSubdirectories = true;
        watcher.EnableRaisingEvents = true;

        Console.WriteLine("Press enter to exit.");
        Console.ReadLine();
    }

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
        if (e.ChangeType != WatcherChangeTypes.Changed)
        {
            return;
        }
        Console.WriteLine($"Changed: {e.FullPath}");
    }

    private static void OnCreated(object sender, FileSystemEventArgs e)
    {
        string value = $"Created: {e.FullPath}";
        Console.WriteLine(value);
    }

    private static void OnDeleted(object sender, FileSystemEventArgs e) =>
        Console.WriteLine($"Deleted: {e.FullPath}");

    private static void OnRenamed(object sender, RenamedEventArgs e)
    {
        Console.WriteLine($"Renamed:");
        Console.WriteLine($"    Old: {e.OldFullPath}");
        Console.WriteLine($"    New: {e.FullPath}");
    }

    private static void OnError(object sender, ErrorEventArgs e) =>
        PrintException(e.GetException());

    private static void PrintException(Exception? ex)
    {
        if (ex != null)
        {
            Console.WriteLine($"Message: {ex.Message}");
            Console.WriteLine("Stacktrace:");
            Console.WriteLine(ex.StackTrace);
            Console.WriteLine();
            PrintException(ex.InnerException);
        }
    }


text:
Q: Spring-WS: How generate the WSDL without having to start the web service? We use Spring-WS as the basis for implementing a web service (with the WSDL generated by the framework). As well as a WAR file our build produces a client side JAR (for use by our Java clients and our own end-to-end functional tests) consisting of schema generated DTOs and stubs for the web service methods. These are generated using wsimport (JAX-WS). Problem is this gives rise to a multi-step build process:

*

*Build the server WAR file;

*Start Tomcat (to make the WSDL available);

*Generate the client side stubs (pointing wsimport at the WSDL url).

Is there some way to generate the WSDL without having to start the web service? Then we could build everything in a single step.

A: This example code is suitable for the basis of an Ant task:
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerFactory;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;
import org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection;

....

private String generateWsdlFromSpringInfrastructure() throws Exception
{
    // We only need to specify the top-level XSD
    FileSystemResource messagesXsdResource = new FileSystemResource("C:/MyProject/xsds/my-messages.xsd");
    CommonsXsdSchemaCollection schemaCollection = new CommonsXsdSchemaCollection(new Resource[] {messagesXsdResource});
    // In-line all the included schemas into the including schema
    schemaCollection.setInline(true);
    schemaCollection.afterPropertiesSet();

    DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
    definition.setSchemaCollection(schemaCollection);
    definition.setPortTypeName(portTypeName);
    definition.setLocationUri("http://localhost:8080/myProject/services");
    definition.setTargetNamespace("http://www.acme.com/my-project/definitions");
    definition.afterPropertiesSet();

    StringResult wsdlResult = new StringResult();
    TransformerFactory.newInstance().newTransformer().transform(definition.getSource(), wsdlResult);
    return wsdlResult.toString();
}

A: Another option may be to get already configured bean from app context:
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ws.wsdl.WsdlDefinition;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:yourWsdlConfig.xml"})
public class WsdlGeneratorTest {

    @Autowired
    private ApplicationContext ctx;

    /*
     * Path relative to module root (or absolute path can be used).
     */
    private static final String OUTPUT_PATH = "target";

    @Test
    public void test() {
        String names[] = ctx.getBeanNamesForType(WsdlDefinition.class);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        for (String name : names) {
            String filename = OUTPUT_PATH + File.separator + name + ".wsdl";
            WsdlDefinition wd = (WsdlDefinition) ctx.getBean(name);
            Source source = wd.getSource();
            try {
                Transformer transformer = tFactory.newTransformer();
                FileOutputStream fo = new FileOutputStream(filename);
                StreamResult result = new StreamResult(fo);
                transformer.transform(source, result);
                fo.close();
            } catch (TransformerException e) {
                fail("Error generating " + filename + ": TransformerException: " + e.getMessage());
            } catch (IOException e) {
                fail("Error generating " + filename + ": IOException: " + e.getMessage());
            }
        }
    }
}


text:
Q: Retrieve synonyms list from database in Elasticsearch Is it possible to configure Elasticsearch to retrieve synonyms list from database/sql instead of file?

A: Unfortunately it is not possible.
ES supports file or online synonyms. It supports solr synonyms format..
doc
But you can add all the synonyms along with original field as an array in ES. While querying, you can use that array field and retrieve the original field.


text:
Q: Magento - Associated products are not showing under configurable product I'm using Magento Community Edition 1.9.3.2.
I created configurable product and created an associated products also. My issue is,

*

*Configurable products are not displaying front page

*Associated products also not displaying backend. but if i click on
reset filter button it is showing simple products which belongs to
some other configurable products.

And i have checked:
Stock Availability
Qty
Website
Visibility
Catalog
Price
All are correct. Does any one know what was the issue?

A: After click on reset filter it does not show wrong products. It shows all the simple products which can assign to this configurable product. Just click on checkbox for the product which you want to associate and click on save button then the checked products will be associated to this configurable product.


text:
Q: How to read certificate from smart card via python? I have a Smart Card (actually USB Token) with some certificate and keys written on it. Now I need to retrieve this certificate using python on Windows. How can it be achieved?
I had a look on pyscard package but it seems too low-level and probably not a most simple way of doing this. But if you know that low-level answer then your help will be appreciated.
Seems like CryptAcquireContext function from pywin32 (win32crypt) allow me to use private key from smart card for encryption purposes but I cannot get the certificate itself.
Do you have any suggestions?

A: Found an answer myself though. Hope it will help someone:
Usually smart card manufacturers provide a library (.so or .dll) implementing PKCS#11 standard.
There are several solutions which you can use to communicate with your smart card via this library. Such as: pkcs11-tool (CLI interface), PyKCS11 (python wrapper).
Here is an example how it could be achieved with PyKCS11:
from asn1crypto import x509
from PyKCS11 import *

pkcs11 = PyKCS11Lib()
pkcs11.load('<MANUFACTURER_LIBRARY_PATH>')
# get slot value via pkcs11.getSlotList(tokenPresent=False). Usually it's 0
session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login('<SMART_CARD_PIN_CODE>')
result = []
certs = session.findObjects([(CKA_CLASS, CKO_CERTIFICATE)])
for cert in certs:
    cka_value, cka_id = session.getAttributeValue(cert, [CKA_VALUE, CKA_ID])
    cert_der = bytes(cka_value)
    cert = x509.Certificate.load(cert_der)
    result.append(cert)
print(result)

This way I was able to list certificates on smart card both on Linux and Windows


text:
Q: How to set a gamemode radius with command blocks? I've been trying to figure out how to change a player's gamemode from adventure to survival when walking out a certain radius. The map size I'm using is 2956x2956 & I wanna be sure to cover all of it. I tried using /gamemode creative @a [r=10] with a repeat block just to test out what'll happen. But no matter how far I am from the block it keeps setting my gamemode to creative. Can someone show me how to properly write what I'm trying to do for minecraft 1.12.2? Screenshots would be much appreciated.  (also how can I stop the commands from blowing up my chat lol?)

A: If your command is actually as you wrote, your mistake is that there is no space between "@a" and "[r=10]". Here it is:
/gamemode creative @a[r=10]

And well, if you need it for 2956x2956 radius, simply change [r=10] to [r=2956] (Maybe 2956 won't be enough as the raidus is circular and not a square form. Test it out and see how big does it need to be).
Also, to disable the command feeback in chat, simply type in you chat:
/gamerule commandBlockOutput false

This will disable any and every feedback that otherwise the command would send to your chat.


text:
Q: Filter Backbone collection on multiple model attributes I have a bit of a problem with how to best filter a Backbone collection on its models Attributes. My setup is like this:
I have a collection with several models in it. Each model has an attribute which holds an array of numbers ("type"). Like this:
- Collection
- model
    - id: 1
    - name
    - phone
    - type [3]
- model
    - id: 2
    - name
    - phone
    - type [2]
- model
    - id: 3
    - name
    - phone
    - type [1,2]

What I want to do here is to be able to filter this collections on the models "type" attribute.
I have this "type" attribute because this is for a contact list and each contact can be of several types. E.g. the collection should be able to be filtered on unlimited types. You should be able to filter on lets say type "1" and type "2" which will then show model 2 and model 3. Cause model 1 does not have the "type" 1.
Any good code examples or other help on this would be great. Thanks!

A: You can use following code
var filColl=myColl.filter(function(o){return _.indexOf(o.get('type'), 1) >-1 })

Here is jsFiddle link of working code,with some sample data.

A: Hi here is code which can filter for multiple types, stored in array
var typesTofilter=[5,1,2];//array of type tobe search.
    var f2=friends.filter(function(o){ var accept=false;
                                       $(typesTofilter).each(function(i,val){
                                         if(_.indexOf(o.get('type'), val) >-1){
                                           accept= true;
                                            }
                                        })
                                        return accept;
                         });

And here is jsFiddle.


text:
Q: Adding OnClick(View v) in the textview's i have added onClick in my mainactivity for my textview and i had no errors but when i run the app it crashes saying app has stopped working even though i have no errors in my codes i dont know what's the problem
i hope you can help me and thanks in advance
this is my logcat
12-25 03:32:44.694: I/Ads(1433): AdLoader timed out after 60000ms while getting the URL.
12-25 03:33:00.234: I/Process(1433): Sending signal. PID: 1433 SIG: 9
12-25 03:33:38.454: D/dalvikvm(1559): GC_FOR_ALLOC freed 40K, 4% free 3135K/3248K, paused 283ms, total 286ms
12-25 03:33:38.504: I/dalvikvm-heap(1559): Grow heap (frag case) to 4.200MB for 1127536-byte allocation
12-25 03:33:38.654: D/dalvikvm(1559): GC_FOR_ALLOC freed 2K, 3% free 4233K/4352K, paused 146ms, total 146ms
12-25 03:33:39.144: D/dalvikvm(1559): GC_FOR_ALLOC freed <1K, 3% free 4238K/4352K, paused 46ms, total 47ms
12-25 03:33:39.304: I/dalvikvm-heap(1559): Grow heap (frag case) to 9.535MB for 5591056-byte allocation
12-25 03:33:39.394: D/dalvikvm(1559): GC_FOR_ALLOC freed <1K, 2% free 9698K/9816K, paused 84ms, total 84ms
12-25 03:33:40.284: V/WebViewChromium(1559): Binding Chromium to the background looper Looper (main, tid 1) {b1d56e50}
12-25 03:33:40.304: I/chromium(1559): [INFO:library_loader_hooks.cc(112)] Chromium logging enabled: level = 0, default verbosity = 0
12-25 03:33:40.334: I/BrowserProcessMain(1559): Initializing chromium process, renderers=0
12-25 03:33:40.514: D/(1559): HostConnection::get() New Host Connection established 0xb7a714f8, tid 1559
12-25 03:33:40.594: W/chromium(1559): [WARNING:proxy_service.cc(888)] PAC support disabled because there is no system implementation
12-25 03:33:41.664: E/ActivityThread(1559): Failed to find provider info for com.google.plus.platform
12-25 03:33:41.774: I/Ads(1559): To get test ads on this device, call adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
12-25 03:33:42.194: D/AndroidRuntime(1559): Shutting down VM
12-25 03:33:42.194: W/dalvikvm(1559): threadid=1: thread exiting with uncaught exception (group=0xb1a83ba8)
12-25 03:33:42.214: E/AndroidRuntime(1559): FATAL EXCEPTION: main
12-25 03:33:42.214: E/AndroidRuntime(1559): Process: imamalsajadsayings.android.com, PID: 1559
12-25 03:33:42.214: E/AndroidRuntime(1559): java.lang.RuntimeException: Unable to start activity ComponentInfo{imamalsajadsayings.android.com/imamalsajadsayings.android.com.MainActivity}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.LinearLayout
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.os.Looper.loop(Looper.java:136)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.app.ActivityThread.main(ActivityThread.java:5017)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at java.lang.reflect.Method.invokeNative(Native Method)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at java.lang.reflect.Method.invoke(Method.java:515)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at dalvik.system.NativeStart.main(Native Method)
12-25 03:33:42.214: E/AndroidRuntime(1559): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.LinearLayout
12-25 03:33:42.214: E/AndroidRuntime(1559):     at imamalsajadsayings.android.com.MainActivity.onCreate(MainActivity.java:20)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.app.Activity.performCreate(Activity.java:5231)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-25 03:33:42.214: E/AndroidRuntime(1559):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
12-25 03:33:42.214: E/AndroidRuntime(1559):     ... 11 more
12-25 03:33:43.064: D/dalvikvm(1559): DexOpt: --- BEGIN 'ads478949099.jar' (bootstrap=0) ---
12-25 03:33:46.024: D/dalvikvm(1559): DexOpt: --- END 'ads478949099.jar' (success) ---
12-25 03:33:46.024: D/dalvikvm(1559): DEX prep '/data/data/imamalsajadsayings.android.com/cache/ads478949099.jar': unzip in 54ms, rewrite 2963ms
12-25 03:33:46.844: I/Ads(1559): adRequestUrlHtml:
12-25 03:33:48.574: I/Process(1559): Sending signal. PID: 1559 SIG: 9

and is my mainactivity.java
package imamalsajadsayings.android.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {
private LayoutInflater inflater;
private LinearLayout someLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView someLayout = (TextView)findViewById(R.id.state2);
inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
runNextTask(someLayout);

}
  public void runNextTask(View v){
   LinearLayout mInflatedLayout = (LinearLayout)       inflater.inflate(R.layout.activity_main, null);
   @SuppressWarnings("unused")
final TrackerInfo newInfo = new TrackerInfo();
   //set up for model selection
   someLayout.addView(mInflatedLayout);
   someLayout = (LinearLayout) findViewById(R.id.linearlayout1); //layout present in
   someLayout.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {

       }
   });
   }

  @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.main, menu);
 return true;
 }

}

and this is my mainactivity with the textviews and linearlayout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="vertical"
tools:context=".MainActivity" >

                    <LinearLayout
                    android:id="@+id/linearlayout1"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:gravity="right"
                    android:orientation="vertical"
                    android:background="@drawable/images" >

                   <com.google.ads.AdView
                   android:id="@+id/ad"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   ads:adUnitId="a152b5665edfefd"
                   ads:loadAdOnCreate="true"
                   ads:adSize="BANNER" />

                <TextView
                    android:id="@+id/state1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="قال (عليه السلام): (من كرمت عليه نفسه هانت عليه الدنيا)                                                                         "
                    android:paddingTop="10sp"
                    android:clickable = "true"
                    style="?android:listSeparatorTextViewStyle" />

                <TextView
                    android:id="@+id/state2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="قال (عليه السلام): (الخير كله في صيانة الإنسان نفسه)                                                                "
                    android:paddingTop="10sp"
                    style="?android:listSeparatorTextViewStyle"
                    android:clickable="true" />

                <TextView
                    android:id="@+id/state3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="قال (عليه السلام): (ما أحب المؤمن معافى في الدنيا، وفي نفسه وماله، ولا يصاب بشيء من المصائب)"
                    android:paddingTop="10sp"
                    android:clickable = "true"
                    style="?android:listSeparatorTextViewStyle"/>

                <TextView
                    android:id="@+id/state4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=" قال (عليه السلام): (ضل من ليس له حليم يرشده، وذل من ليس له سفيه يعضده..)                                                "
                    android:paddingTop="10sp"
                    android:clickable = "true"
                    style="?android:listSeparatorTextViewStyle"/>

                <TextView
                    android:id="@+id/state5"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="قال (عليه السلام): (ويل لمن غلبت آحاده أعشاره)                                                                                "
                    android:paddingTop="10sp"
                    android:clickable = "true"
                    style="?android:listSeparatorTextViewStyle"/>
                </LinearLayout>

              </ScrollView>

A: This is getting really interesting:
 E/AndroidRuntime(1559): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.LinearLayout

the declaration:
private LinearLayout someLayout;

and another confused naming
TextView someLayout = (TextView)findViewById(R.id.state2);

and, how is that possible if someLayout can addView() before loading from layout?
someLayout.addView(mInflatedLayout);
someLayout = (LinearLayout) findViewById(R.id.linearlayout1);

Well, I suggest you should start with a proper basic Android learning first,
private LayoutInflater inflater;
private LinearLayout someLayout;
private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mTextView = (TextView) findViewById( R.id.state2 );
    mTextView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // do something here
        }
    });
}

A: EDIT: The guy over me had an better explanation!


text:
Q: When I pressed setState function, numbers are not adding On numbers are not adding when I press the calculate button
Variable I took
String _bmi = "0";

Here's the code portion
     OutlinedButton(
        child: Text('Calculate',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: kTitleTextColor,
          ),
        ),
        onPressed: () {
          setState(() {
            int sum = int.parse(massNumber.text) + int.parse(heightNumber.text);
            _bmi = sum.toString();
          });
        },
      ),
      Text(_bmi,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          color: kTitleTextColor,
          fontSize: 18.0,
        ),
      ),

Please help

A: Your function works fine. I have added a dummy data function below so you can see it. So either you have an error with your data that comes, maybe the are null or empty or not integer or you have another error in your console.

A: refer this example
void main()

{
  double num = 0;
  String wight = "40";
  String height = "20";
  double sum = double.parse(wight) + double.parse(height);
  num = sum;
  print(num.toString());
}

https://dartpad.dev/?

A: The code using setState() is working correctly.
Try it out.
int sum = int.parse(massNumber.text) + int.parse(heightNumber.text);

is replaced to ↓
int sum = int.parse("1") + int.parse("2");

and run it, it works correctly.
Are the numbers in massNumber.text and heightNumber.text correct?


text:
Q: concatenate before urlencode in django I'm new to django and trying to concatenate a variable and string before urlencoding the two.
I already have #{profile.name|urlencode} but need something like #{urlencode('string' + profile.name)}
Any help is very appreciated

A: Concatenate string with profile.name using add and assign variable to it:
{% with name="string"|add:profile.name %}
    {{ name|urlencode  }}
{% endwith %}


text:
Q: How to access numpy that was installed with conda Following instructions from numpy.org I have installed numpy
conda install numpy

The installation was successful, as when I type the above command again, I see the message
Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.

However, when I start python with python and type import numpy I see an error message
Python 3.8.6 (default, Sep 25 2020, 09:36:53)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'

How can I get access to numpy?
I am using Ubuntu 20.10 and my conda 4.9.2 is installed in
~/.local/opt/anaconda3/ if this can help.
Thanks!


text:
Q: How may i get /var/log/dnf.log to log times in my system timezone? How may i get /var/log/dnf.log to log times in my system timezone?  Neither man dnf nor google have yet enlightened me on this.  Centos8/rhel8.

A: Apparently the source of confusion was the system in question was configured for UT rather than our timezone.  i remained unaware of that because my. bashrc sets TZ, thus hiding the system timezone.  So the answer to the question is dnf.log already does log times using the system timezone.