text:
Q: (Laravel) Unable to get response from PayPal IPN but simulated response returns verified I've added a PayPal plugin to a membership page on my website, I pay using sandbox mode but I do not get any IPN responses from PayPal but I can simulate the IPN response and it returns handshake verified
I've gone to My Account > Selling Preferences > IPN and updated the URL there, and  also in the plugin I am using I have changed the notify_url bit to the IPN url aswell
The plugin: https://github.com/srmklive/laravel-paypal
On my IPN handler below i have it inserting the post response into a database table so I can see if I get anything from PayPal
Plugin config
return [
    'mode'    => env('PAYPAL_MODE', 'sandbox'), // Can only be 'sandbox' Or 'live'. If empty or invalid, 'live' will be used.
    'sandbox' => [
        'username'    => env('PAYPAL_SANDBOX_API_USERNAME', ''),
        'password'    => env('PAYPAL_SANDBOX_API_PASSWORD', ''),
        'secret'      => env('PAYPAL_SANDBOX_API_SECRET', ''),
        'certificate' => env('PAYPAL_SANDBOX_API_CERTIFICATE', ''),
        'app_id'      => 'APP-80W284485P519543T', // Used for testing Adaptive Payments API in sandbox mode
    ],
    'live' => [
        'username'    => env('PAYPAL_LIVE_API_USERNAME', ''),
        'password'    => env('PAYPAL_LIVE_API_PASSWORD', ''),
        'secret'      => env('PAYPAL_LIVE_API_SECRET', ''),
        'certificate' => env('PAYPAL_LIVE_API_CERTIFICATE', ''),
        'app_id'      => '', // Used for Adaptive Payments API
    ],

    'payment_action' => 'Sale', // Can only be 'Sale', 'Authorization' or 'Order'
    'currency'       => 'GBP',
    'notify_url'     => 'https://www.mywebsite.com/paypal/ipn', // Change this accordingly for your application.
    'locale'         => '', // force gateway language  i.e. it_IT, es_ES, en_US ... (for express checkout only)
    'validate_ssl'   => false, // Validate SSL when creating api client.
];

The IPN handler
public function ipn(Request $request)
{
    $data = [
        'post' => json_encode($request->all()),
        'created_at' => date('Y-m-d H:i'),
    ];
    // Import the namespace Srmklive\PayPal\Services\ExpressCheckout first in your controller.
    $provider = new ExpressCheckout;

    $request->merge(['cmd' => '_notify-validate']);
    $post = $request->all();

    $response = (string) $provider->verifyIPN($post);
    $data['response'] = $response;

    DB::table('ipn_responses')->insert($data);

    if ($response === 'VERIFIED') {
        // Your code goes here ...
    }
}

A: Turns out I was using the plugin wrong. I needed to "do" the payment on the success_url
So for example, when PayPal returns me to the website, the payment hasn't gone through yet. It's the following code that processes the payments and then checks. I always thought it was sent through the IPN
/**
 * Payement success
 * @param Request $request
 * @return \Illuminate\Http\RedirectResponse
 */
public function success(Request $request)
{
    $token = $request->get('token');
    $PayerID = $request->get('PayerID');
    $cart = $this->getCartDataFromToken($token);

    // Verify Express Checkout Token
    $response = $this->provider->getExpressCheckoutDetails($token);

    // Check express checkout was a success
    if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {

        // Perform transaction on PayPal
        $response = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
        $order = $this->finalizeOrder($cart, $response);

        if($order->paid) {

            $order->user->startMembership($order->membership);

            FormResponse::set('Your order has been successfully completed and your membership has begun. You may check your My Account page to view your membership status.');
        }
        else {
            FormResponse::set('Your payment could not be completed (Error 2)');
        }
    }
    else {
        FormResponse::set('Your payment could not be completed (Error 1)');
    }

    return redirect()->route('memberships');
}


text:
Q: How to automate information extraction about an organization's hierarchy from outlook mail? I want to get information about a company's hierarchy, i.e who reports to whom. In microsoft outlook there is an organization tab where I can see it. Is there a process to do this directly and get the output as a CSV?

A: In the Outlook Object Model, you can use ExchangeUser.GetExchangeUserManager() and ExchangeUser.GetDirectReports(). From there you can build the complete org hierarchy.
The initial ExchangeUser object can come the current user (Namespace.CurrentUser.AddressEntry.GetExchangeUser()), message sender (MailItem.Sender.GetExchangeUser()) or an arbitrary user resolved by name (Application.Session.CreateRecipient / Recipient.Resolve / Recipient.AddressEntry.GetExchangeUser()).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove existence/non-existence of a pdf given mean, std, range Given:
Mean = 100,
Range = [4, 10000],
std = 3000
Is it possible to prove whether a pdf exists or not that satisfies these values? If it does exist, what would be approximate shape of the distribution?

A: The standard deviation looks suspiciously high.  Let's see: the
largest standard deviation for a given mean and range should
be when all the mass is at the extremes of the range.  If you put mass $m$ at $4$ and $1-m$ at $10000$, to have mean $100$ you need $m = 825/833$, and then
the standard deviation is $\sqrt{825/833 (4^2) + 8/833 (10000^2) - 100^2} \approx 974.8846$.  So the answer is that there is no such pdf.


text:
Q: How to update rows values with other rows values from the same table I have the following table:
Parameters
id, ownerId, paramId, value
1,    500,    100,    12345
2,    500,    100,    54321
3,    500,    101,      900
4,    500,    101,      901
5,    501,    101,      888
6,    501,    101,      777

Expected result:
Parameters
id, ownerId, paramId, value
1,    500,    100,      900
2,    500,    100,      901
3,    500,    101,      900
4,    500,    101,      901
5,    501,    101,      777
6,    501,    101,      777

I am trying to update the firs two rows values with the values from the last two rows, generally, I wish to update the value from 100 paramId with the value from 101 paramId where I have the same ownerId.
I am trying with the following script:
Update Parameters
    set value = t1.value
    from Parameters t1
    where ownerId = t1.ownerId AND paramId = 100 And t1.paramId = 101

This script returns (0 row(s) affected)

A: both your rows with ids 3 & 4 have same data for columns ownerId, paramId and value. You will need to filter by column id to update your rows.
Something like:

Update Parameters
      set value = (select value from Parameters where id=3) where id = 1
Update Parameters
      set value = (select value from Parameters where id=4) where id = 2

A: You may need to clarify why record 1 should be updated with the value from record 3 and record 2 should be updated with the value from record 4? But this will work otherwise...
update
    p
set
    p.value = t.value
from
    Parameters p
join
    Parameters t
on
    t.ownerId = p.ownerId
    and t.paramId = 101
where
    p.paramId = 100


text:
Q: Withcolumn when isNotNull Pyspark I'm getting the following error from the console:

TypeError: _() takes 1 positional argument but 2 were given

Here is the code used:
import pyspark.sql.functions as f

start = '2020-10-20'
end = '2021-01-20'

country = 'es'
spark.conf.set('spark.sql.legacy.timeParserPolicy', 'LEGACY')

dim_customers = (spark.table(f'nn_team_{country}.dim_customers')
           .select(f.col('customer_id').alias('customers'),
                   f.col('hello_pay_date').alias('hello_pay_date'),
                      )
                 .withColumn('HelloPay_user',
                             f.when((f.col('lidl_pay_date').isNotNull(1)).otherwise(0))
           ))

I tried several combinations of () but without result. Any idea about why I'm getting this error?

A: Your syntax is incorrect. You should put 1 in the when clause, not inside isnotnull.
dim_customers = (spark.table(f'nn_team_{country}.dim_customers')
           .select(f.col('customer_id').alias('customers'),
                   f.col('hello_pay_date').alias('hello_pay_date'),
                      )
                 .withColumn('HelloPay_user',
                             f.when(f.col('lidl_pay_date').isNotNull(), 1).otherwise(0))
           ))


text:
Q: SSIS Parameter to Variable Switch I am trying to bind an execution parameter in SSIS to a variable by using a swicth case SQL statement in an SQL Task :
SELECT  @[User::StartTime]=

CASE @[$Project::CmdParam]
WHEN 'Full' THEN '20000101000100'
WHEN 'Day-1' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -1, GETDATE() ), 112),0,12)+''+'235000')
WHEN 'Day-2' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -2, GETDATE() ), 112),0,12)+''+'235000')
WHEN 'Day-3' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -3, GETDATE() ), 112),0,12)+''+'235000')
ELSE @[$Project::CmdParam]+'235000'
END;
I am able to run the query in SSMS but it fails in my package.
It cannot parse the query.

A: SELECT
CASE WHEN @[$Project::CmdParam]='Full'  THEN '20000101000100'
     WHEN @[$Project::CmdParam]='Day-1' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -1, GETDATE() ), 112),0,12)+''+'235000')
     WHEN @[$Project::CmdParam]='Day-2' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -2, GETDATE() ), 112),0,12)+''+'235000')
     WHEN @[$Project::CmdParam]='Day-3' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -3, GETDATE() ), 112),0,12)+''+'235000')
     ELSE @[$Project::CmdParam]+'235000'
 END

Make sure the  parameter name in Parameter Mapping page match exactly the same as @[$Project::CmdParam] and CASE WHEN is used as like above. More important, choose Single Row as the reulst, and choose @[User::StartTime] as the stored variable in Result page
UPDATE
Like Nick said, switch to ADO.Net as the Connection Type since you are working with SQL Server, then you could use the above mapping methods, otherwise, you have to use ?, replace each @[$Project::CmdParam] in the query, then the Parameter Name for mapping parameters will be, in your case, 0,1,2,3,4, stay same with the result mapping.
2nd UPDATE
If you are using ADO.net now, forget about 0-4 thing, Paste the following query to you statement in Execute SQL Task:
SELECT
CASE WHEN @a = 'Full'  THEN '20000101000100'
     WHEN @a = 'Day-1' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -1, GETDATE() ), 112),0,12)+''+'235000')
     WHEN @a = 'Day-2' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -2, GETDATE() ), 112),0,12)+''+'235000')
     WHEN @a = 'Day-3' THEN (SELECT SUBSTRING(CONVERT(nvarchar(12),DATEADD("Day", -3, GETDATE() ), 112),0,12)+''+'235000')
     ELSE @a + '235000'
 END

After pasting, choose Single Row as the Result set in the same page, next go to the Parameter Mapping page, choose $Project::CmdParam as the Variable Name, type @a for the Parameter Name, which will map your package variable to @a in the query. Then go to Result Set page, Add new result, Result Name should be 0, and choose User::StartTime as the variable that store the query result.
After all the above steps, should be fine this time.


