text:
Q: Log transformed dependent variable with interaction terms I have three questions regarding a regression equation where the dependent is log transformed, a dummy $D$ is interacted with yer dummies, and other independent variables are present on the right hand side: $\newcommand{\year}{{\rm year}}$
$${\rm ln}(Y) = \alpha + \beta_{0}.D + \beta_{1}.\year1990 + \beta_{2}.\year1995 + \beta_{3}.\year2000 + \beta_{4}.D.\year1990 + \beta_{5}.D.\year1995 + \beta_{6}.D.\year2000 + \beta_{7}.X + {\rm error}$$

*

*How can I get the average effect of $D$ from this regression?

*Am I right to think that the coefficient of dummy + coefficient of dummy year interaction (say for 2000) gives the percent difference relative to the same coefficients for the year dummy omitted omitted due to collinearity?

*What would be the most meaningful interpretation of this regression?

A: 1) The average impact of D on Y is \begin{equation} \beta_{0} +mean(0,\beta_{4},\beta_{5},\beta_{6})\end{equation}
You might want to weight the mean by the frequency with which the years appear in your dataset
2) $ \beta_{0}$ is the impact of D on $Ln(Y)$ in the omitted year. Therefore, $ \beta_{6}$ On it's own is the relative percentage impact D being 1 has on Y, when compared to the omitted year. I.e. if $ \beta_{6}$ =0.1. Then D being equal to 1 had 10 (exp(0.1)*100) percentage point greater impact on Y in 2000.
3)It depends on what your coefficients are and what D and Y stand for!

A: The answer depends on what you mean by the average impact of $D$ on $Y$.  Each of the words "average" and "impact" are ambiguous.
"Average" has to be relative to some population.  The average height in the US is different from the average height in the NBA.  "Impact" can be in units, how many dollars/gallons/whatever does $Y$ increase when $D$ goes from 0 to 1; it can be in percents, how many percents does $Y$ increase when $D$ goes from 0 to 1; or it can be in some other sense (though units and percents are the most common).
Suppose you are interested in the average percent impact of $D$ in your sample.  You calculate that as follows.  The effect for each observation in the population is:
\begin{align}
\text{Effect}_i &=  \beta_0 + \beta_4 yr_{1990,i} + \beta_5 yr_{1995,i} + \beta_6 yr_{2000,i}
\end{align}
And the average percent effect in this population (i.e. the population consisting of your sample) is just the mean of the above:
\begin{align}
\overline{\text{Effect}} &=  \beta_0 + \beta_4 \overline{yr_{1990}} + \beta_5 \overline{yr_{1995}} + \beta_6 \overline{yr_{2000}}
\end{align}
This is subject to the usual caveat that coefficients on dummies (and non-dummies, for that matter) in log regressions can only be interpreted as percent effects as long as the coefficients are less than about 0.2 in absolute value.  Otherwise, you have to do the calculation properly.
On the other hand, if you want the average effect of $D$ on $Y$ in units, you do a different calculation.  The effect of $D$ on $Y$ for a single observation is:
\begin{align}
\frac{\partial Y_i}{\partial D_i} &= \left( \beta_0 + \beta_4 yr_{1990,i} + \beta_5 yr_{1995,i} + \beta_6 yr_{2000,i} \right)exp(\widehat{lnY_i}) \left( \frac{1}{N}\sum exp(e_i) \right)
\end{align}
If this formula is unfamiliar to you, you might look at my answer here, for example.  Or, you might search the site for the re-transformation problem or Duan's smearing estimator.
Then, if, again, you are interested in the average effect over your sample, you just take sample means:
\begin{align}
\overline{\frac{\partial Y}{\partial D}} &= \left[ \frac{1}{N}\sum \left( \beta_0 + \beta_4 yr_{1990,i} + \beta_5 yr_{1995,i} + \beta_6 yr_{2000,i} \right)exp(\widehat{lnY_i}) \right] \left[ \frac{1}{N}\sum exp(e_i) \right]
\end{align}
Again, there is a caveat.  Since we are using a derivative (i.e. approximation) here, it's important that the individual-level percent effects, $\left( \beta_0 + \beta_4 yr_{1990,i} + \beta_5 yr_{1995,i} + \beta_6 yr_{2000,i} \right)$, not be bigger than about 0.2 in absolute value.  If they are, then you have to do something else.


text:
Q: Can not find module webpage using PhantomJS I am using PhantomJS to search for words on a web page, I tried to set it up like:
const phantomjs = require("phantomjs-prebuilt");

if (cmd === `${prefix}check`) {
    let word = (args[0]);
    var page = require('webpage').create();
    page.open('https://discordapp.com/channels/000/000', function(err, data) {
        if (err) throw err;
        if (data.indexOf(word) >= 0) {
            message.reply(word+ ' Found!');
        } else {
            message.reply(word+ ' Not found.');
        }
    });
}

However I'm getting the following error:

(node:3520) UnhandledPromiseRejectionWarning: Error: Cannot find
  module 'webpage'

What is causing this?
Edit
I just saw that it does not work with Node JS, is it possible to call the seperate JS file and pass the (args[0]);?

A: If you want to use PhantomJS from node.js, you can, there are several packages for that, one of them is phantom. It supports Promises and async/await functions:
const phantom = require('phantom');

(async function() {
  const instance = await phantom.create();
  const page = await instance.createPage();
  await page.on('onResourceRequested', function(requestData) {
    console.info('Requesting', requestData.url);
  });

  const status = await page.open('https://stackoverflow.com/');
  const content = await page.property('content');
  console.log(content);

  await instance.exit();
})();

You can of course just launch PhantomJS from command-line and pass necessary arguments to it:
phantomjs script.js https://stackoverflow.com

and then recieve them in the script with system.args
var system = require('system');
var args = system.args;

if (args.length === 1) {
  console.log('Try to pass some arguments when invoking this script!');
} else {
  args.forEach(function(arg, i) {
    console.log(i + ': ' + arg);
  });
}

Please note that you're using page.open wrong, there's no data var in callback function signature. If you want to get all of a page's contents, refer to page.content variable:
page.open('http://phantomjs.org', function (status) {
  var content = page.content;
  console.log('Content: ' + content);
  phantom.exit();
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding index on joined tables SQL Server Is it possible to add an index to select statements with joined tables? If it's possible to add an index to select statements similar to this:
SELECT DISTINCT
    V.colA, VE.colB
FROM
    tbl1 V
JOIN
    tbl2 VE ON V.colAB = VE.colAB
WHERE
    VE.colBC = '1' AND V.colUser = 'userId'

I want it to create an index that gets the columns VE.colBC and V.colUser using SQL Server Management Studio. I do not know how to put it into the query. I tried this but apparently it is incorrect:
CREATE INDEX indexTest ON tbl1 (colUser, colBC)

So how can I make it work?

A: You can not add index on select statement, but you can create Indexed View.


text:
Q: How to refresh as well as savstate of datatable when status is updated in laravel In my project, I want to refresh as well as savestate of the data table (datatable saveState) while updating the status in Laravel, the status is getting updated into the database but the data table is not refreshed nor the savestate is done, I am not able to understand where I am doing the mistake, below here is the code that I am using
Route
Route::get('/list-category', [CategoryController::class, 'listcategory'])->name('listcategory');

Controller
public function changestatus($id){

$cat_statuss = Category::find($id);

if (!empty($cat_statuss)) {
    // dd('Record is available.');
    $cat_status = Category::where('id',$id)->first();
    $status  = $cat_status->status;
    $statuss = 'active';
    if($status=='active'){
        $statuss = 'inactive';
    }else{
        $statuss = 'active';
    }

    $cat_status->status = $statuss;

    if($cat_status->update()){
        // return redirect('/list-category')->with('status_change','Updated Successfully.');
        return response()->json(array(
            'success' => true,
            'message'=> 'Status Changed Successfully.',
            'errors' => false

        ), 200);
    }else{

        return response()->json(array(
            'success' => false,
            'errors' => array('status_change_err'=>'Oops! There is an error.')

        ), 400);

    }
}else{
    // dd('Record is not available.');
    return response()->json(array(
        'success' => false,
        'errors' => array('status_change_err'=>'Category Not Found.')

    ), 404);
}

}

List Category Page

id}}" onclick="return confirm('Are you sure want to change the status?');" class="status_button btn btn-sm btn-<?php if($cate->status=='inactive'){ echo 'danger'; }else{ echo 'success'; } ?>" data-id="{{$cate->id}}"> <?php if($cate->status=='active'){ echo 'Active'; }else{ echo 'Inactive'; } ?>


text:
Q: Cannot install asdf erlang on MAC OSX Mojave I am trying to install Erlang in a Mac OS system with Mojave on it. However the installation hangs for no apparent reason:
$ asdf install erlang 22.2.8
asdf_22.2.8 is not a kerl-managed Erlang/OTP installation
The asdf_22.2.8 build has been deleted
Extracting source code
Building Erlang/OTP 22.2.8 (asdf_22.2.8), please wait...

I know the issue is not the network, as I have downloaded everything and the step that hangs forever is the Building step.
I have removed and re-installed both asdf and Erlang from scratch as well, but it didn't fix the issue.
I believe I have all necessary dependencies as well, otherwise the re-installation would have failed.
What can I do to fix this?

A: Go to ~/.asdf/plugins/erlang/kerl-home/builds/asdf_22.2.8 and look at the otp_build_22.2.8.log file. It should tell you what's going on.

A: Solution
Thanks to the post by @legoscia I went to ~/.asdf/plugins/erlang/kerl-home/builds/asdf_22.2.8 and looked at the otp_build_22.2.8.log while it was still being built.
By checking this I was actually able to find out that I had a problem with my brew installation, which in turn meant I was using a very outdated version of XCode and XTools.
By forcing an upgrade on my machine (and as a consequence fixing my broken brew installation), I was then able to smoothly run and install asdf install erlang.
I know this is the solution, but I will give credit to @legoscia, as without him/her I would not have been able to fix my issue.


text:
Q: how to delete subfolder in ADLS gen2 via azure databricks I need to delete ADLS Gen2 subfolder with specific name using databricks dbutils but not able to perform wild card recursion.
e.g.
adlsstorageaccount/container1/folder2/folder3/folderA/**abc**/.parquet
adlsstorageaccount/container1/folder2/folder3/folderB/**abc**/.parquet
adlsstorageaccount/container1/folder2/folder3/folderC/**abc**/.parquet

Need to delete subfolder name "abc" & its contents only, entire path is dynamic.

A: We have reproduced the same Folders in our environment and here are the commands that worked.
$FileSystemName="<Your Container Name>"
$dirname="folder2/folder3/folderA/abc/"
$ctx=New-AzStorageContext -StorageAccountName '<Your Storage Account>' -StorageAccountKey '<Your Access Key>'
Remove-AzDataLakeGen2Item -Context $ctx -FileSystem $filesystemName -Path $dirname

and then confirm it with Y - 'yes'
Here are the screenshots for your reference
Before using the command execution

After the command execution

REFERENCES:
https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-directory-file-acl-powershell#delete-a-directory

A: you need just use magic command %sh in databricks and remove it with wilcard using standard linux commands, something like:
%sh
rm /dbfs/mnt/adlsstorageaccount/container1/folder2/folder3/folderA/*abc*/*.parquet


