text:
Q: Seg. fault when initialising a variable using a method initialised during same initialising list Why does this gives seg. fault. Clearly it is due to my way of initialising partners_ in C1 , but I am not sure why it is not allowed  like this
#include <memory>
#include <vector>
class C2{
  std::vector<int> partners_;
  public:
  C2(){
   partners_.resize(10);
   for( auto& n: partners_ ) n = 1;

   }
   public:
   const std::vector<int>& GetPart( void )const
   {
     return partners_;
   };
};

class C1{

   private:

   const std::vector<int>& partners_;
   const std::unique_ptr<const C2>& C2METHOD;
   public:
   C1(const std::unique_ptr<const C2>& C2METHOD_) : C2METHOD(C2METHOD_), partners_(C2METHOD->GetPart()) { }

};

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

   auto TaskDivider = std::make_unique<const C2>(  );
   auto shm     = std::make_unique<C1>( TaskDivider ) ;

};


text:
Q: how to add data in a mysql table so i was creating a menu option where user enters some data and using a function all of that data is added to a MySQL table however the data table is not being updated properly
I have checked there is nothing wrong with the table created so I think the problem lies in the code somewhere
import mysql.connector
def add_det(x1, x2, x3, x4):
                global icode, iname, price, quantity
                try:
                    conn=mysql.connector.connect(host='localhost', database='practicals', user='root', password='root1')
                    cursor=conn.cursor()
                    print("cursor objected created")
                    sql = """#INSERT INTO inventory(item_code, item_name, price, quantity) VALUES (%s,%s,%s,%s)"""
                    t=(x1, x2, x3, x4)
                    print(t)
                    cursor.execute(sql)
                    conn.commit()
                    print(cursor.rowcount, "Records inserted")
                except mysql.connector.Error as e:
                    print("Failed to get record from Mysql table: {}", format(error))
                finally:
                    if conn.is_connected():
                        print("closing...")
                        cursor.close()
                        conn.close()
                        print("Mysql connection is closed")
            add_det(icode, iname, price, quantity)

could anyone pls help me in finding the error?

A: What happens when you remove the # in front of your SQL query?
Or try to change your code with:
sql = """#INSERT INTO inventory(item_code, item_name, price, quantity)
    VALUES ({}, {}, {}, {})""".format(
    x1, x2, x3, x4
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Boehm-Demers-Weiser garbage collector not finding lgc I'm trying to compile a C file and I get this error:
gcc -g -ansi -pedantic -Wall -D_C_SOURCE=1 -DGC_BDW  -static  interp.o
scan.o  utils.o  main.o  -L gc/.libs -lgc  -lm  -o joy
/usr/bin/x86_64-linux-gnu-ld: cannot find -lgc

I've already installed the Boehm-Demers-Weiser garbage collector.
Any ideas?
This is what I'm trying to compile: https://github.com/xieyuheng/joy
In joy-master/src I cloned and installed the repo of gc following this: https://github.com/ivmai/bdwgc


text:
Q: how to convert mix of text and numerical data to feature data in apache spark I have a CSV of both textual and numerical data. I need to convert it to feature vector data in Spark (Double values). Is there any way to do that ?
I see some e.g where each keyword is mapped to some double value and use this to convert. However if there are multiple keywords, it is difficult to do this way.
Is there any other way out? I see Spark provides Extractors which will convert into feature vectors. Could someone please give an example?
48, Private, 105808, 9th, 5, Widowed, Transport-moving, Unmarried, White, Male, 0, 0, 40, United-States, >50K
42, Private, 169995, Some-college, 10, Married-civ-spouse, Prof-specialty, Husband, White, Male, 0, 0, 45, United-States, <=50K

A: Finally I did this way. I iterate through each data and make a map with key as each item and increment a Double counter.
def createMap(data: RDD[String]) : Map[String,Double] = {
 var mapData:Map[String,Double] = Map()
 var counter = 0.0
 data.collect().foreach{ item =>
  counter = counter +1
  mapData += (item -> counter)
 }
 mapData
}

def getLablelValue(input: String): Int = input match {
 case "<=50K" => 0
 case ">50K" => 1
}

val census = sc.textFile("/user/cloudera/census_data.txt")
val orgTypeRdd  = census.map(line => line.split(", ")(1)).distinct
val gradeTypeRdd = census.map(line => line.split(", ")(3)).distinct
val marStatusRdd = census.map(line => line.split(", ")(5)).distinct
val jobTypeRdd = census.map(line => line.split(", ")(6)).distinct
val familyStatusRdd = census.map(line => line.split(", ")(7)).distinct
val raceTypeRdd = census.map(line => line.split(", ")(8)).distinct
val genderTypeRdd = census.map(line => line.split(", ")(9)).distinct
val countryRdd = census.map(line => line.split(", ")(13)).distinct
val salaryRange = census.map(line => line.split(", ")(14)).distinct

val orgTypeMap = createMap(orgTypeRdd)
val gradeTypeMap = createMap(gradeTypeRdd)
val marStatusMap = createMap(marStatusRdd)
val jobTypeMap = createMap(jobTypeRdd)
val familyStatusMap = createMap(familyStatusRdd)
val raceTypeMap = createMap(raceTypeRdd)
val genderTypeMap = createMap(genderTypeRdd)
val countryMap = createMap(countryRdd)
val salaryRangeMap = createMap(salaryRange)

val featureVector = census.map{line =>
  val fields = line.split(", ")
 LabeledPoint(getLablelValue(fields(14).toString) , Vectors.dense(fields(0).toDouble,  orgTypeMap(fields(1).toString) , fields(2).toDouble , gradeTypeMap(fields(3).toString) , fields(4).toDouble , marStatusMap(fields(5).toString), jobTypeMap(fields(6).toString), familyStatusMap(fields(7).toString),raceTypeMap(fields(8).toString),genderTypeMap (fields(9).toString), fields(10).toDouble , fields(11).toDouble , fields(12).toDouble,countryMap(fields(13).toString) , salaryRangeMap(fields(14).toString)))
}


text:
Q: After installing VS 2015 Update 2, IIS Express closes when I stop debugging This problem occurs despite unchecked 'Enable Edit & Continue`:

A: You have to use Debug -> Detach All button instead.
How to add "Detach All" button inside of "Stop":
1-
2-
3-
4-
Update:
In Visual Studio 2015 Update 3 you have Enable Edit & Continue in project's properties again.

A: This issue has been resolved in Visual Studio 2015 Update 3.  Read the release notes here.
Web Developer Tools

For ASP.NET Web Application projects, when "Enable Edit and Continue" checkbox is unchecked, the IIS Express process will no longer stop
  every time you stop debugging.

A: This work-around is working for me. Instead of hitting the "Stop" debugging button, go to the Debug menu item and select "Detach All". This will detach VS from IIS Express, but leave it up and running.


text:
Q: What time do the daily quests reset? What time do daily quests reset?  Is it the same time per server (going by server time), per region, or is it a timer per person?

A: I am told: 7 AM EST (with weeklies resetting Tuesday).
Further more, it is my understanding this is universal (6 AM CST, 1 PM CET).

A: Tested today for you:
7AM server time on Space Slug.
US West Coast server.
Hope this helps.


text:
Q: notifyItemMoved() not working when migrated to ListAdapter Android We have this feature in our App where we can drag recycler view Items up and down.
Inside onMove() of ItemTouchHelper.Callback() we call
adapter.onItemMove(source.adapterPosition, target.adapterPosition)

and the adapter code goes like this
override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
    Collections.swap(dataList, fromPosition, toPosition)
    notifyItemMoved(fromPosition, toPosition)
    return true
}

Now, earlier adapter class was extending RecyclerView.Adapter() and we have following method to update our list using DiffUtils
fun setDataList(feeds: List<User>): DiffUtil.DiffResult {
    val diffResult = DiffUtil.calculateDiff(ContentDiffCall(mFeeds, feeds))
    this.mFeeds.clear()
    this.mFeeds.addAll(feeds)
    return diffResult
}

Drag and drop were working fine with this.
But when we have extended our adapter class from ListAdapter, the already working functionality(drag and drop) is breaking. The first item in the recycler view is not dragging beyond the second item and also position item dragged is not getting updated.
Reverting ListAdapter implementation makes it work again.
Couldn't understand why is this not working when ListAdapter itself extends RecyclerView.Adapter.
Adapter class
class ContentListAdapter(
private val headerListener: HeaderClickListener?,
private val listener: ListItemClickListener?,
private val screen: Screen,
private val feedInteractor: FeedInteractionManager
) : ListAdapter<BaseUiModel, RecyclerView.ViewHolder>(ContentListDiffCall()), ContentTouchHelperAdapter {

private var dataList = ArrayList<BaseUiModel>()

init {
    setHasStableIds(true)
}

fun setDataList(data: List<BaseUiModel>) {
    dataList.clear()
    dataList.addAll(data)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    return when (viewType) {
        HFType.CONTENT_LIST_HEADER.ordinal -> ContentListHeaderViewHolder.getInstance(
            parent,
            headerListener,
            R.layout.layout_content_list_header,
            screen
        )
        HFType.SONG.ordinal -> SongViewHolder.getInstance(parent, listener)
        else -> throw RuntimeException("there is no type that matches the type $viewType ; make sure your using types correctly")

    }
}

override fun getItemViewType(position: Int): Int {
    return getItem(position).hfType.ordinal
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    val data = getItem(position)
    when (holder) {
        is SongViewHolder -> {
            if (data is SongUiModel) {
                holder.bindViews(data)
            }
        }
        is ContentListHeaderViewHolder -> {
            if (data is HeaderUiModel) {
                holder.bindViews(data)
            }
        }
    }
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList<Any>) {
    if (payloads.isEmpty()) {
        onBindViewHolder(holder, position)
        return
    }
    val data = getItem(position)
    when (holder) {
        is SongViewHolder -> {
            if (data is SongUiModel) {
                holder.bindViews(data, payloads)
            }
        }
        is ContentListHeaderViewHolder -> {
            if (data is HeaderUiModel) {
                holder.bindViews(data, payloads)
            }
        }
    }
}

override fun getItemId(position: Int): Long {
    val data = getItem(position)
    return data.hashCode().toLong()
}

override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
    Collections.swap(dataList, fromPosition, toPosition)
    notifyItemMoved(fromPosition, toPosition)
    return true
}

override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
    super.onViewAttachedToWindow(holder)
    if (holder is HomeFeedViewHolder<*>) {
        holder.onHolderAttachedInViewPort()
    }
}

}
interface ContentTouchHelperAdapter {
      fun onItemMove(fromPosition: Int, toPosition: Int): Boolean
}

Code snippet inside fragment
private fun setUpRecyclerView() {
    rv_item_list.apply {
        layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        recycledViewPool.setMaxRecycledViews(HFType.SONG.ordinal, 12)
     recycledViewPool.setMaxRecycledViews(HFType.CONTENT_LIST_HEADER.ordinal, 1)
    }

    val spaceItemDecorator = ContentListSpaceDecorator(25.dpToPx())
    rv_item_list.addItemDecoration(spaceItemDecorator)

    adapter = ContentListAdapter(this, this, this, screen, this)
    rv_item_list.adapter = adapter

    val callback = SimpleTouchListener(adapter, contentListViewModel)
    itemTouchHelper = ItemTouchHelper(callback)
    itemTouchHelper.attachToRecyclerView(rv_item_list)

  }

