text:
Q: Highlight lost data bit in tikz-timing with nodes or some other method I want to highlight a lost data bit using nodes or something that will give me similar results.
Following code
\begin{figure}[h]
\centering
% !{code} Places given code into the internal tikzpicture
\begin{tikztimingtable}
 [timing/slope=.5]
 C1                     & 2C 8{4C} 2C                           \\
 C2                     & 17{2C}   2C                           \\
 A                      & 2X 8L  4H 4L 18H                      \\
 B                      & 10X 16L 10H                           \\
 \extracode
  \draw (0,0) circle (0.2pt); %Origin
  \begin{pgfonlayer}{background}
    \vertlines [help lines]{2,10,14,18,26,34}
 \end{pgfonlayer}
\end{tikztimingtable}

\caption[Zeitablaufdiagramm Datenverlust]{Zeitablaufdiagramm Datenverlust}
\label{fig:zeitablauf_datenverlust}
\end{figure}

gives me

What I want to create is something like this

It may be possible using !{code} and drawing this circle arrow and text manually inside the tikzpicture enviroment.

*

*How can I draw this circle with the arrow and text in my tikz-timingtable?

A: Each line is node with the name rowN, with N increasing from 1. Several anchors are defined, see figure 2.1 in the manual of tikz-timing. I just used the start anchor of the third row, and positioned a node with a pin relative to that. See page 19 (section called Positions & nodes inside the table) of the manual for a description of the coordinate system used.
More detail
In this case the highlighting is done by adding the following after \extracode:
\path [every pin edge/.style={<-,thick,red}] (row3.start) ++(12,-0.9\rowdist)
      node[red,circle,draw,minimum size=1.2cm,pin={[red]300:Bitfehler}]{};

*

*[every pin edge/.style={<-,thick,red}] defines how the pin line should be drawn. A pin can be used as an annotation for a node, it's simply a new node placed next to the "parent" node, with a line drawn from it to the parent.

*(row3.start) is a coordinate specification. As mentioned above, each of the lines in the timing table are nodes that have several anchors. The start node is unsurprisingly at the start of the line.

*++(12,-0.9\rowdist) means that the point is moved a distance of 12 units in the current coordinate system to the right, and 0.9\rowdist down. Why 12? A quote from the manual:

The timing column starts at x = 0 and goes into the positive range while scaled using the period width. Example: HHHh has a width of 3.5.

The place where you wanted to have your circle is between 10 and 14, this is also reflected in the coordinates for your vertical lines.
Why -0.9\rowdist? Trial and error, to be honest.

*node[red,circle,draw,minimum size=1.2cm,pin={[red]300:Bitfehler}]{}; -- at the active coordinate (i.e. 12 to the right and a bit down from the start of the line), add a red circular node that should be at least 1.2cm in diameter, and where the border is drawn. In pin={[red]300:Bitfehler} the square brackets are where you can add options for the pin label. 300 is an angle, it indicates where on the node the pin should be drawn.

\documentclass[border=5mm]{standalone}
\usepackage{tikz-timing}

\begin{document}
% !{code} Places given code into the internal tikzpicture
\begin{tikztimingtable}
 [timing/slope=.5]
 C1                     & 2C 8{4C} 2C                           \\
 C2                     & 17{2C}   2C                           \\
 A                      & 2X 8L  4H 4L 18H                      \\
 B                      & 10X 16L 10H                           \\
 \extracode
  \draw (0,0) circle (0.2pt); %Origin

   \path [every pin edge/.style={<-,thick,red}] (row3.start) ++(12,-0.9\rowdist)
      node[red,circle,draw,minimum size=1.2cm,pin={[red]300:Bitfehler}]{};
  \begin{pgfonlayer}{background}
    \vertlines [help lines]{2,10,14,18,26,34}
 \end{pgfonlayer}
\end{tikztimingtable}
\end{document}


text:
Q: Getting statuses after gdb finishes When GDB finishes, I get the following output:
─── Output/messages ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
[Inferior 1 (process 18473) exited with code 05]

*

*Is there a way to capture the exit code in the prompt, 5, after gdb has finished?

*Does 18473 refer to the thread ID, the (unix) process ID, or something else?

*Finally, why it is called an "inferior" process?

A:
Is there a way to capture the exit code in the prompt, 5, after gdb has finished?

In GDB, you could use $_exitcode convenience variable.

Does 18473 refer to the thread ID, the (unix) process ID, or something else?

The UNIX process ID.

Finally, why it is called an "inferior" process?

That's just what GDB developers call it. It the same as "the process GDB is debugging" (as opposed to the GDB process itself), and is much shorter. It's also "inferior" to GDB in the sense that GDB is controlling it (making it stop, single-step, or run as GDB desires).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting to Asterisk Manager Interface using php Http Connection I am trying to connect to my Asterisk Manager interface using Http Connection. This is not working for me. Anyone can help for me?
I need to login to Asteric manager interface using php. PHP file should be in another server.
manager.conf
[general]
enabled = yes
webenabled = yes
port = 5038
bindaddr = 0.0.0.0
displayconnects=no ;only effects 1.6+

[sameera]
secret = 123123
deny=0.0.0.0/0.0.0.0
permit=192.168.100.122/255.255.255.0
read = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originate
write = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originate
writetimeout = 5000

192.168.100.122 is my server ip address
login.php
<?php

    $timeout = 3;

    $socket = fsockopen("192.168.100.122",'12321',$errno,$errstr,$timeout);

    fputs($socket,"Action: Login\r\n");
    fputs($socket,"Username: sameera\r\n");
    fputs($socket,"Secret: 123123\r\n\r\n");

    $line="";
    $response="";

    while($line != "\r\n"){
            $line = fgetss($socket,128);
            $response .= $line;
    }

    echo $response;
?>

A: Your port number is wrong, change 12321 to 5039
$socket = fsockopen("192.168.100.122",'5039',$errno,$errstr,$timeout);
<?php
$timeout = 3;
$socket = fsockopen("127.0.0.1",'5038',$errno,$errstr,$timeout);
fputs($socket,"Action: Login\r\n");
fputs($socket,"Username: julio\r\n");
fputs($socket,"Secret: 12345\r\n\r\n");
$line="";
$response="";
while($line != "\r\n"){
        $line = fgetss($socket,128);
        $response .= $line;
}

echo $response;

?>

A: Use phpagi/ami library,NOT re-create it again
Do debug of your code and ensure your firewall allow connect.


text:
Q: Python list append issue One of my function appends an item to the list. This appended list is then sent as argument into two recursive function. But when one of the called function updates its own local list, the original list gets modified because of which second recursive function gets modified list as input.
Basically this is a sort of thing that i am trying to do. Here i want
[2]
[2,3]
[2,4] as output but i am getting [2][2,3] as only output as the original list is getting modified. Is there any way that i can send same list in two functions.
def Growtree(llst, x):
  if len(llst) == 2:
    return

  llst.append(x)
  print(llst)

Growtree(llst,3)
Growtree(llst,4)

A: When Growtree(llst, 4) is called there is already 2 and 3 in the list llst. So it returns without appending a new element because of your if.
What you need is to make a copy of the list (before to call Glowtree of inside, it depends if you want the orignal list to get modified).
To copy a list, see https://stackoverflow.com/a/2612815/3410584

A: use copy.deepcopy()
The reason why the original list got modified in your functions, is that generally when you passing an mutable obj in python. It's the reference got passed into.


text:
Q: Woocommerce Product Scraping Regular and Sale Price not extracting I am creating a data scraper using scrapy. I shell the product url using
scrapy shell 'https://royalprint.pk/product/name-print-superhero-sweatshirt-011/'

and then run this command
In [43]: response.css('span.woocommerce-Price-currencySymbol::text').get()
Out[43]: 'Rs'

It only returns the currency symbol.
Here is the source code product image

Someone please correct me what I did wrong here ?
Regards

A: Its might help.
for price in response.css('p.price'):
    print(price.xpath('./del/span/bdi/text()').get())
    print(price.xpath('./ins/span/bdi/text()').get())

A: Nothing wrong really, but you just mistaken the element you need to get. I guess you want to get the price number, in that case you should use something like:
span.woocommerce-Price-amount bdi::text

as you can see, it's the bdi element the one containing the information you want, not the inner span

A: The span element you are referencing only contains Rs text.
Rs
But the price information you want is after the closing tag of the span element.
The price is included in the bdi element. since we have other bdi elements on the webpage so we need to reference the exact one.
response.xpath("//p[@class='price']//bdi/text()").extract()


text:
Q: How to define a `Any.x` type value in ts-toolbelt? Why does ts-toolbelt define x as typeof _ & {} and what does this mean?
// ts-toolbelt:Any/x.d.ts

declare const _: unique symbol;
/**
 * A placeholder that is used in various ways
 */
export declare type x = typeof _ & {};
export {};

I tried to define a type x variable but have this error:
import { Any } from 'ts-toolbelt'

// Type 'unique symbol' is not assignable to type 'x'.
export const __: Any.x = Symbol('__fp_pieces_gap__')