text:
Q: Pop up window on specific time I'd like to know if there is a way to show scheduled pop up windows, say you're hosting a virtual conference at 6pm, and you want to warn your users an hour early by showing a pop up window at 5pm with a messagge like "Main conference starts in one hour".
This is for a webpage intended to work on desktop and mobile, thus I'm working on HTML and javascript.
Haven't code anything yet, I'm rather looking for a starting point.
Appreciate the help.

A: So based on what you just said, I think that the following js code will solve your issue, however, since I don't know what is your current environment, you will have to change the code to your needs:

// Always use a 24 hour format with this implementation.
function scheduleDailyConferences(timeArray) {
    const offset = 60; // alert offset (1h prior in minutes)
    const now = new Date();
    const current = now.getHours() * 60 + now.getMinutes();
    for (let time of timeArray) {
        let tot = time.h * 60 + time.m - offset;
        if (tot < current) continue;
        tot -= current;
        setTimeout(() => {
            alert(`Your meeting starts in ${offset} minutes.`);
        }, tot * 60 * 1000);
    }
}

// assuming the following conferences of the day:
scheduleDailyConferences([
    { h: 13, m: 45 } // 1:45 pm
    { h:  4, m: 00 } // 4:00 pm
]);

Basically, given a time table timeArray in a human readable format, it reads every entry, subtracts a given offset of 1 hour and figures out when to fire an alert.
If the meeting has already ended or begun, it doesn't fire an alert (but you can easily change that).


text:
Q: Drop-Down List Detached From ComboBox - Excel VBA The drop down list of a ActiveX ComboBox detaches whenever I scroll down the page. How
can I fix it so it won't move?
Here's the VBA code designated for the comboBox.
Private Sub ComboBox1_Change()

ComboBox1.ListFillRange = "DropDownList"
Me.ComboBox1.DropDown

End Sub

A: If you switch out your ComboBox to the one from the Forms toolbar, then it collapses the list as soon as you start scrolling. I think the "detaching" of the dropdown is the default behavior and I don't think you can influence that programmatically (as in here, too).
See this post on the different options for the comboboxes:
Run Macro When ComboBox is Clicked
Another option is to disable the mouse scroll, as in this post:
VBA Excel Combobox: drop-down list scrolling issue


text:
Q: Equal sign does not show up in beamer I'm doing my beamer now and if I write the equal sign (=) whether it is in math mode or not, it does not appear in the output. Help? Thanks.
\documentclass{beamer}
\begin{document}

\begin{frame}{a}

= aaaaaaa

$ = $
\end{frame}

\end{document}

the output is

aaaaaaaaaa

no equal sign


text:
Q: Can't use cx_Oracle on MacOS even though it is already installed I opened a Terminal window under MacOS High Sierra and when I run the python command "import cx_Oracle" everything is fine.
When I run a .py file on a PyCharm project, which the very first line of code is "import cx_Oracle" I get the following error message:
"ModuleNotFoundError: No module named 'cx_Oracle'".
I have aliased my python3 command to python and when I run the command "python -m pip install cx_Oracle" I get a message telling me it's alright:
"Requirement already up-to-date: cx_Oracle in /usr/local/lib/python3.8/site-packages (8.0.0)"
I simply don't know what to do. Is that a matter of adding any path to any environment variable or a virtual environment under PyCharm related problem?
Why does my Python Interpreter running through Terminal not alert me about any error, when I run the install command, everything is fine, but through my Python IDE I keep being alerted about a non existent module?
Any help would be much appreciated.
Thank you in advance!

A: Try installing cx_Oracle using the python binary that PyCharm runs.  I.e. with something like:
/Users/cjones/j/PycharmProjects/p1/venv/bin/python -m pip install cx_Oracle

The python binary is shown in the PyCharm Run console when you execute a script.


text:
Q: Spark Stream - 'utf8' codec can't decode bytes I'm fairly new to stream programming. We have Kafka stream which use Avro.
I want to connect a Kafka Stream to Spark Stream. I used bellow code.
kvs = KafkaUtils.createDirectStream(ssc, [topic], {"metadata.broker.list": brokers})
lines = kvs.map(lambda x: x[1])

I got bellow error.

return s.decode('utf-8')
    File "/usr/lib64/python2.7/encodings/utf_8.py", line 16, in decode
      return codecs.utf_8_decode(input, errors, True)
  UnicodeDecodeError: 'utf8' codec can't decode bytes in position 57-58: invalid continuation byte

Do i need to specify that Kafka use Avro, Is above error for that? If it is how I can specify it?

A: Right, the problem is with deserialization of the stream. You can use  confluent-kafka-python library and specify valueDecoder in :
from confluent_kafka.avro.cached_schema_registry_client import CachedSchemaRegistryClient`
from confluent_kafka.avro.serializer.message_serializer import MessageSerializer

kvs = KafkaUtils.createDirectStream(ssc, [topic], {"metadata.broker.list": brokers}, valueDecoder=MessageSerializer.decode_message)`

Credits for the solution to https://stackoverflow.com/a/49179186/6336337

A: Yes you should specify it.
With java :
creation of stream :
final JavaInputDStream<ConsumerRecord<String, avroType>> stream =
                KafkaUtils.createDirectStream(
                        jssc,
                        LocationStrategies.PreferConsistent(),
                        ConsumerStrategies.Subscribe(topics, kafkaParams));

in the kafka consumer config :
kafkaParams.put("key.deserializer", org.apache.kafka.common.serialization.StringDeserializer.class);
        kafkaParams.put("value.deserializer", SpecificAvroDeserializer.class);


text:
Q: DOTA 2 borderless window moved down I am pretty new to ubuntu but just switched as I realized that my favorite game is supported in linux. I have a 2560 * 1080 screen and want to play the game in 1920*1080. That works by settings the game to borderless window.
Now my issue: ubuntu's top-bar moves the dota window down, which causes the bottom ledge of the game to be moved off the screen.Now I am unable to move the camera ingame as I need to move the mouse to the screen ledges.
Is it possible to move the game-window above the top-bar?
Moving the window while holding ALT renders the game below the top bar.
edit:/
Screenshot of the game in a smaller resolution than 1920*1080 so you see everything it includes:

Screenshot of the game in 1920*1080:

A: There is currently no fix for this available. According to Valve, they are working on improving the HUD to support bigger screen sizes.
Update
Valve updated the HUD (a while ago) which allows playing the game on the full screen without any further issues.


text:
Q: Is the Hulk in the Avengers the same as in the other movies? I hadn't seen the two Hulk movies (Hulk (2003) and The Incredible Hulk (2008)) before seeing The Avengers.  In a comment on In the Avengers movie, why is Hulk's behaviour inconsistent? I commented on

 Bruce Banner developing the ability to control himself as the Hulk during the movie.

Reddy pointed out this also occurred in the previous Hulk movies.  So is The Avengers meant to be in the same universe or continuity as one or both of the previous Hulk movies?
In-universe (movie references) or out-of-universe (quotes from Marvel or Joss Whedon, etc) references are fine.

A: There are several links to The Incredible Hulk in later MCU works.

*

*The Consultant
This one shot connects The Incredible Hull to the rest of the MCU by featuring Thunderbolt Ross, Agent Sitwell, Agent Coulson and Tony Stark, as well as mentioning Abomination.

*

*Daredevil (2015)
A newspaper covering an event from the film can be seen in multiple scenes.

*

*Captain America: Civil War
The character Thunderbolt Ross returns in Captain America: Civil War, portrayed by the same actor as in The Incredible Hulk, William Hurt.

Hulk (2003), however, is not considered part of the franchise or shared universe, as mentioned in other answers.

A: With the release of the film Iron Man, Marvel started releasing movies under their own Marvel Studios banner.  This marked a change as all previous Marvel comic book films were made and financed by other studios who licensed Marvel properties.  At time of writing, Marvel has released these films via Marvel Studios:

*

*Iron Man

*The Incredible Hulk

*Iron Man 2

*Thor

*Captain America: The First Avenger

These films comprise the canon that leads up to The Avengers, and are all part of a shared universe.  Each film has a post-credit scene that builds upon this shared universe (excepting The Incredible Hulk; due to the immense success of Iron Man, Marvel had the post-credit scene include Robert Downey Jr's Tony Stark appear, and had the scene occur before the credits).
The question's spoiler builds upon the ending of The Incredible Hulk, which has Banner

 accept that he can't get rid of the Hulk.  So he starts to induce 'Hulk episodes' and stop trying to perpetually suppress him.  The climactic battle of the film has Banner essentially use the Hulk as a weapon against the film's villain.  During this battle, the Hulk and the Abomination destroy a good chunk of Harlem, which is explicitly called-back to in dialogue in Avengers.

Unfortunately, The Incredible Hulk's Edward Norton couldn't or wouldn't return for The Avengers, so he is replaced by Mark Ruffalo in The Avengers and future films.
Prior Marvel movies include the X-Men films (which Fox makes), Fantastic Four (also Fox), Daredevil (Fox again), Blade (New Line Cinema), Spider-Man (Sony; and this covers both the completed trilogy, and this year's reboot), and Hulk (the 2003 one, which Universal made.  Universal partnered with Marvel for the later The Incredible Hulk).  That's not a complete list, quite a few movies were made when Marvel was licensing out their characters.  Interestingly, Fox's license to the X-Men means that they can use the characters Scarlet Witch and Quicksilver (Magneto's kids) as mutants and in relation to Magneto, meanwhile Marvel can use them as Avengers, so long as they don't mention mutants or Magneto (cite).

A: It appears after starting their own studio, Marvel created its own universe for its films. As per tradition they have labelled it with a number:

199999 - The Marvel Cinematic Universe, covering the Iron Man film series, Thor, The Incredible Hulk (2008), Captain America and the upcoming Avengers film. Anything spinning off of or relating to the Avengers is likely to be within this universe. The number is given in the Official Handbook of the Marvel Universe.

~ Wikipedia's Phrasing of the Matter.
It seems only those films are in that universe. The X-Men, Spider/Man (pre-2012) and Fantastic Four films all exist in their own separate universes. It's likely that the original Hulk films are not in the same universe, though without an official statement (that I can't find) there's also no reason to exclude them from the latest film universe.

A: The Incredible Hulk (2008) was a reboot of Ang Lee's 2003 Hulk, and it was the origin of the Hulk we see in the Avengers. If you watch Iron Man 2 you can see the easter egg of the Hulk. "Shows footage from the University army fight scene."
So The Incredible Hulk is the Hulk they use in the Avengers and many more Marvel movies to come.

A: It is in the same universe because at the end of the second Hulk movie you see Tony Stark (Robert Downey Jr) talking to someone - I think it was Nick Fury.