SimpleTouchListener class
class SimpleTouchListener(
    private val listAdapter: ContentListAdapter,
    private val viewModel: ContentListViewModel
) :
    ItemTouchHelper.Callback() {
    private var fromPosition: Int? = null
    private var toPosition: Int? = null

    override fun isLongPressDragEnabled(): Boolean {
        return false
    }

    override fun isItemViewSwipeEnabled(): Boolean {
        return false
    }

    override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
        var dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
        if (viewHolder is ContentListHeaderViewHolder) {
            dragFlags = 0
        }
        return makeMovementFlags(dragFlags, 0)
    }

    override fun onMove(
        recyclerView: RecyclerView,
        source: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        if (source.itemViewType != target.itemViewType) {
            return false
        }
        if (fromPosition == null) {
            fromPosition = source.adapterPosition
        }
        toPosition = target.adapterPosition
        listAdapter.onItemMove(source.adapterPosition, target.adapterPosition)
        return true
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, i: Int) {
        // Notify the adapter of the dismissal
    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            if (viewHolder is ItemTouchHelperViewHolder) {
                val itemViewHolder = viewHolder as ItemTouchHelperViewHolder?
                itemViewHolder?.onItemSelected()
            }
        }
        super.onSelectedChanged(viewHolder, actionState)
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
        if (viewHolder is ItemTouchHelperViewHolder) {
            // Tell the view holder it's time to restore the idle state
            val itemViewHolder = viewHolder as ItemTouchHelperViewHolder
            itemViewHolder.onItemClear()
        }
        if (fromPosition != null && toPosition != null) {
            //This method updates the list ordering in DB
            viewModel.onContentPositionChange(fromPosition, toPosition)
        }
        fromPosition = null
        toPosition = null
    }
}

we call setAdapterMethod from an observer on Success
private fun setAdapterData(contentList: List<BaseUiModel>?) {
    contentList?.let { it ->
        adapter.setDataList(it)
        adapter.submitList(it)
    }
}

A: ListAdapter updates its content through submitList function:
/**
* Submits a new list to be diffed, and displayed.
* <p>
* If a list is already being displayed, a diff will be computed on a background thread, which
* will dispatch Adapter.notifyItem events on the main thread.
*
* @param list The new list to be displayed.
*/
public void submitList(@Nullable List<T> list) {
    mDiffer.submitList(list);
}

Then you can just call:
listAdapter.submitList(updatedList)


text:
Q: A conjecture about quadratic residues given $p \equiv 5 \pmod 8$ Original Problem
$p$ is a prime that is congruent to $5$ modulo $8$ and $a$ is a quadratic residue modulo $p$.
Prove that excactly one of $x_1=a^{\frac{p+3}{8}},x_2=(2a)(4a)^{\frac{p-5}{8}}$ is the solution to the congruence $x^2 \equiv a \pmod p$.
What I have already proved
$x_1^2 \equiv a \pmod p$ if $a^{\frac{p-1}{4}} \equiv 1 \pmod p$.
$x_2^2 \equiv a \pmod p$ if $a^{\frac{p-1}{4}} \equiv -1 \pmod p$.
Corollary
Assume that $a \equiv r \pmod p,\quad (1\leq r\leq p-1)$. Then $a^{\frac{p-1}{4}} \equiv r^{\frac{p-1}{4}} \pmod p$, and hence
(a). $x_1^2 \equiv a \pmod p$ if $r^{\frac{p-1}{4}} \equiv 1 \pmod p$.
(b). $x_2^2 \equiv a \pmod p$ if $r^{\frac{p-1}{4}} \equiv -1 \pmod p$.
Examining the cases where $p=5$ and $p=13$, I came up with a conjecture.
Conjecture
(I). $r^{\frac{p-1}{4}} \equiv 1 \pmod p$ if $r$ is odd.
(II). $r^{\frac{p-1}{4}} \equiv -1 \pmod p$ if $r$ is even.
Remark
Notice that $b^2 \equiv a \equiv r \pmod p$ for some nonzero integer $b$.
By Euler's Criterion, we have that $r^{\frac{p-1}{4}} \equiv (b^2)^{\frac{p-1}{4}} \equiv b^{\frac{p-1}{2}} \equiv \genfrac(){}{0}{b}{p} \pmod p$.
Equivalent form of the conjecture
(III). $b$ is a quadratic residue modulo $p$ if $r$ is odd.
(IV). $b$ is a quadratic nonresidue modulo $p$ if $r$ is even.
Can you prove or disprove (III) and (IV) using only the law of quadratic reciprocity?

A: Let $p=8k+5$.  By Euler's Criterion, $a^{4k+2}\equiv 1\pmod{p}$ and therefore $a^{2k+1}\equiv \pm 1\pmod{p}$.
Suppose that $a^{2k+1}\equiv 1\pmod{p}$. Then $a^{2k+2}\equiv a\pmod{p}$, and $a$ is congruent modulo $p$ to the square of $a^{k+1}$.
Now suppose that $a^{2k+1}\equiv -1\pmod{p}$. Since $p$ is of the form $8k+5$, it follows that $2$ is a quadratic non-residue of $p$, and therefore $2^{4k+2}\equiv -1\pmod{p}$. It follows that $2^{4k+2}a^{2k+1}\equiv 1\pmod{p}$, and therefore
$$2^{4k+2}a^{2k+2}\equiv a\pmod{p}.$$
Thus the square of $2^{2k+1}a^{k+1}$, that is, of $(2a)(4a)^k$, is congruent to $a$ modulo $p$.


text:
Q: Hyperlink in TextBlock is is not clickable I have made this in code-behind :
var finishedText = new Run("Some text");
var finishedUrl = new Run("http://somewhere");

var hyperlink = new Hyperlink(finishedUrl) { NavigateUri = new Uri("http://somewhere") };

hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
FinishedTextBlock.Inlines.Clear();
FinishedTextBlock.Inlines.Add(finishedText);
FinishedTextBlock.Inlines.Add(hyperlink);
FinishedTextBlock.Inlines.Add(Environment.NewLine);
FinishedTextBlock.Inlines.Add(finishedUrl);

In XAML :
<TextBlock Grid.Row="0"
           x:Name="FinishedTextBlock"
           Width="Auto"
           Margin="10 10 0 0">
</TextBlock>

The text is not clickable.

What am I doing wrong?

A:
The text is not clickable.

That is because your Hyperlink text is not even shown. You see the last Run that you have added to the Inlines collection, not the hyperlink itself.
You add the same Run named finishedUrl to your Hyperlink and its containing TextBlock, but you have to create a separate Run instance for the Hyperlink.
var finishedText = new Run("Some text");
var finishedUrl = "http://somewhere";
var finishedUrlRun = new Run(finishedUrl);

var hyperlink = new Hyperlink(finishedUrlRun) { NavigateUri = new Uri("http://somewhere") };

hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
FinishedTextBlock.Inlines.Clear();
FinishedTextBlock.Inlines.Add(finishedText);
FinishedTextBlock.Inlines.Add(hyperlink);
FinishedTextBlock.Inlines.Add(Environment.NewLine);

var finishedUrlRun1 = new Run(finishedUrl);
FinishedTextBlock.Inlines.Add(finishedUrlRun1);

Even better, just do not add the last Run, as it is redundant, and replace the NewLine with a LineBreak to get the same layout as in your image but with a link.
FinishedTextBlock.Inlines.Clear();
FinishedTextBlock.Inlines.Add(finishedText);
FinishedTextBlock.Inlines.Add(new LineBreak());
FinishedTextBlock.Inlines.Add(hyperlink);

A: Unless your hyperlink is inside a webview then nothing will happen when you click on a hyperlink.
You need to handle the RequestNavigate event and do something before you'll see a web browser appear with a page in it.
If this was a wpf page inside a frame, or navigationwindow then it would also navigate without code.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.documents.hyperlink?view=netcore-3.1

Remarks

Hyperlink implements the NavigateUri property that you set
with the Uri of the content that should be navigated to when the
Hyperlink is clicked. Hyperlink navigation can only occur, however, if
either the direct or indirect parent of a Hyperlink is a navigation
host, including NavigationWindow, Frame, or any browser that can host
XBAPs (which includes Internet Explorer 6 and later versions, and
Firefox 2.0+). For more information, see the Navigation Hosts topic in
Navigation Overview.

As it is, you need an event handler.
I'm not clear whether you intend the url to appear or a string. If you want a different string then this should work:
        TextBlock tb = new TextBlock();
        tb.Inlines.Add(new Run {Text="Some text" } );
        tb.Inlines.Add(new LineBreak());
        Run linkRun = new Run("Link To Google");
        Hyperlink hyper = new Hyperlink(linkRun) { NavigateUri = new Uri(@"http://www.google.com") };
        hyper.RequestNavigate += (o, e) => Process.Start(new ProcessStartInfo(e.Uri.ToString()){ UseShellExecute = true });
        tb.Inlines.Add(hyper);

If you want the url to appear rather than some other string then:
        TextBlock tb = new TextBlock();
        tb.Inlines.Add(new Run { Text = "Some text" });
        tb.Inlines.Add(new LineBreak());
        string url = @"http://www.google.com";
        Run linkRun = new Run(url);
        Hyperlink hyper = new Hyperlink(linkRun){ NavigateUri = new Uri(url) };
        hyper.RequestNavigate += (o, e) => Process.Start(new ProcessStartInfo(e.Uri.ToString()) { UseShellExecute = true });
        tb.Inlines.Add(hyper);
        sp.Children.Add(tb);

Note
One the process start, you will often get an error on win 10 machines without that useshellexecute in the process startinfo.
In older OS ( and you would see in old SO answers ) you used to be able to just process start with a URL and it would work with the default browser.
There is a linebreak inline which is intended to add a linebreak between a series of runs in a textblock.

A: In XAML, it needs to be like this:
<TextBlock Grid.Row="0"
    x:Name="FinishedTextBlock"
    Width="Auto"
    Margin="10 10 0 0">
<Run Text="Some text" />
<LineBreak/>
<Hyperlink>http://somewhere</Hyperlink>
</TextBlock>

The hyperlink in your code does not content anything. The hyperlink constructor parameter
[finishedUrl] did not initialized the hyperlink to contain the string "http://somewhere".
You can change your code something like below:
var finishedText = new Run("Some text");
var finishedUrl = new Run("http://somewhere");

var hyperlink = new Hyperlink() { NavigateUri = new Uri("http://somewhere") };
hyperlink.Inlines.Add(finishedUrl.Text);

hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
FinishedTextBlock.Inlines.Clear();
FinishedTextBlock.Inlines.Add(finishedText);
FinishedTextBlock.Inlines.Add(Environment.NewLine);
FinishedTextBlock.Inlines.Add(hyperlink);