text:
Q: How to statically compile an SDL game on Windows with VS2010 I downloaded the latest SDL HG from http://www.libsdl.org/ and compiled them using VS2010. And everything is working, but the dynamic linking is inconvenient.
I changed the project properties (in SDL HG) to static compilation, but now in projects (that use these libraries) are a lot of mistakes linker "unresolved external symbol".
How to correctly compile a library?

A: If you want statically compile SDL in VS2010 you must change type of configuration from dll to lib and set all dependency in "Librarian" (for lib configuration) as in "Linker" (for dll configuration).
E.g. from my SDL_VS2010.vcxproj
<Lib>
  <AdditionalDependencies>winmm.lib;imm32.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Lib>
<Lib>
  <AdditionalLibraryDirectories>$(DXSDK_DIR)\lib\x86</AdditionalLibraryDirectories>
</Lib>
<Lib>
  <IgnoreAllDefaultLibraries>true</IgnoreAllDefaultLibraries>
  <SubSystem>Windows</SubSystem>
  <TargetMachine>MachineX86</TargetMachine>
</Lib>
<ProjectReference>
  <LinkLibraryDependencies>false</LinkLibraryDependencies>
</ProjectReference>


text:
Q: Number of powers of $2$ having leading digit $1$ How many of the numbers $2^m$ (where $0\le m\le M)$ have leading digit $1$?
My trial -
Since leading digit $=1$, whenever $2^m$ reaches or just crosses a $10^x$ and is less than $2 \cdot 10 ^ x$, that $m$ is eligible i.e.
$$10^x \le 2^m \lt 2\cdot 10^x.$$
But $x$ also depends on the current $m$, so $x$ must also satisfy
$$(m-1)\cdot \log 2 \le x \lt m \cdot \log 2$$ (which directly follows from the previous inequality).
So the final summation is:
$$\sum\limits_{(x, m)}\left([10^x \le 2^m \lt 2\cdot 10^x]\cdot[(m-1)\log 2 \le x \lt m \log 2]\cdot[0 \le m \le M]\right).$$
I think I am making it a bit too complex, my main confusion is regarding the manipulation of $x$, can anyone help? (The brackets are Iverson notation which is $1$ if true and $0$ if false).

A: If $2^m$ starts with a $1$ then $2^{m-1}$ and $2^{m+1}$ do not.  And if $2^m$ has one more decimal digit than $2^{m-1}$ then it must start with a $1$.
So all you need to know is how many powers of $10$ are less than or equal to $2^M$.  This is $$\lfloor 1+ \log_{10} 2^M \rfloor = 1+\lfloor M\log_{10} 2\rfloor $$ where you need to add $1$ to deal with $2^0=1$. For $M \gt 0$ you could instead write $\lceil M\log_{10} 2\rceil$.


text:
Q: Selecting from DB where some data points can be NULL (psycopg2) I have the following query, where some of the values I am trying to select with can be empty and therefore default to None.
So I've come up with something like this:
   db.cursor.execute(
        '''
            SELECT
                s.prod_tires_size_id as size_id
                ,s.rim_mm
                ,s.rim_inch
                ,s.width_mm
                ,s.width_inch
                ,s.aspect_ratio
                ,s.diameter_inch
            FROM product_tires.sizes s
            WHERE
                s.rim_mm %(rim_mm)s
            AND s.rim_inch %(rim_inch)s
            AND s.width_mm %(width_mm)s
            AND s.width_inch %(width_inch)s
            AND s.aspect_ratio %(aspect_ratio)s
            AND s.diameter_inch %(diameter_inch)s
        ''', {
            'rim_mm': data['RIM_MM'] or None,
            'rim_inch': data['RIM_INCH'] or None,
            'width_mm': data['WIDTH_MM'] or None,
            'width_inch': data['WIDTH_INCH'] or None,
            'aspect_ratio': data['ASPECT_RATIO'] or None,
            'diameter_inch': data['OVL_DIAMETER'] or None,
        }
    )

However, = NULL does not work.
If I use IS, then it will not match the values I am proving.
How can I solve this problem?

A: Generate the query using python:
k = {'rim_mm':        'RIM_MM',
     'rim_inch':      'RIM_INCH',
     'width_mm':      'WIDTH_MM',
     'width_inch':    'WIDTH_INCH',
     'aspect_ratio':  'ASPECT_RATIO',
     'diameter_inch': 'OVL_DIAMETER',
}

where = []