A: Yes, it is the same Hulk character, same universe.
Hulk (2003) had a sequel in The Incredible Hulk (2008), which was also a sequel to Iron Man (2008), thus it was a crossover between Hulk (2003) and Iron Man (2008).
But the 2003 movie is not considered part of the Marvel Cinematic Universe (the MCU) because that's Iron Man's universe (synonymous with the MCU).  So it's two universes crossing over in The Incredible Hulk and most of the following films and series that share characters from Hulk and all characters introduced in the following crossover installments.
Watch both films and notice how The Incredible Hulk picks up from where Hulk left off.  The newspapers/articles/documents shown in the opening montage also explain what happens in the time gap between the years the two films take place in, matching that time gap and the narrative.
Marvel Studios created a movie studio & wanted to create a cinematic universe & went all in with Iron Man. The success of Iron Man determined if they'd float or not. They also collaborated with Universal & made The Incredible Hulk at the same time, a sequel to Hulk, but in Marvel's own style, latching on to a movie universe already established (Hulk).
There were creative tensions when making the film because Universal wanted it more as a sequel to Hulk and Marvel wanted to make it more of their own.
There were also tensions between Edward Norton, alongside the director Louis Leterrier, against the studio, Marvel.  They wanted it more character driven - like Ang Lee's Hulk - whereas Marvel wanted a more action-oriented quickie.
There's a finished cut of the film called the 'Norton Version' that was supposed to be the released version (almost an hour longer), but Marvel cut it down, significantly, right before release. (It's hard to find, but it's floating around thanks to piracy).
Leterrier describes the out-takes: "It's like the back story. It's more the sequel to the Ang Lee movie."
https://www.slashfilm.com/the-truth-about-edward-norton-vs-marvel/
In an interview with Gale Anne Hurd, producer of 2003's Hulk and 2008's The Incredible Hulk:

Collider: It's set up so that it could be a sequel or a remake, depending on how you look at it. Was that something you were very conscious of?
Gale: To be honest, that was was one of those things where we said, "Look, we don't want to tell another origin story." One thing we absolutely knew for certain was that we didn't want to start with Bruce Banner and how he becomes the Hulk. From that point on, we couldn't quite figure out how to term this. I think at one point we asked if anyone could come up with the appropriate term and someone one line had a "re-quel" which I think was actually perfect. It's kind of a reboot and it's kind of sequel.

https://www.webcitation.org/6EdwMPN77?url=http://collider.com/entertainment/interviews/article.asp/aid/8230/tcid/1
Iron Man opened May 2008 to unexpectedly enormous success, while Incredible Hulk opened one month later to tepid success, which, creatively, had one foot in Hulk universe & one in MCU. Marvel doesn't own 2003's Hulk (movie), so deny connections to it.
Marvel Studios owns the character of Hulk, but Universal owns the distribution rights to a Hulk film.  That's why Hulk appears in Marvel films but we have never seen another solo Hulk film, because Universal would be needed to distribute it.  Marvel & Universal realized they don't play well together, so there's never been another solo Hulk film since.


text:
Q: How to provide a dependency with @SessionScope and @ActivityScope using Dagger 2.10 Android Injector? Suppose you have an application where user logs in on the first screen and, from that moment on, you have access to an User object. I would like to provide this dependency under a @SessionScope - it means, when user logs out, all dependencies provided through a component annotated as @SessionScope would die.
Despite the dependencies provides via @SessionScope I would like to have dependencies provided via @ActivityScope, an ActivityPresenter for instance and, of course, I would have to provide dependencies from @SessionScope and @ActivityScope together to an Activity consumer class.
What is the best to do it using Dagger 2 new AndroidInjector feature?
So far I'm able to provide dependencies under @ActivityScope like shown below:
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope

@Module
abstract class ActivitiesBuilder {

    @ActivityScope
    @ContributesAndroidInjector(modules = arrayOf(HomepageModule::class, FacebookModule::class))
    abstract fun providesHomepageViewImpl(): HomepageViewImpl

}

@Module
abstract class AppModule {

    @Provides
    @Singleton
    fun provides (application: Application) : Context = application

}

@Singleton
@Component(
        modules = arrayOf(
                AndroidInjectionModule::class,
                ActivitiesBuilder::class,
                AppModule::class
        )
)
interface AppComponent : AndroidInjector<App> {

    @Component.Builder
    abstract class Builder : AndroidInjector.Builder<App>()

}

class App : DaggerApplication() {

    override fun onCreate() {
        super.onCreate()
        Timber.plant(Timber.DebugTree())
    }

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> = DaggerAppComponent.builder().create(this)
}

A: Tutorial

*

*Create a custom scope named @SessionScope;

*Create a class named as SessionActivityBinding:

*

*add a method that will bind the activity sub component that will be provided under session scope - further details on this implementation can be found here;

*Create a subcomponent named SessionComponent:

*

*annotate this subcomponent with the custom scope created on step 1;

*create a @Subcomponent.Builder and add a method that will receive a User object as parameter;

*

*annotate this method with @BindsInstance;

*add this method fun build(): SessionComponent in order to allow the provision of this SessionComponent - this will be necessary in order to release this component when user loggs out;

*add SessionActivityBinding class into the module array;

*[OPTIONAL]: Add a SessionModule class to provide dependencies that should be provided under @SessionScope;

*On AppModule add SessionComponent as a subcomponent;

*Add the AppModule in the list of module's from AppComponent;

*When user successfully authenticate into the system, and an User object is acquired, create an instance of SessionComponent that must remain live until user logs out;

*Whenever user logs out, discard the old instance of SessionComponent like: sessionComponent = null - this will discard all dependencies provided under @SessionScope;

*Whenever user logs in again, repeat the process from step 6;

Further details and examples can be found here;


text:
Q: Using reflection to get method name and parameters I am trying to workout a way to programatically create a key for Memcached, based on the method name and parameters. So if I have a method,
string GetName(int param1, int param2);

it would return:
string key = "GetName(1,2)";

I know you can get the MethodBase using reflection, but how do I get the parameters values in the string, not the parameter types?

A: What you're looking for is an interceptor. Like the name says, an interceptor intercepts a method invocation and allows you to perform things before and after a method is called. This is quite popular in many caching and logging frameworks.

A: You can't get method parameter values from reflection. You'd have to use the debugging/profiling API. You can get the parameter names and types, but not the parameters themselves. Sorry...

A: This is what I've come up with (however, it may not be particularly efficient):
MethodBase method = MethodBase.GetCurrentMethod();
string key = method.Name + "(";
for (int i = 0; i < method.GetParameters().Length; i++) {
  key += method.GetParameters().GetValue(i);
  if (i < method.GetParameters().Length - 1)
    key += ",";
}
key += ")";


text:
Q: Using jQuery tokeninput from loopj.com I am able to select multiple options that I send from my .jsp file in JSON format. However, when I want to SUBMIT/access the values from the text input element "tokenize", I get a undefined output. I am a novice to java script and so what to touch and what not to touch.
Q: Could someone provide/point me to some detail on how to achieve this at the earliest??
   Is there something missing below?
Thnx in Advance,
Aditya
Note: The body tag got split into a separate code block. Pls donot get confused.

<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />

    <link rel="stylesheet" href="css/token-input.css" type="text/css" />
    <link rel="stylesheet" href="css/token-input-facebook.css" type="text/css" />

Jquery Tokenizing Autocomplete Input

<form name="myForm">

List style

        <input type="text" id="tokenize" name="blah"/>

        <input type="submit" value="Parse" onClick="showList()"/>

Facebook style

        <input type="text" id="tokenize2" name="blah2" />

</form>

A:

A: Instead of:
var t = document.getElementById('tokenize').valueOf()

use
var t = document.getElementById('tokenize').value;


text:
Q: Compiler code error : 'a' was not declared Ok. Trying to generate a code by displaying the stack contents after each instruction where we assume that the variables are initialized with the values: a=22, b=33 and c=44
Also, assume the following address environment:
ρ={a I→5,b I→6,cI→7}