text:
Q: Help with LEDs in parallel I am working on a project where I have to use string LEDs running on 5V (USB power.)
I had purchased one such string, which is 10m in length and has roughly 50 LEDs inside.
My specification requires me to use 20m of this string light , so I tried to join them together. That didn't work as the brightness of the second string attached was way lower than the first one connected.
I found that at the joint for the second string I was getting 2.4V (starting with 5V.)
This becomes a problem as I need them to be equal brightness.
I am not able to find why this would happen as all the LEds are in parallel and should get equal voltage along the string.
There is another seller selling the same LEDs in parallel and they work just fine. They have 3 wires running instead of 2 , and I can't figure out what the 3rd wire does exactly. (It's too expensive for me to break it apart and reverse engineer it.)
Please help me out.
LED string lights.

A: Those string lights have tiny wires with considerable resistance. It is unclear how you are attaching them, but if you are wiring them sequentially in parallel, the voltage drop along the wire results in much less voltage at the far end of the 10m line.
There are two options that I can see:
Run a separate, lower gauge wire to each strip and posibly to both ends of each strip so that current doesn't have to pass through the more resistive strip wires.
Wire the strips in series and connect them end to end. This will require a 15v power supply.


text:
Q: How do I kill all active tasks/apps using ADB? Is it possible to kill ALL the active tasks/apps in the task manager using ADB? This would be equivalent of opening the task manager and killing each task one by one...
I tried using the the following adb shell command but that didn't kill all the task.
adb shell am kill-all

I can't use the adb shell am force-stop <PACKAGE> command because it would require me to know which package/app is running. I want to kill ALL the user apps task that are running. Similarly to using the task manager and killing each task one by one.
According to the command description, kill-all kills all background processes. Are background processes equivalent to "services" and task equivalent to "activities"?
Also, is it possible to clear cache of apps using ADB while keeping the user data? I seems that the adb shell pm clear clears all the user data. I want to only clear the cache.
The reason why I am asking is because I am doing some performance testing on few user apps. To make each test valid, I want to ensure none of the user apps have any task, activities, services, and cache already in the background.

A: If you want to start clean slate i.e close the app and clear its data too you can do the following
adb shell pm clear com.yourapp.package

A: For non rooted devices I expanded on Faisal Ameer's Script
adb shell ps | grep -v root | grep -v system | grep -v "android.process." | grep -v radio | grep -v "com.google.process." | grep -v "com.lge." | grep -v shell | grep -v NAME | awk '{print $NF}' | tr '\r' ' ' | xargs adb shell am force-stop

The adb shell am force-stop does not require root permission. Note that the applications still show up in the devices running application drawer but I have verified that the packages processes have been cleared using.
adb shell dumpsys meminfo relevant.package.names

A: You can use force-stop, it doesn't require root permission.
adb shell am force-stop <PACKAGE>

And you can get the package name from the top running activity/app
adb shell "dumpsys activity | grep top-activity"

After that you need to play a bit with the result, to extract the package, here my java code that does that:
public void parseResult(String line){
        int i = line.indexOf(" 0 ");
        if(i == -1){
            return;
        }
        line = line.substring(i);
        i = line.indexOf(":");
        if(i == -1){
            return;
        }
        line = line.substring(i + 1);
        i = line.indexOf("/");
        return line.substring(0, i);
}

A: find running apps, ignoring system apps etc and kill, the following command does it all;
adb shell ps|grep -v root|grep -v system|grep -v NAME|grep -v shell|grep -v smartcard|grep -v androidshmservice|grep -v bluetooth|grep -v radio|grep -v nfc|grep -v "com.android."|grep -v "android.process."|grep -v "com.google.android."|grep -v "com.sec.android."|grep -v "com.google.process."|grep -v "com.samsung.android."|grep -v "com.smlds" |awk '{print $2}'| xargs adb shell kill

you can add more exceptions if you find any like this; grep -v "exception"


text:
Q: How to add target="_blank" into a URL in php on Wordpress I have used the following codes to add target="_blank" to a URL (password-reset page) on my website:
add_filter( 'lostpassword_url', 'my_lost_password_page', 10, 2 );
function my_lost_password_page( $lostpassword_url, $redirect ) {
    return home_url( '/password-reset/?redirect_to=target="_blank"' . $redirect );
}
}

It does not work as it still opens the same window when pressing that page URL.
Can you please give a right direction?

A: Try with below code i am not sure with below code but this is the only possible way.
//$redirect = "https://www.gooogle.com";
echo '<script>window.open(' . $redirect . ',"_blank");</script>';

A: I have updated the latest version of RegistrationMagic a momment ago, there is no need to edit the codes I posted above. It is working as intended. Many thanks especially for @Aki. However, if anyone could help guide how to insert that _blank into the above codes, that may be useful for many people. Thanks


text:
Q: ASP.NET Application Object Getters and Setters I have had a hard time finding a newbie friendly example of accessing the Application Object. I have few things ( arrays ) I would like to store in the Application Object to keep as persistent data for about 2 hours until AppRecycle.
Anyhow, I know how to set an Application Object variable this way:
// One way
String[] users = new String[1000];
Application["users"] = users;

// Another way
Application.Add("users", users);

However I do not know how to access these variables once they are inside the Application Object. There is a Getter method Get. However it requires int index. The other method, Contents, get's everything, not just my array.
Here I try to retrieve my String[] array, but it gives me a error that I am trying to convert Object to String.
String[] usersTable = Application["users"];
// Since this is an object i also tried Application.users but gives error

A: In Application you only save type "object". You need to cast to the desired type
string[] usersTable = (string[])Application["users"];

A: You need to cast the value back to String[]:
String[] usersTable = (String[])Application["users"];

See How to: Read Values from Application State

A: First I suggest for your case to simple use a static variable on the string
static String[] users = new String[1000];

and manipulate that. Is better than Application state. What Microsoft says about:

ASP.NET includes application state primarily for compatibility with
  classic ASP so that it is easier to migrate existing applications to
  ASP.NET. It is recommended that you store data in static members of
  the application class instead of in the Application object. This
  increases performance because you can access a static variable faster
  than you can access an item in the Application dictionary.

Now if you continue to use the Application I strongly suggest to use use Application.Lock(); and Application.UnLock();  when you manipulate the data of the Application and your code will be as:
String[] _users = null;
String[] users
{
    get
    {
        if (_users == null)
        {
            Application.Lock();
            if (!(Application["_users_"] is String[]))
            {
                Application["_users_"] = new String[1000];
            }
            _users = (String [])Application["_users_"];
            Application.UnLock();
        }

        return _users;
    }
}

Why I suggest to simple use a static ?
Because the Application["_users_"] is actually a call to a static Dictionary<k,v> that store among other data, and the data you set as String[]. No actually reason to make that, a  static can do the same.

A: A better solution, IMO, would be use the WebCache (http://msdn.microsoft.com/en-us/library/d59zceh7.aspx) due to the amount of control you can have over expiration and dependencies. This way, if you had the desire to no longer recylce your app-pool, you could still keep the data for a limited, set period of time.
         string[] Cache["users"];

That's all you need to access the cache for your object. Setting it is easy as well. See: http://msdn.microsoft.com/en-us/library/system.web.caching.cache.add(v=vs.100).aspx


text:
Q: Django - Order of WHERE statements in filter I want to make a specific odrer of WHERE statements in my query to use multicolumn index in database.
But oder in code is not the same as result query:
code:
filter(user=self.user, province=self.province, city=self.city)

Mysql result:
WHERE (`accounts_usercity`.`province_id` = 6 AND `accounts_usercity`.`city_id` = 32 AND `accounts_usercity`.`user_id` = 26 )

How to force my own order?

A: If you chain the filters it should work:

filter(user=self.user).filter(province=self.province).filter(city=self.city)

I tried it in django 1.2.5 and it's working.


text:
Q: cmake copying fortran modules failure on linux I have a fortran code build that uses cmake to build. This is currently working on Mac OS X, but when I try to build it on Linux, it fails. Cmake generates the makefile successfully but when I try to run the makefile it fails when trying to copy the modules.
The top level cmake file is:
cmake_minimum_required (VERSION 2.8)

# Start Project and note the language used.
project (v3fit_suite Fortran)

# Set a directories to build all binary files.
set (EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/build/bin)
set (LIBRARY_OUTPUT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/build/lib)

# Fortran specific settings. The first setting tells the compiler to use the C preprocessor. The second places a common directory to place all of the module files.
set (CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -cpp")
set (CMAKE_Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build/modules)

# List all the subdirectories these are in library dependancy order.
add_subdirectory (LIBSTELL)
add_subdirectory (VMEC2000)
add_subdirectory (V3FITA)
add_subdirectory (MAKEGRID)
add_subdirectory (V3POST)
add_subdirectory (V3RFUN)

All the modules should be copied to to build/modules. When I run the Makefile with VERBOSE=1 on Linux I get:
/usr/bin/cmake -H/home/user/reconstruction -B/home/user/reconstruction --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /home/user/reconstruction/CMakeFiles /home/user/reconstruction/CMakeFiles/progress.marks
make -f CMakeFiles/Makefile2 all
make[1]: Entering directory `/home/user/reconstruction'
make -f LIBSTELL/CMakeFiles/stell.dir/build.make LIBSTELL/CMakeFiles/stell.dir/depend
make[2]: Entering directory `/home/user/reconstruction'
cd /home/user/reconstruction && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /home/user/reconstruction /home/user/reconstruction/LIBSTELL /home/user/reconstruction /home/user/reconstruction/LIBSTELL /home/user/reconstruction/LIBSTELL/CMakeFiles/stell.dir/DependInfo.cmake --color=
make[2]: Leaving directory `/home/user/reconstruction'
make -f LIBSTELL/CMakeFiles/stell.dir/build.make LIBSTELL/CMakeFiles/stell.dir/requires
make[2]: Entering directory `/home/user/reconstruction'
make -f LIBSTELL/CMakeFiles/stell.dir/build.make LIBSTELL/CMakeFiles/stell.dir/Sources/Modules/stel_kinds.f.o.provides.build
make[3]: Entering directory `/home/user/reconstruction'
/usr/bin/cmake -E cmake_progress_report /home/user/reconstruction/CMakeFiles
[  0%] Building Fortran object LIBSTELL/CMakeFiles/stell.dir/Sources/Modules/stel_kinds.f.o
cd /home/user/reconstruction/LIBSTELL && /usr/bin/f95  -o CMakeFiles/stell.dir/Sources/Modules/stel_kinds.f.o  -cpp  -J../build/modules   -c /home/user/reconstruction/LIBSTELL/Sources/Modules/stel_kinds.f
/usr/bin/cmake -E cmake_copy_f90_mod build/modules/stel_kinds LIBSTELL/CMakeFiles/stell.dir/stel_kinds.mod.stamp GNU
Error copying Fortran module "build/modules/stel_kinds".  Tried "build/modules/STEL_KINDS.mod" and "build/modules/stel_kinds.mod".
make[3]: *** [LIBSTELL/CMakeFiles/stell.dir/Sources/Modules/stel_kinds.f.o.provides.build] Error 1
make[3]: Leaving directory `/home/user/reconstruction'
make[2]: *** [LIBSTELL/CMakeFiles/stell.dir/Sources/Modules/stel_kinds.f.o.provides] Error 2
make[2]: Leaving directory `/home/user/reconstruction'
make[1]: *** [LIBSTELL/CMakeFiles/stell.dir/all] Error 2
make[1]: Leaving directory `/home/user/reconstruction'
make: *** [all] Error 2

I'm having the same problem when using the gfortran as my compiler instead of f95. Why is this working on Mac OS X but failing on Linux? On Mac OS X I have version 2.8.8 of cmake installed and on Linux version 2.8.

A: Turns out there was a seemingly unrelated error that was causing the problem. I had some statements to add an include path that was being empty.
find_library (NETCDF_F netcdff PATHS ${NETCDF_LIB_PATH})
find_file (NETCDF_I netcdf.inc ${NETCDF_INC_PATH})
if (NETCDF_C AND NETCDF_F AND NETCDF_I)
    message (STATUS "Using netcdf")
    set (CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -D NETCDF -I ${NETCDF_INC_PATH}")
endif ()

The if statement was always coming up true even when 'NETCDF_INC_PATH' was empty. This was causing an extra -I in the compiler command line that was screwing everything up.


text:
Q: Binding set to CheckBoxes in WPF using Entity Framework (C#) I have a User class which has ONE:MANY mapping to the UserRight class (simply, user has a set of rights). Each right is identified by a string. And now, because the maximum number of possible rights is finite (<10) I'd like to have 10 CheckBoxes and edit the subset of rights for a given user manually.
What is the nice way to do it?
James

A: Create a RightViewModel class to contain user rights:
public class RightViewModel : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            Change("Name");
        }
    }

    private bool _hasRight;
    public bool HasRight
    {
        get { return _hasRight; }
        set
        {
            _hasRight = value;
            Change("HasRight");
        }
    }

    public void Change(string strPropertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

Create a similar class for your user, containing a member Rightsof type ObservableCollection<RightViewModel>.
In you XAML, use an ItemsControl:
<ItemsControl ItemsSource="{Binding Rights}"
    ItemTemplate="{StaticResource RightTemplate}"/>

And a template definition:
<DataTemplate x:Key="RightTemplate">
    <CheckBox Content="{Binding Name}" IsChecked="{Binding HasRight, Mode=TwoWay}"/>
</DataTemplate>

Mode=TwoWay makes the binding update your RightViewModel instance.
Define the ItemsControl's ItemsPanel if you need to display your checkboxes with a different layout.
Finally set your user as the DataContext of your container.


text:
Q: When will $\mathbb{E}[g(S_n/n)]$ exist given $\mathbb{E}[g(X_1)]$ exists? Suppose $X_1, X_2,..., X_n$ are i.i.d. random variables with distribution $\pi$ on some probability space. Let $g$ be a measurable function such that $\mathbb E_\pi[g(X_1)]<\infty$. I am curious about what we can say about $\mathbb E_\pi[g(S_n/n)]$, where $S_n = \sum_{k=1}^n X_k$?
My guess is the quantity $\mathbb E_\pi[g(S_n/n)]$ is not necessarily finite in general, but should be finite if $g$ satisfies appropriate regularity conditions. I am wondering if there are any existing studies on this topic?


text:
Q: Convert screen from portrait to landscape it does not keep it landscape while rotate it left to right and vice-varsa i did change orientation of uidevice as per screen requirement.
For example screen A
Which i need to make portrait only.
Screen B
It should be landscape and i did it.
But after going back to screen A and again i go to screen B and rotate device left to right or right to left screen B's orientation changes to portrait.
Please comment if anyone have solution for this.
Here i will explain whole scenario what i am doing in my project:
AppDelegate.swift
var orientationLock = UIInterfaceOrientationMask.portrait   //Defined variable for orientation

func application(_ application: UIApplication,
                 supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return shouldRotate ? .allButUpsideDown : .portrait
}

In class A
   override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
        let value = UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        Global.appDelegate.shouldRotate = false
    }

In class B
DispatchQueue.main.async {
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}
Global.appDelegate.shouldRotate = false

Now i tried to make B screen landscape in all rotation, for that i tried method below:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: nil, completion: {
        _ in
        if UIDevice.current.orientation == .portrait || UIDevice.current.orientation == .portraitUpsideDown {
            //                Global.AppUtility.lockOrientation(.landscape)
            let value = UIInterfaceOrientation.landscapeLeft.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
            Global.appDelegate.shouldRotate = true
        }
    })

}