for column, key in k.items():
    if data[key]:
        where.append("%s=%%(%s)s" % (column,key)")
    else:
        where.append("%s IS NULL" % column)

sql = "your select where " + " AND ".join(where)

cursor.execute( sql, data )


text:
Q: Reduce spacing after glossary title I would like to reduce the spacing after the Acronyms title to match spacing of a regular section, but don't know how.

I tried to reduce it manually using \renewcommand{\glossarypreamble}{\vspace*{-\baselineskip}}, which works, but is a really bad way of doing it.
MWE:
\documentclass[a4paper, 12pt]{article}

\usepackage[acronym]{glossaries}

\setglossarystyle{alttree}

\makeglossaries
\newacronym{frc}{FRC}{First Robotics Competition}
\newacronym{ftc}{FTC}{First Technical Challenge}
\newacronym{fll}{FLL}{First Lego League}
\glsaddall
\glsfindwidesttoplevelname

\begin{document}
  \section{Sample Text}
  \gls{frc}, \gls{ftc}, \gls{fll}

  \printglossary[type=\acronymtype]
\end{document}

A: For some reason, glossaries does \mbox{}\par at the start of a glossary, so adding an empty line.
\documentclass[a4paper, 12pt]{article}

\usepackage[acronym]{glossaries}

\setglossarystyle{alttree}
\setglossarypreamble[acronym]{\vspace*{-\baselineskip}}

\makeglossaries

\newacronym{frc}{FRC}{First Robotics Competition}
\newacronym{ftc}{FTC}{First Technical Challenge}
\newacronym{fll}{FLL}{First Lego League}

\glsaddall
\glsfindwidesttoplevelname

\begin{document}

\section{Sample Text}

\gls{frc}, \gls{ftc}, \gls{fll}

\printglossary[type=\acronymtype]

\section*{Acronyms}

\textbf{FLL} First Lego League. 1

\end{document}

A: The additional space is caused by \setglossarystyle{alttree}. Use \setglossarystyle{tree}.
\documentclass[a4paper, 12pt]{article}

\usepackage[acronym]{glossaries}

\setglossarystyle{tree}

\makeglossaries
\newacronym{frc}{FRC}{First Robotics Competition}
\newacronym{ftc}{FTC}{First Technical Challenge}
\newacronym{fll}{FLL}{First Lego League}
\glsaddall
\glsfindwidesttoplevelname

\begin{document}
  \section{Sample Text}
  \gls{frc}, \gls{ftc}, \gls{fll}

  \printglossary[type=\acronymtype]
\end{document}


text:
Q: Why doesn't MySQL call a function correct in a Query with left outer join inside a where condition This problem is not present in MariaDB 10.6 anymore.
We have a problem with outer join and a function call inside a where condition. It seems that the function is not called if the outer join don't find records in the outer table.
In real the function are more complex this is simplify by eample to demonstrate the problem.
Simple Test Returns nothing, but 1 record would be correct:
SELECT *
FROM (SELECT 1 ID) t1
LEFT JOIN (SELECT 1 ID, null as date FROM (SELECT 1) x WHERE 1=2) t2 ON t2.ID=t1.ID
WHERE
IS_LOWHIGH_DATE(t2.date)

Complex Test also returns nothing, but one record would be correct:
SELECT *
FROM (SELECT 1 ID1, cast(null as date) as date1 ) t1
LEFT JOIN (SELECT 2 ID2, cast(null as date) as date2) t2 ON t2.ID2=t1.ID1
WHERE
IS_LOWHIGH_DATE(t2.date2)

Return one record with correct results:
SELECT *, IS_LOWHIGH_DATE(NULL), IS_LOWHIGH_DATE(t1.date1), IS_LOWHIGH_DATE(current_date)
FROM (SELECT CAST(NULL as date) as date1) t1

Should by return two records but don't do that, only one line returns:
SELECT t1.*, IS_LOWHIGH_DATE(t1.date1), NULL, NULL
FROM (SELECT 1 ID1, cast(null as date) as date1 ) t1
UNION ALL
SELECT t1.*, IS_LOWHIGH_DATE(t1.date1), t2.*
FROM (SELECT 1 ID1, cast(null as date) as date1 ) t1
LEFT JOIN (SELECT 2 ID2, cast(null as date) as date2) t2 ON t2.ID2=t1.ID1
WHERE
IS_LOWHIGH_DATE(t2.date2)

This works with coalesce() arround the attribute:
SELECT *
FROM (SELECT 1 ID) t1
LEFT JOIN (SELECT 1 ID, null as date FROM (SELECT 1) x WHERE 1=2) t2 ON t2.ID=t1.ID
WHERE
IS_LOWHIGH_DATE(COALESCE(t2.date))

Simple test with dummy return value (doesn't matter)
CREATE FUNCTION is_lowhigh_date
 (p_date date) RETURNS tinyint(1)
  NO SQL DETERMINISTIC
BEGIN
 RETURN true;
END

The function at is
CREATE FUNCTION is_lowhigh_date
 (p_date date) RETURNS tinyint(1)
  NO SQL DETERMINISTIC
BEGIN
 RETURN CASE
   WHEN p_date is NULL OR p_date <= '0001-01-01' or p_date >= '9999-12-31' THEN
     true
 ELSE
   false
 END;
END

You can try sqlfiddle: http://sqlfiddle.com/#!2/513671/6

A: This will give you your expected result (avoiding the empty set caused by the last where)
SELECT * FROM (SELECT 1 ID) t1
LEFT JOIN (SELECT 1 ID, null as date FROM (SELECT 1) x WHERE 1=2) t2
ON (t2.ID=t1.ID AND IS_LOWHIGH_DATE(t2.date))

A: Run these commands:
explain extended
SELECT *
FROM (SELECT 1 ID) t1
LEFT JOIN (SELECT 1 ID, null as date FROM (SELECT 1) x WHERE 1=2) t2 ON t2.ID=t1.ID
WHERE
IS_LOWHIGH_DATE(t2.date)
;
show warnings;

this will give you your query after optimalizaltion
/* select#1 */ select '1' AS `ID`,NULL AS `ID`,NULL AS `date`
from (/* select#3 */ select 1 AS `ID`,NULL AS `date`
from (/* select#4 */ select 1 AS `1`) `x` where 0) `t2` where 0

The last WHERE 0 means WHERE false => MySql doesn't execute this query at all, so the subquery nor function in the subquery are not executed too.


text:
Q: dodge/displace/repel axis tick labels in ggplot? What I want is probably not possible without a lot of work, but maybe someone has a solution.  I have a plot like the following (this is an oversimplified example of course) where I have tick labels that fall very close to each other:
dd <- data.frame(x=1:4, y=c(-10,10.5,10.6,10.7),
                 z = LETTERS[1:4])
library(ggplot2)
gg1 <- ggplot(dd, aes(x,y)) +
  geom_point() +
  geom_segment(x=0, aes(xend=x, y=y, yend=y)) +
  scale_y_continuous(breaks=dd$y, labels=dd$z)

If I really want to I can export as SVG, dump it into Inkscape, and move the labels apart manually (even adding in little indicator lines connecting the labels with the precise y-axis positions):

It would be nice to be able to do something like this programmatically/automatically. I thought about:

*

*ggrepel package (only works on labels/text within the plot AFAIK)

*directlabels package (it has some placement options like "first.bumpup" that might be adaptable/hackable for this case)

*the n.dodge and check.overlap arguments to guide_axis as illustrated here look useful and interesting, and they almost handle this case, but n.dodge dodges labels horizontally, which will get ugly if the labels are longer than a few characters ...

I would be happy enough with a label.pos.nudge argument that could be specified manually to displace the positions of the labels along the axis from their corresponding

A: Thanks to the suggestion to look at this question (and this question letting me know about coord_cartesian(clip = "off"), I made the following work (note that I had to change geom_segment(x=0, ...) to geom_segment(x=-Inf, ...) in the base example above, so that turning off clipping didn't mess things up).
gg1 + coord_cartesian(clip = "off") +
  theme(axis.text.y = element_blank(),
        plot.margin = margin(t=5.5, r=5.5, b=5.5, l=30, unit="pt")) +
  geom_text_repel(x = 0.85, aes(label = z, y = y),
                  direction = "y",
                  force_pull = 100,
                  hjust = -7,
                  xlim = c(0.8,1))

Note that this may require a fair amount of fussing with plot margins and the arguments of geom_text_repel (force, force_pull, hjust, xlim, etc.) to get it looking right ... I still haven't gotten my real plot just the way I want it, but it's getting close. (It's possible that the x and hjust values are redundant here ...)


text:
Q: how can I write thie for loop I try to write  my own shell script but I have some trouble.
What should I do?
./test_online.sh: line 47: host.booking.yh: command not found

host_tmp='host.booking'
host=$host_tmp'kpt' $host_tmp'yh' $host_tmp'mt'
for each_site in $host
    do
     #cd /home/toptrain/workspace/op_tools/ansible && ansible-playbook -i hosts/$each_site  test.yaml --extra-vars "branch=$branch" -v --tags "update" -v
     echo $each_site

I what after for loop,it can output host.booking.kpt host.booking.yh host.booking.mt.but got this error

A:
host=$host_tmp'kpt' $host_tmp'yh' $host_tmp'mt'

If you want to assign something containing spaces to a variable, you must quote those spaces, e. g.:
host="$host_tmp.kpt $host_tmp.yh $host_tmp.mt"


text:
Q: Spring Security login with UserDetailsService and Java config I am trying to add login functionality with a database lookup with Spring Security, and I am really struggling. I want to look up the user by implementing the UserDetailsService interface. I have read a ton of documentation and Googled for hours, but I am still stuck. Most of the examples that I could find are using XML, so maybe my problems are related to converting those to Java configuration.
UserDetailsService
@Service
public class AccountServiceImpl implements AccountService { // AccountService implements UserDetailsService
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        // The email variable is always ''

        List<GrantedAuthority> authList = new ArrayList<>();
        authList.add(new Role("ROLE_USER")); // Role implements GrantedAuthority

        return new User("test@example.com", "password", true, true, true, true, authList);
    }
}

Security config
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private AccountService accountService;

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        // This bean is required for using method security annotations
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login/process")
                .failureUrl("/login?error=true")
                .defaultSuccessUrl("/", false)
                .and()
                //.userDetailsService(this.accountService)
                .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessHandler(this.logoutSuccessHandler)
                    .invalidateHttpSession(true)
                .and()
                // Permissions here
                .csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("test@example.com").password("password").roles("USER");
    }

    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                //.userDetailsService(this.accountService);
                .inMemoryAuthentication()
                .withUser("test@example.com").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }*/

    /*@Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(this.accountService);
        return provider;
    }*/
}

As you can see, there is a bunch of outcommented code, which are just some of the things I tried to make it work. I also tried with simple in-memory authentication, but that didn't work either.
login.jsp
<form action="/login/process" method="POST">
    <input name="j_username" id="j_username" type="text" />
    <input name="j_password" id="j_password" type="password" />

    <input type="submit" value="Login" />
</form>

Debug
DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Request is to process authentication

DEBUG org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider

DEBUG org.springframework.security.authentication.dao.DaoAuthenticationProvider - User '' not found

DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials

DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Updated SecurityContextHolder to contain null Authentication

The above seems to always be the case for all of the configurations that I tried. I am not even sure why the DaoAuthenticationProvider is used, even if I try to override it; I guess it's a default. For some of the configuration above, my UserDetailsService implementation gets called, but with an empty string as the parameter. Also, even if I return a hard coded UserDetails object with the same credentials as the ones I entered in my form, the authentication still fails, and I get redirected back to /login?error=true.
What am I doing wrong here? Please inform me about my mistakes or provide a simple example using Java configuration. Thanks!

A: When using Spring Security with Java based configuration the name of the request parameters are username and password and not j_username and j_password anymore.
You can either fix your login form
<form action="/login/process" method="POST">
    <input name="username" id="j_username" type="text" />
    <input name="password" id="j_password" type="password" />

    <input type="submit" value="Login" />
</form>

or adapt your configuration to use the old field names.
formLogin().usernameParameter("j_username").passwordParameter("j_password");

Either way will resolve your issue.


text:
Q: Remapping a pair of 2D points to another pair of points I have been working on the following problem for a while, but I am not making any headway:
Given two points in a view A (ax,ay) and B (bx,by), transform them so that they are positioned at C (cx,cy) and D (dx,dy) respectively.  Additionally, since this is for presentation/image processing, the resulting complete transformation must be proportional and not reflected.
Specifically what I want is to directly calculate the single transformation matrix M that can make this change in one step and without using any trigonometric functions, if possible. In other words:
M:               A:     C:
| xx  yx  wx |   |ax|   |cx|
| xy  yy  wy | * |ay| = |cy|
| 0   0   1  |   | 1|   | 1|

And
M:               B:     D:
| xx  yx  wx |   |bx|   |dx|
| xy  yy  wy | * |by| = |dy|
| 0   0   1  |   | 1|   | 1|

And I want to directly calculate the values of the matrix M.
Now I know that it could be accomplished with the following standard transforms:

*

*Translate B to the origin:  T(-bx,-by)

*Counter-rotate the slope B-A to zero.

*Rotate to the slope D-C.

*Scale distance ||A-B|| to distance ||C-D||: (i.e. ||C-D||/||A-B||)

*Translate from origin to D.

Or, in transform shorthand:

*

*T(-bx,-by)

*R(-s(B:A))

*R(s(D:C))

*S(|C-D|/|A-B|)

*T(dx,dy)

However, I am using this in a real-time program to present two different dynamic POVs and the overhead of 5 transforms is pretty significant.  I also know that I can combine steps 2 and 3, but that would require additional trig functions and trig functions also have a lot of overhead for a real-time display.
Finally, the source points A and B are moving dynamically in the original POV so I cannot just combine all of the steps into one static transform matrix and reuse that  (I am actually dynamically remapping the entire view to the second viewport, the GUI will do it for me, if I can supply it with the transform matrix).
I have been trying to derive the calculations by symbolically combining the transformation arrays, or alternatively trying to solve the simultaneous equations using equivalences and proportionality principles but the terms and radicals start to explode and exceed my manual limits pretty quickly.  I have been able to avoid the trig functions using slopes and Pythagorean equivalences instead, but that has meant that I end up with a lot of nested expressions with radicals and also the loss of signs that comes with both radicals and slopes.  So at this point I think I need some help.
I can supply what I have so far on either approach, but they're pretty far into the weeds and I'm hoping that this is some standard operation that has a known solution (it's certainly seems like it would come up a lot).  I looked at this question Remapping plane parameters for a different Cartesian system which seemed related, but I didn't understand the question or the answer well enough to reapply it.
Bonus question:  Does this operation have a standard name?  I have been calling it "Remapping", but that seems pretty generic and search for that doesn't results in anything specific to this.
Also: I don't know Tex, etc. so anyone who wants the Editor points can edit my post to make it look better symbolically.

I have updated the text above with:
Additionally, since this is for presentation/image processing, the resulting complete transformation must be proportional and not reflected.

A: Note that
$$\left[ \begin{matrix} x_x & y_x & t_x \\ x_y & y_y & t_y \\ 0 & 0 & 1 \end{matrix} \right ] \left [ \begin{matrix} a_x \\ a_y \\ 1 \end{matrix} \right ] = \left [ \begin{matrix} c_x \\ c_y \\ 1 \end{matrix} \right ]$$
is exactly equivalent to
$$\left[ \begin{matrix} x_x & y_x \\ x_y & y_y \end{matrix} \right ] \left [ \begin{matrix} a_x \\ a_y \end{matrix} \right ] + \left[ \begin{matrix} t_x \\ t_y \end{matrix} \right ] = \left [ \begin{matrix} c_x \\ c_y \end{matrix} \right ]$$
A pure 2D rotation matrix by counterclockwise angle $\theta$ is
$$\mathbf{R}_\theta = \left [ \begin{matrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{matrix} \right ]$$
So, if we write $\mathbf{R}$ as say
$$\mathbf{R} = \left [ \begin{matrix} c & -s \\ s & c \end{matrix} \right ]$$
we have four equations in four unknowns ($c$, $s$, $t_x$, and $t_y$):
$$\left\lbrace ~ \begin{aligned}
c a_x - s a_y + t_x &= c_x \\
s a_x + c a_y + t_y &= c_y \\
c b_x - s b_y + t_x &= d_x \\
s b_x + c b_y + t_y &= d_y \\
\end{aligned} \right.$$
This has exactly one solution, if and only if
$$\Delta = (b_x - a_x)^2 + (b_y - a_y)^2 \ne 0$$
or in other words, iff points $A$ and $B$ differ.

To minimize numerical error, I would suggest calculating
$$\begin{aligned}
\Delta &= (b_x - a_x)^2 + (b_y - a_y)^2 \\
C &= (b_y - a_y)(d_y - c_y) + (b_x - a_x)(d_x - c_x) \\
S &= (b_x - a_x)(d_y - c_y) - (b_y - a_y)(d_x - c_x) \\
\end{aligned}$$
Note that $S^2 + C^2 = 0$ if and only if points $C$ and $D$ are the same, and/or points $A$ and $B$ are the same.
Then, the solution (rotation and scaling, but not skewing or mirroring) for $c$ and $s$ is
$$\left\lbrace ~ \begin{aligned}
c &= \displaystyle \frac{C}{\Delta} \\
s &= \displaystyle \frac{S}{\Delta} \\
\end{aligned} \right .$$
If you require a pure rotation solution, without scaling, use
$$\left\lbrace ~ \begin{aligned}
s &= \displaystyle \frac{S}{S^2 + C^2} \\
c &= \displaystyle \frac{C}{S^2 + C^2} \\
\end{aligned} \right .$$
If you are interested in the angle of rotation $\theta$, you can use
$$\left\lbrace ~\begin{aligned}
\theta &= \operatorname{atan2}(S, C) \\
s &= \cos\theta \\
c &= \sin\theta \\
\end{aligned} \right.$$
After calculating $s$ and $c$, again in an effort to keep numerical errors to a minimum,
$$\left\lbrace ~ \begin{aligned}
t_x &= \displaystyle \frac{ c_x + d_x + s (a_y + b_y) - c (a_x + b_x) }{2} \\
t_y &= \displaystyle \frac{ c_y + d_y - c (a_y + b_y) - s (a_x + b_x) }{2} \\
\end{aligned}\right.$$
Because the form I used is equivalent to OP's, the single 2×3 transformation matrix sought for is
$$\mathbf{M} = \left [ \begin{matrix} c & -s & t_x \\ s & c & t_y \\ 0 & 0 & 1 \end{matrix} \right ]$$


text:
Q: Retrieve data inside () with regex I would like to retrieve a numeric value from a webpage using regex.
(I was not able to get simple_php_dom handling https requests.)
Here is the code containing the numeric value (78)

Display all tables (78)

Here is the command I use
preg_match_all("/Display all tables \((.*)\)/", $file_content, $matches);
var_dump($matches[0][0]);

but it returns
string(137) "

Display all tables (78)
"

Edit: my mistake
var_dump($matches[1][0]);

is correct, but then it returns
string(9) " (78)"

To Return the value
echo $matches[1][0];

:)

A: Try this instead:
preg_match_all('/Display all tables \((\d+)\)/', $file_content, $matches);
$mtch = (int)$matches[1][0];
var_dump($mtch);

A: Try this:
<?php
$string = <<<EOS

Display all tables (78)

EOS;

preg_match_all("/Display all tables \((.*)\)/", $string, $matches);

echo $matches[1][0] . " - " . gettype($matches[1][0]) . "\n";
echo (int)$matches[1][0] . " - " . gettype((int)$matches[1][0]) . "\n";

After all you're getting substring that matches your regex. Even if you do it like this:
preg_match_all("/Display all tables \((\d+)\)/", $string, $matches);

But you can cast it to integer though.


text:
Q: New to python - trying to chose individual columns from transposed matrix So presently code is as so:
table = []
for line in open("harrytest.csv") as f:
   data = line.split(",")
   table.append(data)
transposed = [[table[j][i] for j in range(len(table))] for i in range(len(table[0]))]
openings = transposed[1][1: - 1]
openings = [float(i) for i in openings]

mean = sum(openings)/len(openings)
print mean

minimum = min(openings)
print minimum

maximum = max(openings)
print maximum

range1 = maximum - minimum
print range1

*

*This only prints one column of 7 for me, it also leaves out the bottom line. We are not allowed to import with csv module, use numpy, pandas. The only module allowed is os, sys, math & datetime.

*How do I write the code so as to get median, first, last values for any column.

A: Change this line:
openings = transposed[1][1: - 1]

to this
openings = transposed[1][1:]

and the last row should appear. You calculations for mean, min, max and range seem correct.
For median you have to sort the row and select the one middle element or average of the two middle elements. First and last element is just row[0] and row[-1].


text:
Q: How to end C Shell Script when calling continues process Ok, I apologize. Been playing around with the process by killing it and starting it and it looks like I am not ending the script properly.
I have a csh script that I run to start a java application on an AIX system.
What I normally do:
In a typescript/terminal I run
startApp.csh >> ../log/app.log &
But I am running into an issue where the startApp.csh will not stop after java app starts up. It shows up in the background like:
/bin/csh startApp.csh
along side the java process $JRE_HOME/bin/java -XMS16M -Xmx512M \-Set \-all \-necessary \-environments $argv[*]. They are both now dependent on each other to keep running. If I kill the /bin/csh startApp.csh the java application wont stop with my port calls, unless I do akill -9
startApp.csh
#!/bin/csh
setenv JAR_HOME /to/directory/
setenv JAVA_HOME /to/directory/
setenv JRE_HOME /to/directory/
set CLASSPATH="${CLASSPATH}:$to/path"
$JRE_HOME/bin/java -XMS16M -Xmx512M \-Set \-all \-necessary \-environments $argv[*]

I dont know how to tell my script to end when java application runs. How can I achieve that?

An Update:
This is what I have tried so far to have the java child process run on its own and for the parent shell-script to die.
In a typescript/terminal I run
startApp.csh >> ../log/app.log
#!/bin/csh
setenv JAR_HOME /to/directory/
setenv JAVA_HOME /to/directory/
setenv JRE_HOME /to/directory/
set CLASSPATH="${CLASSPATH}:$to/path"
nohup $JRE_HOME/bin/java ... $argv[*] &

The nohup command & will ignore the fact that the parent has ended and will take me back to my typescript/terminal for next input.
I just dont know enough if it matters that the process runs as a child with a PPID of 1.

A: Simple, use exec:
#!/bin/csh
setenv JAR_HOME /to/directory/
setenv JAVA_HOME /to/directory/
setenv JRE_HOME /to/directory/
set CLASSPATH="${CLASSPATH}:$to/path"
exec $JRE_HOME/bin/java -XMS16M -Xmx512M \-Set \-all \-necessary \-environments $argv[*]

Without exec the csh assumes that it needs to stick around as a process and will wait for the java process to end, it will then execute the next line in the csh script. In your case there is no next line, so it ends.
With exec the csh process is ''replaced'' with the Java process, with the same process id.


text:
Q: Setup Php Session Login On Clustered Servers I have 3 servers. One MySQL database and 2 Apache web servers with a load balancer. Www1 copies it's data to www2 every other minute and vice versa. The issue I'm having is that say a user goes to the site and hits the www1 server, attempts to login, the page refreshes and now they are on www2 and then not logged in. Then if you refresh the page and if you hit www1 you are logged on again. This happens for about 2 minutes until the servers match info and depending which one does first you might not be logged in anymore.  I set up a simple php session login. Does anyone have experience with working on clustered systems and setting up logins. Any advice would help. Hank you for your time.

A: I would suggest creating a memcache server and store your PHP sessions from both apache servers on the memcache server.

A: Since you already have a MySQL Database. Create database based PHP sessions. The session information can be passed via the url and auto clean after so many minutes of inactivity and the page is loaded requiring customer to relogin.


text:
Q: What is the chance of repeating a combination of random image sets within 20 images over 100 trials? Title states an example, I'll give the general case question then repeat an example.
I have N images and plan to randomly pick k of the possible N images into a set. The order does not matter. I repeat for T trials. What is the chance that any of the k-image sets are repeated at least once across the T trials?
More specifically, I have 20 images and plan to randomly pick 10 of the possible 20 images into a set. The order does not matter. I repeat this for 100 trials. What is the chance that any 10-image sets are repeated at least once across the 100 trials?
I realize this is similar to the Birthday problem, however I believe in that problem N equals T. Could be wrong...

A: Let $M = {N \choose k}$, the number of possible $k$-image sets.  There are $M!/(M-T)!$ possible sequences of $T$ distinct sets, and $M^T$ possible sequences if they don't have to be distinct, so the probability of no repetitions is $\dfrac{M!}{(M-T)! M^T}$, and the probability of at least one repetition is $1 - \dfrac{M!}{(M-T)! M^T}$.
In your example with $N=20$, $k=10$, $T=100$, $M = 184756$ and the probability of at least one repetition is approximately $.02644105288$.


text:
Q: I'm trying to understand the solution to this simple mathematical modelling question This is an example from Gary Chartrand's "Introductory Graph Theory" (Page 8, Example 1.5).  He provides an answer without actually showing the steps or working, and I am unable to figure it out.  The statement of the problem is (after editing out extraneous content):
A golf course charges \$11.75 one day and gets 50 players.  When on another day the rate is reduced to \$11.00, 100 people pay to play, and finally when the rate is \$9.75, 150 people pay to play.  What mathematical model would represent this situation?
I approached this problem by figuring that the independent variable is the price, the variation of which causes the variation in the number of players.  We then have three sets of points: A (11.75,50), B (11,100) and C (9.75,150).  A quick check of the slopes between points A and B and B and C shows that the slope changes, hence the solution would be a non linear expression.  I assumed it to be a quadratic equation (with a little bit of cheating, since the author's answer is a quadratic).
Given that p is the price charged and c is the number of players,  I figured that the solution to be an expression of the form $ap^2 + bp = c$.

*

*For the first set of adjacent points A and B, I then get the simultaneous equations

$$
a*(11.75)^2 + b*11.75 = 50$$
$$a*(11)^2 + b*11 = 100
$$
Similarly the next two points B and C are represented by a set of simultaneous equations as follows:
$$
a*(11.00)^2 + b*11.00 = 100$$
$$a*(9.75)^2 + b*9.75 = 150
$$
However I am getting different values for a and b when I solve these two sets of equations.
The author has approached the problem differently, providing an expression for the price in terms of the player count.  I am unable to understand the reason for this, given that it is is the price that determines the number of players, and not the player count that determines the price.  I would hugely appreciate having someone point out the flaws in my reasoning.
Thanks!

A: Often, you won't be able to solve 3 equations if you only have 2 variables. If you allow a quadratic of the form: $$a*p^2 + b*p + c = y$$ where y is the number of customers, you may have more luck. Try solving the system of equations: $$a*(11.75)^2 + b*(11.75) +c = 50$$$$a*(11)^2 + b*(11) + c = 100$$$$a*(9.75)^2 + b*(9.75) + c = 150$$ for a, b and c. If you want the answer, according to wolfram alpha, mouseover:

 a = -13.33, b = 236.66, c = -890


text:
Q: PHP - Convert RGB values to CMYK percentages I am getting RGB Values using this php code
<?php
$im = imagecreatefrompng("img/t4.png");
$rgb = imagecolorat($im, 15, 15);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
?>

And i need CMYK percentages also
Can someone please give me som guide lines.
Thanks.

A: <?
function hex2rgb($hex) {
  $color = str_replace('#','',$hex);
  $rgb = array('r' => hexdec(substr($color,0,2)),
               'g' => hexdec(substr($color,2,2)),
               'b' => hexdec(substr($color,4,2)));
  return $rgb;
}

function rgb2cmyk($var1,$g=0,$b=0) {
   if(is_array($var1)) {
      $r = $var1['r'];
      $g = $var1['g'];
      $b = $var1['b'];
   }
   else $r=$var1;
   $cyan    = 255 - $r;
   $magenta = 255 - $g;
   $yellow  = 255 - $b;
   $black   = min($cyan, $magenta, $yellow);
   $cyan    = @(($cyan    - $black) / (255 - $black)) * 255;
   $magenta = @(($magenta - $black) / (255 - $black)) * 255;
   $yellow  = @(($yellow  - $black) / (255 - $black)) * 255;
   return array('c' => $cyan / 255,
                'm' => $magenta / 255,
                'y' => $yellow / 255,
                'k' => $black / 255);
}

$color=rgb2cmyk(hex2rgb('#FF0000'));
pdf_setcolor($pdf, "both", "cmyk", $color['c'], $color['m'], $color['y'], $color['k']);
?>


text:
Q: Can we use AJAXToolKit and Jquery in the same page can we use AJAXToolKit and Jquery in the same page?
Say i have ScriptManage in that same page and i have also included the

A: Yes you can. However, you may want to make use of jQuery's noConflict() statement.
I recommend putting your jQuery script directive in the ScriptManager, and use AJAXToolkit's ToolkitScriptManager, in place of ScriptManager.
Wrapping your <Scripts> in a <CompositeScript> tag, in conjunction with AJAXToolkit's ToolkitScriptManager, will combine all script files into 1 download at runtime.

A: The jQuery library, and virtually all of its plugins are constrained within the jQuery namespace. As a general rule, "global" objects are stored inside the jQuery namespace as well, so you shouldn't get a clash between jQuery and any other library (like Prototype, MooTools, or YUI).
That said, there is one caveat: By default, jQuery uses "$" as a shortcut for "jQuery"
However, you can override that default by calling jQuery.noConflict() at any point after jQuery and the other library have both loaded. For example:
   <script>
     jQuery.noConflict();

     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });

     // Use Prototype with $(...), etc.
     $('someid').hide();
   </script>

this way Query won't conflict with another library


text:
Q: JavaScript - html div as audio source i have a problem. I want to make html div that is source of audio. I see it as when i move cursor nearer to div audio will make louder, and when farer it will make quieter. But it has to be limited range to not play audio on whole website
I had idea to make it by cursor x and y, but i think that there is spexiaf function for this
case


text:
Q: comparison slider img text disapear then slide on or behind text I have img comparison slider, its working fine, but i wanna add Before and after text. Then i add it looks like not good, then you make only one img.
My img comparison slider.
https://www.w3schools.com/code/tryit.asp?filename=GI7TREPS8JY8

img-comparison-slider {
  --divider: 7x solid #c0c0c0;
  --hint-opacity: 0.8
}

.container {
  position: relative;
  text-align: center;
  color: white;
}

.top-left {
  position: absolute;
  top: 8px;
  left: 16px;
}

.top-right {
  position: absolute;
  top: 8px;
  right: 16px;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

<link rel="stylesheet" href="https://unpkg.com/img-comparison-slider@latest/dist/collection/styles/initial.css" />

After

Before

So i want make text disappear then my slider is on or behind text.


text:
Q: Using fork() to run mutltiple tasks Trying to run 'tasks' in parallel but (obviously) I am failing miserably.
What I want it to do: split the size into 8 different (equal size) tasks and "doSomething" on them simultaneously.
#include <stdio.h>
#include <unistd.h>
#include  <sys/types.h> //pid_t
void doSomething(const int start, const int end){
    printf("%d. Doing %d to %d \n", getpid(), start, end);
}

int main(){

    int word_size = 10000;

    for(int i=0; i<3; i++){
        pid_t pid;
        pid = fork();
        if(pid == 0){
            doSomething((i)*(word_size/8), (i+1)*(word_size/8));
        }
        else {
            doSomething((i+1)*(word_size/8), (i+2)*(word_size/8));
        }
    }
    return 0;
}

Any help would be appreciated.

A: You are not really splitting it in 8 even parts. You are just starting 4 parallel processes and execute other 4 parts sequentially in the main thread. Also, you exit your main thread as soon as you done and let your parallel processes to finish at their leisure. So, in reality you would need something like the following:
    pid_t pid[8];
    for (int i = 0; i < 8; i++) {
        pid[i] = fork();
        if(pid[i] == 0){
            doSomething((i)*(word_size/8), (i+1)*(word_size/8));
            return 0;  // or exit(0);
        }
   }

Note that after forking, the child process should not return to the loop. I added teh return 0; statement to return from the main at this point. Or yuo can use exit(0); if this is not a main routing. I think that the most logical would be using exit(0); in the doSomething function.
now you have all pids of all process you started. you need to wait in the main thread till all of them finish (unless you really want to let them run on their own. Something like the following:
for (int i = 0; i < 8; i++) {
     int status;
     waitpid(pid[i], &status, WNOHANG);
}

A: According to your logic, you would be able to cover only till 5000 words (according to your wordsize of 1000) even though you will have 8 duplicate processes running.
I suppose you want help with the logic. A bit tweak of your for loop would do the trick :
#include <stdio.h>
#include <unistd.h>
#include  <sys/types.h> //pid_t
void doSomething(const int start, const int end){
    printf("%d. Doing %d to %d \n", getpid(), start, end);
}

int main(){

    int word_size = 10000;

    for(int i=0; i<=6; i=i+2){        //the tweaks
        pid_t pid;
        pid = fork();
        if(pid == 0){
            doSomething((i)*(word_size/8), (i+1)*(word_size/8));
        }
        else {
            doSomething((i+1)*(word_size/8), (i+2)*(word_size/8));
        }
    }
    return 0;
}

Hope this helps


text:
Q: Not getting selected radio button value from one HTML form to another in Python Flask I have a home page with radio buttons. I select an item (database type) and want to get the checked-value in python code and then after some validation want to display another form to connect to the selected database type. But after trying so many things, I am unable to get the selected-radio-button value and then unable to process conndb.html below. I am quite new to Python web development. Not getting anything working to meet this requirement. Home page pyhton code is
@bp.route('/')
def index():
db = get_db()
if request.method == 'GET':
    posts = db.execute(
            'SELECT id, DB_Tp'
            ' FROM DB_Type'
            ' ORDER BY DB_Tp ASC'
            ).fetchall()

    error = None
    if len(posts) == 0:
        error = 'No Database Type To Choose For Meta Data. Create New Entry'
        flash(error)

    return render_template('meta/index.html', posts = posts)
else:           **#=> from here the code is never executed. It always falls thru to next function**

    checked = request.form['dbtype']
    print("This is ", checked, flush = True)
    if checked == "MySql":
        return render_template('meta/conndb.html')
    else:
        error = "Nothing checked "
        flash(error)
        return redirect(url_for("meta.index"))

index.html is -
{% extends 'base.html' %}

{% block header %}

{% block title %}Select Database Type{% endblock %}

{% endblock %}

{% block content %}
   <form class="post" action="/conndb">
{% for post in posts %}

    <input type="radio" name="dbtype" required>{{post['DB_TP']}}

{% if not loop.last %}
{% endif %}
{% endfor %}
    <button type="submit">Next</button>
</form>

{% endblock %}

Depending on the selected radio button, I want to perform different operations with different kind of DB. After getting the value from the selected radio button, I render this template to connect to database...
conndb.html
{% extends 'base.html' %}

{% block header %}

{% block title %}Provide Details To Connect To Database{% endblock %}

{% endblock %}

{% block content %}
 <form method="post">
 Host Name
 <input name="host" id="host" required>
 User ID
 <input name="user" id="user" required>
 Password
 <input type="password" name="passwd" id="passwd" required>
 Schema
 <input name="db" id="db" required>
 <input type="submit" value="Get MetaData">
 </form>
{% endblock %}

Any help is greatly appreciated.

A: "value" attribute is missing in radio html.
e.g.:
<input type="radio" name="dbtype" value="{{post['DB_TP'].id}}" required>{{post['DB_TP']}}


text:
Q: Empty response from Google Vision API with an image stored in Google Cloud Storage I am trying to use the cloud vision API and I am able to make a successful request, but my response comes back empty, even with the test image provided on the API docs.
Request Body:
const imagePath = `gs://[bucket_name]/faulkner.jpg`;
const requestObject = {
  requests: [
    {
      image: {
        source: {
          gcsImageUri: imagePath
        }
      },
      features:[
        {
          type: 'LABEL_DETECTION',
          maxResults: 100
        }
      ]
    }
  ]
};

faulkner.jpg
Response Body:
{
  "responses": [{}]
}

I have even tried using the cloud API console and copy the request fields, and that too does not work
const apiKey = 'myAPIKey';
const fields = `fields=responses(labelAnnotations)&`;
const visionAPI = `https://vision.googleapis.com/v1/images:annotate?${fields}key=${apiKey}`;

Any help would be greatly appreciated.

A: Are you doing OAuth2 with the appropriate token. For using Vision API with gCS Images, we cannot just use the API Key.

A: Have you tried making the request using an oauth2 access key? There's a quick-and-dirty way to test this on the command line if you have the gcloud tool:

*

*Create and download a service account json key

*Set gcloud to use that service account:
gcloud auth activate-service-account --key-file <service-account-file.json>

*Get an access token using gcloud auth print-access-token and perform a curl request with it:
curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "content-type: application/json" \
    --data-binary '{"requests": [{"image": {"source": {"gcs_image_uri": "gs://your-bucket/your-object.jpg"}}, "features":  [{"type": "LABEL_DETECTION", "maxResults": 100}]}]}' \
    "https://vision.googleapis.com/v1/images:annotate?alt=json"

For production use, though, you'll want to explicitly use the oauth2 flow to get your access tokens, since they're short-lived and require refreshing.

A: I was having this exact issue, this is what worked for me...

*

*You do not need OAuth, just an API key.

This is what I was doing wrong...
In my HTTP call I needed to wrap my request in a new object literal as in
{data: requestBody }

To clarify,
// My old call
HTTP.call("POST", "https://vision.googleapis.com/v1/images:annotate?key=myAPIKey", requestBody, myCallback);

// To my new call
HTTP.call("POST", "https://vision.googleapis.com/v1/images:annotate?key=myAPIKey", {data: requestBody}, myCallback);

// reqeustBody example

{
  "requests":
    [
      {
        "features":
          [
            {
              "type": "LABEL_DETECTION"
            }
          ],
        "image":
          {
            "source":
              {
                "gcsImageUri": "gs://myBucketNameHere/myDemoImageNameHere.jpg"
              }
          }
      }
    ]
  }

NOTE: A few things that need to be done.

*

*Image is in your Google Cloud Platform Storage Bucket.

*The image name is exact in the call as it is in storage.

*The image must have something to detect i.e. if using FACE_DETECTION the image must have a human face.

*The image in Google Cloud Platform Storage MUST be checked to Share publicly.

I am using the very same call above with my image named demo-image.jpg and everything works now that I wrapped the requestBody.


text:
Q: Replacing the explorer pane in windows? When a user puts in a CD and autoruns, I want to "browse" the CD but I want to do some extra processing of the disk contents.  If I wanted to replace the ListView in windows explorer with one of my own, how would I start?  What terms should I search for to find out how to do this.  I want to get the treeview part that explorer provides,  and all the shell interaction, I just want to hide the extra extension on the end of the file names (.pgp) and show the icons for the files as if they weren't encrypted.

A: I think your best option is use a Shell Namespace extension like the GMail Drive shell

see this links

*

*An almost complete Namespace Extension Sample

*Create Namespace Extensions for Windows Explorer with the .NET Framework

*Tips in Writing Namespace Extensions (I) - Implements Subfolder

*Tips in Writing Namespace Extensions (II) - Implement Create and Delete Object Operations
Bye.


text:
Q: Create a text file in %temp% and write content in it using vbs Basically, I want to create a new file and write in it in a directory on the PC, pointed to by the %TEMP% variable. However, the revised code below does not work:
Dim oFile
Dim shell
Set oShell = CreateObject("WScript.Shell")
user = oShell.ExpandEnvironmentStrings("%Temp%")
Set oFile = CreateObject("Wscript.Shell")
Set oFile = oFile.CreateTextFile("%Temp%\d.txt")
oFile.WriteLine "here is my contant"
oFile.Close

Error Message:

run time error
  line no: 3
  object required

Old Code
Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
FileName = "%TEMP%\myfile.txt"
Set tf = fso.CreateTextFile(FileName, True)

If I use the file name "C:\myfile.txt" it works fine.
Error Message:

Path not found

A:
In VBA, you can just use Environ("TEMP") to expand the Environment variable - if this does not work in VBScript, you may need to bind the WScript.Shell object and use the ExpandEnvironmentStrings property instead, like so:
Set oShell = CreateObject("WScript.Shell")
FileName = oShell.ExpandEnvironmentStrings("%TEMP%") & "\myfile.txt"
Set oShell = Nothing

Following from comments below
Here is a "fully fixed" code:
'Declare variables/objects first
Dim fso AS Object, oFile AS Object
Dim oShell AS Object, FileName AS String

'This bit turns "%TEMP%" into a real file path
Set oShell = CreateObject("WScript.Shell")
FileName = oShell.ExpandEnvironmentStrings("%Temp%\d.txt")
Set oShell = Nothing 'Tidy up the Objects we no longer need

'This bit creates the file
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(FileName)
oFile.WriteLine "here is my content"
oFile.Close
Set oFile = Nothing 'Tidy up the Objects we no longer need
Set fso = Nothing 'Tidy up the Objects we no longer need

A: you can use Environ("temp") to write to C:\Users\[username]\AppData\Local\Temp


text:
Q: How to evenly space children in a RelativePanel in Universal app I have a UserControl that contains a RelativePanel. I'm using a RelativePanel because I need this UserControl to be displayed at the top of the screen when I'm on a narrow state (phone app) and displayed along the left edge of the screen when it is in a wider screen.
The children are buttons with images which I use as a toolbar for navigation. The problem is that I cannot find a way to evenly space the buttons in the RelativePanel. The buttons appear stuck to each other left-aligned.
I tried using a Grid, and it worked, but I was forced to create two user controls, one for the top menu and one for the left edge menu, because the VisualStateManager does not allow me to change ColumnDefinitions to RowDefinitions.
The advantage of a RelativePanel is that I can do it with one user control, avoiding code duplication.
Here is the XAML:
<UserControl
x:Class="Innobec.Mobile.Apps.CityScope.UserControls.TopHorizontalToolBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Innobec.Mobile.Apps.CityScope.UserControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="80"
d:DesignWidth="400">

<RelativePanel x:Name="MainPanel">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="WindowStates">
            <VisualState x:Name="WideState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="660"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="newsButton.(RelativePanel.Below)" Value="pinButton"/>
                    <Setter Target="weatherButton.(RelativePanel.Below)" Value="newsButton"/>
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="NarrowState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="1"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="newsButton.(RelativePanel.RightOf)" Value="pinButton"/>
                    <Setter Target="weatherButton.(RelativePanel.RightOf)" Value="newsButton"/>
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
        <Button x:Name="pinButton" Background="Red" VerticalAlignment="Center" Click="pinButton_Click" Style="{StaticResource TopHorizontalToolBarButtonStyle}">
            <Image Source="/Assets/Top-Pin-Icon-60px.png" Stretch="None"/>
        </Button>
        <Button x:Name="newsButton" Background="Red" VerticalAlignment="Center" Click="newsButton_Click" Style="{StaticResource TopHorizontalToolBarButtonStyle}">
            <Image Source="/Assets/Top-News-Icon-60px.png" Stretch="None"/>
        </Button>
        <Button x:Name="weatherButton" Background="Red" VerticalAlignment="Center" Click="weatherButton_Click" Style="{StaticResource TopHorizontalToolBarButtonStyle}">
            <Image Source="/Assets/Top-Weather-Icon-60px.png" Stretch="None"/>
        </Button>
</RelativePanel>

Is there a control that I can place inside the RelativePanel that will evenly space the children? Please note that I'm new to XAML so it may be possible, it's just that I haven't figured it out yet.

A: One option is to dynamically change the sizes of the RelativePanel's children in the code behind using the RelativePanel's SizeChanged event. You could even keep it fairly dynamic by doing something like this:
  private void RelativePanel_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        RelativePanel panel = sender as RelativePanel;

        if(panel != null)
        {
            double childCount = panel.Children.Count;

            for (int i = 0; i < panel.Children.Count; i++)
            {
                FrameworkElement child = panel.Children[i] as FrameworkElement;

                if (child != null)
                {
                    if(spacedHorizontally)
                    {
                        child.Height = panel.ActualHeight;
                        child.Width = panel.ActualWidth / childCount;
                    }
                    else
                    {
                        child.Height = panel.ActualHeight / childCount;
                        child.Width = panel.ActualWidth;
                    }
                }
            }
        }
    }

This would evenly space out the children either Horizontally or Vertically (using the spacedHorizontally bool in my example) and stretch the children in the other direction.


text:
Q: Deployment of the dbxdrivers.ini and dbxconnections.ini files in xe5 We have a D7 vcl app that uses dbexpress to connect to oracle (via the devart oracle driver for dbexpress). We converted this app to XE5. In D7 the dbxdrivers.ini and dbxconnections.ini files have been deployed in the same directory as the exe and the application read the them from this location without any intervention (i.e. dbexpress found automatically all the settings)
In XE5 deploying the dbxconnections.ini file doesn't work in the same way it worked in D7, in other words the application doesn't seem to use/find the two ini files when they are deployed in the same folder as the exe.
Based on my observations and reading the delphi code, I need to call the TSQLConnection.LoadParamsFromIni method and pass the dbxconnections.ini file name, otherwise the TSQLConnection object ends up reading the location from the registry: HKCU\Software\Embarcadero\BDS\12.0\DBExpress\Connection Registry File. dbexpress will read the dbxdrivers.ini from the exe directory, if it is there.
Any thoughts on this? Could you please confirm that this is how it's done?
Thanks
Update: After more testing here is the behavior that I am seeing:

*

*If the HKEY_CURRENT_USER\Software\Embarcadero\BDS\12.0\DBExpress key is not present at all, and the dbx***.ini files are deployed only in the exe folder the XE5 app uses them without having to call LoadParamsFromIni.

*If the HKEY_CURRENT_USER\Software\Embarcadero\BDS\12.0\DBExpress key is present with all the settings (Connection Registry File etc.) pointing to the ini files in the public folder, and the dbx***.ini files are deployed only in the exe folder, then the app doesn't read the ini files from the application folder and I need to explicitly call LoadParamsFromIni.

I think it is more reliable to call the LoadParamsFromIni than relying on the default behaviour of dbexpress.


text:
Q: Room TypeConverter for Custom Object in Java This is my custom object:
public class Proceeding {

    @SerializedName("code")
    private String code;

    @SerializedName("hasAccount")
    private boolean hasAccount;

    @SerializedName("description")
    private String description;

    @SerializedName("pricePattern")
    private String pricePattern;

    // Getters & Setters ...
}

I need a TypeConverter class for Room and this is my TypeConverter class:
public class ProceedingTypeConverter {

    @TypeConverter
    public static Proceeding fromString(String value) {
        Type type = new TypeToken<String>() {
        }.getType();
        return new Gson().fromJson(value, type);
    }

    @TypeConverter
    public static String fromObject(Proceeding obj) {
        Gson gson = new Gson();
        return gson.toJson(obj);
    }
}

but I'm getting error in return new Gson().fromJson(value, type); line.
Error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected a string but was BEGIN_OBJECT at line 1 column 2 path $

How can I solve the problem?
UPDATE:
I changed my TypeConverter class to:
public class ProceedingTypeConverter {

    @TypeConverter
    public Proceeding fromString(String value) {
        return new Gson().fromJson(value, Proceeding.class);
    }

    @TypeConverter
    public static String fromObject(Proceeding obj) {
        Gson gson = new Gson();
        return gson.toJson(obj);
    }
}

but I'm still getting error when I Call API:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected a string but was BEGIN_OBJECT at line 1 column 3125 path $[0].store


text:
Q: WMIC call in BATCH FOR command Returns unexplained Error I am trying to create a Volume Shadow copy from a BATCH file but have encountered a issue I am unable to explain.
When running the below command:
FOR /F "tokens=3" %%A IN ('"WMIC shadowcopy call create ClientAccessible,"C:\""^| FIND /I "ShadowID"') DO SET ID=%%A

I receive the below error

Invalid format. Hint <paramlist> = <param> [, <paramlist>].

but if I replace FIND with FINDSTR and remove the quotes from around the word I am searching for it seems to work correctly.
FOR /F "tokens=3" %%A IN ('"WMIC shadowcopy call create ClientAccessible,"C:\""^| FINDSTR /I ShadowID') DO SET ID=%%A

Can anyone explain to me why the first command will not work or what I am overlooking to make the first command work?
Yes, I know there are many other, including better, ways to achieve what I am wanting to do but for now I am just trying to better understand what I am missing here.
Thanks greatly

A: There are two problems in your code:

*

*You stumbled upon a strange behaviour of FOR /F: it does not only remove the single quotes (apostrophies, '') around the command to parse, it also removes enclosing quotation marks if the first and last character of the remaining string are " both1, so the command line that is actually tried to be executed is WMIC shadowcopy call create ClientAccessible,"C:\""| FIND /I "ShadowID, which is invalid of course.

*The WMIC command line is enclosed in quotation marks, so even if the above issue was not there, your code would fail, because the command interpreter tries to find a command or program named "WMIC shadowcopy call create ClientAccessible,", which does not exist of course.

So the corrected command line is:
FOR /F "tokens=3" %%A IN ('WMIC shadowcopy call create ClientAccessible^,"C:\" ^| FIND /I "ShadowID"') DO SET "ID=%%A"

Note that you need to escape the , herein (similar to the pipe).

1)  You can affirm that by trying the command line FOR /F "tokens=3" %%A IN ('"WMIC" shadowcopy call create ClientAccessible^,"C:\" ^| FIND /I "ShadowID"') DO SET "ID=%%A", which fails, and FOR /F "tokens=3" %%A IN ('^""WMIC" shadowcopy call create ClientAccessible^,"C:\" ^| FIND /I "ShadowID"^"') DO SET "ID=%%A", which works because there are additional "" put around (they are escaped like ^" so that the command line does not need to be altered in terms of escaping; you could also state the " literally, but then you needed to unescape the , and the |).

In addition, I recommend to nest another FOR /F loop inside yours, because WMIC returns Unicode text, which could leave artefacts (orphaned carriage-return characters) when being parsed by FOR /F (as it expects ANSI text); an additional parsing phase eliminates such noise:
FOR /F "tokens=3" %%A IN ('WMIC shadowcopy call create ClientAccessible^,"C:\" ^| FIND /I "ShadowID"') DO FOR /F "delims=" %%B in ("%%A") DO SET "ID=%%B"

This method is credited to dbenham -- see his answer to Why is the FOR /f loop in this batch script evaluating a blank line? and also his external article WMIC and FOR /F : A fix for the trailing <CR> problem.

A: This is happening because the output of the WMCI command is in unicode. See this post Editing WMIC output format


text:
Q: Grow Heap problems in Android I got problems about grow heap which I have 2 questions to ask.
First, How can I suppose to check current grow heap in my devices?
Second, How can I decrease my grow heap size to prevent out of memory error?

A: Do you mean you want to check the total size of the heap your application can use? Or how much free memory is left in the heap?
To see the total size of the heap you could call
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));