My background: 4th day of Compiler Design and Virtual Machines. New to this stuff and evidently this is not C++, but something else. Prog is VERY "hands off", especially current prof.
int main (void)  {
a = 22
b = 33`
c = 44
p = {'a' : 5, 'b' : 6, 'c' : 7}
for each instruction in the generated code:
if instruction.startswith ('a'):
p['a'] = instruction[1]
elif instruction.startswith ('b'):
p['b'] = instruction[1]
elif instruction.startswith ('c'):
p['c'] = instruction[1]
print (f'a = {p['a']},  b = {p['b']}, c = {p['c']}')
     }

To be honest, I was expecting it to compile and return back a = 22, b = 33, and c = 44??
Got back a few errors:
main.cpp:12:9: warning: character constant too long for its type
12 | print (f'a = {p['a']},  b = {p['b']}, c = {p['c']}')
|         ^~~~~~~~~~

main.cpp: In function 'int main()':
main.cpp:2:1: error: 'a' was not declared in this scope
2 | a = 22
| ^

main.cpp: At global scope
6 | if instruction.startswith ('a'):
| ^~
main.cpp:13:6: error: expected declaration before '}' token
13 |      }
|      ^


text:
Q: C# Asp.Net Core Use Redis for IDistributedMemoryCache and DataProtection as the title suggests I should use Redis both as DistributedCache and to store the key for the DataProtection, the problem is that I don't know if it is correct to register the Redis instance twice, like this:
public void ConfigureServices(IServiceCollection services)
{
    //......

    // First Instance of Redis
    serviceCollection.AddStackExchangeRedisCache(options =>
    {
        options.ConfigurationOptions = new ConfigurationOptions();
        options.ConfigurationOptions.EndPoints.Add("127.0.0.1", 6379);
        options.ConfigurationOptions.Password = "*********";
        options.ConfigurationOptions.ConnectRetry = 5;
    });

    // Second Instance of Redis
    var redis = ConnectionMultiplexer.Connect("127.0.0.1:6379");
    serviceCollection.AddDataProtection()
        .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");

    //......
}

or it is possible to share the same instance already registered in the first method?
In case it is possible to come to do?
Thanks

A: in .NET 6, microsoft have added new option when configuring redis to allow get or set delegate to create ConnectionMultiplexer, below is naive example
ConnectionMultiplexer cm = ConnectionMultiplexer.Connect("server1:6729");
services.AddSingleton<IConnectionMultiplexer>(cm);

services.AddStackExchangeRedisCache(options =>
        {
            options.ConnectionMultiplexerFactory = () =>
            {
                var serviceProvider = services.BuildServiceProvider();
                IConnectionMultiplexer connection = serviceProvider.GetService<IConnectionMultiplexer>();
                return Task.FromResult(connection);
            };
        });

A: Wy not like this?
        IConnectionMultiplexer? connectionMultiplexer = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("LockExchange"));
        services.AddSingleton(connectionMultiplexer);
        services.AddStackExchangeRedisCache(options =>
        {
            options.ConnectionMultiplexerFactory = () => Task.FromResult(connectionMultiplexer);
        });


text:
Q: Folium Chloropleth not showing colors Geojson File: https://raw.githubusercontent.com/sejal234/heatmaps_by/main/Zip_Codes.geojson
CSV: https://raw.githubusercontent.com/sejal234/heatmaps_by/main/oyzipsattempt.csv (this is labelled new in my code)
I want to create a chloropleth showing the number of OY (opportunity youth) per zipcode in Houston.
The following code:
  n = folium.Choropleth(
                 geo_data=r'https://raw.githubusercontent.com/sejal234/heatmaps_by/main/Zip_Codes.geojson',
                    data=new,
                    columns=['ZIPCODE','oy_count'],
                    key_on='feature.properties.ZIP_CODE',
                    fill_color='YlGn',
                    nan_fill_color="White",
                    fill_opacity=1,
                    line_opacity=0.5,
                    legend_name='Num of OY', #title of the legend
                    highlight=True,
                    line_color='black')
        n.add_to(htx_map2)
        folium.LayerControl().add_to(htx_map2)
        htx_map2

Should return a chloropleth on the yellow green scale, but instead returns the following (empty) map:

What am I doing wrong?


text:
Q: How can i add a counter badge to a widget? How can I add a counter badge to a widget? Like in this screenshot
Google Reader also has a widget with counter.

A: What is the problem? A home screen widget can have a layout, and that layout can contain an ImageView and a TextView.
You will then create a background service that is checking how many messages there are e.g. every 15 minutes, and then update the widget.


text:
Q: Flask with a webserver breaks all sessions? For example, this code:
from flask import session

@app.route('/is_logged_in/')
def is_logged_in():
  return 'user' in session

It runs fine for me when running Flask's development server, but it throws a 500 error with any webserver setup (FastCGI, uWSGI, etc.) on any server (Apache, nginx, Lighttpd).
Anybody know why?

My actual code is on GitHub, if it matters.
It works flawlessly when running with Flask's internal server, but I can't get any session variables to work with a production webserver: https://github.com/Blender3D/Webminal/blob/master/server.py

A: I finally tried Tornado, thinking it would help with my problems (it's written in Python, after all).
Lo and behold, a readable traceback:
RuntimeError: the session is unavailable because no secret key was set.
Set the secret_key on the application to something unique and secret.

Looks like I just forgot to add a secret key to sign sessions with:
app.secret_key = 'why would I tell you my secret key?'

A: Your return value must be one of several types: a basestring (string or unicode), a tuple (representing arguments passed to the constructor of a Response object), a Response object itself, or -- failing those -- a WSGI-callable function.
You are returning a bool. Flask is assuming that since it's not a basestring, tuple or  Response object, it must be a WSGI-callable. Subsequently, when processing the response it attempts to call() your bool return value which results in an exception. Flask catches the resulting TypeError. When Flask is in debug mode, it'll pass this back up to Werkzeug's simple webserver, which will invoke the built-in debugger. When Flask is in production mode, however, it'll merely bubble up an internal server error -- e.g., code 500 -- with no further information.
So, to fix your problem, make sure you do this instead:
return str('user' in session)

A: Though, it doesn't really answer your question, I would rewrite it this way:
from flask import redirect, session, url_for

@app.route('/')
def index():
    return 'foo'

@app.route('/is_logged_in/')
def is_logged_in():
    user = session.get('user', None)
    if user:
        return user
    return redirect(url_for('index'))


text:
Q: Can I "Stamp" a .zip file with Data when a file is being downloaded? is there a way that I can "Stamp" my .zip files with some type of hidden Data (like the email address of the buyer/downloader) every time that .zip is being downloaded?
Basically trying to inject some type of Unique variable into the .zip, for tracking/security reasons.
I'm not even sure if I can modify a .zip like that, but I figured that I should ask, because I've been searching around and could not find an answer.

A: How would you go about "tracking" this zip file?
Are you going to ask the user to send you the zip file so you can see if it's legitimate? Not sure what you're going for here.
Having said that. Some ideas:
Take the contents of the zip file concatenated with the email address of the buyer/downloader + some key that only you know. Take the MD5 of that and name the zip file {THATMD5}.zip. Or, you could put something like Key.txt into the zip file and key.txt could contain {THATMD5}. Again, not sure how you plan to "track" this though.


text:
Q: restrict access to specific attributes openldap proxy I try to config OpendLdap in proxy mode of Active Directory to browse specific attributes and not all.
When I browse my AD with ldapsearch, it works, but it displayed all of attributes, I just want attributes as:
sn,givenName,streetAddress,l,postaCode,mail,telephoneNumber,mobile.

I've create an access rule on this specific attributes for a specific user, but it don't works
see my rule :
access to dn.subtree="ou=xxxx,dc=xxxx,dc=fr" attrs="entry,sn,givenName,
    streetAddress,l,postaCode,mail,telephoneNumber,mobile"
    by dn="cn=xxxxxx,OU=xxxxx,dc=xxx,dc=fr" read
    by * none

What did I forget?


text:
Q: How to use jQuery to load codepress I am using codepress in a CMS to edit files in the filesystem. Everything works nicely, however when trying to load the same page using jQuery load() function, codepress seems to break.
My javascript code looks like this which loads the php file with codpress, however codepress seems to not fire.
$('.content').on('click', '#fileSystemWrap a', function (event) {
    event.preventDefault();
    var fileName = $(this).data('file');
    $('#rightColWrap').fadeOut(150, function(){
        $('#rightColWrap').load('/?url=developer/edit-file.php&open=' + fileName, function(){
            $('#rightColWrap').fadeIn(150);
        });
    });
});

Digging into codepress.js I see this at the end of the file but I'm not understanding if there is something I could add to my initial on click event listner script to help codpress fire.
if(window.attachEvent) window.attachEvent('onload',CodePress.run);
else window.addEventListener('DOMContentLoaded',CodePress.run,false);

Here is the link to codepress on sourceforge
https://sourceforge.net/projects/codepress/

A: To be logic : when the data are loaded, we want to initialize CodePress.
So your code should look like :
$('.content').on('click', '#fileSystemWrap a', function (event) {
    event.preventDefault();
    var fileName = $(this).data('file');
    $('#rightColWrap').fadeOut(150, function(){
        $('#rightColWrap').load('/?url=developer/edit-file.php&open=' + fileName, function(){
            CodePress.run();
            $('#rightColWrap').fadeIn(150);
        });
    });
});

If this didn't work please provide error from the console.
Edit : corrected answer, seen Robson França's comment.
Last issue was that CodePress.run; should have been written CodePress.run();

A: The answer was that we needed to add parentheses to CodePress.run and after the fadeIn() call.
$('#content').on('click', '#fileSystemWrap a', function (event) {
    event.preventDefault();
    var fileName = $(this).data('file');
    $('#content').fadeOut(150, function(){
        $('#content').load('/?url=developer/edit-file.php&open=' + fileName, function(){
            $('#content').fadeIn(150, function(){
                CodePress.run();
            });
        });
    });
});


text:
Q: Multithreaded semaphore program I've spent quite a few hours on trying to figure this one out and I'm completly stuck. The program is supposed to start 6 threads. Where some threads start where others end. Right now, I'm trying to get one single thread (thread 0) to execute. The caps lock commenting shows where I have added code and done my mistakes. My main struggle here is dealing with the pointers. Could anyone give me any pointers (ha..ha.. :c )?
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define SHARED 1
sem_t sem[6];

struct threadargs
 {
 int id;        /* thread number */
 int sec;       /* how many sec to sleep */
 int signal[6]; /* which threads to signal when done */
 };

void *tfunc(void *arg)
 {
 int i;
 struct threadargs *targs=arg;
 sem_wait(sem);                              //WAIT FOR OWN SEMAPHORE
 printf("Thread %d is running\n", targs->id);
 sleep(targs->sec);
 printf("Thread %d is completed and may wake others..\n", targs->id);
 for(i=0; i<6; i++)                          //ITERATE OVER signal_ARRAY &
  {                                          //WAKE THREAD NUMBER i IF
  if(targs->signal[i] == 1)                  //signal[i] IS 1
    pthread_cond_signal(&sem[i]);
  }
 }

int main(void)
 {
 int i, j;
 struct threadargs *targs[6];
 pthread_t tid[6];
 for(i=0; i<6; i++)
 {
 targs[i] = (struct threadargs*) malloc(sizeof(struct threadargs));
 for(j=0; j<6; j++)
  { targs[i]->signal[j]=0; }
 }
targs[0]->id=1;
targs[0]->sec=1;
targs[0]->signal[1]=1;
targs[0]->signal[4]=1;
sem[0] = 0;                                 //INITIALIZE THREAD'S SEMAPHORE TO 0 or 1
pthread_create(targs[0], NULL, tfunc, NULL) // START THREAD

for(i=0; i<6; i++)
 pthread_join(tid[i], NULL);
return 0;
 }

A: Alright. First things first, I do recommend taking a second look at your coding style. It is of course highly subjective and I won't say yours is bad, but it took me a while to figure it out (if you really want to know, I recommend the Linux coding style for C/C++ code).
Lets get on with your problem. As far as I can see, the main issue seems that you're basically comparing pointers to apples with pointers to banana's (in other words, you're using the wrong pointer type in the wrong place).
To make sure that calls to functions and the like are correct, make sure to look up the API documentation for functions that are new to you (examples: pthread_create, sem_init, sem_wait, sem_post, pthread_cond_signal).
As you can see, pthread_cond_signal doesn't take a sem_t* as argument, and therefore you can't pass one to it and expect it to work. Below you'll find an example program showing how semaphores are used.
First, a new thread is created which will be put in waiting state instantly. As soon as the main tread finished counting from 0 to 150, it will post ('unlock') the semaphore and allowing the second thread to finish its execution.
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

static sem_t sem_thread_one;
static pthread_t thread_one_data;

static int x;

static void *tfunc(void *arg)
{
    sem_wait(&sem_thread_one);
    printf("Thread 1 is running. The value of x is %i\n", x);
    return NULL;
}

int main(int argc, char **argv)
{
    sem_init(&sem_thread_one, 0 /* don't share between processes */, 0);

    if(pthread_create(&thread_one_data, NULL, &tfunc, NULL)) {
        fprintf(stderr, "Could not create thread, exiting!\n");
        return -EXIT_FAILURE;
    }

    while(x < 150) {
        x++;
    }

    sem_post(&sem_thread_one);

    if(pthread_join(thread_one_data, NULL)) {
        fprintf(stderr, "Could not join threads, exiting!\n");
        return -EXIT_FAILURE;
    }

    sem_destroy(&sem_thread_one);
    printf("Program ran succesfully!\n");
    return -EXIT_SUCCESS;
}

Save in a file sem.c and compile & link using:
gcc -Wall -Os -pthread -o sem_test sem.c

Now a second example, but now using pthread_cond_t. The functionality of the program is somewhat similar, it waits for a counter to reach a certain number.
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

static pthread_t thread_one_data, thread_two_data;
static volatile int x, y, idx = 10;
static int count = 1;

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

static void *cond_test_wait(void *arg)
{
    pthread_mutex_lock(&mutex);
    while(count < 10) {
        printf("Waiting for `count < 10' to become true\n");
        pthread_cond_wait(&condition, &mutex);
    }
    pthread_mutex_unlock(&mutex);

    printf("Test wait thread finished. Value of count: %i\n", count);
    return NULL;
}

static void *cond_test_signal(void *arg)
{
    while(count < 10) {
        pthread_mutex_lock(&mutex);
        pthread_cond_signal(&condition);

        /* do more intelligent things here */
        count++;
        pthread_mutex_unlock(&mutex);
    }

    printf("Test signal thread finished\n");
    return NULL;
}

int main(int argc, char **argv)
{

    if(pthread_create(&thread_one_data, NULL, &cond_test_wait, NULL)) {
        fprintf(stderr, "Could not create thread, exiting!\n");
        return -EXIT_FAILURE;
    }

    if(pthread_create(&thread_two_data, NULL, &cond_test_signal, NULL)) {
        fprintf(stderr, "Could not create thread, exiting!\n");
        return -EXIT_FAILURE;
    }

    pthread_join(thread_one_data, NULL);
    pthread_join(thread_two_data, NULL);

    pthread_cond_destroy(&condition);
    pthread_mutex_destroy(&mutex);

    printf("Program ran succesfully!\n");
    return -EXIT_SUCCESS;
}

Save in a file cond.c and compile & link using:
gcc -o cond -pthread -Os -Wall cond.c

Do note how neat condition work in this example. You can use them to wait until any expression (= condition) becomes true. After the condition becomes true normal execution continue's.
If you need any more help, don't hesitate to ask in the comments. Good luck combining the above examples to fix up your program.