text:
Q: Dynamically select all items in a Multi-Select listbox using jquery I'm very new to using Javascript/Jquery, so I appreciate you reading and your patience with what is likely a simple problem. This is a bit of a multi-tiered question, so let me explain.
I have several databound ASP listboxes. I also have several checkboxes, one for each listbox. I have the checkboxes wired, using Javascript, to select or deselect all the Listbox items on click.
My goal was to construct a single method that will pass the checkbox and its corresponding listbox to the javascript method and either select or unselect everything in the listbox. I could do this very simply in C#, but we can't use a postback, as the page is already slow and complex.
So this already WORKS in Javascript (and I'll post my code below this), but the problem I'm encountering is that when we have a longer listbox (that is, 20+ list items), IE essentially makes you watch as it scrolls through all of them and selects them all. Chrome doesn't have this problem, and Firefox is at least a lot faster, but IE is the browser a good 75%+ of our customers use.
ASP:
<asp:ListBox ID="StatusListBx" runat="server" DataSourceID="StatusLds"
    DataTextField="Status" DataValueField="StatusID"  Width="140px" Height="55px" AppendDataBoundItems="true"
    SelectionMode="Multiple"/>
<asp:LinqDataSource ID="StatusLds" runat="server"
    ContextTypeName="ElementDataConnector.ElementDBDataContext"
    Select="new (StatusID, Status)" Where="StatusID < 4" TableName="Lookup_Status" >
</asp:LinqDataSource>
<br />
<asp:CheckBox id="SelectAllProjectStatusChkbx" runat="server" Text="Select All" />

C#:
protected void Page_Load(object sender, EventArgs e)
{
    SelectAllProjectStatusChkbx.Attributes.Add("onclick", "selectDeselect(" + StatusListBx.ClientID + ",this)");
}

Javascript:
function selectDeselect(listbox, checkbox) {
    if (checkbox.checked) {
        var multi = document.getElementById(listbox.id);
        for (var i = 0; i < multi.options.length; i++) {
            multi.options[i].selected = true;
        }
    } else {
        var multi = document.getElementById(listbox.id);
        multi.selectedIndex = -1;
    }
}

(I've replicated this for every applicable Listbox/Checkbox combination - it's a scalable task)
So to the actual questions:

*

*Were I to utilize JQuery rather than Javascript for this functionality, would I be able to avoid that whole "scrolling/selecting" effect?

*If I can avoid that scrolling effect, how can I dynamically pass the listbox to JQuery rather than having to write a custom method out for each Listbox/Checkbox combination?
Thank you for reading and thank you for any help offered.

A: Check out this post:
http://www.craiglotter.co.za/2010/02/26/jquery-select-all-options-in-a-multiple-select-listbox/
jQuery: Select all options in a Multiple Select Listbox
$("#multipleselect option").prop("selected",true);

A multiple select listbox with everything already selected for you!

A: I don't have IE on hand to check the scrolling effect you are referring to but it should be easy enough for you to test.  You could keep your selectDeselect function but it might change to something like this (assuming jQuery ~ 1.7.2+):
function selectDeselect(listbox, checkbox) {
    var select_all = $(checkbox).prop('checked') ? true : false;
    var select = $(listbox);
    $('option', select).prop('selected', select_all);
}

I would expect the non-jQuery code to be faster but give it a go...
Edit: The above is slow in IE too.
I'm not a fan of this method but you could try replacing the actual HTML in the select dropdown.  Something like:
function selectDeselect(listbox, checkbox) {
    var select_all = $(checkbox).prop('checked') ? true : false;
    var select = $(listbox);
    if (select_all) {
        var clone = select.clone();
        $('option', clone).attr('selected', select_all);
        var html = clone.html();
        select.html(html);
    }
    else $('option', select).removeAttr('selected');
}

It seems to work in IE9: jsfiddle


text:
Q: What is the equivalent of Python 3 sys.stdout.fileno() in Python 2 I am working on a code in Python 2.7. I use a very specific library written partially in C with a Python API. This library uses printf to output to stdout. I would like to suppress that. I already found this question: How do I prevent a C shared library to print on stdout in python? All of the provided answers use sys.stdout.fileno(). When I run my code I get:
original_stdout_fd = sys.stdout.fileno()
AttributeError: 'FlushingStringIO' object has no attribute 'fileno'

I suspect the problem is that I am using Python 2.7. Are my assumptions correct and is there a way to achieve this with Python 2.7?

A: The problem was that sys.stdout was replaced by FlushingStringIO by a library: https://github.com/flexible-atomic-code/fac. It also somehow depends on this detail and breaks otherwise. As there is no reasonable alternative to the library there is no way to suppress stdout output in this case.


text:
Q: Mysql query to add a table and insert table data from another table? I am trying to create a table (nightly routine) and then insert table data from another table.  Right now I get that the table already exists.  Not sure the syntax I should be using here.
[Err] 1050 - Table 'testgiver.safewp_users' already exists
DROP TABLE
IF EXISTS testgiver.safewp_users;
CREATE TABLE `testgiver.safewp_users` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_login` varchar(60) NOT NULL DEFAULT '',
  `user_pass` varchar(64) DEFAULT '',
  `user_nicename` varchar(50) NOT NULL DEFAULT '',
  `user_email` varchar(100) NOT NULL DEFAULT '',
  `user_url` varchar(100) DEFAULT '',
  `user_registered` datetime NOT NULL DEFAULT '2014-01-01 10:00:00',
  `user_activation_key` varchar(60) NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  `display_name` varchar(250) NOT NULL DEFAULT '',
  PRIMARY KEY (`ID`),
  KEY `user_login_key` (`user_login`),
  KEY `user_nicename` (`user_nicename`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
INSERT INTO safewp_users (`user_login`, `user_nicename`, `user_email`, `display_name`)
    SELECT
    ldap_full.uid,
    ldap_full.sn,
    ldap_full.mail,
    ldap_full.cn
FROM
    ldap_full

A: This looks like a simple typo.
CREATE TABLE `testgiver.safewp_users`

should probably read
CREATE TABLE `testgiver`.`safewp_users`

Otherwise, you are attempting to create a table called 'testgiver.safewp_users' every single time.

A: Get rid of the quotes in your create table statement.  The quotes are causing you to attempt to create a table named testgiver.safewp_users in the default schema, instead of a table named safewp_users in the testgiver schema.


text:
Q: Why is OnDragEnter not called? I have added the COleDropTarget variable to my view class and registered it in the OnCreate(), which is being called at startup. I added the OnDragEnter and OnDrop virtual functions (not the others yet, as OnDragLeave). But they are not called when I drag (or drop) a piece of text over them.
I just happened to think about the fact that I had already implemented the dropfiles function to the same window. Is this preventing the text drag?
What else do I need?
TIA,
Harvey

A: Solved:
In using F1 to get the syntax for OnDrop and the others, MSDN gave me:
virtual BOOL OnDrop(
   CWnd* pWnd,
   COleDataObject* pDataObject,
   DROPEFFECT dropEffect,
   CPoint point
);

But the correct virtual function does not have the first parameter and should be:
virtual BOOL OnDrop(
   COleDataObject* pDataObject,
   DROPEFFECT dropEffect,
   CPoint point
);

Same with the others. So I was never actually overriding the default functions.


text:
Q: Marketing Cloud Automation studio won't update data extension We are having trouble updating records in a data extension from an automation. It creates new records but it won't update. We have the salesforce custom object ID set up as the primary key and the subscriber key linked up in the extension. We then run a SQL activity in the automation studio which "Updates" the data extension, but it doesn't update existing record, it just adds any new ones.
Can anyone help please?
Many Thanks
**** Edit ****
So here is my data extension, the ID is set to the primary key. I can't use the subscriberKey because it is a one to many relationship so there would be multiple records with the same subscriberkey in this data extension

My SOQL that is used in the automation to populate the data extension.
Select id,
Buyer_Type__c as PlotID ,
Developments__c as DevelopmentID,
Region__c as RegionID,
Lead__c as SubscriberKey,
Customer_Email__c as EmailAddress,
Status__c as Status,
Record_Type_Name__c as RecordType
from Interest__c_Salesforce
where Status__c = 'Active'

A: Check that your update type/data action is toUpdate and not Append:


text:
Q: how to link the class shown below with main activity here is the code of the class which i created which extends MainActivity and how can i call this from MainActivity?
I'm trying to figure out where I went wrong on referencing my surface view class, not my view. I only did the view as an example.  Here is my main class:
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

 public class SurfaceViewExample extends Activity implements OnTouchListener{

     OurView v;
     Bitmap ball;
     float x,y;

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        v=new OurView(this);
        v.setOnTouchListener(this);
      ball=BitmapFactory.decodeResource(getResources(),R.drawable.tennis_ball);
        x = y = 0;
        setContentView(v);
    }

    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        v.resume();
    }
    public class OurView extends SurfaceView implements Runnable{
      Thread t;

      SurfaceHolder holder;

      boolean isItOk=false;

  public OurView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        holder=getHolder();
    }

    public void run() {

        // TODO Auto-generated method stub

        while( isItOk ==true)
        {
         //drawing
         if(holder.getSurface().isValid()) {

            continue;

         }

     Canvas c=holder.lockCanvas();
         c.drawARGB(255,150,150,10);
         c.drawBitmap(ball, x+(ball.getWidth()/4), y+(ball.getHeight()), null);

         holder.unlockCanvasAndPost(c);

        }
     }
    public void pause()
    {
        isItOk=false;
        while(true) {
            try {
                t.join();
            }catch(InterruptedException e) {

                e.printStackTrace();

            }
            break;

        }
    }

    public void resume()
    {
       isItOk=true;
       t=new Thread(this);
       t.start();
    }

     }
     public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    return false;
      }

  }

A: The much i got is that you want to go SurfaceViewExample  from your main activity for that you need to use intent on button click like
Intent i = new Intent(this, SurfaceViewExample.class);

startActivity(i) ;

and you have to add a permission in menifest to got to that activity like
<activity android:enabled="true" android:name="SurfaceViewExample" />

and you can see these links also

Calling one Activity from another in Android
http://developer.android.com/reference/android/content/Intent.html


text:
Q: Kettle - Filter duplicated rows by field value I have a single input stream from a csv file. This stream is from a User Table, where the user may be duplicated with different ID's.
I need to clean this stream. The combo of [Name + Surname] always is unique, but I need to make a comparison before selecting one, because I want to keep the information of the most recent and create a new field based on the comparison of other value.
I have a Timestamp that will be used for selecting the row.
This is a example of input stream:

And this is a example of the output I want:

What tool would be the best for this task?
Thanks in advance.

A: This should work with a bit of sorting and grouping in pentaho kettle.

*

*CSV-File Input with your table (be sure that TimeUpdated is a date-format)

*Sort-Step: Sort by Name, Surname, Surname2, TimeUpdated (Asc: No)

*Group by-Step: Group by Name, Surname, Surname2; Aggregate: id (first value), TimeUpdated (first value), Status (Concatenate String seperated by (value: +)

A: You can do the following:

*

*Sort the rows by Name, Surename1, Surename2 and TimeUpdate using a step called Sort rows;

*Do either of the following:

*

*A step called Unique rows, where the Fields to compare on would state the fields which you are willing to make unique;

*A step called Group by, where The fields that make up the group would state those fields you want to make unique, and the Aggregates would state all other fields. The Type dropdown next to each of the aggregates should be set according to the way you sorted your data in step 1:

*

*If you decided that the most important rows to keep, out of duplicates, are the ones with the most recent data, and you sorted TimeUpdate descending , then choose Type = "Last value" or "Last non--null value" for all of the Aggregates;

Another thing you should note, but that's more general - there's a step called Memory Group by, which saves you the expensive computational time of sorting before grouping, but that step is good only if you can make sure that the data passing through it won't overflow the memory, i.e. small data sets.


text:
Q: Determining the number of files and subdirectories in Linux When displaying directories in Linux using ls -ld, I get something like this:
user@shell:~/somedirectory$ ls -ld
drwxr-xr-x 2014 K-rock users 65536 20011-11-05 11:34
user@shell:~/somedirectory$

How would I find the number of subdirectories and files in the somedirectory using the result above? From what I understand, the number of links corresponds to the number of subdirectories, but what about the number of files? How would I read the result of the ls -ld to find those numbers?
Also, this is an assignment and I have to say the number of files and subdir that are in somedirectory using the result shown above. So I can't really use any other code unfortunately.

A: Since, you want to decipher from the output that you have got, we will try and simplify things.
ls -ld
drwxr-xr-x 4 root root 4096 Nov 11 14:29 .

Now, ls -ld on a directory gives me the output as above. Now, the number 4 is something that you need to concentrate on. The 4 corresponds to:

*

*the entry for that directory in its parent directory;

*the directory's own entry for .;

*the .. entries in the 2 sub-directories inside the directory.

To verify this, if I just issue ls I could see that I have couple of more directories. So, this gives an idea of what we could decipher from the output of your case.
drwxr-xr-x 2014 K-rock users 65536 20011-11-05 11:34

There are 2012 sub-directories inside which is why you get 2014 in the output.
As to the number of files, it is not possible to find it out from the output that you have.
To test if my theory is correct, I did the below testing.
ls -la | grep -E '[d]' #Display only directories
drwxr-xr-x 12 root root 4096 Nov 11 14:42 .
drwxr-xr-x  4 root root 4096 Nov 11 14:20 ..
drwxr-xr-x  3 root root 4096 Nov 11 14:45 hello1
drwxr-xr-x  2 root root 4096 Nov 11 14:42 hello2
drwxr-xr-x  2 root root 4096 Nov 11 14:42 hello3
drwxr-xr-x  2 root root 4096 Nov 11 14:42 hello4
drwxr-xr-x  2 root root 4096 Nov 11 14:42 hello5
drwxr-xr-x  2 root root 4096 Nov 11 14:42 hello6
drwxr-xr-x  2 root root 4096 Nov 11 14:42 hello7
drwxr-xr-x  2 root root 4096 Nov 11 14:42 hello8
drwxr-xr-x  2 root root 4096 Nov 11 14:21 hello-subdir
drwxr-xr-x  2 root root 4096 Nov 11 14:29 spaced hello

Now, I issue ls -ld command and the output I get is,
ls -ld
drwxr-xr-x 12 root root 4096 Nov 11 14:42 .

It did not take into consideration the files or subdirectories nested inside the subdirectories of the folder. Basically, the above command says I have 10 directories inside my folder.
P.S.: It is often a bad idea to parse something from ls output as it is not reliable. Use find with -maxdepth instead if you have a chance to use it.

A: If you can use ls, then I assume you can use builtin bash functionality too.
Using pure bash to count all entries in the current directory:
$ num_entries () (       # Define a function to:
> shopt -s nullglob      # expand * to empty string if no files
> shopt -s dotglob       # include .files in * expansion
> a=( * )                # create array containing all entries in current directory
> echo ${#a[@]}          # display length of array (number of directory entries)
> )
$ num_entries            # call function for current directory
467
$

Using pure bash to count all subdirectories in the current directory:
$ num_dirs () (
> shopt -s nullglob
> shopt -s dotglob
> a=( */ )               # note the */ glob which selects only directories
> echo ${#a[@]}
> )

I put these in ( ) function bodies so the shopt settings would only have effect within that function and have no other side effects.

A: In a simple case this works:
ls -A1 | wc -l

A: You may combine a couple of approaches

*

*Number of files in a directory
ls -l | grep "^-" | wc -l

*Walk through subdirectories
find ./subdirectory -type d

*put together in one command
 find ./subdirectory -type d | xargs -I{} sh -c "ls -l {} | grep -c '^-'"

Will recursively result a count of files restisting in the directories.
Of course there a multiple ways to prettify or enrich the output.


text:
Q: Is there any function that can change the column names dynamically as per filter changes in Tableau CRM Is it possible changing the columns dynamically in Tableau crm lens as per filter changes.?

A: Not sure what exactly your issue is; but you can bind your static toggle to make the changes in columns of a lens.


text:
Q: How to see if values are in the same "line" within an object in javascript Not sure how to approach this problem, but I want to see if two values are in the same 'line'
var inventory_needed = [
    { section: "hardware",          supplies: "hammers"                       },
    { section: "plumbing",          supplies: "pipes"                         },
    { section: "garden",            supplies: "grass seeds"                   },
    { section: "cleaning supplies", supplies: ["hand sanitizer", "detergent"] },
    { section: "appliances",        supplies: ["fridges", "dishwashers"]      }
];

psuedocode of what I want to try to attempt
if(section.value && supplies.value in the same line) {
    return true;
}
else {
    return false;
}

//example 1
if("appliances" && "fridges" in the same line) {
    return true; //would return true
}
else {
    return false;
}

//example 2
if("plumbing" && "fridges" in the same line) {
    return true;
}
else {
    return false; //would return false
}

A: By in the same line, you seem to mean defined within the same object in the array. If that's correct, the way to do that is like this:
function inTheSameLine(section, supplies){
    return inventory_needed.some(obj => {
        return obj.section === section && (
            obj.supplies === supplies || (
               Array.isArray(obj.supplies) && obj.supplies.includes(supplies)
            )
        );
    });
}

The JavaScript array some function returns true if any of  the array elements satisfy the condition.


text:
Q: how to listen to an xml file and update the view when content changes? android now i have an app that read the xml file from internet, how to listen to this file and notify the user whenever the content has changed on the server side? so that user don't need to press refresh.

A: Try to use the AlarmManager class, and setRepeating method.
It will help you to create a repeating action for reading the xml file.
See this


text:
Q: What would the relationship be in terms of an ERD? I'm designing an online learning platform, in that I have entities like Instructor and Courses. Currently the relationship they are having is Many to Many, with a third table which joins the two entities. I wanted to know for sure if this is the most suitable solution or is there even some better way to associate the two?

A: I think a many to many relationship is just right for your use case. However, you should be careful how you implement the multiplicities.
So if the relationship is defined as (1...n) <--> (1..n) then every instructor you want to store must have at least one course.
If you want to store an instructor who has no courses yet, I would recommend the following: (0...n) <--> (1..n).


text:
Q: BUILD TARGET Runner OF PROJECT Runner WITH CONFIGURATION Debug === The path does not exist Command /bin/sh failed with exit code 255 Im getting the following error when running my flutter app as iOS. And when i run it as Android on Android emulator, it builds successfully and it works fine. I don't know whats wrong with the iOS part.
BUILD FAILED
Xcode's output:
↳
    === BUILD TARGET Runner OF PROJECT Runner WITH CONFIGURATION Debug ===
    The path  does not exist
    Command /bin/sh failed with exit code 255

Could not build the application for the simulator.
Error launching application on iPhone 11 Pro Max.

A: I have solved that issue by deleting "Runner.xcodepro" , "Pods" , "Runner.xcworkspace" and "Podfile" then executed "flutter create ." in project root directory. Build succeeded.

A: I was able to solve the error by doing the following:
1.Open your project in Xcode by right clicking the Runner.xcworkspace folder, then go down to Flutter and select it, and then select Open iOS module in Xcode.
2.Then select Runner(or the name of your project in Xcode) by going to show project navigator.
3.Then under Project Runner(or the name of your project in Xcode), select info.
4.Then under Configuration, set Runner to Generated, do that for all three(Debug, Release, Profile).
After that try to build again, and you will be able to build successfully, then you can run your app again.
I hope this helps someone else out there who is facing this kinda error.

A: If your problem happened after you had updated your flutter, creating a new flutter project from scratch and transfer your work to the new project might be the only way out.
Source: https://github.com/flutter/flutter/issues/56642


text:
Q: How to change color of text when entering fixed div using jQuery I have a div with a background color that is fixed in the browser.
Scrolling through the site, I want the text color to change from black to white when it meets this overlay, then back to black again as it leaves it. This isn't really possible in css yet, so how can I set this in jQuery?
I'm using the ScrollTo plugin (http://flesler.blogspot.com/2007/10/jqueryscrollto.html) for my scrolling.
fiddle (css and html):
http://jsfiddle.net/L76NP/
html:

Section 1

Section 2

Section 3

Section 4

css:
body {color: #000000}

#wrapper { margin-left: auto;
    margin-right: auto}

.section {
    height: 300px;
    width: 400px;
    margin: 0 auto;
    padding: 15px;}

#redbox {
    background-color: #FF0000;
    position: fixed;
    top:100px;
    bottom: 200px;
    left: 0;
    right: 0;
    z-index: -100;}

A: Try this out:
http://jsfiddle.net/ALcm6/3/
Basically checking if the section fits within the box, and if so it's changing the text color. You can alter this for your specific needs.
$(window).scroll(function () {
    var redbox = $("#redbox");
    var redBoxTop = redbox.position().top;
    var redBoxBottom = redBoxTop + redbox.outerHeight();
    $(".section").each(function () {
        var section = $(this);
        var sectionTop = section.position().top - $(window).scrollTop() + 15;
        var sectionBottom = section.position().top - $(window).scrollTop() + section.height();
        if ((sectionTop >= redBoxTop && sectionTop <= redBoxBottom) || (sectionTop <= redBoxTop && sectionBottom >= redBoxBottom) || (sectionBottom >= redBoxTop && sectionBottom <= redBoxBottom)) {
            section.css("color", "white");
        } else {
            section.css("color", "black");
        }
    });

});

A: $('#redbox').css('background-color','rgb(255,255,255)');//it's css controller

this is scroll event:
var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
     $('#redbox').css('background-color','rgb(255,255,255)');
   } else {
     $('#redbox').css('background-color','rgb(0,0,0)');
   }
});

http://jsfiddle.net/LQ9QP/

it's a sample code And You can customize it.


text:
Q: How to use criteria query on refrence collection in mongo db How do I find all the person which are having city ="XYZ" in Address collection
public class Person {
 @Id
private String id;

private String description

@DBRef
private Address address;

// Getters and Setters
}

public class Address
{
@Id
private String id;

private String area

private String city

// Getters and Setters
}

A: Mongo understands @DBRef as a reference to another document, in this case, an Address document and ultimately when the object is loaded from MongoDB, those references will be eagerly resolved and this will get populated to the user as a HATEOAS friendly link.  You will get back a mapped object that looks the same as if it had been stored embedded within your master document.
You can define your repository, which will map the endpoints to your database, for the given object, like PersonRepository defined below as an example:
import com.mycompany.domain.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface PersonRepository extends MongoRepository<Person, String> {

    List<Person> findByCity(@Param("city") String city);

}

Another way you could go around this using the query criteria methods is executing two queries.

*

*First query would be to fetch the address documents which have the city = "XYZ". Resolve the ids from the list returned.

*Generate another query on the Person entity using the ids from the previous operation.

The following demonstrates this approach
Query addressQuery = new Query(where("city").is("XYZ"));
addressQuery.fields().include("_id");
List<Address> addressList = mongoTemplate.find(addressQuery, Address.class, "address"); // get the addresses list that satisfy the given city criteria

// Resolve the ids for the addresses
final List<ObjectId> addressIds = new ArrayList<ObjectId>(addressList.length);
for(final Address address : addressList) {
    addressIds.add(new ObjectId(address.getId()));
}

// Get the Person list using the ids from the previous operation
Query personQuery = new Query(where("address.$id").in(addressIds));
List<Person> list = mongoTemplate.find(personQuery, Person.class, "person");

If you knew the address id before hand you can then use a custom query:
public interface PersonRepository extends MongoRepository<Person, String> {

    @Query("{ 'address': {'$ref': 'address', '$id': { '$oid': ?0 } } }")
    List<Person> findByAddres(String addressIdAsString);
}


text:
Q: class system extension proposal I'm solving some ploblem on generating ancestor instances in Haskell. Recently I found this on Haskell wiki: Class system extension proposal. So, I would like to know, are there any solutions for this proposal already?
Here are the examples from the Proposal:

The current class system in Haskell is based on the idea that you can
  often provide default implementations for class methods at the same
  time as defining the class, by using other methods of the class or its
  ancestors. However consider the following hierarchy, adapted from
  Functor hierarchy proposal and The Other Prelude:
class Functor m where
    fmap :: (a -> b) -> m a -> m b

class Functor m => Applicative m where
    return :: a -> m a

    apply :: m (a -> b) -> m a -> m b

    (>>) :: m a -> m b -> m b
    ma >> mb = (fmap (const id) ma) `apply` mb

class Applicative m => Monad m where
    (>>=) :: m a -> (a -> m b) -> m b

For all concrete instances of Monad we can define fmap, apply, and
  (>>)in terms of return and (>>=) as follows:
fmap f ma = ma >>= (\a -> return (f a))

apply mf ma = mf >>= \f -> ma >>= \a -> return (f a)

ma >> mb = ma >>= \_ -> mb

In other words, we'd like to be able to write:
class Applicative m => Monad m where
    (>>=) :: m a -> (a -> m b) -> m b

    fmap f ma = ma >>= (\a -> return (f a))

    apply mf ma = mf >>= \f -> ma >>= \a -> return (f a)

    ma >> mb = ma >>= \_ -> mb

and be able to define new instances of Monad just by supplying
  definitions for return and (>>=) by writing:
instance Monad T where
    ma >>= a_mb = ... -- some definition

    return a = ... -- some definition

Explicit import/export of instances
This is needed so that large programs can be built without fear of
  colliding instance declarations between different packages. A possible
  syntax could be:
module M
     -- exported instances
   ( instance Monad T
   , instance Functor (F a) hiding (Functor (F Int), Functor (F Char))
   , F(..)
   ) where

import Foo (instance Monad a hiding Monad Maybe)

data T a
data F a b

where the context is elided because this isn't used in instance
  selection (at the moment). The import directive tells the compiler to
  use all Monad instances exported by Foo except for the Monad Maybe
  instance (it doesn't matter whether or not Foo actually does export a
  Monad Maybe instance - all that matters here is that we don't want it
  if there is one).

A: Yes, the DefaultSignatures extension allows this. For example, for the Functor/Applicative example, one could write
{-# LANGUAGE DefaultSignatures #-}
class Functor f where
    fmap :: (a -> b) -> f a -> f b
    default fmap :: Applicative f => (a -> b) -> f a -> f b
    fmap = liftA


text:
Q: Why is "loop14" not listed in lsblk? Upon listing the blocks using lsblk, I found 14 look blocks listed, from loop 0 to loop 13.
me@alpha:~$ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop0    7:0    0  87.9M  1 loop /snap/core/5662
loop1    7:1    0 140.7M  1 loop /snap/gnome-3-26-1604/74
loop2    7:2    0   3.7M  1 loop /snap/gnome-system-monitor/57
loop3    7:3    0 140.9M  1 loop /snap/gnome-3-26-1604/70
loop4    7:4    0  34.6M  1 loop /snap/gtk-common-themes/818
loop5    7:5    0  42.1M  1 loop /snap/gtk-common-themes/701
loop6    7:6    0  89.5M  1 loop /snap/core/6130
loop7    7:7    0   2.3M  1 loop /snap/gnome-calculator/238
loop8    7:8    0 130.2M  1 loop /snap/gnome-3-28-1804/4
loop9    7:9    0  14.5M  1 loop /snap/gnome-logs/45
loop10   7:10   0    13M  1 loop /snap/gnome-characters/124
loop11   7:11   0  53.7M  1 loop /snap/core18/536
loop12   7:12   0    13M  1 loop /snap/gnome-characters/139
loop13   7:13   0   2.3M  1 loop /snap/gnome-calculator/260
sda      8:0    0   113G  0 disk
├─sda1   8:1    0   512M  0 part /boot/efi
└─sda2   8:2    0 112.5G  0 part /

However, when I list using ls /dev and find blocks using grep 'loop', I found 15 blocks listed, with an extra loop14 shown.
me@alpha:~$ ls /dev | grep 'loop'
loop0
loop1
loop10
loop11
loop12
loop13
loop14
loop2
loop3
loop4
loop5
loop6
loop7
loop8
loop9
loop-control

Why loop14 is not listed from lsblk?

A: lsblk lists loop devices with a backing file. In your case, loop devices 0-13 have backing files, and show up.
losetup --find, used to find the next available loop device, automatically creates a new loop device if all existing loop devices are in use (if run as root). So some process might have run losetup --find as root to look for an available loop device, and probably didn't use it.
Example:
I have seven loop devices, all backed:
$ sudo losetup --list --all
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop1         0      0         1  1 /var/lib/snapd/snaps/core_5897.snap
/dev/loop6         0      0         0  0 /tmp/foo
/dev/loop4         0      0         0  0 /tmp/foo
/dev/loop2         0      0         1  1 /var/lib/snapd/snaps/core_6130.snap
/dev/loop0         0      0         1  1 /var/lib/snapd/snaps/vuze-vs_3.snap
/dev/loop7         0      0         0  0 /tmp/foo
/dev/loop5         0      0         0  0 /tmp/foo
/dev/loop3         0      0         1  1 /var/lib/snapd/snaps/core_6034.snap
$ ls /dev/loop*
/dev/loop0  /dev/loop2  /dev/loop4  /dev/loop6  /dev/loop-control
/dev/loop1  /dev/loop3  /dev/loop5  /dev/loop7

I ask losetup for the next available loop device as root:
$ sudo losetup --find
/dev/loop8

And losetup has created this for me:
$ ls /dev/loop*
/dev/loop0  /dev/loop2  /dev/loop4  /dev/loop6  /dev/loop8
/dev/loop1  /dev/loop3  /dev/loop5  /dev/loop7  /dev/loop-control

But it's not in lsblk:
$ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop1    7:1    0  88.2M  1 loop /snap/core/5897
loop6    7:6    0     1M  0 loop
loop4    7:4    0     1M  0 loop
sr0     11:0    1  1024M  0 rom
loop2    7:2    0  89.5M  1 loop /snap/core/6130
loop0    7:0    0 280.2M  1 loop /snap/vuze-vs/3
loop7    7:7    0     1M  0 loop
sda      8:0    0    41G  0 disk
└─sda1   8:1    0    41G  0 part /
loop5    7:5    0     1M  0 loop
loop3    7:3    0  89.5M  1 loop /snap/core/6034

Because it's not backed by anything usable as a block device.


text:
Q: How to run VBScript from command line without Cscript/Wscript I am a beginner in VBScript. I googled it & got to know that we can run VBScript from command line by executing below command:
For Example my vbscript name is Converter.vbs & it's present in folder D:\VBS.
I can run it through following methods:
CScript "D:\VBS\Converter.vbs"

OR
WScript "D:\VBS\Converter.vbs"

Now I would like to execute above VBScript without Cscript or Wscript command by simply typing the name of VBscript name i.e. Converter.
I DON'T WANT TO SPECIFY THE FULL PATH OF VBSCRIPT EVERYTIME.
Can anyone please guide me on how to do that ?

A: I am wondering why you cannot put this in a batch file. Example:
cd D:\VBS\
WSCript Converter.vbs

Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.

A: Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.
Check the answer -> Here
And here is an example:
Converter.bat
::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b

:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b

'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester

A: I'll break this down in to several distinct parts, as each part can be done individually. (I see the similar answer, but I'm going to give a more detailed explanation here..)
First part, in order to avoid typing "CScript" (or "WScript"), you need to tell Windows how to launch a * .vbs script file. In My Windows 8 (I cannot be sure all these commands work exactly as shown here in older Windows, but the process is the same, even if you have to change the commands slightly), launch a console window (aka "command prompt", or aka [incorrectly] "dos prompt") and type "assoc .vbs". That should result in a response such as:
C:\Windows\System32>assoc .vbs
.vbs=VBSFile

Using that, you then type "ftype VBSFile", which should result in a response of:
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*

-OR-
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\CScript.exe" "%1" %*

If these two are already defined as above, your Windows' is already set up to know how to launch a * .vbs file. (BTW, WScript and CScript are the same program, using different names. WScript launches the script as if it were a GUI program, and CScript launches it as if it were a command line program. See other sites and/or documentation for these details and caveats.)
If either of the commands did not respond as above (or similar responses, if the file type reported by assoc and/or the command executed as reported by ftype have different names or locations), you can enter them yourself:
C:\Windows\System32>assoc .vbs=VBSFile

-and/or-
C:\Windows\System32>ftype vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*

You can also type "help assoc" or "help ftype" for additional information on these commands, which are often handy when you want to automatically run certain programs by simply typing a filename with a specific extension. (Be careful though, as some file extensions are specially set up by Windows or programs you may have installed so they operate correctly. Always check the currently assigned values reported by assoc/ftype and save them in a text file somewhere in case you have to restore them.)
Second part, avoiding typing the file extension when typing the command from the console window.. Understanding how Windows (and the CMD.EXE program) finds commands you type is useful for this (and the next) part. When you type a command, let's use "querty" as an example command, the system will first try to find the command in it's internal list of commands (via settings in the Windows' registry for the system itself, or programmed in in the case of CMD.EXE). Since there is no such command, it will then try to find the command in the current %PATH% environment variable. In older versions of DOS/Windows, CMD.EXE (and/or COMMAND.COM) would automatically add the file extensions ".bat", ".exe", ".com" and possibly ".cmd" to the command name you typed, unless you explicitly typed an extension (such as "querty.bat" to avoid running "querty.exe" by mistake). In more modern Windows, it will try the extensions listed in the %PATHEXT% environment variable. So all you have to do is add .vbs to %PATHEXT%. For example, here's my %PATHEXT%:
C:\Windows\System32>set pathext
PATHEXT=.PLX;.PLW;.PL;.BAT;.CMD;.VBS;.COM;.EXE;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY

Notice that the extensions MUST include the ".", are separated by ";", and that .VBS is listed AFTER .CMD, but BEFORE .COM. This means that if the command processor (CMD.EXE) finds more than one match, it'll use the first one listed. That is, if I have query.cmd, querty.vbs and querty.com, it'll use querty.cmd.
Now, if you want to do this all the time without having to keep setting %PATHEXT%, you'll have to modify the system environment. Typing it in a console window only changes it for that console window session. I'll leave this process as an exercise for the reader. :-P
Third part, getting the script to run without always typing the full path. This part, in relation to the second part, has been around since the days of DOS. Simply make sure the file is in one of the directories (folders, for you Windows' folk!) listed in the %PATH% environment variable. My suggestion is to make your own directory to store various files and programs you create or use often from the console window/command prompt (that is, don't worry about doing this for programs you run from the start menu or any other method.. only the console window. Don't mess with programs that are installed by Windows or an automated installer unless you know what you're doing).
Personally, I always create a "C:\sys\bat" directory for batch files, a "C:\sys\bin" directory for * .exe and * .com files (for example, if you download something like "md5sum", a MD5 checksum utility), a "C:\sys\wsh" directory for VBScripts (and JScripts, named "wsh" because both are executed using the "Windows Scripting Host", or "wsh" program), and so on. I then add these to my system %PATH% variable (Control Panel -> Advanced System Settings -> Advanced tab -> Environment Variables button), so Windows can always find them when I type them.
Combining all three parts will result in configuring your Windows system so that anywhere you can type in a command-line command, you can launch your VBScript by just typing it's base file name. You can do the same for just about any file type/extension; As you probably saw in my %PATHEXT% output, my system is set up to run Perl scripts (.PLX;.PLW;.PL) and Python (.PY) scripts as well. (I also put "C:\sys\bat;C:\sys\scripts;C:\sys\wsh;C:\sys\bin" at the front of my %PATH%, and put various batch files, script files, et cetera, in these directories, so Windows can always find them. This is also handy if you want to "override" some commands: Putting the * .bat files first in the path makes the system find them before the * .exe files, for example, and then the * .bat file can launch the actual program by giving the full path to the actual *. exe file. Check out the various sites on "batch file programming" for details and other examples of the power of the command line.. It isn't dead yet!)
One final note: DO check out some of the other sites for various warnings and caveats. This question posed a script named "converter.vbs", which is dangerously close to the command "convert.exe", which is a Windows program to convert your hard drive from a FAT file system to a NTFS file system.. Something that can clobber your hard drive if you make a typing mistake!
On the other hand, using the above techniques you can insulate yourself from such mistakes, too. Using CONVERT.EXE as an example.. Rename it to something like "REAL_CONVERT.EXE", then create a file like "C:\sys\bat\convert.bat" which contains:
@ECHO OFF
ECHO !DANGER! !DANGER! !DANGER! !DANGER, WILL ROBINSON!

ECHO This command will convert your hard drive to NTFS! DO YOU REALLY WANT TO DO THIS?!
ECHO PRESS CONTROL-C TO ABORT, otherwise..

REM "PAUSE" will pause the batch file with the message "Press any key to continue...",
REM and also allow the user to press CONTROL-C which will prompt the user to abort or
REM continue running the batch file.
PAUSE

ECHO Okay, if you're really determined to do this, type this command:
ECHO.    %SystemRoot%\SYSTEM32\REAL_CONVERT.EXE
ECHO to run the real CONVERT.EXE program. Have a nice day!

You can also use CHOICE.EXE in modern Windows to make the user type "y" or "n" if they really want to continue, and so on.. Again, the power of batch (and scripting) files!
Here's some links to some good resources on how to use all this power:
http://ss64.com/
http://www.computerhope.com/batch.htm
http://commandwindows.com/batch.htm
http://www.robvanderwoude.com/batchfiles.php
Most of these sites are geared towards batch files, but most of the information in them applies to running any kind of batch (* .bat) file, command (* .cmd) file, and scripting (* .vbs, * .js, * .pl, * .py, and so on) files.

A: When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by
assoc | grep -i vbs
.vbs=VBSFile

ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*

to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.
As
cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]

Options:
 //B         Batch mode: Suppresses script errors and prompts from displaying
 //D         Enable Active Debugging
 //E:engine  Use engine for executing script
 //H:CScript Changes the default script host to CScript.exe
 //H:WScript Changes the default script host to WScript.exe (default)
 //I         Interactive mode (default, opposite of //B)
 //Job:xxxx  Execute a WSF job
 //Logo      Display logo (default)
 //Nologo    Prevent logo display: No banner will be shown at execution time
 //S         Save current command line options for this user
 //T:nn      Time out in seconds:  Maximum time a script is permitted to run
 //X         Execute script in debugger
 //U         Use Unicode for redirected I/O from the console

shows, you can use //E and //S to permanently switch your default host to cscript.exe.
If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable
set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1

contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.
Update wrt comment:
If you 'don't want to specify the full path of my vbscript everytime' you may:

*

*put your CONVERTER.VBS in a folder that is included in the PATH environment variable; the shell will then search all pathes - if necessary taking the PATHEXT and the ftype/assoc info into account - for a matching 'executable'.

*put a CONVERTER.BAT/.CMD into a path directory that contains a line like cscript p:\ath\to\CONVERTER.VBS
In both cases I would type out the extension to avoid (nasty) surprises.

A: You may follow the following steps:

*

*Open your CMD(Command Prompt)

*Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:

*Type 'CD VBS' and hit Enter. Example: D:>CD VBS

*Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs


text:
Q: TSQL : Find PAIR Sequence in a table I have following table in T-SQL(there are other columns too but no identity column or primary key column):
    Oid Cid
    1    a
    1    b
    2    f
    3    c
    4    f
    5    a
    5    b
    6    f
    6    g
    7    f

So in above example I would like to highlight that following Oid are duplicate when looking at Cid column values as "PAIRS":
Oid:
1 (1 matches Oid: 5)
2 (2 matches Oid: 4 and 7)

Please NOTE that Oid 2 match did not include Oid 6, since the pair of 6 has letter 'G' as well.
Is it possible to create a query without using While loop to highlight the "Oid" like above? along with how many other matches count exist in database?
I am trying to find the patterns within the dataset relating to these two columns. Thank you in Advance.

A: Here is a worked example - see comments for explanation:
--First set up your data in a temp table
declare @oidcid table (Oid int, Cid char(1));
insert into @oidcid values
(1,'a'),
(1,'b'),
(2,'f'),
(3,'c'),
(4,'f'),
(5,'a'),
(5,'b'),
(6,'f'),
(6,'g'),
(7,'f');

--This cte gets a table with all of the cids in order, for each oid
with cte as (
    select distinct Oid, (select Cid + ',' from @oidcid i2
                          where i2.Oid = i.Oid order by Cid
                          for xml path('')) Cids
    from @oidcid i
)
select Oid, cte.Cids
from cte
inner join (
    -- Here we get just the lists of cids that appear more than once
    select Cids, Count(Oid) as OidCount
    from cte group by Cids
    having Count(Oid) > 1 ) as gcte on cte.Cids = gcte.Cids
-- And when we list them, we are showing the oids with duplicate cids next to each other
Order by cte.Cids

A: select o1.Cid, o1.Oid, o2.Oid
     , count(*) + 1 over (partition by o1.Cid) as [cnt]
from table o1
join table o2
  on o1.Cid = o2.Cid
 and o1.Oid < o2.Oid
order by o1.Cid, o1.Oid, o2.Oid

A: Maybe Like this then:
WITH CTE AS
(
    SELECT Cid, oid
    ,ROW_NUMBER() OVER (PARTITION BY cid ORDER BY cid) AS RN
    ,SUM(1) OVER (PARTITION BY oid) AS maxRow2
    ,SUM(1) OVER (PARTITION BY cid) AS maxRow
    FROM oid
)
SELECT * FROM CTE WHERE maxRow != 1 AND maxRow2 = 1
ORDER BY oid


text:
Q: How do I solve time format VBA overflow error? I'm using a userform to schedule a task. In that userform, I have two Combo Boxes to select:

*

*The time it should be scheduled.

*The duration of the task.

For those two fields I use following code:
Option Explicit

Private Sub ScDuration_Change()
   ScDuration = Format(ScDuration, "hh:mm")
End Sub

Private Sub ScDuration_AfterUpdate()
   ScDuration = Format(ScDuration, "hh:mm")
End Sub

Private Sub ScTime_Change()
   ScTime = Format(ScTime, "hh:mm")
End Sub

Private Sub ScTime_AfterUpdate()
   ScTime = Format(ScTime, "hh:mm")
End Sub

But this is giving me an overflow error Run-time error '6': Overflow for which I already spent hours trying to fix. Can somebody help me please?

A: I hope this solve your problem or at least help you
Be patient and change all your need to adapt it to your code
Good Luck!
'Here begin the code, all inside the form code
Private GLOBAL_DATE As Double
Private GLOBAL_DURATION As Double ' I didnt use it but could be used
Private GLOBAL_UOM_TIME As Double
Private Const FORMAT_DATE_DISPLAY = "DD-MM-YYYY"

'Label1 = time
'Label2 = duration
'Define max valuee for duration in minutes, hours, seconds
'Define max vaule of your dateSpinner
'in minutes divide 1440
'hours divide 24
'seconds 86400

Sub Global_initiation()
    GLOBAL_DATE = CDbl(Now)
    GLOBAL_DURATION = 0
    GLOBAL_UOM_TIME = 1440

End Sub

'You will recibe the value of spiner
Function HandleMinutes(nMinutes_ As Double) As String
    HandleMinutes = Format(nMinutes_ / GLOBAL_UOM_TIME, "hh:mm")
End Function

Function HandleDate(nDays_ As Double) As String
    HandleDate = Format(GLOBAL_DATE + nDays_, FORMAT_DATE_DISPLAY)
End Function

Private Sub SpinButton1_Change() ' date
    Label1.Caption = HandleDate(SpinButton1.Value)
End Sub

Private Sub SpinButton2_Change() ' duration
    Label2.Caption = HandleMinutes(SpinButton2.Value)
End Sub

Private Sub UserForm_Initialize()
    Global_initiation
End Sub

'Here ends the code--------------------

A: Try this:
ScTime.Value = Application.WorksheetFunction.Text(ScTime.Value, "h:mm")
Considering the comments in the Randy's video bellow, it seems that one some machines "Format" may not work: https://www.youtube.com/watch?v=h79SNTpxKzc


text:
Q: EmberJS not making a request to get data from rest api I'm trying to integrate ember into my app. I want to replace a table that shows list of records with ember. I've got a rest api that will return the data for the table. However, the below ember code never makes a request to get the data from the rest api.
var App = Ember.Application.create({});

App.Router.map(function() {

});

App.Store = DS.Store.extend({
    revision: 11,
    adapter: DS.RESTAdapter.extend({
        url: '/myapp/stuff/list'
    })
});

App.Response = DS.Model.extend({
    author: DS.attr("string"),
    book: DS.attr("string")
});

Below is what I have in my html page:

However, on the browser the only thing I see is whatever. I do not see the results from the API nor do I see a request being made to myapp/stuff/list.
My API looks like this:
{
  "meta": {
     "code": 200
   }
   "response": {
      "stuff": [{
         "id": 1,
         "author": "someone",
         "book": "some book"
         },
         {
         "id": 2,
         "author": "some author",
         "book": "anotherbook"
         }
       ]
   }
}

A: OK there are a few things going on here. First is that there is no route definition, that is where you specify how ember should lookup your model data. In this case you can specify an application route with a model hook that calls your api, like:
App.ApplicationRoute = Ember.Route.extend({
  model: function(){
    return App.Response.find();
  }
});

With this in place ember will attempt to call your api. But the request will not be to the url you are expecting: instead it will call /myapp/stuff/list/responses since ember appends the pluralized model name to the adapter's base url.
Finally if your api returns the above json ember will complain that Your server returned a hash with the key response but you have no mapping for it. By convention the API should be returning an array of responses instead of a single response. The following will work:
{
"meta": {
 "code": 200
 },
 "responses": [
   { "id": 1, "author": "someone", "book": "some book "},
   { "id": 2, "author": "some author", "book": "anotherbook" }
 ]
}

I've posted a working example here (using a custom adapter that simulates your api response) http://jsbin.com/ICoYUxU/2/edit?html,js,output
App = Ember.Application.create({});

App.Router.map(function() {});

App.Response = DS.Model.extend({
    author: DS.attr("string"),
    book: DS.attr("string")
});

App.ApplicationRoute = Ember.Route.extend({
  model: function(){
      return App.Response.find();
  }
});

App.Store = DS.Store.extend({
  adapter: 'App.Adapter'
});

var responses = {
  "meta": {
     "code": 200
   },
   "responses": [
     { "id": 1, "author": "someone", "book": "some book "},
     { "id": 2, "author": "some author", "book": "anotherbook" }
   ]
};

App.API = {
  '/myapp/stuff/list/responses': responses
};

App.Adapter = DS.RESTAdapter.extend({
  url: '/myapp/stuff/list',
  ajax: function(url, type, hash) {
    json = App.API[url];
    console.log('App.Adapter.ajax:', url, type, hash, json);
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.run(null, resolve, json);
    });
  }
});


text:
Q: UIScrollView and CATiledLayer from the ground up my situation: I created an UIScrollView with an UIView inside which calls a Graph class which draws a nice graph on a context.
Now I discovered that the phone wouldn't render the UIView if it's width is larger than 8192 pixels. In fact, according to Apple's docs, if I want it larger than 1024px, I should implement CATiledLayer.
But after reading and googling a lot, I still find it difficult to understand the basics of CATiledLayer for this task-I'm somehow lost between Quartz vs. Cocoa and layers and sublayers vs. views and subviews.
Ideally I would like to keep the Graph class untouched, just draw the context entirely, split it into tiles and scroll those. The scrollview should just scroll horizontal, no zooming or vertical scrolling required. Is that possible? If so, how should I continue?
Perhaps someone could give me an outline, just some bulletpoints or pseudocode, how I should restructure the scrollview, uiview and the graph class to use tiling.
Thank you very much in advance for any reply.

A: It's been a month since you asked but this may still be of use. I just started using CATiledLayer tonight. I think the idea behind a CATiledLayer seems to be that you add it to a view:
CATiledLayer *tiled = [CATiledLayer layer];
[self.view.layer addSublayer:tiled];

and that you set a delegate, implementing just one method:
MyTLDelegate *myDelegate = [[MyTLDelegate alloc] init];
tiled.delegate = myDelegate;
// I haven't checked if CATiledLayer retains myDelegate, check this!

...
@implementation MyTLDelegate {

-(void)drawLayer:(CATiledLayer *)layer inContext:(CGContextRef)ctx
{
    CGRect dirtyRect = CGContextGetClipBoundingBox(ctx);
    // draw!
}

That's basically all there is to it, you can just draw as if the entire coordinate space is just there. So you should only need to slightly modify your Graph class so it can act as a CATiledLayer delegate. In my case it was 20 minutes well spent, boosting user experience by several orders of magnitude. (compared to doing the tedious scrolling, scaling and redrawing myself)
ps. this is only the pseudo code you asked for, you may need some extra glue to get things going, e.g. for quality and/or frame sizes.


text:
Q: System Settings won't open Ubuntu 16.04 A few days ago I noticed that the battery icon on the menu bar wasn't there anymore so I tried to fix the problem through settings but when I clicked on the GUI icon it wouldn't load so I looked up the problem online and tried running unity-control-center
but the gave me the messagebus error (core dumped).
So, after reinstalling Unity-control-center and Ubuntu-desktop it still gives me the same error. Does anyone know how to fix it?
(edit): I mistyped and put 15.04 instead of 16.04 I'm using 16.04 LTS with the 32-bit version of Ubuntu.
(edit) The same applies to Rhythmbox and Amarok


text:
Q: MVC diagrams - do they really show how MVC works? When I look at MVC diagrams I have this objection: why Controller is pictured facing user and View is hidden somewhere behind?
In my opinion user sees and interacts with View (this is what he sees in browser) and via View user "talks" to Controller, so why Controller is first in line?
Also, shouldn't diagram be shown like tower structure (instead of triangle):
View -allows user talking to- Controller - to- Model (on the bottom) - then (feed)back to- Controller -adjustment made to- View
When I see diagram with Controller facing user, I always have this strange picture of user, with a MVC diagram in one hand and screwdriver in another, popping computer's box open and looking for a Controller to get MVC started.

A: It's really unfortunate that most articles and books still use such useless diagrams to represent MVC. A more useful diagram for MVC is actually a UML sequence diagram like Dino Esposito uses on his book Microsoft .NET: Architecting Applications for the Enterprise
Secondly, as you point out, most MVC articles and books have not been updated to describe how MVC is applied nowadays in web applications and still talk about MVC as it was originally envisioned 20+ years ago.
The Esposito book that I mentioned has a really good chapter about this where he describes how MVC (as originally described) is dead and we should now be focusing in modern variations of it like Model2, Passive View, and Supervising Controller. I've got a review of this chapter on my blog that you might find useful.


text:
Q: MSAccess VBA, filtering query results via combo box (text) I want to filter date values (text) in a query based on a comboBox text value.
Here is what I have:
ComboBoxTimePeriod (ID [num], TimePeriod [text]).
In ComboBox I select Time period, like "16.10.2017-15.11.2017".
In a query I have Date field with single date, like "20.10.2017" (text).
What I want is to write an SQL code which searches for all records with date within TimePeriod range.
So far Idea is to extract SatrtDate and EndDate from TimePeriod like this:
    Dim strStartDate As String
    Dim strEndDate As String

    strStartDate = Mid(Me.cboTimePeriod.Text, 1, 10)
    strEndDate = Mid(Me.cboTimePeriod.Text, 12, 10)

Now from TimePeriod "16.10.2017-15.11.2017" I have StartDate (16.10.2017) and EndDate (15.11.2017).
And I want to filter all records which have date within those two dates.
This is where I need you guys.
Note that this is different issue from my last question, where I searched for a records with TimePeriodID (Subform filtering based off multiple parameters (Combobox AND Textbox)).

A: Always handle dates as Date, not text:
Dim StartDate As Date
Dim EndDate As Date
StartDate = DateValue(Split(Me.cboTimePeriod.Value, "-")(0))
EndDate = DateValue(Split(Me.cboTimePeriod.Value, "-")(1))

The build your filter:
... " Between #" & Format(StartDate, "yyyy\/mm\/dd") & "# And #" & Format(EbdDate, "yyyy\/mm\/dd") & "#"

To filter a form:
Me.Filter = "[Date Field] Between #" & Format(StartDate, "yyyy\/mm\/dd") & "# And #" & Format(EbdDate, "yyyy\/mm\/dd") & "#"
Me.FilterOn = True

And do make sure that your Date Field is of data type Date, not Text.


text:
Q: How to use the `colspan` in css3 inside the `row` I am trying to make 2 columns, underneath one of the column need to have 3 rows. each rows has seperate number of cells. but it's not working for me. it should 100% wide, but it look like inline-table - how to fix this?

#table {
    display:table;
    width:100%
}

.row {
    display:table-row;
}

.cell {
    display:table-cell;
    border:1px solid grey;
}

.row1 {
   display: table-caption;
}

.cell1 {
    width:30%
}

30%

90%

10%

40%

20%

20%

20%

100%


text:
Q: get result filtered by count grouped by date in cakephp 3 I am working on CakePHP 3.4
I am building some application which uses API key. One key is limited to 100 calls per day, so I'm using multiple keys and want to loop through it.
In my controller, I'm calling a model's function to get API
$api_key = $this->CustomApi->getKey();
if (!$api_key) {
    $this->Flash->error(__('API key not found'));
} else {
    ...
}

In model CustomApi I want to write getKey() function which will find Api key whose call count of the day is less than 100.
Columns of custom_api table are id, api_key and calls are recorded in api_calls table whose columns are id, user_id, custom_api_id, created
Everytime user access function which requires API, a record is created in api_calls table with the time call has been made and primary key of the custom_api.
My question is, How to get Api key from CustomApi model whose call counts are less than 100 for that day (ie., today)

Edit 2 : My Try

$key = $this
    ->find()
    ->select(['CustomApi.id', 'CustomApi.api_key'])
    ->where(['CustomApi' => /* count is less than 100 */])
    ->leftJoinWith('ApiCalls', function ($q) {
          return $q->where(['ApiCalls.created' => date('Y-m-d')]);
    })
    ->group('CustomApi.id');

How to make a count in where?

A: You're nearly there, you need to use a HAVING clause, WHERE won't work here, as it works on single results, rather than on aggregated ones, which is what you need here.
SQL functions can be built using the function builder, and in order to create a comparison with a function expression, you'll have to leavarege the expression builder, using for example the lt() (less than) method.
$this
    ->find()
    ->select(['CustomApi.id', 'CustomApi.api_key'])
    ->leftJoinWith('ApiCalls', function ($q) {
        return $q->where(['ApiCalls.created' => date('Y-m-d')]);
    })
    ->group('CustomApi.id')
    ->having(function ($exp, $q) {
        return $exp->lt(
            $q->func()->count('ApiCalls.id'),
            100
        );
    });

And in case ApiCalls.created isn't a date only column, you'd use a BETWEEN clause, or manually clamp the value using >= and <= comparisons against the beginning and the end of the day.
See also

*

*Cookbook > Database Access & ORM > Query Builder > Using SQL Functions

*Cookbook > Database Access & ORM > Query Builder > Advanced Conditions

*API > \Cake\Database\FunctionsBuilder

*API > \Cake\Database\Expression\QueryExpression


text:
Q: Split a string on multiple blankspaces but not on single? I have a string that i need to split where there are 2 or more blankspaces, but i dont want to split it on single blankspace.
For example, a string might look something like this:

"Name of something   "five blanks"   Name of something else "three blanks"  And so on"

And i need the split to be:

*

*Name of something

*Name of something else

*And so on

I hope you kan help me

A: As you said, you can use RegEx to accomplish that, but that's a bit of overkill.  The String.Split method has an overload that takes an array of strings to use as delimiters:
line.Split(New String() {"  "}, StringSplitOptions.None)


text:
Q: $f(z)$ entire and $|f(z)| \le (1+|z|)^n$ implies $f(z)$ is polynomial Suppose that $f:\mathbb{C}\to \mathbb{C}$ is an entire function, $n\ge 1$ is an integer, and that $|f(z)|\le (1+|z|)^n$ for all $z\in\mathbb{C}$. Prove that $f$ is a polynomial.
Proof:
Since $f$ is entire, we can write it as $$f(z) = \sum\limits_{m=0}^\infty c_m z^m$$
By Cauchy Estimates, for any closed disk $\mathbb{D}$ of radius $r>0$ centred about $z=0$, $$|f^{(m)}(0)|\le \frac{M_r m!}{r^m}$$ where $M_r=\sup\{|f(z)|:z\in\mathbb{D}\}\le (1+r)^n$. Let $n<m$, then
$$ |c_m|=\frac{|f^{(m)(0)}|}{m!}\le \frac{M_r m!}{m! r^m}=\frac{M_r}{r^m}\le \frac{(1+r)^n}{r^m} $$
Also, $|c_m|=\lim\limits_{r\to \infty}|c_m|\le 0$.

Hence, $f(z)=c_0+c_1z+\dots+c_nz^n$ is a polynomial of at most degree $m$.

My question is this: how does the above proof show that $f$ is a polynomial?

A: From Cauchy's Integral Formula, for an analytic function $f$ we have
$$f^{(m)}(0)=\frac{m!}{2\pi i}\oint_{|z|=r>0}\frac{f(z)}{z^{m+1}}\,dz$$
Given that $|f(z)|\le (1+|z|)^n$, we have the estimate for $f^{(m)}(z_0)$
$$|f^{(m)}(0)|\le \frac{m!}{2\pi }\frac{2\pi r (1+r^n)}{r^{m+1}}$$
For $m>n$, we find that
$$f^{(m)}(0)=0$$
Thus, we have
$$\begin{align}
f(z)&=\sum_{m=0}^\infty\frac{f^{m}(0)}{m!}z^m\\\\
&=\sum_{m=0}^n\frac{f^{m}(0)}{m!}z^m+\underbrace{\sum_{m=n+1}^\infty\frac{f^{m}(0)}{m!}z^m}_{=0}\\\\
&=\underbrace{\sum_{m=0}^n\frac{f^{m}(0)}{m!}z^m}_{\text{A polynomial of order}\,n}
\end{align}$$
Hence, $f$ is a polynomial of, at most, order $n$.


text:
Q: Maximize windows without maximize button I am using IntelliJ IDEA on Ubuntu 20.04. Some of its dialogs pop up and do not have a button to maximize it, even though it has the handles to manually change its size. This particular dialog has a lot of information to convey, I like it to be maximized, but after some whatever, the dialog sometimes loses my carefully manually-resized "maximized-like" positioning. I wish there was an easy way to maximize this dialog.
Super+Up or Alt+F10 does not work for this window.
Drag and snap does not work for this window.
This used to be possible with the extension Window Buttons, but that no longer works.
I understand this may be an IntelliJ IDEA problem, but I have little confidence in that getting any traction, so I'm looking for an Ubuntu/Gnome solution or workaround.
I am wondering if there are any other ways. (I'd be fine with a command-line solution that I can hook up to a shortcut of sorts.) There's just not much I can find (googling for "gnome" and "maximize" mostly just brings me to the Ubuntu 12 era when Gnome reportedly removed the maximize buttons for everyone). Thank you.

A: It is extremely annoying. We have large monitors and we cannot maximize the 'modal' window. And Jetbrains by the way does encourage to make usage of the keyboard and shortcuts. I have something for you. On Ubuntu you can increase the size of a Window using ALT+F8. Then use SHIFT and the arrow keys. The window is maximized into the direction of the key.
SHIFT+LEFT, SHIFT+RIGHT, SHIFT+DOWN and finally SHIFT+UP.
Seems Intellij records the size of the modal.
Example. You commit your changes, (CONTROL+K), resize the modal window as explained above,  you do ESC and then try to commit a second time (CONTROL+K) and the size of the window is restored.


text:
Q: Function Keys don't work I know this is a commonly asked question, but some function keys dont work (Fn + F5, F6, C, V and Space). I got the Asus eeePC F201E-KX067DU which came shipped with Ubuntu 12.04 LTS and after the first boot-up every function key was working out of the box. I changed the OS to Ubuntu 12.10 and since then some Fn keys didn't work anymore (I also tried installing 12.04 LTS again to see if those keys work again).
I already searched for some hours now, without any results ... editing /etc/default/grub with:
GRUB_CMDLINE_LINUX_DEFAULT="nosplash acpi_osi=Linux acpi_backlight=vendor"

or
GRUB_CMDLINE_LINUX_DEFAULT="nosplash acpi_osi="

doesn't seems to work.


text:
Q: How to select the next table's row clicking a checkbox Here the HTML:

        Customer Reviews

        <input type="checkbox" name="p_reviews" /> (checkbox that trigger action)

 (row to select)

        How many reviews do you want to display?

    ...

And here the javascript:
$("form[name='myform'] input[name='p_reviews']").click(function() {
if ($(this).is(':checked')){
    $(this).closest('tr').next().show();
} else{
    $(this).closest('tr').next().hide();
}
});

This is not working. Any tip?
EDIT: Sorry folks, Yes, it is working. Just was a HTML double-quote missing!

A: $('form[name="myform"] input[name="p_reviews"]').click(function() {
    if ($(this).is(':checked')){
        $(this).closest('tr').next('tr').show();
    } else{
        $(this).closest('tr').next('tr').hide();
    }
});

A: Make sure you run that code on document ready. And also you can just use this.checked. Try this
$(function(){
  $("form[name='myform'] input[name='p_reviews']").click(function() {
     if (this.checked){
         $(this).closest('tr').next().show();
     } else{
         $(this).closest('tr').next().hide();
     }
  });
});

Alternatively you can use toggle which is much simpler.
    $(function(){
      $("form[name='myform'] input[name='p_reviews']").click(function() {
         $(this).closest('tr').next().toggle(this.checked);
      });
    });


text:
Q: How to handle backstack between fragments and viewpagers? I am using a ViewPager having 2 pages. First page of that ViewPager is MainFragment. MainFragment has ViewPager as bottomNavigationView. Each page has a FragmentContainerView and By default they contains HomeFragment, CommunityFragment and NotificationFragment respectively.
This is the Source Code and this is the APK of the project. So you can test it and improve it easily.
Now if i am in HomeFragment and I click on a profile button so It transact to ProfileFragment and from there setting and so on. And on clicking on back button it get back perfectly one-by-one. But it does not happens same with other FragmentContainerView. Even they get back directly to the parent fragment. Overall i am unable to handle the backstack between different ViewPagers and fragments.
To avoid the confusion of FragmentContainers i transact it like this
val containerId = (view?.parent as ViewGroup).id
activity?.supportFragmentManager?.beginTransaction()?.add(containerId, profileFragment)?.addToBackStack(null)?.commit()

Now the handling of BackPressed() in MainActivity is here
if (view_pager_main_activity?.currentItem == 0)
{
    if (view_pager_main_fragment?.currentItem == 0)
    {
        val recyclerView = findViewById<RecyclerView>(R.id.recycler_view_home)
        val appbarHome = findViewById<AppBarLayout>(R.id.appbar_home)
        val layoutManager = recyclerView?.layoutManager as LinearLayoutManager
        when {
            layoutManager.findFirstCompletelyVisibleItemPosition() == 0 -> {
                super.onBackPressed()
            }
            supportFragmentManager.backStackEntryCount != 0 -> {
                supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
            }
            else -> {
                layoutManager.scrollToPositionWithOffset(0, 0)
                appbarHome.setExpanded(true)
                //recyclerView.smoothScrollToPosition(0)
            }
        }
    }
    else
    {
        // Otherwise, select the previous step.
        view_pager_main_fragment?.setCurrentItem(view_pager_main_fragment.currentItem - 1, false)
    }
}
else
{
    // Otherwise, select the previous step.
    view_pager_main_activity?.currentItem = view_pager_main_activity.currentItem - 1
}

A: I checked your code and the problem was the usage of
supportFragmentManager.popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE)

If you read the description of the flag POP_BACK_STACK_INCLUSIVE it says:

If set, and the name or ID of a back stack entry has been supplied,
then all matching entries will be consumed until one that doesn't
match is found or the bottom of the stack is reached.  Otherwise, all
entries up to but not including that entry will be removed.

So it was removing the multiple entries at once.
The reason it worked for Home screen was that it never reached that case. It always went in the first case of:
layoutManager.findFirstCompletelyVisibleItemPosition() == 0 -> {
                        super.onBackPressed()
                    }

And that's what you exactly need for your case just call super.onBackPressed() when you want to pop only one fragment at once. So your final code becomes like this:
In your MainActivity's onBackPressed()
override fun onBackPressed() {
        if (view_pager_main_activity?.currentItem == 0) {
            if (view_pager_main_fragment?.currentItem == 0) {
                val recyclerView = findViewById<RecyclerView>(R.id.listRecyclerView)
                val appbarHome = findViewById<AppBarLayout>(R.id.appbar_home)
                val layoutManager = recyclerView?.layoutManager as LinearLayoutManager
                when {
                    layoutManager.findFirstCompletelyVisibleItemPosition() == 0 -> {
                        super.onBackPressed()
                    }
                    //This is never reached. It can be removed
                    supportFragmentManager.backStackEntryCount != 0 -> {
                        supportFragmentManager.popBackStack(
                            null,
                            FragmentManager.POP_BACK_STACK_INCLUSIVE
                        )
                    }
                    else -> {
                        layoutManager.scrollToPositionWithOffset(0, 0)
                        appbarHome.setExpanded(true)
                        //recyclerView.smoothScrollToPosition(0)
                    }
                }
            } else if (supportFragmentManager.backStackEntryCount != 0) {
                super.onBackPressed()
            } else {
                // Otherwise, select the previous step.
                view_pager_main_fragment?.setCurrentItem(
                    view_pager_main_fragment.currentItem - 1,
                    false
                )
            }
        } else if (supportFragmentManager.backStackEntryCount != 0) {
            super.onBackPressed()
        } else {
            // Otherwise, select the previous step.
            view_pager_main_activity?.currentItem = view_pager_main_activity.currentItem - 1
        }
    }

Edit 1: From the comments

I want to clear the backstack when bottom nav selection changes.

If you want to clear the selection when you change the bottom navigation selection changes then you've to set a listener and clear the back stack in your MainFragment as following:
view?.bottomNavView?.setOnNavigationItemSelectedListener { item ->
            //check if item is being re-selected then just return and don't do anything
            if (bottomNavView.selectedItemId == item.itemId){
                return@setOnNavigationItemSelectedListener false
            }
            //if the bottom nav item selection changes then clear the back stack of previous tab
            parentFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)

            when (item.itemId) {
                R.id.homeFragment -> viewPager2.setCurrentItem(0, false)
                R.id.searchFragment -> viewPager2.setCurrentItem(1, false)
                R.id.notificationsFragment -> viewPager2.setCurrentItem(2, false)
            }
            true
        }

And the rest can remain same. Try this out and do let me know.


text:
Q: How to notify user when he enters a CLLocation? SITUATION:
I followed the following tutorial:
https://www.raywenderlich.com/95014/geofencing-ios-swift

PROBLEM:
The following functions never get triggered:
AppDelegate.swift
func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
    if region is CLCircularRegion {
        handleRegionEvent(region)
    }
}

func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
    if region is CLCircularRegion {
        handleRegionEvent(region)
    }
}

func handleRegionEvent(region: CLRegion!) {

     print("Geofence triggered!")

    // Show an alert if application is active
    if UIApplication.sharedApplication().applicationState == .Active {
        if let message = notefromRegionIdentifier(region.identifier) {
            if let viewController = window?.rootViewController {
                showSimpleAlertWithTitle("Congratulations", message: "You just found: " + message , viewController: viewController)
            }
        }
    } else {
        // Otherwise present a local notification
        let notification = UILocalNotification()
        notification.alertBody = "You just found: " + notefromRegionIdentifier(region.identifier)!

        notification.soundName = "Default";
        UIApplication.sharedApplication().presentLocalNotificationNow(notification)
    }
}

QUESTION:
The tutorial was written for iOS 8. I am currently on iOS 9.3. What caused this issue in your opinion and how do I fix it ?

A: You didn't show the code that you use to set up CL - which is probably where your problem lies.
Did you edit info.plist?
Are you requesting permission?
Did you call one of the start functions on the CL manager?

A: Make sure of two things :-
1.) You have added These to your viewDidLoad() :-
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.requestWhenInUseAuthorization()
    locationManager.startMonitoringSignificantLocationChanges()
    locationManager.startUpdatingLocation()

Another alternative to requestWhenInUseAuthorization() and startUpdatingLocation() initialisation in specific to Swift 2.2, since in Swift 2.2 the string literals for selectors is deprecated, and instead there this new operator #selector that you need to be using. :-
you can also use :-
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone

    locationManager.startMonitoringSignificantLocationChanges()
     if locationManager.respondsToSelector(#selector(locationManager.requestWhenInUseAuthorization)) {
        locationManager.requestWhenInUseAuthorization()
    }
    else {
        locationManager.startUpdatingLocation()
    }
      //Prefer the FIRST ONE.

2.) You have updated your info.plist with :-
NSLocationAlwaysUsageDescription : String :-> I need location.
NSLocationWhenInUseUsageDescription: String :-> I need location.
privacy - location usage description: String :-> I need location.
Edit I need location according to the app's need
PS :- If it still not calls your locationManager functions
Simulator :- look for location settings of your app in your simulator settings.
Device: - Go in settings > Privacy > Location services > Your app > Always.
you also might find this explanation useful : - https://stackoverflow.com/a/26090094/6297658

A: initialize your location manager in app delegate on did finish launching


text:
Q: Making API with authentication of an existing rails MVC app with Devise I have a social web app in production made with Rails 4.1.6 (MVC) and I'm making a (non native) mobile version of it (Intel XDK). Currently, a user must sign in/up via email+password, Facebook or Google+ to access the app. I'm using Devise (>3.2) and omniauth.
After reading tons of Q/A, examples and tutorials my brain is full and, unlike Jimmy Cliff sing, I can't see clearly now... I have 2 questions:

*

*what is the best solution(s) to create an API on top of this current app?

*how to implement an auth solution so that existing users can sign in and new users can sign up to the mobile app with email+password as well as FB/G+ auth?

And of course, a user can sign in both to mobile and web app.
Thanks!


text:
Q: Sort an ArrayList of semicolon separated values by a field I have an ArrayList of semicolon separated values that needs to be sorted by the second field of each of the ArrayList elements.
Each of the elements of the array list have the form:
  field1;field2;field3;field4

and need to be sorted by field.2 Is there a way to do this without having to create a temporary array, switch field1 and field2, sort that array, and then switch field1 and field2 again?
Thank you for any help you might be able to offer

A: You need to write a Comparator<String> that extracts the second field and compares it. No intermediate array needed. Just a bit of substring/indexof/regex/substringBetween.

A: This code will do it for you:
Collections.sort(list, new Comparator<String>(){
    @Overide
    public int compare(String s1, String s2){
        return s1.split(";")[1].compareTo(s2.split(";")[1]);
    }
});

A: You can do this, to create own Comparator and use Collections.sort something like
Collections.sort(yourArrayList, new Comparator<String>(){
       @Overide
       public int compare(String s1,  String s2){
            String s1Field2, s2Field2;
            // Do your extracting of field 2 for each String
            s1Field2 = s1.split(";")[1];
            s2Field2 = s2.split(";")[1];
            // You may also want to add to this to ensure that the original strings
            // do contain a 'field2'
            return s1Field2.compareTo(s2Field2);
       }
   });


text:
Q: Ruby ActiveRecord validation based on existing value in database I know the common ways of validation in Ruby.
My current problem is, I would like the insert to fail if the record exists with boolean set to true. Example
Columns in table are => Name, Address, Has_changed, id
Now if has_changed is set to true in table, I would like to add new entry in the table (in a separate call) which will have name, Address (new one), has_changed(set to false) and id. I would not like to update existing entry as I want to keep history for the record.
Is there a way to have such a validation by using Ruby?
Thanks in advance.

A: I think its better use "new" and "create" actions in your controller
class RecordsController < BaseController
  def new
    @record = Record.find(params[:id])
  end

  def create
    Record.create(params[:record])
  end
end

Your form just contains adress
In your model make a before_create hook
class Record < ActiveRecord::Base

  default_value_for :has_changed, false
  before_create :check_changed

  ...

  private

  def check_changed
    changed_record = Record.where(name: name, has_changed: false).first
    if changed_record && (changed_record.address != address)
      changed_record.has_changed = true
      changed_record.save
    end
  end
end

And add a validation for address to avoid duplication


text:
Q: Pass RecyclerView press to super view I have a RecyclerView (which scrolls vertically) whose ViewHolders contain RecyclerViews that scroll horizontally. When you tap on an item in horizontal (nested) RecyclerViews, I want the entire row to have the ripple effect.
To do this, I've been trying to override the touch events and get them to get passed up the view stack (by returning false in touch event handlers). This works on views other than RecyclerViews, but it isn't having the desired effect for RecyclerViews.
How do I correctly pass the tap event on a RecyclerView up to the enclosing view?

A: Haven't found a way to pass the click event up to a recycler view's parent view, but the important thing was getting the ripple effect to happen – which I was able to do. So when a view holder's itemView get's tapped, I do this:
val background = itemView.background
if (background is RippleDrawable) {
    background.setState(intArrayOf(android.R.attr.state_pressed, android.R.attr.state_enabled))
}

Which manually triggers the ripple effect.


text:
Q: Can't get VMware-tools to work (copy&paste and shared folders) I've googled tried reinstall, many different things but copy&paste or shared folders won't work. What works is windows scaling, eg I can make window full screen it it is adjusted correctly which doesn't happen without the tools installed.
However I really need copy&paste and drag&drop. I also followed instructions here. I remember for others vms this used to actually work more or less. I have also run vmtools-config.pl multiple times and yes, the 2 options in Guest isolation are checked.
Ubuntu 16.04 LTS.
Host is widndows 7.
So I have no clue what else I can do?
EDIT:
Was not able to get it to work. Tried it with Lubuntu and there it worked just fine: sudo apt-get install open-vm-tools-desktop -y and then reboot. This is for a simple dev environment so Lubuntu works just as fine.

A: Because VMware is proprietary software, it may be hard to get a good answer here.
But I have a suggestion, can you use VirtualBox?
I built a VM of Windows with it, and installed their version of tools, and found it quite simple.  Thiers comes as an ISO file that you mount after your VM is up, and run on the VM.  it might be worth a try.
Other than that this question is better posed on a VMWare forum, because I don't think the problem is with Linux.
Chris


text:
Q: Catching errors or exceptions I built a mashup of google maps and weather.com and everytime  one of these server is not responding my application hangs up too.What do you think I can do to prevent or minimize hanging up of my web apps?Hanging up like you can't navigate away from that page....
I got this code on my app code to access the weather service;

Public Class WeatherIn
    Private _path As String
    Private _cachedFile As String
     Public Sub New(ByVal path As String)
        _path = path
        _cachedFile = String.Format("{0}\WeatherInCache.xml", _path)
    End Sub

Public Function GetWeather(ByVal arg As String) As String

    Return _getWebWeather(arg)

End Function

Private Function _getCachedWeather() As String
    Dim str As String = String.Empty

    Using reader As New StreamReader(_cachedFile)
        str = reader.ReadToEnd()
    End Using

    Return str
End Function

Private Function _getWebWeather(ByVal arg As String) As String

    Dim baseUrl As String = "http://xoap.weather.com/weather/local/{0}?cc=*&dayf=5&link=xoap&prod=xoap&par={1}&key={2}"
    Dim jane As String = arg
    Dim james As String = "api key"
    Dim john As String = "another api key"

    Dim url As String = String.Format(baseUrl, jane, james, john)

    Using client As New WebClient()

        Try

            Dim xml As New XmlTextReader(client.OpenRead(url))

            Dim xslt As New XslCompiledTransform()
            xslt.Load(_path + "/Pathto.xslt")

            Using writer As New StreamWriter(_cachedFile)
                xslt.Transform(xml, Nothing, writer)
            End Using

            Return _getCachedWeather()
        Catch exception As WebException

            Dim xmlStr As String = "<errorDoc>"
            xmlStr += "<alert>An Error Occurred!</alert>"
            xmlStr += [String].Format("<message>{0}</message>", exception.Message)
            xmlStr += "</errorDoc>"

            Dim doc As New XmlDocument()
            doc.LoadXml(xmlStr)

            Dim reader As New XmlNodeReader(doc)

            Dim xslt As New XslCompiledTransform()
            xslt.Load(_path + "/Pathto.xslt")

            Dim resultDocument As New XmlDocument()
            Using writer As XmlWriter = resultDocument.CreateNavigator().AppendChild()
                xslt.Transform(reader, DirectCast(Nothing, XsltArgumentList), writer)
            End Using

            Return resultDocument.OuterXml
        End Try
    End Using
End Function

Then I used the class above on my page where I display the weather like this:

'specific zip code or could be retrieved from querystring for dynamic retrieval

var jay="94576"

Dim weather As New WeatherIn(Server.MapPath(String.Empty))
                Dim weatherData As String = weather.GetWeather(jay)

                Response.ContentType = "text/xml"
                Response.CacheControl = "no-cache"

                Response.Write(weatherData)

which I retrieve the data and write on the page through javascript.Most of the time its the weather.com that goes down.I got no problem with google map its reliable....anybody got a solution why my page hangs up too if the remote server is not responding?The mashup  is running smoothly if the remote server is responding...

A: When depending on external web services it is best to load asynchronously so that if one of them is slow you can show some kind of loading spinner to the page viewer. If it fails your page could simply report that reading from the web server failed and to try again later.
In this case I would load up the page with the Google map in place and then make an AJAX request for the Weather data.


text:
Q: obtain the String matching only the immediate predecessor I have the below String
"8 IN, Ball Valve, Trunnion, Gen manu, CL 900, BW, Body LTCS, Metal Seat, Gear Operated, Trim Alloy 825, Full Bore, NACE MR 0175/ISO 15156 -with extended pup-piece as pipe schedule. VBFW 91Z08"
I need to obtain the string Gen Manu thats available before the , CL and After the previous comma (the comma after Trunnion in this case). I have tried below so far
(?=\,).(?=.\w).*.(?=\,.CL)
I am unable to perform a partial match
below is where I saved my work, any help regarding this is greatly appreciated
https://regexr.com/59deb
thanks

A: You can use this regex: (?<=, )[^,]+(?=, CL)
(?<=, ) before the match there is a comma followed by space.
[^,]+ the match is at least one character excluding any commas.
(?=, CL) match should be followed by the string ", CL"
Demo: https://regex101.com/r/tMlQby/1