This will tell you how much memory in bytes your app is allowed to use (source)
To find out how much is left you could do the following
When are you getting out of memory errors? A starting point could be to override onLowMemory() method...


text:
Q: Properly setting up vscode for C? The recommended Microsoft C/C++ extension for VSCode works great for C++ but fails at some places with C giving false errors. Here's one I have found:

void f(int a,int b, int arr[][b]);

This is valid C code and yet it says there's an error.
So how do I properly set up my intellisense to account for such nuances?


text:
Q: What can be said about eigenvalues from the sum of elements in a row? Here I'm struggling with my math. Now I have this question which seems unmanageable. Let $A \in M_n(\mathbb{R})$, with $n\ge2$. Assume that the sum of any row is $1$. What can be said about eigenvalues and eigenvectors of $A$? The alternatives are irrelevant but say something like: $A$ can never have real eigenvalues or $1$ and $0$ are always eigenvalues of $A$. I can't find the relation between the sum of elements per row and eigenvalues/eigenvectors! Can someone please, give me a direction?

A: Finally, I think I completely understand the question. Here is a proof that if $k \in \mathbf{R}, k \neq 0$ is the sum of the elements of each row in a square matrix A, then $k$ is an eigenvalue of A.
Let $v = (1,1,1,...,1)$. Calculating $Av$ will result in $(k,k,k,...,k) = k(1,1,1,...,1) = kv$. By the definition, $k$ is an eigenvalue with associated eigenvector $v$.
Now, for the particular question, $k=1$ and the only information we can get is that $1$ is an eigenvalue associated with eigenvector $(1,1,1,...1)$.
Thank you all for the help.