text:
Q: tikz - checkmarker node line width not match cross marker I try below code to create a checkmark and crossmark, but the checkmark size not match the crossmark!
\documentclass{standalone}
\usepackage{tikz}
\usepackage{amssymb}
\usetikzlibrary{calc,chains,positioning}
\begin{document}
\begin{tikzpicture}
    \newcommand{\cross}{$\mathbin{\tikz [red,line width=4pt,line cap=round] \draw (-0.5,-0.5) -- (0.5,0.5) (-0.5,0.5) -- (0.5,-0.5);}$}%
    \node[red] (A) {\checkmark};
    \node[red,right=of A,minimum width=1,minimum height=1] {\cross};
    %\draw[red] (0,0) circle (1);
\end{tikzpicture}
\end{document}

How to make both marker the same size?

A:
\documentclass{standalone}
\usepackage{tikz}
\usepackage{amssymb}
\usetikzlibrary{calc,chains,positioning}
\begin{document}
    \begin{tikzpicture}
        \newcommand{\cross}{$\mathbin{\tikz [red,line width=2pt,line cap=round,scale=0.2] \draw (-0.5,-0.5) -- (0.5,0.5) (-0.5,0.5) -- (0.5,-0.5);}$}%
        \node[red] (A) {\checkmark};
        \node[red,right=of A,minimum width=1,minimum height=1] {\cross};
        %\draw[red] (0,0) circle (1);
    \end{tikzpicture}
\end{document}


text:
Q: What are parent and child tables? I'm new to Oracle and was watching a tutorial on it. In the tutorial, the presenter mentioned parent and child table several times but I could not understand what they mean. Can someone please explain it to me with an example?

A: The are probably poor choices for names, but everyone uses them because the names are convenient and because of how the entities appear in an entity relationship diagrams.
A child table has a reference (aka a foreign key) to the parent table.
Eg an employee table that had a (foreign key) column called department_id, whose values were found in the department table's id (primary key) column would represent a (many-to-one) child/parent relationship.

A: Child tables and parent tables are just normal database tables, but they're linked in a way that's described by a parent–child relationship.
It's usually used to specify where one table's value refers to the value in another table (usually a primary key of another table).
For example, imagine a news article. This could be represented by a table called articles and has fields for id, headline, body, published_date and author. But instead of placing a name in the author field, you could instead put the ID value of a user in a separate table—maybe called authors—that has information on authors such as id, name, and email.
Therefore, if you need to update an author's name, you only need to do so in the authors (parent) table; because the articles (child) table only contains the ID of the corresponding author record.
Source: What is a Parent table and a Child table in Database?


text:
Q: WPF Change between 2 windows I have been searching everywhere for the answer to my problem but i cant seem to locate anything.
I am trying to open 2 different windows, that i have already created, after a button press. On the button press, i go to open the new window, but it just opens a blank window, not the window i want.
This is my function that i am trying to open my new window with, and it is inside my MainWindow, and i want to open my window i have created in Jobs (see image below).
void Jobs_Clicked(object sender, RoutedEventArgs e)
{
    Window Jobs_Window = new Window();
    App.Current.Jobs = Jobs_Window;
    Jobs_Window.Show();
    this.Close();
}

Solution Explorer

A: You are creating an instance of the standard Window class rather than your custom Window that you have made.
If you have added a Window, called JobsWindow for example, then create an instance of that rather than just the .NET built-in Window:
void Jobs_Clicked(object sender, RoutedEventArgs e)
{
    Window Jobs_Window = new JobsWindow();
    App.Current.Jobs = Jobs_Window;
    Jobs_Window.Show();
    this.Close();
}


text: Q: how to create jbehave report with jenkins pipeline? i have some set of jbehave tests and regular jenkins job with xunit plugin that create report from xml files. So far so good. Now, unfortunately i need to add some actions and it is easier to add them in pipeline. But i don't get how to generate jbehave report in pipeline. Been trying to use 'pipeline-syntax' help but this page only generate xunit([<object of type org.jbehave.jenkins.JBehavePluginType>])


text:
Q: How do you enable the Raspberry Pi camera in Yocto I'm trying to get my Raspberry Pi camera to work with my Yocto image.
I found here that I need to add the following line:
VIDEO_CAMERA = "1"

I added it to my meta's recipes-core/images/example-image.bb but still when I try to take a picture I get:
root@user:~# raspistill -o testshot.jpg
mmal: mmal_vc_component_create: failed to create component 'vc.ril.camera' (1:ENOMEM)
mmal: mmal_component_create_core: could not create component 'vc.ril.camera' (1)
mmal: Failed to create camera component
mmal: main: Failed to create camera component
mmal: Camera is not enabled in this build. Try running "sudo raspi-config" and ensure that "camera" has been enabled

So it seems like it's not enabled. And raspi-config seems to be only available on Raspbian, in fact it's not recognised as a command.
Am I missing anything else? I can't find much info out there and I'm still new to Yocto.


text:
Q: Fetching data from backend causes infinite loop and never successfully loads This is probably my inexperience with Async functions showing here but i'm having an issue where my code to fetch templates from a back-end into react simply repeats without properly setting the state to the data
import React, { useState} from 'react';
import './main.css';
import Frame from './Components/Frame';

function App() {
    const [view, setView] = useState(window.location.pathname);

    console.log('logging view ' + view);

    return (

            <Frame viewF={'nav'} />

                <Frame viewF={view} />

    );

}

export default App;

main component
import React, { useState } from 'react';

function createMarkup(markup) {
    return { __html: markup };
}