But this method works first time only, after selecting A and again i go to screen B it keep it portrait.


text:
Q: Using Shareplum to download, alter and then upload a file to sharepoint Exactly as the title says, I have this code
from shareplum import Site
from shareplum import Office365
from shareplum.site import Version

authcookie = Office365('https://mysite.sharepoint.com/', username='username', password='password').GetCookies()
site = Site('https://mysite.sharepoint.com/sites/mysite/', version=Version.v2016, authcookie=authcookie)
folder = site.Folder('Shared Documents/Beta Testing')
file = folder.get_file('practice.xlsx')
with open("practice.xlsx", "wb") as fh:
    fh.write(file)
print('---')
folder.upload_file('xlsx', 'practice.xlsx')

Currently it downloads the file just fine which is fantastic, however I do not know how to reverse what I did with opening and downloading the file. Basically I need to be able to upload the file with the exact same name as the one I downloaded in the exact same format (in this case xlsx) as to overwrite the one in the sharepoint with the updated document.

A: Your post indicates that you want to modify the file so you will need some file handling for the downloaded file once it is saved after modification. Once the file modification has been done you need to open the file in 'rb' and then read that to a variable which will be the content when calling folder_obj.upload_file(content, name).
#this is your step to modify the file.
with open("practice.xlsx", "wb") as fh:
    #file modification stuff... pyxlsx?
    fh.write(file)

#open the file and read it into a variable as binary
with open("practice.xlsx", "rb") as file_obj:
    file_as_string = file_obj.read()

#upload the file including the file name and the variable (file_as_string)
folder.upload_file(file_as_string, 'practice.xlsx')

This has been working for me. If you want to change the name of the file to include a version, delete the old file by calling folder.delete_file("practice.xlsx").

A: Can you try the below and see if it works?
    with open("practice.xlsx", "wb") as fh:
       file_content =  fh.write(file)
    folder.upload_file(file_content,'practice.xlsx')


text:
Q: Find repeated words in a string and delete duplicates Let's say I have a string that contains many words such as:
string SetenceString= "red white black white green yellow red red black white"

I want to delete all dupplicates and return each word only once:
SetenceString= "red white black green yellow"

How can I do so with C# ? All help is well appreciated.

A: You haven't even told us what you have tried but..
string SetenceString = "red white black white green yellow red red black white";
var result = string.Join(" ", SetenceString.Split(' ').Distinct());
Console.WriteLine(result);

Output will be;

red white black green yellow

But hey, how does that work exactly?

*

*We split our string with white space to get all your words in a string array.

*We used Distinct() method to get only distinct words in our string array.

*And we used string.Join to combine all these distinct words with white space.

A: If your words are always  separated:
String.Join(" ", SetenceString.Split(' ').Distinct())

Else you should rather use regular expressions

A:     string SetenceString = "red white black white green yellow red red black white";
    string[] data = SetenceString.Split(' ');
    HashSet<string> set = new HashSet<string>();
    for (int i = 0; i < data.Length; i++)
    {
        set.Add(data[i]);
    }

set varible now contains only unique items


text:
Q: Poincare' map to find periodic solution. Consider the equation $\dot{y} = (acos(t) + b)y - y^3$ $a > 0, b>0$. I know that I need to recast the equation as a first order system $\dot{y} = (acos(x) +b)y - y^3, \dot{x} = 1$. Also, we are given that $\alpha \in R$ let $(x(t, \alpha), y(t, \alpha))$ denote the solution of the system with initial values $x(0, \alpha) = 0$, $y(0, \alpha) = \alpha$. Also, we know the line $\sum =  \{(x, y)| x = 0\}$  with each line $ \{(x, y)| x = 2\pi*L\}$. L is an integer. We also have $T$ x $R$ where $T$ is the torus. $\alpha \in R$ is the coordinates of the point $\sum$, the Poincare' map is given by $P(\alpha) = y(2\pi, \alpha)$
I know that the fixed point of the Poincare' map corresponds to a periodic orbit by definition where 0 is a trivial solution.
I want to show $ P'(0) > 1)$ I know for this I need to look into the equation that satisfies the partial $y_{\alpha}$ at $\alpha = 0$.
I also need to use $P'(0) > 1$ , and continuity of $P'(\alpha)$ to show that there exists $ 0 < c < a + b + 1$ such that $P$ maps $[ c, a+b+1]$ into itself.
and finally I need to Prove P has a fixed point in [c, a+b+1].
I also know that I will take the derivative and plug in the critical value it's got to be greater than or less than some number for it to be stable. Any help will be greatly appreciated. Thanks.


text:
Q: Why does AWS boto3 call to associate_iam_instance_profile cause InvalidParameterValue for invalid name when the name is valid? I have code that is calling AWS boto3 APIs.  This code does several things using an iam client and an ec2 client:
iam_client = boto3.client('iam')
ec2_client = boto3.client('ec2')

For all of these calls the role name and the profile name are the same: MyExampleName

*

*Invoke iam_client.create_instance_profile to create a new instance profile

*Invoke iam_client.create_role to create a new role

*Invoke iam_client.attach_role_policy to attach an AWS-managed policy to the new role

*Invoke iam_client.add_role_to_instance_profile to add the new role to the instance profile

*Invoke ec2_client.associate_iam_instance_profile to associate the profile to an instance

But the last call is failing with a message such as this:

INFO "FAILED: An error occurred (InvalidParameterValue) when calling
the AssociateIamInstanceProfile operation: Value (MyExampleName) for
parameter iamInstanceProfile.name is invalid. Invalid IAM Instance
Profile name, Account Id: XXXXXXXXXXXXX, Resource: EC2 instance:
i-78sd976sd6912"

I just created the profile, so how is it that the call to associate_iam_instance_profile is saying it is invalid?

A: There is a bit of a timing issue using both the IAM client and the EC2 client.  The profile created via the iam_client may not immediately be usable by the ec2_client.  With some retry logic, the name seems to eventually work--it isn't really invalid, it just isn't found yet:
import time

logger.info('Attaching profile: MyExampleName'))
counter = 0
while counter < 60:
    try:
        ec2_client.associate_iam_instance_profile(IamInstanceProfile={'Name': 'MyExampleName'},
                                                  InstanceId='i-78sd976sd6912')
        break
    except ClientError as err:
        if err.response['Error']['Code'] == 'InvalidParameterValue':
            counter = counter + 1
            logger.info('The ec2 client did not find the profile yet; wait 1 second and then try again')
            time.sleep(1)
logger.info('Finally worked!')

The following logs show a real-world sample of log entries that show the EC2 client is eventually consistent with the IAM client:
INFO "Attaching profile: MyExampleName"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "The profile is not found yet; wait 1 second and then try again"
INFO "Finally worked!"

A: The more convenient approach would be to rely on boto3 waiters purposely built do wait for certain resources to become available.
waiter = client.get_waiter('instance_profile_exists')
waiter.wait(
    InstanceProfileName='string',
    WaiterConfig={
        'Delay': 123,
        'MaxAttempts': 123
    }
)