A: With just what you said, you can say that there is an eigenvalue of $1$, by writing down the corresponding right eigenvector (just a vector of $1$s). For the other eigenvalues, the best you can do is Gerschgorin's theorem, which only gives an estimate. You can say a bit more if you assume the elements are nonnegative, but you didn't say that here.


text:
Q: PHP-FPM Active Processes are high(zabbix) how to edit this Expression? In the past few days, my Zabbix agent on a specific web server is triggering alerts every few minutes.
I have this Expression
{Template App PHP-FPM:service.phpfpm.status[activeProcesses].last()}>20

This is the basic template for PHP-FPM.
how can I edit this so it will be:
if the active process is high for 5 minutes then send the alert?

A: you can fire the alert when the maximum value, within 5 minutes, is more than 20
{Template App PHP-FPM:service.phpfpm.status[activeProcesses].max(5m)}>20


text:
Q: Finding a ¬ character in linux and Windows I am currently working on a c# project that needs to run on both Windows and Linux. The program has to search for a pointer in the file which is the '¬' character. This works fine on Windows but when I try and run the program on linux the ¬ character is replaced by � so the program is failing.
How can I get this to work.
Thanks for any help you can provide

A: Use the character hex code: '\x00AC'

A: I i found out that @alfonso was right using the characters hex code but although it still displayed the funny character, I found that I need to change the encoding for the stream to UTF7.
Thanks for your help