const Frame = (props) => {
    const [content, setContent] = useState('');

    const contactBackend = async () => {
        try {
            const response = await fetch('http://localhost:5000/' + props.viewF, {
                'methods': 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            if (!response.ok) {
                throw Error(response.statusText);
            }
            //const data = response.json(); //alternate approach
            //console.log(data);
            setContent(response.json());

        } catch (error) {
            console.log(error);
        }
    }

    contactBackend();

    return (

    )

};

export default Frame;

The backend can send data, it worked in an earlier and simpler version. I can also see the returned values with some console logs. but the most it ever puts into the returned div is [object Promise] and then it sends 1000s of requests until the back-end crashes

A: The code is unconditionally calling contactBackend in the function body, and the result is an enqueued state update which triggers a component rerender. This is an unintentional side-effect.
Typically this is called in an useEffect hook when mounting.
response.json() also returns a Promise, so you also want to wait for that to resolve.
Example:
useEffect(() => {
  const contactBackend = async () => {
    try {
      const response = await fetch('http://localhost:5000/' + props.viewF,
        {
          'methods': 'GET',
          headers: {
          'Content-Type': 'application/json'
          }
        }
      );

      if (!response.ok) {
        throw Error(response.statusText);
      }

      const content = await response.json();
      setContent(content);
    } catch (error) {
      console.log(error);
    }
  }

  contactBackend();
}, []); // <-- empty dependency to run once after initial render


text:
Q: Check the version of an app installed on iPad Is there anyway to check the version of an app installed on a iPad without connecting back to iTunes on my desktop / laptop?

A: iOS provides a list with all installed Apps and their memory usage. Tapping on any App on that list will, besides giving you the option to delete it, display the name, the version, its size and how much memory it's using.
The path to access this list has changed through the iOS versions:
iOS 11: Settings / General / iPad Storage
iOS 9: Settings / General / Storage and iCloud usage / Manage Storage
iOS 8: Settings / General / Usage / Manage Storage
iOS 7: Settings / General / Usage


text:
Q: Jquery Sort and give message correct or incorrect I have a list item that is sortable.

alpha

beta

gamma

thita

pie

Now I want is to display a message whenever users made a sort. Here I am trying to compare two arrays. It only shows a message as "Incorrect Order" even if the array is matching.
var correctOrder = ["sort_one", "sort_two", "sort_three", "sort_four", "sort_five"];
var userOrder = $(".sortable.reImbursementdiv li").toArray().map(function(i) {
    return i.id
});

function arraysEqual(arr1, arr2) {
    if (arr1.length !== arr2.length)
        return false;
    for (var i = arr1.length; i--;) {
        if (arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

$(".sortable").sortable({
    update: function(event, ui) {

        if (arraysEqual(correctOrder, userOrder) == true) {
                showMsg("reImbursement_msg", "Correct Order", "success");

        } else {
            showMsg("reImbursement_msg", "Incorrect Order", "danger");
            console.log($(".sortable.reImbursementdiv li").toArray().map(function(i) {
                return i.id
            }));
        }

        return true;
    }
}).disableSelection();

function showMsg(box, msg, msgStatus) {
    $("#" + box)
            .removeClass()
            .show()
            .addClass("alert alert-" + msgStatus)
            .html(msg);
}

I have created a pen as per request.
Codepen link demo

A: In your example, you never update userOrder so the order, that is being compared, never changes. Please review:

$(function() {
  var correctOrder = ["sort_one", "sort_two", "sort_three", "sort_four", "sort_five"];
  var userOrder = [];

  function arraysEqual(arr1, arr2) {
    var result = true;
    if (arr1.length === arr2.length) {
      $.each(arr1, function(key, val) {
        result = result && (arr1[key] === arr2[key]);
      });
    } else {
      result = false;
    }
    console.log(arr1, arr2, result);
    return result;
  }

  function showMsg(box, msg, msgStatus) {
    $(box)
      .removeClass()
      .show()
      .addClass("alert alert-" + msgStatus)
      .html(msg);
  }

  $(".sortable").sortable({
    update: function(event, ui) {
      userOrder = $(".sortable.reImbursementdiv li").toArray().map(function(i) {
        return i.id
      });
      if (arraysEqual(correctOrder, userOrder)) {
        showMsg("#reImbursement_msg", "Correct Order", "success");
      } else {
        showMsg("#reImbursement_msg", "Incorrect Order", "danger");
        console.log($(".sortable.reImbursementdiv li").toArray().map(function(i) {
          return i.id
        }));
      }
      return true;
    }
  }).disableSelection();

  userOrder = $(".sortable.reImbursementdiv li").toArray().map(function(i) {
    return i.id
  });
});

five

one

four

three

two

You also have to be mindful of the order of operations.
Hope that helps.

A: It seems I missed the latest order from user after the sorting is done.
$(".sortable").sortable({
  update: function(event, ui) {
  var userOrder = $(".sortable.reImbursementdiv li").toArray().map(function(i) {
      return i.id
  });
      if (arraysEqual(correctOrder, userOrder) == true) {
              showMsg("reImbursement_msg", "Correct Order", "success");

      } else {
          showMsg("reImbursement_msg", "Incorrect Order", "danger");
          console.log($(".sortable.reImbursementdiv li").toArray().map(function(i) {
              return i.id
          }));
      }

      return true;
  }
}).disableSelection();


text:
Q: Office 365 Calendar Id changes We are experiencing that ids of calendars created using MS Graph sometimes changes. The calendars are created using a POST request to /me/calendars, and the id of the returned calendar object is stored in our database so that we can synchronize with the calendar later. Unfortunately sometimes we see that the id of the calendar in the users Outlook account has changed later the same day. We are using the immutable id header in all requests.
It looks like this problem (or similar problems) has been reported multiple times on SO:
microsoft graph API /calendars id is not unique
Office 365 default Calendar's ID changes automatically
Why would a Calendar Id change when using the Outlook REST API?
but I can't see from the answers what the solution is, or if MS was able to fix a bug.
Any update on this issue would be appreciated.

A: When I encountered this problem, I solved it by using Microsoft 365 groups and their default calendars to ensure an immutable id that you can access from no matter what user and adding/removing members to manage the permissions.

For us we also had this problem, that in microsoft graph api the calendar id(that was created by user A) is different for user A and B for the following request, as it is a base64 encoding of something:
/users/user-id/calendars

More about the graph api groups you can find here.


text:
Q: How to transform Array[RDD[Row]] to SchemaRDD -- OR -- how to split SchemaRDD, in which the results be SchemaRDDs? I want to use the implementation of pipeline in MLlib. To use pipeline, there should be sequence of LabeledDocument to be passed to the pipeline (SchemaRDD).
I create SchemaRDD as follows:
val data = sc.textFile("/test.csv");
val parsedData = data.map { line =>
        val parts = line.split(',')
        LabeledPoint(parts(0).toDouble, Vectors.dense(parts.tail))
        }.cache()
val rddSchema = parsedData.toSchemaRDD;

I want to split the new rddSchema into training (80%) and test (20%). If I use randomSplit, it returns a Array[RDD[Row]] instead of SchemaRDD.
Problem: How to transform Array[RDD[Row]] to SchemaRDD
-- OR --
How to split SchemaRDD, in which the results be SchemaRDDs?
I appreciate your help.

A: I know this is old, but did you try that :
val splits = parsedData.randomSplit(Array(0.6, 0.4), seed = 11L)
val training = splits(0)
val test = splits(1)


text:
Q: Correctness of reading data from multiple threads I create a global variable (C++) in main thread and set its value to X then to Y.
After that I spawn multiple threads and read  from this variable.
Do I have a guarantee that I will read Y ?
If not, would read(shared)-mutex protection solve it ? (even though mutex can be always taken)
What exactly forces caches of multiple processors to be synchronized?

A: Starting a thread introduces an implicit memory barrier.
C++11 guarantees this for constructing std::threads in §30.3.1.2:

Synchronization: The completion of the invocation of the constructor
  synchronizes with the beginning of the invocation of the copy of f.

Where f is the function being executed by the thread. Also see §1.10 for the definition of synchronizes with (or take a look at this blog post).
In layman's terms, it is safe to read the value from different threads concurrently and it is guaranteed that they will all read the latest, correct value. This of course is only true as long as no one performs any writes on that variable once you began starting threads. In that case you will need atomics or explicit locks (i.e. mutexes).

A: If you spawn your threads after assigning Y to your variable, they will indeed see that value.

would read(shared)-mutex protection solve it ?

Mutexes are only required when you modify your variable concurrently (whether the other concurrent operations are read or write). If you never modify your variable concurrently (as is the case here), you don't need mutexes.

What exactly forces caches of multiple processors to be synchronized?

Typically, a write to a memory location will invalidate the corresponding cache entries on the other processors. When you access that variable again, the corresponding processor will repopulate the cache if needed.


text:
Q: Compare two files and combine different columns of two files together into a single file using shell I have two files file1.txt and file2.txt.
file1.txt
Amal=123=amal@gmail.com
Anil=342=anil@gmail.com
Ajith=548=ajith@gmail.com
Aravind=998=arav@gmail.com

file2.txt
Anil=Active
Amal=Active
Ajith=Inactive
Aravind=Active
Midhun=Active

I need to add an extra column in file1.txt from file2.txt mentioning whether each of them is active or inactive and also remove lines from file2.txt which are not present in file1.txt.(for example, Midhun is not present in file1.txt. So i need to remove midhun from file2.txt)
My output file should be
output.txt
Amal=123=Active
Anil=342=Active
Ajith=548=Inactive
Aravind=998=Active

I tried the following. But it is not working.
while IFS= read -r line
do
    key=`echo $line | awk -F "=" '{print $1}'` < file1.txt
    key2=`echo $line | awk -F "=" '{print $2}'` < file1.txt
    value=`echo $line | awk -F "=" '{print $2}'` < file2.txt
    echo "$key=$key2=$value"
done

A: No need for scripting. Sort the files and then it's a simple join.
join -t= <(sort file1.txt) <(sort file2.txt)

To comply with the OP's update, let's cut only the first two fields of file1:
join -t= <(sort file1.txt | cut -d= -f-2) <(sort file2.txt)

A: EDIT: Since OP changed his requirement so adding this solution now.
awk '
BEGIN{
  FS=OFS="="
}
FNR==NR{
  a[$1]=$2
  next
}
($1 in a){
  $3=""
  sub(/=$/,"")
  print $0,a[$1]
}
'  Input_file2   Input_file1

This should be a simple task for awk, please try following.
awk 'BEGIN{FS=OFS="="} FNR==NR{a[$1]=$2;next} ($1 in a){print $0,a[$1]}' file2 file1

Explanation: Adding detailed explanation for above code here.
awk '              ##Starting awk program from here.
BEGIN{             ##Starting BEGIN section for this program from here.
  FS=OFS="="       ##Setting FS and OFS value as = here for all lines.
}                  ##Closing BLOCK for BEGIN here.
FNR==NR{           ##Checking condition FNR==NR which will be TRUE when first Input_file is being read.
  a[$1]=$2         ##Creating array a with index $1 and value $2.
  next             ##next will skip all further statements from here.
}
($1 in a){         ##Checking condition ig $1 of current line(from file1) is present in array a then do following.
  print $0,a[$1]   ##Printing current line and value of array a with index $1 of current line here.
}
' file2 file1      ##Mentioning Input_file names here.


text:
Q: zindex and child element http://jsfiddle.net/cxwQF/12/.
Note: Red and green boxes should intersect. Green box is image or video. When hover it became yellow. But not on the bottom where the red box starts. Red box is control (for example, next image).
Question. How can I put parent div behind the image and child div to the top.
Markup:

CSS:
#image {
    position: relative;
    width: 100%;
    height: 500px;
    background: green;
    z-index: 2;
}

#image:hover {
    background: yellow;
}

#parent {
    position: fixed;
    bottom: 0;
    width: 100%;
    z-index: 1;
}

/*#parent:hover {
    background: blue;
} */

#child {
    position: relative;
    margin: 0 auto;
    width: 100px;
    height: 100px;
    background: red;
    z-index: 3;
}

A: How does this suit you? It's hard to know how to structure it without knowing what you are trying to achieve.
http://jsfiddle.net/cxwQF/21/
I've created another, invisible div for your 'child' but the original (foot) remains in the same place.

Sorry about the border styles its purely for test purposes.

A: I found the pure CSS solution. Markup remains the same.
CSS:
#image {
    width: 100%;
    height: 500px;
    background: green;
}

#image:hover {
    background: yellow;
}

#parent {
    position: fixed;
    bottom: 0;
    width: 100%;
    z-index: 1;
    visibility: hidden;
}

#child:hover {
    background: pink;
}

#child {
    margin: 0 auto;
    visibility: visible;
    width: 100px;
    height: 100px;
    background: red;
}

Solution: #parent's "visibility" should be set to "hidden", #child's "visibility" should be set to "visible"
Fiddle is here: http://jsfiddle.net/cxwQF/22/


text:
Q: Location clustering in SQL Server I am working on displaying about 40,000 latitude longitude points on a map over Australia, I suspect most points are in towns but don't have data on the towns and would like to be able to cluster the points to get it to a size where I could put pins with totals on a map, to help get a better understanding of the data.
Is there some way to query to get a list of clusters with location of the cluster and count for the point at that cluster?


text:
Q: How to implement Exponential Power distribution in JAGS I would like to fit a simulated data to Exponential Power likelihood using uniform mixture with gamma mixing presented in "Scale Mixtures Distributions In Statistical Modelling" by Choy and Chan: $EP(x|\mu,\sigma,\beta) = \frac{c_1}{\sigma}exp(-|\frac{c_0^{1/2}(x-\mu)}{\sigma}|^{\frac{2}{\beta}})$, where $c_0 = \frac{\Gamma(3\beta/2)}{\Gamma(\beta/2)}, c_1=\frac{c_0^{1/2}}{\beta\Gamma(\beta/2)}$ are fixed functions of $\beta$. According to the authors the sampling hierarchy is $X|\mu,\sigma^2,\beta,u\sim U(\mu-\frac{\sigma}{\sqrt{2c_0}}u^{\beta/2},\mu+\frac{\sigma}{\sqrt{2c_0}}u^{\beta/2})$ , $u|\beta\sim Ga(1+\frac{\beta}{2},2^{-1/\beta})$. I used JAGS in R with the below codes
Y <- rnorm(1000)
N <- length(Y)
jagsscript = cat("
model{

  for(i in 1:N){
    Y[i] ~ dunif(mu - d[i], mu + d[i])
    d[i] <- tau/pow(2*c0,0.5)*pow(u[i],beta/2)
    u[i] ~ dgamma(1+beta/2,pow(2,-1/beta))
  }
  #prior
  beta ~ dunif(0.0001,2)
  sigma ~ dgamma(0.01,0.01)
  tau <- 1/sqrt(sigma)
  mu ~ dnorm(0,0.0001)
  c0 <- exp(loggam(3*beta/2)-loggam(beta/2))
}",file=model.loc)

Now I am stuck because I can't get this model to run since I might have Y observed outside of the boundaries of the uniform distribution. Is there a way to avoid this from happening or is there any better way to use JAGS to model an exponential power likelihood? Any help would be appreciated!


text:
Q: Powershell: how to fill Placeholder (Variables) from an external HTML-Document? I want to send an HTML-Email with Powershell and the Send-MailMessage Function. To keep my Code lightweigt, I have placed the HTML-Code for the Mailbody outside my Powershell-Code.
The challange is, to replace the Varibales inside the HTML-File with Powershell variables before sending the E-Mail.
The code here is not complete. I have shortened it to clarify the problem.
body.htm
<html>
<body>
<h1> Hello $Salutation! </h1>
</body>
</html>

myscript.ps1
$MailBody = Get-Content body.htm -Raw
$Salutation = "Foo Bar!"

$MailMessageParam = @{
            "Subject"     = "Mail from Powershell!"
            "Encoding"    = "UTF8"
            "Body"        = $MailBody
            "BodyAsHtml"  = $true
        }

Send-MailMessage @MailMessageParam

My Problem is, that the Variable $Salutation will not be filled. The $MailBody Variables behaves like a Passthrough. Any idea how to solve this?

A: One solution I can think of is to replace the $Salutation with a placeholder and use the format operator to format it. So change body.htm to
<html>
<body>
<h1> Hello {0}! </h1>
</body>
</html>

And then in the hashtable($MailMessageParam) set,
"Body" = ($MailBody -f $Salutation)

Alternatively you can just use ExpandString method which returns a string with all of the variable and expression substitutions done.
"Body" = $ExecutionContext.InvokeCommand.ExpandString($MailBody)

A: Awesome! $ExecutionContext.InvokeCommand.ExpandString($MailBody) solved it!


text:
Q: How to fit a quadratic equation to a plot obtained from plotmeans function in R We are analyzing fixed effects heterogeneity across years of a panel database ("mydata") containing values of an economic explained value depending on 12 independent variables. Data correspond to the period 2007-2017 and 142 countries. We use function plotmeans from package gplots being the script as follows:
plotmeans(D ~ Year, main="Heterogeineity across years", data=mydata)

We obtain the graph hereunder:

Is there any function/script on R that can fit the obtained plot into a quadratic curve providing its equation coefficients?

A: First, fit a quadratic curve:
df <- data.frame(year = c(1,2,3,4,5,6,7,8,9),
                 D = c(35,26,19,6,1,3,5,12,17))

fit<-lm(D~poly(year,2,raw=TRUE), df)

> summary(fit)

Call:
lm(formula = D ~ poly(year, 2, raw = TRUE), data = df)

Residuals:
   Min     1Q Median     3Q    Max
-2.987 -1.872 -0.039  1.545  4.305

Coefficients:
                           Estimate Std. Error t value Pr(>|t|)
(Intercept)                  52.786      3.400   15.53  4.5e-06 ***
poly(year, 2, raw = TRUE)1  -17.103      1.561  -10.96  3.4e-05 ***
poly(year, 2, raw = TRUE)2    1.469      0.152    9.65  7.1e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.67 on 6 degrees of freedom
Multiple R-squared:  0.959, Adjusted R-squared:  0.946
F-statistic: 71.1 on 2 and 6 DF,  p-value: 6.65e-05

Next count the value of year estimation:
quadratic = fit$coefficient[3]*df$year^2 + fit$coefficient[2]*df$year + fit$coefficient[1]

At last fit a quadratic curve:
plot(df$year,df$D, main="Heterogeineity across years",
     xlab="Year ", ylab="D")
par(new = TRUE)
lines(df$year,quadratic, col="red")

Output:

Please note: We don't have your data.

A: A quadratic fit is quite straightforward in R using the linear model lm function with a quadratic term. The I() function (as is) is necessary to inhibit symbolic interpretation of the "^" operator and simplification the quadratic term. summary (or coef) print the coefficients and predict can be used to plot the curve:
## an example data set with 5 replicates
set.seed(123)
mydata <- data.frame(
  Year = rep(2007:2017, each=5),
  D = rep(c(56, 60, 64, 63, 65, 65, 64, 63, 64, 63, 62), each=5) + rnorm(55)
)

## fit a quadratic model
m <- lm(D ~ Year + I(Year^2), data = mydata)

summary(m)
coef(m)

plot(D ~ Year, data = mydata)
lines(mydata$Year, predict(m))

To do the same with plotmeans it is necessary to adjust the x scale.
library(gplots)
plotmeans(D ~ Year, main="Heterogeineity across years", data=mydata)

## plotmeans chances the x axis scale, so we
## need to subtract 2006, so that year 2007 is the first in plotmeans
lines(mydata$Year - 2007 + 1, predict(m), col="red")


text:
Q: How to implement remember me in JSP login page in Spring MVC? I am new to Spring MVC and Cookies thing. I have a login JSP page, in that I am trying to implement a remember me checkbox. Through this a user, whosoever it may, not need to enter their login details every time. Login and password should be saved so that user get a flexibility to not to enter login details every time they visit the application login. I have written my login.jsp and AdminController class below. In AdminController class, I have found somewhere to add cookie thing to persist the login credentials of visitors. But, I have no idea how to implement this thing in my controller class. I have tried this below code but it is not working as expected. Any suggestions may appreciated.
<form action="verify" method="post" name="myform" onsubmit="return validateform()">

 Login Here

                        <input type="text" name="username" placeholder="Email or Phone Number" required="required"/>

                        <input type="password" placeholder="Password" name="password" required />

                    <input type="submit" name="Login" class="btn submit" value="Login"/>

                        <input type="checkbox" checked="checked" name="remember"> Remember Me

                </form>

public User checkCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        User account = null;
        String username = "", password = "";
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase("username")) {
                username = cookie.getValue();
                System.out.println("Username: "+username);
            }
            if (cookie.getName().equalsIgnoreCase("password")) {
                password = cookie.getValue();
            }
        }
        if (!username.isEmpty() && !password.isEmpty()) {
            account = new User();
            System.out.println("User account: "+account);
        }
        return account;
    }