The problem with your approach, is that you're relying on a assumption that a resource will get created within 60 seconds, that might not be always the case. While waiters are keep polling until a resource becomes available.
To read more about available waiters https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.get_waiter


text:
Q: Should I use Vagrant or Docker for creating an isolated environment? I use Ubuntu for development and deployment and have a need for creating an isolated environment.
I am considering either Vagrant or Docker for this purpose. What are the pros and cons, or how do these solutions compare?

A: There is a really informative article in the actual Oracle Java magazine about using Docker in combination with Vagrant (and Puppet):
Conclusion

Docker's lightweight containers are faster compared with classic VMs
  and have become popular among developers and as part of CD and DevOps
  initiatives. If your purpose is isolation, Docker is an excellent choice.
  Vagrant is a VM manager that enables you to script configurations of
  individual VMs as well as do the provisioning. However, it is sill a
  VM dependent on VirtualBox (or another VM manager) with relatively
  large overhead. It requires you to have a hard drive idle that can be
  huge, it takes a lot of RAM, and performance can be suboptimal. Docker
  uses kernel cgroups and namespace isolation via LXC. This means that
  you are using the same kernel as the host and the same ile system.
  Vagrant is a level above Docker in terms of abstraction, so they are
  not really comparable. Configuration management tools such as Puppet are
  widely used for provisioning target environments. Reusing existing
  Puppet-based solutions is easy with Docker. You can also slice your
  solution, so the infrastructure is provisioned with Puppet; the
  middleware, the business application itself, or both are provisioned
  with Docker; and Docker is wrapped by Vagrant. With this range of
  tools, you can do what's best for your scenario.

How to build, use and orchestrate Docker containers in DevOps
http://www.javamagazine.mozaicreader.com/JulyAug2015#&pageSet=34&page=0

A: I preface my reply by admitting I have no experience with Docker, other than as an avid observer of what looks to be a really neat solution that's gaining a lot of traction.
I do have a decent amount of experience with Vagrant and can highly recommend it. It's certainly a more heavyweight solution in terms of it being VM based instead of LXC based. However, I've found a decent laptop (8 GB RAM, i5/i7 CPU) has no trouble running a VM using Vagrant/VirtualBox alongside development tooling.
One of the really great things with Vagrant is the integration with Puppet/Chef/shell scripts for automating configuration. If you're using one of these options to configure your production environment, you can create a development environment which is as close to identical as you're going to get, and this is exactly what you want.
The other great thing with Vagrant is that you can version your Vagrantfile along with your application code. This means that everyone else on your team can share this file and you're guaranteed that everyone is working with the same environment configuration.
Interestingly, Vagrant and Docker may actually be complimentary. Vagrant can be extended to support different virtualization providers, and it may be possible that Docker is one such provider which gets support in the near future. See https://github.com/dotcloud/docker/issues/404 for recent discussion on the topic.

A: They are very much complementary.
I have been using a combination of VirtualBox, Vagrant and Docker for all my projects for several months and have strongly felt the following benefits.
In Vagrant you can completely do away with any Chef solo provisioning and all you need your vagrant file to do is prepare a machine that runs a single small shell script that installs docker.  This means that my Vagrantfiles for every project are almost identical and very simple.
Here is a typical Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "mark2"
  config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
  [3000, 5000, 2345, 15672, 5672, 15674, 27017, 28017, 9200, 9300, 11211, 55674, 61614, 55672, 5671, 61613].each do |p|
    config.vm.network :forwarded_port, guest: p, host: p
  end
  config.vm.network :private_network, ip: "192.168.56.20"
  config.vm.synced_folder ".", "/vagrant", :type => "nfs"
  config.vm.provider :virtualbox do |vb|
    vb.customize ["modifyvm", :id, "--memory", "2048"]
    vb.customize ["modifyvm", :id, "--cpus", "2"]
  end
  # Bootstrap to Docker
  config.vm.provision :shell, path: "script/vagrant/bootstrap", :privileged => true
  # Build docker containers
  config.vm.provision :shell, path: "script/vagrant/docker_build", :privileged => true
  # Start containers
  # config.vm.provision :shell, path: "script/vagrant/docker_start", :privileged => true
end

The Bootstrap file that installs docker looks like this
#!/usr/bin/env bash
echo 'vagrant  ALL= (ALL:ALL) NOPASSWD: ALL' >> /etc/sudoers
apt-get update -y
apt-get install htop -y
apt-get install linux-image-extra-`uname -r` -y
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
echo deb http://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list
apt-get update -y
apt-get install lxc-docker -y
apt-get install curl -y

Now to get all the services I need running I have a docker_start script that looks somthing like this
#!/bin/bash
cd /vagrant
echo Starting required service containers
export HOST_NAME=192.168.56.20
# Start MongoDB
docker run --name=mongodb --detach=true --publish=27017:27017 --publish=28017:28017 dockerfile/mongodb
read -t5 -n1 -r -p "Waiting for mongodb to start..." key
# Start rabbitmq
docker run --name=rabbitmq --detach=true --publish=5671:5671 --publish=5672:5672 --publish=55672:55672 --publish=15672:15672 --publish=15674:15674 --publish=61613:61613 --env RABBITMQ_USER=guest --env RABBITMQ_PASS=guest rabbitmq
read -t5 -n1 -r -p "Waiting for rabbitmq to start..." key
# Start cache
docker run --name=memcached --detach=true --publish=11211:11211  ehazlett/memcached
read -t5 -n1 -r -p "Waiting for cache to start..." key
# Start elasticsearch
docker run --name=elasticsearch --detach=true --publish=9200:9200 --publish=9300:9300 dockerfile/elasticsearch
read -t5 -n1 -r -p "Waiting for elasticsearch to start..." key
echo "All services started"

In this example I am running MongoDB, Elastisearch, RabbitMQ and Memcached
A non-docker Chef solo configuration would be considerably more complicated.
A final big plus is gained when you are moving into production, translating the development environment over to an infrastructure of hosts that are all the same in that they just have enough config to run docker means very little work indeed.
If you interested I have a more detailed article on the development environment on my own web site at
Implementing A Vagrant / Docker Development Environment

A: Vagrant-lxc is a plugin for Vagrant that let's you use LXC to provision Vagrant. It does not have all the features that the default vagrant VM (VirtualBox) has but it should allow you more flexibility than docker containers. There is a video in the link showing its capabilities that is worth watching.

A: With Vagrant now you can have Docker as a provider. http://docs.vagrantup.com/v2/docker/. Docker provider can be used instead of VirtualBox or VMware.
Please note that you can also use Docker for provisioning with Vagrant. This is very different than using Docker as a provider. http://docs.vagrantup.com/v2/provisioning/docker.html
This means you can replace Chef or Puppet with Docker. You can use combinations like Docker as provider (VM) with Chef as provisioner. Or you can use VirtualBox as provider and Docker as provisioner.

A: Disclaimer: I wrote Vagrant! But because I wrote Vagrant, I spend most of my time living in the DevOps world which includes software like Docker. I work with a lot of companies using Vagrant and many use Docker, and I see how the two interplay.
Before I talk too much, a direct answer: in your specific scenario (yourself working alone, working on Linux, using Docker in production), you can stick with Docker alone and simplify things. In many other scenarios (I discuss further), it isn't so easy.
It isn't correct to directly compare Vagrant to Docker. In some scenarios, they do overlap, and in the vast majority, they don't. Actually, the more apt comparison would be Vagrant versus something like Boot2Docker (minimal OS that can run Docker). Vagrant is a level above Docker in terms of abstractions, so it isn't a fair comparison in most cases.
Vagrant launches things to run apps/services for the purpose of development. This can be on VirtualBox, VMware. It can be remote like AWS, OpenStack. Within those, if you use containers, Vagrant doesn't care, and embraces that: it can automatically install, pull down, build, and run Docker containers, for example. With Vagrant 1.6, Vagrant has docker-based development environments, and supports using Docker with the same workflow as Vagrant across Linux, Mac, and Windows. Vagrant doesn't try to replace Docker here, it embraces Docker practices.
Docker specifically runs Docker containers. If you're comparing directly to Vagrant: it is specifically a more specific (can only run Docker containers), less flexible (requires Linux or Linux host somewhere) solution. Of course if you're talking about production or CI, there is no comparison to Vagrant! Vagrant doesn't live in these environments, and so Docker should be used.
If your organization runs only Docker containers for all their projects and only has developers running on Linux, then okay, Docker could definitely work for you!
Otherwise, I don't see a benefit to attempting to use Docker alone, since you lose a lot of what Vagrant has to offer, which have real business/productivity benefits:

*

*Vagrant can launch VirtualBox, VMware, AWS, OpenStack, etc. machines. It doesn't matter what you need, Vagrant can launch it. If you are using Docker, Vagrant can install Docker on any of these so you can use them for that purpose.

*Vagrant is a single workflow for all your projects. Or to put another way, it is just one thing people have to learn to run a project whether it is in a Docker container or not. If, for example, in the future, a competitor arises to compete directly with Docker, Vagrant will be able to run that too.

*Vagrant works on Windows (back to XP), Mac (back to 10.5), and Linux (back to kernel 2.6). In all three cases, the workflow is the same. If you use Docker, Vagrant can launch a machine (VM or remote) that can run Docker on all three of these systems.

*Vagrant knows how to configure some advanced or non-trivial things like networking and syncing folders. For example: Vagrant knows how to attach a static IP to a machine or forward ports, and the configuration is the same no matter what system you use (VirtualBox, VMware, etc.) For synced folders, Vagrant provides multiple mechanisms to get your local files over to the remote machine (VirtualBox shared folders, NFS, rsync, Samba [plugin], etc.). If you're using Docker, even Docker with a VM without Vagrant, you would have to manually do this or they would have to reinvent Vagrant in this case.

*Vagrant 1.6 has first-class support for docker-based development environments. This will not launch a virtual machine on Linux, and will automatically launch a virtual machine on Mac and Windows. The end result is that working with Docker is uniform across all platforms, while Vagrant still handles the tedious details of things such as networking, synced folders, etc.
To address specific counter arguments that I've heard in favor of using Docker instead of Vagrant:

*

*"It is less moving parts" - Yes, it can be, if you use Docker exclusively for every project. Even then, it is sacrificing flexibility for Docker lock-in. If you ever decide to not use Docker for any project, past, present, or future, then you'll have more moving parts. If you had used Vagrant, you have that one moving part that supports the rest.

*"It is faster!" - Once you have the host that can run Linux containers, Docker is definitely faster at running a container than any virtual machine would be to launch. But launching a virtual machine (or remote machine) is a one-time cost. Over the course of the day, most Vagrant users never actually destroy their VM. It is a strange optimization for development environments. In production, where Docker really shines, I understand the need to quickly spin up/down containers.
I hope now its clear to see that it is very difficult, and I believe not correct, to compare Docker to Vagrant. For dev environments, Vagrant is more abstract, more general. Docker (and the various ways you can make it behave like Vagrant) is a specific use case of Vagrant, ignoring everything else Vagrant has to offer.
In conclusion: in highly specific use cases, Docker is certainly a possible replacement for Vagrant. In most use cases, it is not. Vagrant doesn't hinder your usage of Docker; it actually does what it can to make that experience smoother. If you find this isn't true, I'm happy to take suggestions to improve things, since a goal of Vagrant is to work equally well with any system.
Hope this clears things up!