text:
Q: VOLUME_EXTERNAL require API level 29 In Android documentation they said

On API <= 28, use VOLUME_EXTERNAL

but this also requires API level 29, and it doesn't save media files into MediaStore.
 MediaStore.Audio.Media.IS_PENDING
 MediaStore.Video.Media.RELATIVE_PATH
 MediaStore.Video.Media.DATE_TAKEN

also requires API 29, So I feel the doc is not clear, or is there anything I missed?. And how do I save the media files in below Android 10 as well.

A: Even though MediaStore.VOLUME_EXTERNAL was added in API 29, but you are safe to use it as long as you set targetSdkVersion and compileSdkVersion to 29+. I have tested it on API 16 and this constant did not crash my app.
However, if you think this warning is pretty annoying, you can use MediaStore.<MediaType>.EXTERNAL_CONTENT_URI instead. It will return the same value as MediaStore.<MediaType>.getContentUri(MediaStore.VOLUME_EXTERNAL).
For instance, MediaStore.Downloads.EXTERNAL_CONTENT_URI will equal to MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL), i.e. content://media/external/downloads.
Additionally, you can ignore this warning via @SuppressLint("InlinedApi").


text:
Q: GAE - download sample of entities My production app has 23GB of entities in it. I want to download only a handful of these to my dev app to debug.
I have read through https://developers.google.com/appengine/docs/python/tools/uploadingdata. It explains how to download and upload all data, but not just a sample of the data. What I am looking for is a 'number of entity instances to download' config option, but I cannot see it.