@RequestMapping(value = { UrlPath.adminlogin }, method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView adminlogin(HttpServletRequest request, User user, HttpSession session, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView(UrlPath.adminlogin);
        User usermodel = checkCookie(request);
        if(usermodel == null) {
            modelAndView.addObject("user", new User());
            return modelAndView;
        } else {
            User newuser = new User();
            if(newuser.getUsername() != null && newuser.getPassword() != null) {
                session.setAttribute("username", usermodel.getUsername());
                if (request.getParameter("remember") != null) {
                Cookie ckUsername = new Cookie("username", usermodel.getUsername());
                ckUsername.setMaxAge(3600);
                response.addCookie(ckUsername);
                Cookie ckPassword = new Cookie("password", usermodel.getPassword());
                ckPassword.setMaxAge(3600);
                response.addCookie(ckPassword);
                }
            }
        }
        return modelAndView;
    }


text:
Q: What is the purpose of Concurrent API limit? As per the Salesforce Documentation, the Concurrent API limit is a limit for concurrent inbound requests (calls) with a duration of 20 seconds or longer and it differs based on the org type:

*

*Developer Edition and Trial orgs - 5 requests limit

*Production orgs and Sandboxes - 25 requests limit

Also, as per this Salesforce Documentation, we have Maximum CPU time on the Salesforce servers limit, which differs based on the type of the transaction:

*

*Synchronous - 10 seconds

*Asynchronous - 60 seconds

*

*What is the purpose of the Concurrent API limit and why is it so low
(strict), given that some Salesforce orgs might receive tens of calls
from external systems every second?

*If the incoming call is Request and Reply, calling e.g. some custom Apex Class that executes a complex logic and waiting for it to finish to receive a response, the transaction throws an exception after 10 seconds, meaning that the call to Salesforce won't be able to get to 25 seconds. If some logic in the Apex Class executes as asynchronous (using Queueable, Batchable or @future annotation), it processes in a different transaction and the result is not returned to the client calling Salesforce, meaning that this would also not be a reason to reach the limit of 25 seconds. What could be the scenarios of reaching the Concurrent API limit?

A: 1. What is the purpose of the Concurrent API limit and why is it so low?
As per the documentation you referenced:

To maintain optimum performance and ensure that the Lightning Platform API is available to all our customers, Salesforce balances transaction loads by imposing ... limits.

So fundamentally this is one of the limits imposed to prevent a given org from blocking the HTTP based API resources from use by other tenants on the same host. There are only so many connections that can be maintained concurrently by the server.
It is low, I suggest, because the pool of connections is relatively small compared with the number of tenants that can be sharing the same server.
Note that this suggests you write your custom REST API code to avoid long-running actions.
2. The transaction throws an exception after 10 seconds, meaning that the call to Salesforce won't be able to get to 25 seconds?
There are other operations in a transaction that take time but that do not contribute to CPU limits. Two such examples are:

*

*SOQL query time (these can take a long time if you have poorly optimized queries or large data volumes without appropriate custom indexes or skinny tables).

*Time spent waiting for callouts to complete.


text:
Q: Reliable Key-Value File-Based Storage with/without XA Transactions Problem
I'm currently implementing a solution for one pretty old system, which needs a lightweight key-value file-based (a value for a key is stored as a file) storage with simple ConcurrentHashMap-like operations: put(), delete(), get() and listAll() operations.
It has to privide an ability to have concurrent read and write operations with a fully-featured transactional behavior (ACID + repeatable read isolation).
Seems like this component should look pretty similar to the TableFS...
Approach
An initial idea is to take a lightweight embeddable persistent key-value storage  and use it to store a metadata for the value files located in a file system (file key, file path, size, other attributes...). Also, it should provide a quick file searching engine, based on indexes. So that, such storage plays a role of a register...
I have been searching for quite a while for such the key-value storage that can meet the following requirements:

*

*Open source;

*Embeddable;

*Provide a support for Java maps and collections;

*Machine crash/power-off tolerance (write-ahead logs and other approaches);

*Providing ACID transaction;

*Being a read-write storage (comparing to the read-only PalDB).

and came up with the MapDb and LevelDb options.
As far as I need to ensure the concurrency resolution for those read/write user transactions, I need to establish global XA transactions, involving the key-value storage and a file system. For the file system there are the XADisk and Jakarta Commons-Transactions transaction systems, also for the global archestration there is the Atomikos Essintials transaction manager.
However, I cannot find any article that explains how to configure the MapDB or LevelDB with an XA transaction manager...
Questions
Could you please suggest on the following?

*

*whether my approach makes sense or there are some well-known solutions/implementations for the described problem?

*what pitfall can you see in this task/approach?

*are there any resources that describe how to configure such key-value storages for participating in xa transactions?

Updates
There is another database - SQLite - which can be integrated with Atomikos. It does not mimic Java collections, but it is pretty easy to emulate all the opeations manually. The only pitfall that I can see for now, is the way of resolving concurrent key modifications by concurrent transactions (lost update problem). Seems like there would be a requirement of writing a kind of stored procedure with the test-and-set feature based on a key's timestamp...

A: Ok, finally, I worked out an idea for implementing my task, even without XA transactions, file locks and other over-complications.
If somebody is interested, please have a look at my project at GitHub, following this link. The description would be added soon to the GitHub project. Hope, for now, the code is self-explanatory.


text:
Q: Laptop makes loud noise when an external display is connected I've a MSI GS63VR 7RF laptop with a GTX 1070, and suddenly it has started making a loud noise that resembles the noise that printers make while printing some document.
It seems that when I disconnect the secondary monitor this noise stops.
I've been searching without any result, because I found GPU coil whine, but seems to be a different issue.
Also I read about disabling vsync, but doing so didn't affect the noise.
What can be this issue and how to solve it?


text:
Q: Can a transition in DFSA have a power? The Σ is {l,r,u,d} where α ∈ Σ which denote the gamepad controllers (l = left, r = right, u = up and d = down) whilst Strings s, t, ... over Σ⋆ thus denote sequence of commands on the gamepad.
Have a question in regards to the following:
Assume the predicate even :: N -> B that returns true for all the even natural numbers 0, 2, 4 ... and false otherwise.
Design a DFSA M that only accepts the gamepad command language L = { s | s ∈ Σ* and even(lefts(s))}
My question is whether or not transitions can have a power or not, the transitions in M are for example l^n such that n is even.
Can this be done? If not what is the way to tackle such a question?
(ii) Besides that I would like to ask what is the difference between s ∈ L and s ∈ L(M)
TIA
Actual Question
ii


text:
Q: How to debug servlet in eclipse i am using out.print("bug"); at various points in my servlet but the output is not received on the console.
There are no log files either, double clicking on server name in servers tab shows debug logging is not supported in this version of tomcat.
What can i do now to debug my servlet ?


text:
Q: Replacing Files while copying In Win 7, when copying a file "ABC.def" into a folder that already contains a file with the same name, the new file is copied with a "(2)" next to the name. Like this: "ABC (2).def" No popup to select whether to replace or leave both files is displayed. I want to know where is the setting to prevent keeping both files.

A: Are you using Teracopy or any other shell extensions that manage/take over file operations?
If you are, I would look in the settings of that application, however if you are using Explorer / normal drag and drop or similar, this is not normal behaviour, and I am not sure what is going on.
You should be seeing something like this:

If you are not then, please reply with the steps you use to copy the file.


text:
Q: wp_count_posts on all post types? I have 5 different custom post types, Is there any way to count all the publish posts regardless of post_type through any inbuilt functions
Like
wp_count_posts(array('post','books','video'))

any ideas

A: To get the custom post types you would call the get_post_types function.The built-in public post types are post, page, and attachment. By setting '_builtin' to false, we will exclude them and show only the custom public post types. Below is the code.
 <?php
$args = array(
'public'   => true,
'_builtin' => false
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator );
foreach ( $post_types  as $post_type ) {
   $count_posts = wp_count_posts($post_type);
   $published_posts = $published_posts+$count_posts->publish;
}
echo $published_posts;
?>

A: function get_total_posts(){
    $total_posts += (int) wp_count_posts('post')->publish;
    $total_posts += (int) wp_count_posts('page')->publish;
    $total_posts += (int) wp_count_posts('custom')->publish;
    $total_posts += (int) wp_count_posts('other_type')->publish;
    return $total_posts;
}

A: I use to add all post
$total_codes = wp_count_posts(codes);
$total_themes = wp_count_posts('themes');

$codes_count = $total_codes->publish;
$themes_count = $total_themes->publish;
$sum_total = $codes_count + $themes_count;

print ($direct_text . $sum_total);

A: Just try this and reply whether it worked out this will give all pusblish posts ..
<?php
// Get all published pages
$published_pages = wp_count_posts()->publish;
echo 'Total published posts: ' . $published;
?>


text:
Q: mysql query run only for numbers     $username = $_POST['username'];
    $password = $_POST['password'];
    $passworda = $_POST['passworda'];
    $email = $_POST['email'];

    if ($password == $passworda){
        echo 'this is the user name to be chacked:' .$username .'
';
        $query = "SELECT username FROM mishta where username=$username";
        $queryrun = mysql_query($query);
        echo $queryrun .'
';
        echo mysql_num_rows($queryrun) .'
';

        if (mysql_num_rows($queryrun)!=1){
            mysql_query("INSERT INTO mishta(id, username, password, email) VALUES ('', '$username','$password','$email')");
        }
        else{
            echo 'user already exist';
        }

Hello there,
I'm trying to make a simple registration form, I get useername from html form and I want to make sure it doesn't already exist in my database.
the thing is that whenever I run the username as a number (1,2,3...) it runs smoothly.
but, when I try to write anything with letter, like Bob or Dora I get the following error:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in...
Yet the information is still being stored my my data base, means it got false on the last if statement, and it will continue to get false (It will just insert duplicates if I try again).
Any help would be appreciated.

A: You forgot the quotes around the username:
$query = "SELECT username FROM mishta where username='$username'"

Quotes are used as string delimiter. Numbers are not string and it works if you use a number.


text:
Q: JQuery DatePicker Default Date 18 years ago I'm trying to get my jquery datepicker to default to open on 18 years in the past (user must be 18 or over to use app) and I don't want them to be able to select any date that isn't 18 years or more in the past. I have this code but I can't get it to work apart from showing the default todays date. Any help would be appreciated. Thanks.
<link rel="stylesheet" type="text/css" href="css/datepicker.css">
<script type="text/javascript" src="js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$("#datepicker").datepicker("setDate",'1998-01-01');
$(document).ready(function() {

    $('#datepicker').datepicker().on('changeDate', function(ev){
        $(this).datepicker('hide');
    });
});
</script>

A: Create the datepicker by datepicker method and setDate
 $( "#datepicker" ).datepicker();
$("#datepicker").datepicker('setDate','01/01/1998');

http://codepen.io/nagasai/pen/kXyoqb


text:
Q: I'm getting an Uncaught TypeError : Cannot read property 'type' of undefined I'm trying to read a form and store data in database.
I'm using SQL server database. When I execute the following code it gives me an uncaught error [TypeError: Cannot read property 'type' of undefined].
I have checked every variable and none of them have an undefined value. I'm having trouble figuring it out please help.
var express = require('express');
var router = express.Router();
var sql = require('mssql');

router.post('/',function(req,res,next){
   //Fetching form variables
   var ProfCreatedby =req.body.ctl00$ContentPlaceHolder1$DDLProfileCreatedBy;
   var title =req.body.ctl00$ContentPlaceHolder1$DDLTitle;
   var Fname =req.body.ctl00$ContentPlaceHolder1$txtFname;
   var Mname =req.body.ctl00$ContentPlaceHolder1$txtMname;
   var Lname =req.body.ctl00$ContentPlaceHolder1$txtLname;
   var dob =req.body.ctl00$ContentPlaceHolder1$txtDateofBirth;
   var Btime =req.body.ctl00$ContentPlaceHolder1$txtBirthTime;
   var gender =req.body.ctl00$ContentPlaceHolder1$DDLGender;
   var religion =req.body.ctl00$ContentPlaceHolder1$DDLReligion;
   var caste =req.body.ctl00$ContentPlaceHolder1$DDLCaste;
   var education =req.body.ctl00$ContentPlaceHolder1$DDLEducationCatogery;
   var degree =req.body.ctl00$ContentPlaceHolder1$DDLEducationDegree;
   var EduDetail =req.body.ctl00$ContentPlaceHolder1$txtEDucationalDetails;
   var Mtounge =req.body.ctl00$ContentPlaceHolder1$txtMotherTongue;
   var Address1 =req.body.ctl00$ContentPlaceHolder1$txtAddress1;
   var Address2 =req.body.ctl00$ContentPlaceHolder1$txtAddress2;
   var City =req.body.ctl00$ContentPlaceHolder1$txtCity;
   var District =req.body.ctl00$ContentPlaceHolder1$txtDistrict;
   var Country =req.body.ctl00$ContentPlaceHolder1$DDLCountry;
   var State =req.body.ctl00$ContentPlaceHolder1$DDLState;
   var PIN =req.body.ctl00$ContentPlaceHolder1$txtPinCode;
   var Phone =req.body.ctl00$ContentPlaceHolder1$txtPhoneNo;
   var Mobile =req.body.ctl00$ContentPlaceHolder1$txtMobileNo;
   var Email =req.body.ctl00$ContentPlaceHolder1$txtEmailId;
   var Height =req.body.ctl00$ContentPlaceHolder1$DDLHeight;
   var Weight =req.body.ctl00$ContentPlaceHolder1$DDLWeight;
   var Built =req.body.ctl00$ContentPlaceHolder1$DDLBuilt;
   var Complexion =req.body.ctl00$ContentPlaceHolder1$DDLComlixation;
   var BGroup =req.body.ctl00$ContentPlaceHolder1$DDLBloodGroup;
   var PhyDisable =req.body.ctl00$ContentPlaceHolder1$DDLPhyscalyDisable;
   var Intercaste =req.body.ctl00$ContentPlaceHolder1$DDLIntercaste;
   var RforA =req.body.ctl00$ContentPlaceHolder1$DDLReadyForAbroad;
   var Mstatus =req.body.ctl00$ContentPlaceHolder1$DDlMarrigeStatus;
   var ChildIfAny =req.body.ctl00$ContentPlaceHolder1$DDLChildIfAny;
   var AboutMe =req.body.ctl00$ContentPlaceHolder1$txtAboutMe;
   var Expectation =req.body.ctl00$ContentPlaceHolder1$txtExpectionFromPartner;

   // database configuration
   var config = {
       user:'USER',
       password:'PASSWORD',
       server: 'SERVER',
       database: 'DATABASE'
   };
   sql.connect(config).then(function(){
       // input variables for stored procedure
       var request = new sql.Request();
       request.input('@Username',sql.VarChar(256),'ChetanAngari');
       request.input('@ProCreateBy',sql.VarChar(50),profCreatedby);
       request.input('@Title',sql.VarChar(6),title);
       request.input('@Fname',sql.VarChar(50),Fname);
       request.input('@Mname',sql.VarChar(50),Mname);
       request.input('@Lname',sql.VarChar(50),Lname);
       request.input('@DOB',sql.datetime,dob);
       request.input('@DOBTime',sql.Varchar(10),Btime);
       request.input('@Gender',sql.VarChar(6),gender);
       request.input('@Religion',sql.VarChar(50),religion);
       request.input('@Caste',sql.VarChar(50),caste);
       request.input('@EduCate',sql.VarChar(25),education);
       request.input('@Degree',sql.VarChar(25),degree);
       request.input('@EduDetail',sql.VarChar(50),EduDetail);
       request.input('@MotherTonge',sql.VarChar(50),Mtounge);
       request.input('@Add1',sql.VarChar(100),Address1);
       request.input('@Add2',sql.VarChar(100),Address2);
       request.input('@City',sql.VarChar(50),City);
       request.input('@Distric',sql.VarChar(50),District);
       request.input('@State1',sql.VarChar(50),State);
       request.input('@Country',sql.VarChar(50),Country);
       request.input('@PIN',sql.VarChar(50),PIN);
       request.input('@PhNo',sql.VarChar(25),Phone);
       request.input('@MobNo',sql.VarChar(25),Mobile);
       request.input('@Email',sql.VarChar(100),Email);
       request.input('@Ht',sql.Int,Number(Height));
       request.input('@Wt',sql.VarChar(25),Weight);
       request.input('@Built',sql.VarChar(25),Built);
       request.input('@Color',sql.VarChar(25),Complexion);
       request.input('@BldGrp',sql.VarChar(4),BGroup);
       request.input('@PhyDis',sql.VarChar(3),PhyDisable);
       request.input('@IntCaste',sql.VarChar(3),Intercaste);
       request.input('@GoToForeign',sql.VarChar(3),RforA);
       request.input('@MamKul',sql.VarChar(50),'ChetanAngari');
       request.input('@NCKul',sql.VarChar(50),'ChetanAngari');
       request.input('@MStatus',sql.VarChar(20),Mstatus);
       request.input('@Child',sql.Int,parseInt(ChildIfAny));
       request.input('@AboutMe',sql.VarChar(200),AboutMe);
       request.input('@ExpPart',sql.VarChar(200),Expectation);
       request.input('@PhPath1',sql.VarChar(100),'ChetanAngari');
       request.input('@PhLogo',sql.VarChar(100),'ChetanAngari');
       request.input('@ProType',sql.VarChar(1),'C');
       request.input('@PhVerficationPending',sql.VarChar(1),'C');
       request.input('@ProCrtDt',sql.datetime,Date.now());
       request.input('@ProEndDt',sql.datetime,Date.now());
       request.input('@Visible',sql.VarChar(1),'C');
       request.input('@CUser',sql.VarChar(50),'ChetanAngari');
       request.input('@AdminLock',sql.VarChar(1),'C');
       request.execute('STORED PROCEDURE',function(err,recordsets,returnValue){
           if(err) console.log(err);
           console.dir(recordsets);
           console.log(returnValue);
           console.log('Command Success..');
       });
   }).catch(function(err){
       console.log(err);
   });
   res.end();
});
module.exports = router;

Below is the Stack trace....
TypeError: Cannot read property 'type' of undefined
at Request.input (C:\Users\Ishant\Documents\NodeWork\OceanTech\BouddhaLifePartnerMarriage\node_modules\mssql\lib\main.js:1257:19)
at C:\Users\Ishant\Documents\NodeWork\OceanTech\BouddhaLifePartnerMarriage\routes\UserInfoUpdate.js:62:20
at process._tickCallback (node.js:406:9)

A: I know this is crazy old, but I had the same problem and in case anyone else comes across it I found that it was actually a case sensitivity issue in the typing variable of the .input.  You have request.input('@DOB',sql.datetime,dob); it should be request.input('@DOB',sql.DateTime,dob); with the "D" and the "T" capitalized.