A: Using both is an important part of application delivery testing. I am only beginning to get involved with Docker and thinking very hard about an application team that has terrible complexity in building and delivering its software.  Think of a classic Phoenix Project / Continuous Delivery situation.
The thinking goes something like this:

*

*Take a Java/Go application component and build it as a container
(note, not sure if the app should be built in the container or built then
installed to the container)

*Deliver the container to a Vagrant VM.

*Repeat this for all application components.

*Iterate on the component(s) to code against.

*Continuously test the delivery mechanism to the VM(s) managed by Vagrant

*Sleep well knowing when it is time to deploy the container, that integration testing was occurring on a much more continuous basis than it was before Docker.

This seems to be the logical extension of Mitchell's statement that Vagrant is for development combined with Farley/Humbles thinking in Continuous Delivery. If I, as a developer, can shrink the feedback loop on integration testing and application delivery, higher quality and better work environments will follow.
The fact that as a developer I am constantly and consistently delivering containers to the VM and testing the application more holistically means that production releases will be further simplified.
So I see Vagrant evolving as a way of leveraging some of the awesome consequences Docker will have for app deployment.

A: I'm the author of Docker.
The short answer is that if you want to manage machines, you should use Vagrant. And if you want to build and run applications environments, you should use Docker.
Vagrant is a tool for managing virtual machines. Docker is a tool for building and deploying applications by packaging them into lightweight containers. A container can hold pretty much any software component along with its dependencies (executables, libraries, configuration files, etc.), and execute it in a guaranteed and repeatable runtime environment. This makes it very easy to build your app once and deploy it anywhere - on your laptop for testing, then on different servers for live deployment, etc.
It's a common misconception that you can only use Docker on Linux. That's incorrect; you can also install Docker on Mac, and Windows. When installed on Mac, Docker bundles a tiny Linux VM (25 MB on disk!) which acts as a wrapper for your container. Once installed this is completely transparent; you can use the Docker command-line in exactly the same way. This gives you the best of both worlds: you can test and develop your application using containers, which are very lightweight, easy to test and easy to move around (see for example https://hub.docker.com for sharing reusable containers with the Docker community), and you don't need to worry about the nitty-gritty details of managing virtual machines, which are just a means to an end anyway.
In theory it's possible to use Vagrant as an abstraction layer for Docker. I recommend against this for two reasons:

*

*First, Vagrant is not a good abstraction for Docker. Vagrant was designed to manage virtual machines. Docker was designed to manage an application runtime. This means that Docker, by design, can interact with an application in richer ways, and has more information about the application runtime. The primitives in Docker are processes, log streams, environment variables, and network links between components. The primitives in Vagrant are machines, block devices, and ssh keys. Vagrant simply sits lower in the stack, and the only way it can interact with a container is by pretending it's just another kind of machine, that you can "boot" and "log into". So, sure, you can type "vagrant up" with a Docker plugin and something pretty will happen. Is it a substitute for the full breadth of what Docker can do? Try native Docker for a couple days and see for yourself :)

*Second, the lock-in argument. "If you use Vagrant as an abstraction, you will not be locked into Docker!". From the point of view of Vagrant, which is designed to manage machines, this makes perfect sense: aren't containers just another kind of machine? Just like Amazon EC2 and VMware, we must be careful not to tie our provisioning tools to any particular vendor! This would create lock-in - better to abstract it all away with Vagrant. Except this misses the point of Docker entirely. Docker doesn't provision machines; it wraps your application in a lightweight portable runtime which can be dropped anywhere.
What runtime you choose for your application has nothing to do with how you provision your machines! For example it's pretty frequent to deploy applications to machines which are provisioned by someone else (for example an EC2 instance deployed by your system administrator, perhaps using Vagrant), or to bare metal machines which Vagrant can't provision at all. Conversely, you may use Vagrant to provision machines which have nothing to do with developing your application - for example a ready-to-use Windows IIS box or something. Or you may use Vagrant to provision machines for projects which don't use Docker - perhaps they use a combination of rubygems and rvm for dependency management and sandboxing for example.
In summary: Vagrant is for managing machines, and Docker is for building and running application environments.

A: Definitely Docker for the win!
As you may know Vagrant is for virtual machine management whereas Docker is for software containers management.
If you are not aware of the difference, here is:
A software container can share the same machine and kernel with other software containers. Using containers you save money because you don't waste resources on multiple operating systems (kernels), you can pack more software per server keeping a good degree of isolation.
Of course is a new discipline to care with its own pitfals and challenges.
Go for Docker Swarm if your requirements cross the single machine resources limit.

A: If your purpose is the isolation, I think Docker is what you want.
Vagrant is a virtual machine manager. It allows you to script the virtual machine configuration as well as the provisioning. However, it is still a virtual machine depending on VirtualBox (or others) with a huge overhead. It requires you to have a hard drive file that can be huge, it takes a lot of ram, and performance may be not very good.
Docker on the other hand uses kernel cgroup and namespacing via LXC. It means that you are using the same kernel as the host and the same file system.
You can use Dockerfile with the docker build command in order to handle the provisioning and configuration of your container. You have an example at docs.docker.com on how to make your Dockerfile; it is very intuitive.
The only reason you could want to use Vagrant is if you need to do BSD, Windows or other non-Linux development on your Ubuntu box. Otherwise, go for Docker.


text:
Q: How many lowercase strings of 8 letters contain the letters x and y? I am having difficulty solving the above problem.
I understand that the number of strings which have ONLY an $x$ in it is $26^8 - 25^8$, and the same goes for $y$, but I cannot wrap my head around how to solve for $x$ and $y$.
The answer I came up with is ${8}\choose{2}$ $\times 26^6$, the $8\choose 2$ coming from placing $x$ and $y$ into any of the $8$ spots onto the strong, and the $26^6$ filling out the rest of the spots with any letters.
I cannot shake the feeling that this answer is incorrect, and I am looking for someone to help walk me through the problem so I can get a better understanding of it. Thanks.

A: Your answer is indeed incorrect because it has overcounted scenarios where you have more than one $x$ and/or more than one $y$ occurring.  For example, letting the positions chosen in the first step be colored red, you would have considered $\color{red}{XY}xaaaaa$ to be a different outcome than $x\color{red}{YX}aaaaa$ despite them both having the same letters in the same order.
For a corrected approach, consider counting the opposite event:  We have no $X$'s or we have no $Y$'s.
Let $A$ be the set of 8 letter strings where we have no $X$'s.  Let $B$ be the set of 8 letter strings where we have no $Y$'s.  Let $\Omega$ be the set of 8 letter strings with no restrictions.
Remember that $|A\cup B| = |A|+|B|-|A\cap B|$ and remember that $|\Omega| - |A\cup B| = |A^c\cap B^c|$, the total you are really looking for.


text:
Q: ShareLaTex's margins I am a very beginning user of ShareLaTex. Generally I use only the most simple \documentclass{article} which is sufficient for my purpose. However, I consider the left-right top-bottom margins are too wide. How can I reduce them to 1" only?
Thanks for your time and help.


text:
Q: why yum-config-manager isnt part of rhel 7.6 we are using rhel 7.6 version
we are very surprised that yum-config-manager  isnt installed on rhel 7.6 by default
so we download the ISO file of rhel 7.6 , and mount all pkgs from rhel 7.6 to /mnt
and create the repo for rhel 7.6
so now we try to install the yum-config-manager
but:
yum install yum-config-manager
Loaded plugins: langpacks
configuration
No package yum-config-manager available.
Error: Nothing to do

so I not understand why this pkg/rpm isn't part of the ISO?
update , we did also
yum provides */yum-config-manager
Loaded plugins: langpacks
configuration
InstallMedia/filelists_db                                                                                | 3.4 MB  00:00:00

yum-utils-1.1.31-50.el7.noarch : Utilities based around the yum package manager
Repo        : InstallMedia
Matched from:
Filename    : /usr/bin/yum-config-manager

yum-utils-1.1.31-50.el7.noarch : Utilities based around the yum package manager
Repo        : @InstallMedia
Matched from:
Filename    : /usr/bin/yum-config-manager

A: The yum-config-manager program is not a standalone package. It is part of yum-utils package, thus:
yum install yum-utils

A: As the other answer says, it's part of the yum-utils package.  Any other missing package would most likely be on the supplementary binary DVD ISO. They can't fit everything on an ISO that can be burned to a DVD.
If you are installing off a mounted ISO image and aren't registering the system with redhat, why not just use the Everything ISO from CentOS?  It'd be easier to use.


text:
Q: How to chain vavr's Either nicely? I have a function returning an Either<MyError, String> (function2) , which result depends on another function returning another Either<MyError, SomethingElse> (function1)
Both functions rely on a Try block that could fail, and I want to compose those two first function to create a "handle" which will be the main function of my class.
There are basically 3 scenarios possible :

*

*function1 fails : I want handle to return the error given by function1

*function1 succeeds and function2 fails : function2 must return its own error then returned by handle

*both functions work : handle must return the String
Here is my current code :
private Either<MyError, Path> getPath(Arg arg) { // function 1
  return Try.of(() -> //some code that can fail)
              .toEither().mapLeft(e -> new MyError("Error message for function1", e));
}

private Either<MyError, String> getContent(Path path) { // function 2
  return Try.of(() -> //some code that can fail)
              .toEither().mapLeft(e -> new MyError("Error message for function2", e));
}

public Either<MyError, String> handle(Arg arg) {
  return Either.right(arg)
                .map(this::getPath)
                .map(this::getContent);
}

Everything works except the Handle function, I think that my problem might be related to the use of Either::map function, that might not be the thing for my case.
Any thought about this ?
Also, sorry if the answer seems obvious, i am quite new to functionnal programming and vavr.

A: The method that could help to make this work would be flatMap.
So if you use flatMap instead of map, the handle method will become something like:
public Either<MyError, String> handle(Arg arg) {
    return Either.<MyError, Arg>right(arg)
        .flatMap(this::getPath)
        .flatMap(this::getContent);
}

The scenarios you mentioned are all covered with this flatMap method.
See the Either.flatMap documentation for the official docs about it.


text:
Q: Change Default Windows Sound With Powershell I would like to find a way to change the windows default sound with powershell.
In vbs it is written like this:
WshShell.RegWrite "HKCU\AppEvents\Schemes\Apps\.Default\.Default\.Current\","c:\windows\media\horn.wav","REG_SZ"

I tried invoking the command but did not know the correct way to do it.

A: There are (at at least) two pretty simple ways to do this in PowerShell. The first is to use the WShell from within PowerShell (at least in Windows PowerShell 5.1 - unsure about Core):
$wshell = New-Object -ComObject WScript.Shell
$wshell.RegWrite("HKCU\AppEvents\Schemes\Apps\.Default\.Default\.Current\","c:\windows\media\horn.wav","REG_SZ")

The second is a more built-in way using PowerShell's Set-ItemProperty cmdlet - which should work in Core versions.
$SetItemProperty = @{
    Path         = "HKCU:\AppEvents\Schemes\Apps\.Default\.Default\.Current\"
    Name         = "(default)"
    Value        = "c:\windows\media\horn.wav"
}
Set-ItemPoperty @SetItemProperty

(Note: using the hashtable variable with the @ symbol instead of the common $ symbol is called Splatting; it's effectively just matching up parameter names to values so I don't have to write out a really (horizontally) long command.)

A: Powershell does not have a native cmdlets for that, beside you would have to use C# to get that functionality in powershell.
Luckily, someone did the hardwork and put that in to a module, check the following repo :
https://github.com/frgnca/AudioDeviceCmdlets
There are detailed instructions on how to install the module, once you done that you can see all devices
Get-AudioDevice -List

Index   : 1
Default : True
Type    : Playback
Name    : Speakers (2- Jabra EVOLVE LINK)
ID      : {0.0.0.00000000}.{8c58263c-e6a0-4c7b-8e51-5231f04cbcb9}
Device  : CoreAudioApi.MMDevice

From there you can see the current Default device and change it however you like.


text:
Q: Is it possible to start BackgroundTask again when the previous task is over I use UIBackgroundTaskIdentifier to begin background task in my app. When ı use  a IOS device (IOS 11.3) takes about 3 minutes. When ı use the other IOS device (IOS 13.4.1) takes about 30 seconds. This my code give in below;
var threadStarted = false
var backgroundTask : UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid

func extendBackgroundRunningTime() {
        if (self.backgroundTask != UIBackgroundTaskIdentifier.invalid) {
            // if we are in here, that means the background task is already running.
            // don't restart it.
            return
        }

        print("Attempting to extend background running time")

        self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "DummyTask1", expirationHandler: {
            print("Background Time:\(UIApplication.shared.backgroundTimeRemaining)")
            UIApplication.shared.endBackgroundTask(self.backgroundTask)
            self.backgroundTask = UIBackgroundTaskIdentifier.invalid
            self.extendBackgroundRunningTime()

        })

        if threadStarted {
            print("Background task thread already started.")
        }
        else {
            threadStarted = true
            DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async {
                while (true) {
                    // A dummy tasks must be running otherwise iOS suspends immediately
                    Thread.sleep(forTimeInterval: 1);
                }
            }
        }
    }

Please let me know is it possible to extend the working time of background. I get ;
" [BackgroundTask] Background task still not ended after expiration handlers were called: <UIBackgroundTaskInfo: 0x2812d6440>: taskID = 1, taskName = DummyTask1, creationTime = 52268 (elapsed = 0), assertion = . This app will likely be terminated by the system. Call UIApplication.endBackgroundTask(:) to avoid this."
and stop task.


text:
Q: SRC changes from Package to folders for all projects https://4.bp.blogspot.com/-sE4siTbywF8/Uny2CAzkwYI/AAAAAAAAAPc/tM7sQ_rtpN8/s1600/123123.PNG
https://3.bp.blogspot.com/-WV76Fqqag94/Uny2CJyk8TI/AAAAAAAAAPY/geInY3DIaGs/s1600/1231234.png
I don't know if I have touch any settings on eclipse but previously the src folders are suppose to be package and when I right click the options are different previously I even have a build path option anyone could tell me how to change back to my previous setting?
Tried restarted eclipse and it's useless

Solved by resetting perspective Windows>Reset perspective

A: it's a shot in the dark (see my comment) but try: the menu Windows --> Show view --> Package Explorer.


text:
Q: MockK System.getenv only Language: Kotlin
The goal is to test a method that calls System.getenv internally, I'd like to make this method produce a predefined result
Tried:
mockkStatic(System::class)

    every {
        System.getenv(any())
    } answers {
        when {
            firstArg() as String == "clientId" -> "aaa"
            firstArg() as String == "clientSecret" -> "bbb"
            else -> throw IllegalArgumentException("something went wrong")
        }
    }

    mockkStatic(System::class)

This appears to have sent the JVM into a bit of tipsy:
Exception in thread "main" java.lang.StackOverflowError
Exception: java.lang.StackOverflowError thrown from the UncaughtExceptionHandler in thread "main"

How does one test a method like this? (as you can imagine, a lot of code uses environment variables)


text:
Q: Query to find the records between the start date and end date I need to fetch the records that are falling between the start date and end date in oracle SQL. I 'll be having varStartDate and varEndDate. I want to fetch all records that are falling between the varStartDate and varEndDate. I am trying below query where first I am fetching recent start date i.e. in the past and end date i.e. in future. Secondly once I have the start date and end date I am to fetch all the records where startdate >= and enddate <=.
Start Date and End Date are DATE datatype.

Leave Type
Start Date
End Date
LeaveNumber

Annual Leave
08-OCT-21
08-OCT-21
24042

Annual Leave
29-NOV-21
29-NOV-21
24043

Annual Leave
23-DEC-21
23-DEC-21
30069

Annual Leave
29-DEC-21
31-DEC-21
30112

Annual Leave
24-JAN-22
24-JAN-22
30189

Query:
with RosterStartDate as (
  select max(start_date) as START_DATE
  from Payrollrecords
  where START_DATE < TO_DATE('2021-11-20','YYYY-MM-DD')
),
RosterEndDate as (
  select min(end_date) as END_DATE
  from Payrollrecords where END_DATE >= TO_DATE('2022-11-30','YYYY-MM-DD')
)

select *
from Payrollrecords
where START_DATE = (select START_DATE from RosterStartDate)
  and END_DATE = (select END_DATE from RosterEndDate)

The query is returning no records if RosterEndDate.END_DATE is null ( it is null if no end date is found beyond the varEndDate). It would be great if you can help me the with the optimized query.

A: RosterStartDate  is 08-OCT-21, RosterEndDate is NULL. Even if RosterEndDate were not null, but say 23-DEC-21, you wouldn't find a row matching both dates with
where START_DATE = (select START_DATE from RosterStartDate)
  and END_DATE = (select END_DATE from RosterEndDate)

You want this instead:
where START_DATE >= (select START_DATE from RosterStartDate)
  and END_DATE <= (select END_DATE from RosterEndDate)

But as END_DATE can be null, you finally want:
where START_DATE >= (select START_DATE from RosterStartDate)
  and
  (
    END_DATE <= (select END_DATE from RosterEndDate)
    or
    (select END_DATE from RosterEndDate) is null
  )

which is easier to write as
select *
from Payrollrecords
where START_DATE >= (select START_DATE from RosterStartDate)
and END_DATE <= (select nvl(END_DATE, Payrollrecords.END_DATE) from RosterEndDate)

or with an unreachable date literal which may be faster and even clearer:
select *
from Payrollrecords
where START_DATE >= (select START_DATE from RosterStartDate)
and END_DATE <= (select nvl(END_DATE, date '9999-12-31') from RosterEndDate)

Demo: https://dbfiddle.uk/taPsiGJw

A: You can just do this:
SELECT *
FROM Payrollrecords
WHERE start_date > TO_DATE('2021-11-20','YYYY-MM-DD')
AND end_date <= TO_DATE('2022-11-30','YYYY-MM-DD');

A: Not sure to understand properly the whole context of your question.
Payroll records represent date intervals. You want to find all payroll records that intersect with the interval (RosterStartDate - RosterEndDate), where RosterEndDate might be NULL. If it is NULL, we can replace it with today's value, using the NVL() function. So something like the following should do the job
SELECT * FROM Payrollrecords
WHERE START_DATE <= NVL((select END_DATE from RosterEndDate), CURRENT_DATE)
  AND END_DATE >= (select START_DATE from RosterStartDate)

A: Your question is very confusingly written; however, from your comment you appear to simply want:
SELECT *
FROM   Payrollrecords
WHERE  start_date <= DATE '2022-11-30'
AND    end_date   >= DATE '2021-11-20'

If your dates have a time component and you want the full day for 2022-11-30 then use:
SELECT *
FROM   Payrollrecords
WHERE  start_date <  DATE '2022-11-31'
AND    end_date   >= DATE '2021-11-20'

Original Answer
You can eliminate all the sub-queries if you use analytic functions.
If you want all the ranges that entirely are contained within the range then:
SELECT *
FROM   (
  SELECT p.*,
         MAX(CASE WHEN start_date <  DATE '2021-11-20' THEN start_date END) OVER ()
           AS max_start_date,
         COALESCE(
           MIN(CASE WHEN end_date   >= DATE '2022-11-30' THEN end_date   END) OVER (),
           DATE '9999-12-31' -- Or SYSDATE
         ) AS min_end_date
  FROM   Payrollrecords p
)
WHERE  start_date >= max_start_date
AND    end_date   <= min_end_date;

If you want ranges that overlap the range then:
SELECT *
FROM   (
  SELECT p.*,
         MAX(CASE WHEN start_date <  DATE '2021-11-20' THEN start_date END) OVER ()
           AS max_start_date,
         COALESCE(
           MIN(CASE WHEN end_date   >= DATE '2022-11-30' THEN end_date   END) OVER (),
           DATE '9999-12-31' -- Or SYSDATE
         ) AS min_end_date
  FROM   Payrollrecords p
)
WHERE  start_date <= min_end_date
AND    end_date   >= max_start_date;

fiddle

A: I suggest you include a row in the data that has a NULL end_date, such as below:
CREATE TABLE Payrollrecords  (
  leave_type VARCHAR2(50),
  start_date DATE,
  end_date DATE,
  leave_number NUMBER
);

BEGIN
  INSERT INTO Payrollrecords  (leave_type, start_date, end_date, leave_number)
  VALUES ('Annual Leave', DATE '2021-10-08', DATE '2021-10-08', 24042);

  INSERT INTO Payrollrecords  (leave_type, start_date, end_date, leave_number)
  VALUES ('Annual Leave', DATE '2021-11-21', DATE '2021-11-29', 24043);

  INSERT INTO Payrollrecords  (leave_type, start_date, end_date, leave_number)
  VALUES ('Annual Leave', DATE '2021-12-23', DATE '2021-12-23', 30069);

  INSERT INTO Payrollrecords  (leave_type, start_date, end_date, leave_number)
  VALUES ('Annual Leave', DATE '2021-12-23', NULL, 99999);

  INSERT INTO Payrollrecords  (leave_type, start_date, end_date, leave_number)
  VALUES ('Annual Leave', DATE '2021-12-29', DATE '2021-12-31', 30112);

  INSERT INTO Payrollrecords  (leave_type, start_date, end_date, leave_number)
  VALUES ('Annual Leave', DATE '2022-01-24', DATE '2022-01-24', 30189);
END;
/

1 rows affected

select *
from Payrollrecords

LEAVE_TYPE
START_DATE
END_DATE
LEAVE_NUMBER

Annual Leave
08-OCT-21
08-OCT-21
24042

Annual Leave
21-NOV-21
29-NOV-21
24043

Annual Leave
23-DEC-21
23-DEC-21
30069

Annual Leave
23-DEC-21
null
99999

Annual Leave
29-DEC-21
31-DEC-21
30112

Annual Leave
24-JAN-22
24-JAN-22
30189

select *
from Payrollrecords
where start_date <= TO_DATE('2022-11-30','YYYY-MM-DD') --range_end
and (end_date >= TO_DATE('2021-11-20','YYYY-MM-DD') --range_start
    or end_date IS NULL
    )

LEAVE_TYPE
START_DATE
END_DATE
LEAVE_NUMBER

Annual Leave
21-NOV-21
29-NOV-21
24043

Annual Leave
23-DEC-21
23-DEC-21
30069

Annual Leave
23-DEC-21
null
99999

Annual Leave
29-DEC-21
31-DEC-21
30112

Annual Leave
24-JAN-22
24-JAN-22
30189

see this fiddle
Notes:

*

*comparing start_date to the range_end, and end_date to range_start may seem counter-intuitive but this method works and simplifies the predicates needed

*as you include date literals in the CTEs, just use those same literals in the where clause and avoid the CTEs - bind variables will work here as well

*to account for NULLs add "or end_date IS NULL", with appropriate parentheses, don't use NVL or COALESCE in the predicate as these functions can be detrimental to query performance.


text:
Q: How best to read data from AWS Athena to process in a pyspark data frame? I uploaded a file to an S3 bucket and I can read it through AWS Athena.
Now I need to read this data from the S3 backet, with pyspark to make my changes and load it into another athena table (S3).
My doubt is:
What is the best way to do this? I'm currently using spark.sql:
df = spark.sql(f" SELECT sector, employee, employee_quantity FROM company"

Is there a more performative or elegant way to run this query?


text:
Q: How to replace the number values of a column by low to high in python? i have this:
A 29
B 45
C 75
D 22
E 58
E 58
F 61
G 47
G 47

and i need to get this:
A 2
B 3
C 7
D 1
E 5
E 5
F 6
G 4
G 4

i think about sort ascending and rank and after change the column values but this is not applied to the duplicates in the first column. Need the equal values in column 1 has the same rank value in the column 2. Anyone?

A: You can sort the values, enumerate that, then loop through the original data getting the indexes of the value of the original data. Below is an example of what I mean: (just implement it to your needs)
data = {
    "A": 29,
    "B": 45,
    "C": 75,
    "D": 22,
    "E": 58,
    "E": 58,
    "F": 61,
    "G": 47,
}

sorted_data = dict(map(reversed, enumerate(sorted(data.values()), 1)))

result = {k: sorted_data[v] for k, v in data.items()}

result
{'A': 2, 'B': 3, 'C': 7, 'D': 1, 'E': 5, 'F': 6, 'G': 4}


text:
Q: Get day of week of a specific week; Bash; Linux I have a week number in 2018, 38 for example.
And I need to get date of Monday for that week.. (it should be 17092018)
Really weird but I didn't find anything on StackOverflow for this (simple?) task.


text:
Q: How to expand command-mode abbreviations in Vim? I have defined several abbreviations for command and insert-mode, e.g.:
ca selforg :e d:\projects\org\self-org.md

I know that I can list them with :ab
Is it possible to expand the example by typing self<tab> to selforg as it is possible for built-in or plugin commands?

A: List them with :ab; restrict the list with :ab s<Tab>
So, if you type :ab self<tab> this expands to selforg.
If you have similar named abbreviations the menu will show all your possible resolutions.
If you need to "tab complete and auto commit" your abbreviations, see this answer: https://vi.stackexchange.com/questions/7750/how-do-i-manage-and-remember-many-abbreviations-in-my-vimrc


text:
Q: I executed the following program but i m confused about its output? I am confused about the no of child process it is creating on execution
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i=0;
fork();
fork();
fork();
fork();
pid_t pid;
    if((pid=fork()) == 0) {
        printf("I am the child: %u\n", getpid());
}
    else {
        printf("I am the parent: %u and my child is: %u\n", getpid(),pid);
    }

return 0;
}

can somebody help me in understanding that why there are so many child process and why parent id is different every time.
The output I get is :
saqlain@ubuntu:~/Desktop$ gcc -c fork.c
saqlain@ubuntu:~/Desktop$ gcc -o fork fork.c
saqlain@ubuntu:~/Desktop$ ./fork
I am the parent: 11842 and my child is: 11847
saqlain@ubuntu:~/Desktop$ I am the child: 11847
I am the child: 11849
I am the parent: 11846 and my child is: 11850
I am the child: 11867
I am the child: 11869
I am the parent: 11843 and my child is: 11856
I am the child: 11850
I am the parent: 11848 and my child is: 11857
I am the parent: 11852 and my child is: 11860
I am the parent: 11845 and my child is: 11849
I am the parent: 11854 and my child is: 11866
I am the child: 11859
I am the child: 11856
I am the child: 11857
I am the parent: 11862 and my child is: 11869
I am the parent: 11865 and my child is: 11870
I am the child: 11860
I am the child: 11866
I am the parent: 11855 and my child is: 11867
I am the parent: 11851 and my child is: 11859
I am the parent: 11863 and my child is: 11871
I am the parent: 11858 and my child is: 11872
I am the parent: 11868 and my child is: 11873
I am the parent: 11844 and my child is: 11861
I am the child: 11870
I am the child: 11861
I am the child: 11864
I am the child: 11872
I am the child: 11871
I am the child: 11873
I am the parent: 11853 and my child is: 11864

A: You're executing fork 5 times, and on the fifth, printing output.
Each fork splits control into two identical copies, so 2×2×2×2×2 = 32 copies, of which, 16 each identify as parents and children based upon the fifth and final fork.


text:
Q: Trouble installing PyAutoGUI on Python 3.8 (64-bit Windows) I am getting an error when I am installing PyAutoGUI and I cannot find out the problem. I tried installing it using pip. I also installed it using Anaconda but I cannot import it into Python. Any help is appreciated.
Version: Python 3.8
OS: Windows 10
Command Used: pip install pyautogui
Error:
ERROR: Command errored out with exit status 1:
       command: 'C:\Program Files\Python38\python.exe' 'C:\Users\HP\AppData\Roaming\Python\Python38\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\HP\AppData\Local\Temp\pip-build-env-j7d0dtw8\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel
           cwd: None
      Complete output (14 lines):
      Traceback (most recent call last):
        File "C:\Program Files\Python38\lib\runpy.py", line 194, in _run_module_as_main
          return _run_code(code, main_globals, None,
        File "C:\Program Files\Python38\lib\runpy.py", line 87, in _run_code
          exec(code, run_globals)
        File "C:\Users\HP\AppData\Roaming\Python\Python38\site-packages\pip\__main__.py", line 23, in <module>
          from pip._internal.cli.main import main as _main  # isort:skip # noqa
        File "C:\Users\HP\AppData\Roaming\Python\Python38\site-packages\pip\_internal\cli\main.py", line 5, in <module>
          import locale
        File "C:\Program Files\Python38\lib\locale.py", line 16, in <module>
          import re
        File "C:\Program Files\Python38\lib\re.py", line 145, in <module>
          class RegexFlag(enum.IntFlag):
      AttributeError: module 'enum' has no attribute 'IntFlag'
      ----------------------------------------
    ERROR: Command errored out with exit status 1: 'C:\Program Files\Python38\python.exe' 'C:\Users\HP\AppData\Roaming\Python\Python38\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\HP\AppData\Local\Temp\pip-build-env-j7d0dtw8\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel Check the logs for full command output.

A: I think you should re-install your python installation or try using a different version.

A: After Hitesh's answer, I tried downgrading my pip version to 1.2.1 and installed it again which worked. A huge thanks to Hitesh Patil!


text:
Q: Why I cant use the value of a static variable?     public class Test{

            static String symbol;

        public static void main (String[] args){

            String symbol = args[0];

            letter();

        }
        static void letter(){
            System.out.println(symbol);

        }
}

Why every time i try to run this the method letter successfully runs but prints Null? I just want to have one variable for all methods so that they can use its value.

A: When you write String symbol = args[0]; in the main method you are declaring a new local variable, which shadows (hides) the static field called symbol. When you call letter that local variable is no longer applicable (since it is only applicable to main) and thus the value of the static field is printed, but that value is null since that static field was never assigned.
Change that line to symbol = args[0]; so it stores the value of args[0] to the static field instead.


text:
Q: Default outlet routes values in Angular? I have  a general Artists components which has this HTML :

  <router-outlet name="left"></router-outlet>

  <router-outlet name="right"></router-outlet>

The left pane should contain Artists list
The right pane should contain Artist details
Here is the routes definition :
const routes: Routes = [
  {
    path: 'artists',
    component:ArtistsComponent ,
      children: [
          {
              path: 'list',
              outlet: 'left',
              component: ArtistListComponent
          } ,
          {
              path: ':id',
              outlet: 'right',
              component: ArtistDetailsComponent
          }
      ]
}
 ,
  {
    path: '',
      pathMatch:'full' ,
    redirectTo: '/artists',
  }
]

So when The app is up , this is what I see
URL : http://localhost:4200/artists

And if I want to see both left pane and right pane I should navigate to :
URL : http://localhost:4200/artists/(left:list//right:2)

Question :
How can I declare a default outlet routes values ?
Something like :
...
{
   default:'list',
   path: 'list',
   outlet: 'left',
   component: ArtistListComponent
} ,
{
   default:'1',
   path: ':id',
   outlet: 'right',
   component: ArtistDetailsComponent
}

NB
I know I can redirect the app (at startup) straight to
http://localhost:4200/artists/(left:list//right:2) , but I wonder if I can specify default values for outlets in the config itself

A: Use redirectTo with empty path:
const routes: Routes = [
{
  path: 'artists',
  component:ArtistsComponent ,
  children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'artists/(left:list)'
      },
      {
          path: 'list',
          outlet: 'left',
          component: ArtistListComponent
      } ,
      {
          path: ':id',
          outlet: 'right',
          component: ArtistDetailsComponent
      }
  ]

}


text:
Q: Display the date in PHP from a datetime field in SQLExpress I have been crawling through the web and trying to find a solution so I am coming here.
I have an MSSQL database and I am using PHP5.3 to connect and fetch data from one of the tables. The issue I am having has to do with dates.
$result = sqlsrv_query($conn, "SELECT TOP 10 * FROM TAData WHERE DateTime >= '2013-11-11T07:45:00.000'");

while($row = sqlsrv_fetch_array($result))
{
print_r ($row['DateTime']);
echo "<br />";
echo date("Y-m-d H:i:s", strtotime($row['DateTime']));
}

With the output looking like this:
DateTime Object ( [date] => 2013-11-11 07:46:08 [timezone_type] => 3 [timezone] => Africa/Johannesburg )

January 1, 1970, 2:00 am

All I need is a simple date and time (YYYY-MM-DD HH:MM) that I can use. Once I have it in any sort of format (or understand how it works), I can manipulate it from there. But it is not displaying in any functional way.

A: You cannot access property date on DateTime object, like in the other answer:
$dt = new DateTime();
echo $dt->date; # this will trigger Notice: Undefined property: DateTime::$date

Please don't use any strtotime() or date() functions, when you already have DateTime object! Just use method format() on DateTime object to format datetime, like:
echo $dt->format('Y-m-d H:i:s');
# or $row['DateTime']->format('Y-m-d H:i:s'); in your example