A: I believe the bulk download does many small batches of entities; you could just stop it part-way through the process.

A: If your requirement is only a handful of entities and you know which ones or have the query for it, you might write a quick web handler to query the data, and stream the bytes back to function as a simple file download.
In the medium to long term, this might end up as a useful utility to invoke whenever you need the data for debugging.


text:
Q: android phonegap audio player music get stop after 10-15 use i have created an phonegap app in android in which audio player is call on every click event.
after 10-15 use(audio player event called 10-15 times) audio player get stop entirely, app become soundless.
same app run successfully on iphone without such weird issue
i am calling playAudio('music path') on every click event
function playAudio(src) {
        // Create Media object from src
        my_media = new Media(src, onSuccess, onError);

        // Play audio
        my_media.play();

        // Update my_media position every second
        if (mediaTimer == null) {
            mediaTimer = setInterval(function() {
                // get my_media position
                my_media.getCurrentPosition(
                    // success callback
                    function(position) {
                        if (position > -1) {
                            setAudioPosition((position/1000) + " sec");
                        }
                    },
                    // error callback
                    function(e) {
                        console.log("Error getting pos=" + e);
                        setAudioPosition("Error: " + e);
                    }
                );
            }, 1000);
        }
    }

can any one help me.
Thanks in advance.

A: not working in lower android version 2.2 working fine on higher version as this stuff depend on java script engine supported by various devices


text:
Q: Packaging requirejs optimized files in war In a large web application, I'm using requirejs amd modules so that the scripts themselves are modular and maintainable. I have the following directory structure
web
 |-src
    |-main
       |-java
       |-resources
       |-webapp
          |-static
             |-scripts
             |-styles
             |-images
          |-static-built    //output from r.js. not checked into git
          |-WEB-INF

During build js and css are optimized using r.js into static-built folder. Gradle is the build tool.
Now the problem: The jsps refer to the scripts in static/scripts folder and this is how i want when working locally. However when building war, I want the static files to be served from static-built folder. The important thing is the source jsp should not have to change to serve the optimized files from static-built folder.
Two options that I have are: a) the gradle build while making war should include static-built instead of static. b)include static-built in addition to static and using tuckey urlrewrite pick the resouce from static-built rather than static.
What best practices are the community following in similar scenarios?

A: We've setup the server to have a runtime profile (dev, qa, prod, etc) read from a system property which determines some settings based on it. When running in production profile we serve the optimized files from the WAR. In development we serve the non-minified and non-concatenated files directly from the filesystem outside the application context.
Files are structured according to the official multipage example.
Configuring serving files depends on your chosen backend solution. Here's an example for spring.
Alternatively, r.js can generate source maps and those will help with development as well.

A: Not sure if this question is outdated already, but I had a kind of similar problem.
I had similar project structure, but with the only difference - I've split the project into 2 modules:

*

*one of them (let's call it service) was java-module for back-end

*the second one contained only js and other stuff related to front-end (let's call it ui).

Then in Gradle build 'assemble' task of the service depends on 'assemble' task of ui AND another custom task called 'pre-assemble'. This 'pre-assemble' task was copying the optimized js files to place where I wanted them to be.
So, basically, I've just added another task that was responsible for placing all the optimized js files in the proper place.


text:
Q: can i able to ip forward and keep original client ip from server A to B? im  web developer and i have not good knowledge about devOps and server config,
i use this code for forwarding data from server a to b from client my mean is:
client---------->serverA--------->serverB
now how can i keep original client ip when i use ip forward to server B?
is there any way?
i used following commands before but i don't know it work for my new concept or not?
sysctl net.ipv4.ip_forward=1
iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination serverA_IP
iptables -t nat -A PREROUTING -j DNAT --to-destination serverB_IP
iptables -t nat -A POSTROUTING -j MASQUERADE

A: If the 'client' is connecting directly to 'Server A' then you shouldn't need to have any NAT rules for SSH as you are connecting directly to it.
However, if what you want is that the Client connects to Server A's IP Address over SSH but ends up at Server B using port 22 then what you want is:
-A PREROUTING -s x.x.x.x/32 -d x.x.x.x/32 -p tcp -m tcp --dport 22 -j DNAT --to-destination x.x.x.x:22

Replace the first 'x.x.x.x/32' with the IP address that the client is expected to connect from (this one can be removed fully if not know or wanted)
Replace the second 'x.x.x.x/32' with the IP Address you expect the client to access (the IP address of Server A).
Finally change the --to-destination x.x.x.x:22 to the IP address of Server B.
Now if you want to us this same process for different servers this can be done also by changing the --dport to 2201 (for example) and giving this port to client 1 and having --dport 2202 for client 2 but going to different servers.
Hope that helps.
~Regards,
Scott

A: When you are performing DNAT / SNAT like in your example, you cannot preserve the client IP address, since that address is changed in the NAT on ServerA.
Depending on the application protocol, you can get attach client IP to request, for example in HTTP request headers. This requires setting up a reverse proxy on ServerA.
However, there is no such mechanism for SSH for example.


text:
Q: Draw portion of MTLBuffer? I am rendering point fragments from a buffer with this call:
renderEncoder.drawPrimitives(type: .point,
                             vertexStart: 0,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles)

emitter.currentParticles is the total number of particles in the buffer. Is it possible to somehow draw only a portion of the buffer?
I have tried this, but it draws the first half of the buffer:
renderEncoder.drawPrimitives(type: .point,
                             vertexStart: emitter.currentParticles / 2,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles / 2)

In fact, it seems that vertexStart has no effect. I can seemingly set it to any value, and it still starts at 0.
Edit:
Pipeline configuration:
private func buildParticlePipelineStates() {
    do {
        guard let library = Renderer.device.makeDefaultLibrary(),
        let function = library.makeFunction(name: "compute") else { return }

        // particle update pipeline state
        particlesPipelineState = try Renderer.device.makeComputePipelineState(function: function)

        // render pipeline state
        let vertexFunction = library.makeFunction(name: "vertex_particle")
        let fragmentFunction = library.makeFunction(name: "fragment_particle")
        let descriptor = MTLRenderPipelineDescriptor()
        descriptor.vertexFunction = vertexFunction
        descriptor.fragmentFunction = fragmentFunction

        descriptor.colorAttachments[0].pixelFormat = renderPixelFormat
        descriptor.colorAttachments[0].isBlendingEnabled = true
        descriptor.colorAttachments[0].rgbBlendOperation = .add
        descriptor.colorAttachments[0].alphaBlendOperation = .add
        descriptor.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].sourceAlphaBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
        descriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

        renderPipelineState = try
        Renderer.device.makeRenderPipelineState(descriptor: descriptor)
        renderPipelineState = try Renderer.device.makeRenderPipelineState(descriptor: descriptor)
    } catch let error {
        print(error.localizedDescription)
    }
}

Vertex shader:
struct VertexOut {
    float4 position   [[ position ]];
    float  point_size [[ point_size ]];
    float4 color;
};

vertex VertexOut vertex_particle(constant float2 &size [[buffer(0)]],
                             device Particle *particles [[buffer(1)]],
                             constant float2 &emitterPosition [[ buffer(2) ]],
                             uint instance [[instance_id]])
{
    VertexOut out;

    float2 position = particles[instance].position + emitterPosition;
    out.position.xy = position.xy / size * 2.0 - 1.0;
    out.position.z = 0;
    out.position.w = 1;
    out.point_size = particles[instance].size * particles[instance].scale;
    out.color = particles[instance].color;
    return out;
}

fragment float4 fragment_particle(VertexOut in [[ stage_in ]],
                              texture2d<float> particleTexture [[ texture(0) ]],
                              float2 point [[ point_coord ]]) {
    constexpr sampler default_sampler;

    float4 color = particleTexture.sample(default_sampler, point);

    if ((color.a < 0.01) || (in.color.a < 0.01)) {
        discard_fragment();
    }
    color = float4(in.color.xyz, 0.2 * color.a * in.color.a);
    return color;
}

A: You're not using a vertex descriptor nor a [[stage_in]] parameter for your vertex shader. So, Metal is not fetching/gathering vertex data for you. You're just indexing into a buffer that's laid out with your vertex data already in the format you want. That's fine. See my answer here for more info about vertex descriptor.
Given that, though, the vertexStart parameter of the draw call only affects the value of a parameter to your vertex function with the [[vertex_id]] attribute. Your vertex function doesn't have such a parameter, let alone use it. Instead it uses an [[instance_id]] parameter to index into the vertex data buffer. You can read another of my answers here for a quick primer on draw calls and how they result in calls to your vertex shader function.
There are a couple of ways you could change things to draw only half of the points. You could change the draw call you use to:
renderEncoder.drawPrimitives(type: .point,
                             vertexStart: 0,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles / 2,
                             baseInstance: emitter.currentParticles / 2)

This would not require any changes to the vertex shader. It just changes the range of values fed to the instance parameter. However, since it doesn't seem like this is really a case of instancing, I recommend that you change the shader and your draw call. For the shader, rename the instance parameter to vertex or vid and change its attribute from [[instance_id]] to [[vertex_id]]. Then, change the draw call to:
renderEncoder.drawPrimitives(type: .point,
                             vertexStart: emitter.currentParticles / 2,
                             vertexCount: emitter.currentParticles / 2)

In truth, they basically behave the same way in this case, but the latter better represents what you're doing (and the draw call is simpler, which is nice).


text:
Q: Check if value of keys is a string with Handlebars I have an object like this:
{
  id: 1,
  type1: 'Adjective',
  type2: 'Noun',
  type3: 'Noun',
  type4: 'Noun',
  type5: 'Plural Noun',
  type6: 'Person',
  type7: 'Place',
  type8: 'Job',
  type9: 'Adjective',
  type10: 'Adjective',
  type11: 'Famous Person',
  type12: 'Noun',
  type13: 'Noun',
  type14: '',
  createdAt: 2019-10-11T06:49:38.000Z,
  updatedAt: 2019-10-11T06:49:38.000Z
}

Is there any way that I can only get the keys where the values are a string using handlebars helpers?

A: You can write handlebars configuration helper which can check this
module.exports.hbs = exphbs.create({
    defaultLayout: 'layout',
    helpers: {
        //You can Name this anything
        checkIfValuesOfJsonAreStrings: function(jsonList, context) {
        for (var key in obj) {
         if(typeOf obj[key] == "String"){

        }else{
           return context.inverse(this); // This False
        }
      }
      return context.fn(this)
    }
})

Now When writing your .hbs code you can include
{{# checkIfValuesOfJsonAreStrings}}

Yah all the values in JSON are string

{{/checkIfValuesOfJsonAreStrings}}


text:
Q: Proving limits by definition (2 variables) I need to prove with the formal limit definition ( epsilon and delta)

*

*$\lim_{(x,y)\to(-1,8)} xy = -8$ and

*$\lim_{(x,y)\to(2,3)} y\sin(xy-6)=0$

I've been trying to solve them all day, but can't figure out what to do.

A: Note that these are continuous function, so in order to compute them you can just substitute the values.


text:
Q: Retrieve data from SQLiteDatabase and display it in a new activity I can populate my ListView of items from my SQLiteDatabase in lunch.java. now I want to click the one item(total 8 items inside the ListView) and go to a new activity called Display.java and display all the nutrition facts of it.
AFTER EDITING
lunch.java:
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
    switch(pos)

    {
    case 0 :
        String mealName = (String) parent.getItemAtPosition(pos);
        Cursor cursor = dbopener.getBreakfastDetails(mealName);
        cursor.moveToNext();
        id = cursor.getLong(cursor.getColumnIndex(mealName));
        String message = cursor.getString(1)  + "\n" + cursor.getInt(2);
        Intent event1 = new Intent("com.edu.tp.iit.mns.Display");
        event1.putExtra("name", id);
        startActivity(event1);
        break;

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

        TextView tv = (TextView) findViewById(R.id.tvfoodName);

        Intent intent = getIntent();
        long id = intent.getLongExtra("name", -1);
        if(id == -1){
            return;
        }

        tv.setText(-1);

}

A: In the onItemcClick you already have the id of the element that was clicked, the id parameter. Use that to identify the item in your next activity:
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
    Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
    newActivity.putExtra("the_key", id);
    startActivity(newActivity);
}

Then in your Display activity get that long value and get the data from the database corresponding to that id:
Intent newActivity = getIntent();
long id = newActivity.getLongExtras("the_key", -1);
if (id == -1) {
    //something has gone wrong or the activity is not started by the launch activity
    return
}
//then query the database and get the data corresponding to the item with the id above

The above code would work for the case of a Cursor based adapter. But you probably use a list based adapter(because of the getItemAtPosition(pos) returning a String and not a Cursor). In this case I would make the getLunchDetails method to return the unique id of that meal name and pass that to the Details activity:
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
    String mealName = (String)parent.getItemAtPosition(pos);
    Cursor cursor = dbopener.getLunchDetails(mealName);
    cursor.moveToNext();
    long id = cursor.getLong(cursor.getColumnIndex("the name of the id column(probably _id"));
    Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
    newActivity.putExtra("the_key", id);
    startActivity(newActivity);
}


text:
Q: Enviroment variable in htaccess rewrite rule is not set When using the following entries in my .htaccess file
RewriteEngine On
SetEnv rewritten 0
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)(/|$) /#$1 [L,NE,R=302,E=rewritten:1]

Which rewrites <url>/test/ to <url>/#test.
The goal is to keep the "test" part in an environment variable, so I can use php to change the Facebook metatags and also use the anchor to scroll to a section on my one-page-site. For the above example, the rewritten variable is always 0 and if I remove the SetEnv line, the variable will not be set at all.
I have read that the variable might not be retained after a redirect which the 302 will do. Is there any other way to do this? Other solutions are welcome - my overall goal is to link to a specific part of my application and set the metatags according to this section.
There are multiple questions here on SO where people try to rewrite an url with the anchor part, to an url without it - this is not my question, since it can't be done.
Thanks.
Edit
The above is not possible. Added the following to .htaccess, which redirect <url>/test to <url>/?test#test. PHP can then check if the test param is set and modify meta-tags accordingly.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)(/|$) /?$1#$1 [L,NE,R=302]

A: The above is not possible. Added the following to .htaccess, which redirect <url>/test to <url>/?test#test. PHP can then check if the test param is set and modify meta-tags accordingly.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)(/|$) /?$1#$1 [L,NE,R=302]