text:
Q: How to swap array of characters (in-place) in Java So basically without being able / permitted to make a new array. An not being able to returning anything but actually changing and manipulating the current array. How do you take an array of characters and simply flip / reverse them.
Starting array: ['P','e','r','f','e','c','t',' ','M','a','k','e','s',' ','P','r','a','c','t','i','c','e']

Reverse back each word separate by space
Reversed: ['P','r','a','c','t','i','c','e',' ','M','a','k','e','s',' ','P','e','r','f','e','c','t']

This is what I have so far
Code:
  class Main {
     public static void main(String[] args) {
       char[] charArr = new char[] {'P','e','r','f','e','c','t',' ','M','a','k','e','s',' ','P','r','a','c','t','i','c','e'};
       reverseCharArray(charArr);
     }

     public static void reverseCharArray() {
       int arrLength = charArr.length;
       for (int i = 0; i <= arrLength / 2; i++) {
         charArr[arrLength - i - 1] = charArr[i];
         System.out.println(charArr);
       }
     }
   }

Update:
Ok what I have found is that. What I need to do is actually swap the words the sentence of characters spell. So that the sentence is backwards / reversed.
Note: This was attempted in a online interview here:
enter link description here

A: This is definitely not a good solution, but it's a working one.
class Main {

public static void main(String[] args) {
    char[] charArr = new char[] { 'P', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'M', 'a', 'k', 'e', 's', ' ', 'P', 'r',
            'a', 'c', 't', 'i', 'c', 'e' };
    System.out.println(charArr);
    reverseCharArray(charArr,0);
    System.out.println(charArr);
}

public static void reverseCharArray(char[] charArr, int sorted) {

    /* Look for last space*/
    int lastSpace = -1;
    for (int i = 0; i < charArr.length; i++) {
        if (charArr[i] == ' ') {
            lastSpace = i;
        }
    }

    /* Grab the word and move it at the beginning of the sorted array */
    for (int i = lastSpace + 1; i < charArr.length; i++) {

        int k = i;

        while (k != sorted) {
            char tmp = charArr[k-1];
            charArr[k-1] = charArr[k];
            charArr[k] = tmp;
            k--;
        }

        sorted++;
    }

    /* At this point, the last character is a space*/
    /* Else, we've swapped all the words */
    int k = charArr.length - 1;
    if (charArr[k] != ' ') {
        return;
    }

    /* If it's a space, grab it and move it at the beginning*/
    while (k != sorted) {
        char tmp = charArr[k-1];
        charArr[k-1] = charArr[k];
        charArr[k] = tmp;
        k--;
    }
    sorted++;

    /*Recursive call on the not sorted array*/
    reverseCharArray(charArr,sorted);

}}

A: The method below swaps intervals. Note that they must be of same length.
public static char[] swap(char[] arr, int lstart, int rstart, int len){
      for(int i=lstart; i<lstart+len; i++){
        char temp = arr[i];
        arr[i] = arr[rstart+i];
        arr[rstart+i] = temp;
   }
   return arr;
}

A: Let's say you have the following array; [h, e, y,  , y, o, u] you'd have to work in a pattern; from the outside to the inside (or the other way around). so, [1,2,3,4,3,2,1] you'd have to swap 1 and 1, 2 and 2 and so on. as you can see, this array has a length of 7, in this case the amount of swaps needed is exactly 4 (4 is swapped with itsself). To calculate the amount of swaps, you can simply ceil the array length divided by 2.0f.
Now you have to loop trough the array, swapping those indexes. To calculate which index to swap, you have to check at wich swap your are. Let's say you're at the second swap, the indexes of 2 in the array are 1 and 5, those of 3 are 2 and 4. You've probably recognized the pattern by now. The first index is always the amount of done swaps, where the second is the length of the array minus 1 minus the amount of done swaps.
here's this put into code;

    public static void swap(char[] array){
        int totalSwaps = (int) Math.ceil(array.length / 2.0f);
        for(int currentSwaps = 0; currentSwaps < totalSwaps; currentSwaps++){
            char char1 = array[currentSwaps];
            int position2 = array.length - (currentSwaps + 1);
            array[currentSwaps] = array[position2];
            array[position2] = char1;
        }
        System.out.println(Arrays.toString(array));
    }

EDIT: I just saw that you were asking to reverse each word in a char[], you might want to clarify that in the first sentences
to do this; I'd recommend you use String::split to split the string into a string[] and use String::toCharArray to change it to a character array. Though this does create new arrays

A: There is an algorithm for this, is as follows,

*

*Initially, reverse the individual words of the given string one by
one, for the provided example "Perfect Makes Practice", after reversing individual words the string should be "tcefreP sekaM ecitcarP".

*Reverse the whole string from start to end to get the desired output "Practice Makes Perfect" in the above example.

For more check Reverse words in a given string.


text:
Q: CSS background image won't scale I'm trying to learn html and css. Right now I'm trying to make a background image fill the browser window no matter the size.
I've googled it 100 times and every page pretty much says the same thing. So I copied the code and it isn't working for me. When I set my browser to a smaller size, the background image repeats itself. Which I don't want I just want it to fill the window.
Here's my css.
html {
background-image:url(background.jpg);
background-size: 100%;
background-image: no-repeat-y; }

Before I did 100%, I tried using cover instead and that didn't work either. The image is fullscreen when the window is maximized but when I resize it the image will repeat.

A: Using background-size cover will do the job:
html {
  background: url(background.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

A: To scale, the CSS you want to scale needs to be inside a container itself, namely BODY inside the HTML container; try this:
html {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  background-image:url(background.jpg);
  background-size: 100% 100%;
  background-repeat: no-repeat-y;
}

A: You need to specify a height of 100% to the parent div <body> so that any child div with a height: 100%; will take the height of it's parent div. Here's an example:
Wrap your content in a parent div like this:
<html>
  <body>
    <div class="wrapMeTight">
      ....Your page content....
    </div>
  </body>
</html>

And add this to your css:
html, body    {
    height: 100%;
}
.wrapMeTight   {
    min-height: 100%;
    height: 100%;
    background-image: url (/img.jpg);
    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
}

A: Use this:
<html>
  <head>
    <style type="text/css">
        body { background-image: url("background.jpg"); background-size: 100% 100%; background-repeat: no-repeat; height: 100vh; width: 100vh; }
    </style>
  </head>
  <body>

  </body>
</html>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular expandable ui-grid with infinite scroll and dynamic data? I have an expandable ui-grid and need an infinite scroll on the expanded (child) grids.  I will only show the first few lines of data, and will rely on the user to scroll to the bottom of the expanded grid to indicate that more data should be read in (there is a potential for a large amount of data).
I understand I can create a function which will be called when more data is needed:
$scope.subGridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.getDataDown);
But when this function ($scope.getDataDown) is called, I don't know which expanded grid needs more data.  Is there a way to determine which expanded grid is being scrolled?  Once I know that, I can determine the query I need to make to the server to get the next rows of data.

A: When setting up the infinite scroll of the child grid, you set up the function to be called to get more data:
$scope.subGridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.getDataDown);
The called function (getDataDown) doesn't receive any parameters.  But this.grid.api.grid is the current grid, and this.grid.api.grid.parentRow contains the row, which is where I had stored the details of what data I needed to retrieve next.


text:
Q: How can you curl/fold the bottom corner of a UIView I have a UIView with a coloured background and I use a curlup animation to change the background colour to give the effect of turning the page. This works and looks really good.
Whats letting it down is having an arrow button in the bottom corner that you press to turn the page.
Is it possible to actually fold the bottom corner over to show the colour of the page beneath and act as a button to fire the animation?
And if this is even possible, would it be able to be animated to curl/uncurl just this bottom corner?
Thanks

A: use this code
YourViewController * myModalVC = [[YourViewController alloc] init];
[myModalVC setModalTransitionStyle:UIModalTransitionStylePartialCurl];
[myModalVC setDelegate:self];

[self presentModalViewController:myModalVC animated:YES];
[myModalVC release];

and if you want to make a custom animation of partial curl then USE THIS


text:
Q: Using JavaScript utilize "Back to Top" I found a "Back to Top" effect written in JavaScript. But there's something in the code I don't understand.Thanks a lot!
window.onload = function () {
    var oBtn = document.getElementById('btn1');
    var timer=null;

    oBtn.onclick= function () {
       timer=setInterval(function () {
            var scrollTop = document.documentElement.scrolltop || document.body.scrollTop;
            var iSpeed = Math.floor(-scrollTop/8);//what does this mean?
           if(scrollTop===0)
           {
               clearInterval(timer);
           }

            document.body.scrollTop = document.documentElement.scrollTop = scrollTop + iSpeed;
        }, 30);
    };
};

A: -scrollTop means 0-scrollTop.
-scrollTop/8 means 0-scrollTop divided by 8.
Math.floor() rounds down to the nearest whole number.

A: iSpeed is best thought of as a velocity.  As the document scrolls back upwards, it gets set to that velocity which gradually becomes smaller as it gets closer to the targeted element.
Math.floor(-scrollTop/8)
In this case, you're constantly scrolling up an 1/8th of the distance between your position and that element.


text:
Q: How to print out request.body data in django? Just working through the Django tutorials and playing around with stuff. Was going through the HttpResponse and HttpRequest docs and I'm just trying to print out data to see how things work.
However, when I try to print to console the request.body I get nothing back.
def detail(request, question_id):
    current_question_selected = Question.objects.get(pk=question_id)
    choices_for_question = current_question_selected.choice_set.all()
    context = {"choices_for_question":choices_for_question,  "current_question_selected":current_question_selected}
    #print(request.META["REMOTE_USER"])
    print(request.body)
    return render(request,  'polls/detailtext.html', context)

This is what gets pritned to the screen, the letter 'b' with an empty string
[28/Jun/2022 10:59:56] "GET /polls/1/ HTTP/1.1" 200 456
b''

Not sure what i'm missing

A: The print displays an empty string because GET does not accept a body. Taken directly from the Mozilla Web APIs docs:

Note that a request using the GET or HEAD method cannot have a body and null is return in these cases.

If you want to pass data in a GET request, you need to pass them as parameters instead. Then, you can access the parameters using request.GET (HttpRequest.GET) or access them individually with request.GET.get('key').


text:
Q: AWS Access and Secret Keys in Terraform code with Jenkins Pipeline Instead of passing the Access and Secret keys in variables.tf of Terraform code,is there any safe and secure method of passing the keys to the code when Jenkins Pipeline is deployed??
The pipeline will be re-deployed often and the keys should be passed everytime.

A: First of all, you need to store a default credentials in your host to execute some awscli. You can do something like this:
sh "mkdir -p ~/.aws"
sh "cd ~/.aws; rm -rf credentials"
sh "cd ~/.aws; cp credentials-default credentials

In your AWS IAM section, you need to give the default credentials permissions to assume the role you need by command
aws sts assume-role ... > test.txt

In the test.txt file is the credentials with the temporary access and secret key for that session.
You can refer this documents for the above option: https://docs.aws.amazon.com/es_es/cli/latest/reference/sts/assume-role.html

A: If you don't want to store any aws credentials on Jenkins best way would be create a Jenkins slave on EC2 instance and attach the required IAM roles to that instance. This way you don't have to store or predefine any secret id and access key in Jenkins credential manager or Jenkins nodes


text:
Q: Selecting/deleting text between HTML tags in VsVim In the Visual Studio extension VsVim, is there a way to select, delete or change the text between two HTML or XML tags?
It is possible, for example, to select all text between two speech marks using vi" or delete all text between surrounding square brackets using di].
I'd like to apply similar commands to HTML. E.g.
Text to select or delete
.
I think this is the "tag blocks" feature mentioned in the vim documentation but the syntax mentioned doesn't appear to be working in VsVim.

A: The tab blocks feature allows the use of 't' to indicate that the delimiters should be the surrounding tag blocks. For instance, vit with the cursor between on a character between  tags would go into visual mode and highlight all characters between those tags. E.g.
Some text to [s]elect

With the block cursor on the 's' as indicated by the []:

*

*vit will select the text Some text to select

*vat will select the text Some text to [s]elect
This has been implemented in version 1.7.1 of VsVim and can be installed from as a Visual Studio extension from the gallery as normal: https://visualstudiogallery.msdn.microsoft.com/59ca71b3-a4a3-46ca-8fe1-0e90e3f79329


text:
Q: how to show admin notice in custom menu page after submitting the form? Here is my code to save data:
function save_new_exam(){

    extract($_POST);
    global $wpdb;
    $wpdb->insert(
        'wp_absb_exam_setting',
        array(
            'name' => $name,
            'time' => $time,
            'status' => 1,
            'user_id' => get_current_user_id()
        ),
        array(
            '%s',
            '%s',
            '%d',
            '%d'
        )
    );

    do_action( 'admin_notices', 'new_exam_created' );
}
function new_exam_created(){

    ?>

 Saved successfully!

<?php }

Here is the code of the form:
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">

                        <?php _e("Exam Title"); ?>

                        <input name="name" type="text"  value="" size="40" class="regular-text">

                            Give a Meaningful Exam Title.

                        <?php _e("Exam Time"); ?>

                        <input name="time" type="text"  value="" size="40" class="regular-text">

                            Set exam time as HH:MM:SS format.

            <input type="submit" name="submit" id="submit" class="button-primary" value="Save Changes">

    </form>

When I submit the form the data is being saved but no admin notice is being displayed. what is the problem in my code? I googled for couple of hours but no luck. Please help!

A: It should be add_action not do_action.
And if it still doesn't work, that means, your form processing code is being triggered after WP fires admin_notices hook.


text:
Q: Find Range of a number from an array I'm just rephrasing the question I asked a little while ago.
I have a sorted array {2.0,7.8,9.0,10.5,12.3}
If I given an input 9.5
What is the fastest way to find 9.0 and 10.5 to indicate that 9.5 is in between 9.0 and 10.5 (9.5 >=9.0 and <10.5) ?
Is binary search an option?But since the input need not be in the array.I'm not sure how I should do this.
Also If there is any other data structure that is suitable please comment.

A: A binary search would certainly be the "standard" approach - http://en.wikipedia.org/wiki/Binary_search_algorithm. Speed is O(log(N)) as opposed to linear.
In certain specialised cases you can do better than O(log(N)). But unless you are dealing with truly gigantic array sizes and satisfy these special cases then your binary search is really the fastest approach.

A: You could use Arrays.binarySearch to quickly locate 9.0 and 10.0, indeed.

A: I would do it like that
double valuebefore = 0;
            double valueafter = 0;
            double comparevalue = 9;
            foreach (var item in a)
            {
                valueafter = item;
                if (item > comparevalue)
                {
                    break;
                }
                valuebefore = item;
            }

            System.Console.WriteLine("Befor = {0} After = {1}", valuebefore, valueafter);

A: If the input numbers are in an array then binary search will be handy. Every time the search fails, indicating the number is not present in the array, the array elements at index low and high will give you the range.

A: The most efficient (space and time-wise) is to implement this as a modified binary search.
A simple (but less efficient) solution is to replace the array with a NavigableMap<Double, Double> and use floorKey and ceilingKey to find the bounding values.  Assuming that you use a TreeMap, this has the same complexity as binary search.

A: Here's a binary search algorithm I just wrote for you that does the trick:
import java.util.Random;

public class RangeFinder {

    private void find(double query, double[] data) {

        if (data == null || data.length == 0) {
            throw new IllegalArgumentException("No data");
        }

        System.out.print("query " + query + ", data " + data.length + " : ");

        Result result = new Result();
        int max = data.length;
        int min = 0;
        while (result.lo == null && result.hi == null) {

            int pos = (max - min) / 2 + min;
            if (pos == 0 && query < data[pos]) {
                result.hi = pos;
            } else if (pos == (data.length - 1) && query >= data[pos]) {
                result.lo = pos;
            } else if (data[pos] <= query && query < data[pos + 1]) {
                result.lo = pos;
                result.hi = pos + 1;
            } else if (data[pos] > query) {
                max = pos;
            } else {
                min = pos;
            }
            result.iterations++;
        }
        result.print(data);
    }

    private class Result {

        Integer lo;
        Integer hi;
        int iterations;
        long start = System.nanoTime();

        void print(double[] data) {
            System.out.println(

            (lo == null ? "" : data[lo] + " <= ") +

            "query" +

            (hi == null ? "" : " < " + data[hi]) +

            " (" + iterations + " iterations in " +

            ((System.nanoTime() - start) / 1000000.0) + " ms. )");
        }
    }

    public static void main(String[] args) {

        RangeFinder rangeFinder = new RangeFinder();

        // test validation
        try {
            rangeFinder.find(12.4, new double[] {});
            throw new RuntimeException("Validation failed");
        } catch (IllegalArgumentException e) {
            System.out.println("Validation succeeded");
        }
        try {
            rangeFinder.find(12.4, null);
            throw new RuntimeException("Validation failed");
        } catch (IllegalArgumentException e) {
            System.out.println("Validation succeeded");
        }

        // test edge cases with small data set
        double[] smallDataSet = new double[] { 2.0, 7.8, 9.0, 10.5, 12.3 };
        rangeFinder.find(0, smallDataSet);
        rangeFinder.find(2.0, smallDataSet);
        rangeFinder.find(7.9, smallDataSet);
        rangeFinder.find(10.5, smallDataSet);
        rangeFinder.find(12.3, smallDataSet);
        rangeFinder.find(10000, smallDataSet);

        // test performance with large data set
        System.out.print("Preparing large data set...");
        Random r = new Random();
        double[] largeDataSet = new double[20000000];
        largeDataSet[0] = r.nextDouble();
        for (int n = 1; n < largeDataSet.length; n++) {
            largeDataSet[n] = largeDataSet[n - 1] + r.nextDouble();
        }
        System.out.println("done");
        rangeFinder.find(0, largeDataSet);
        rangeFinder.find(5000000.42, largeDataSet);
        rangeFinder.find(20000000, largeDataSet);
    }
}

A: For small numbers of bins a sorted linked list will be most elegant. You scan over it and when you find a number bigger you have the range.
For very large numbers it is worth putting them in a BTree or similar Tree structure in order to get O(log(N)) performance.
In Java you can use a TreeSet for this.
lowerBound = boundaries.headSet(yourNumber).last();
  upperBound = boundaries.tailSet(yourNumber).first();
or similar will be O(logN) for large numbers.


text:
Q: deploy tools: get a list of actions the tool will execute without executing the deploy script We're in the process of evaluating MSBuild and Nant for deploys. We may roll our own tool. One thing that a different business unit -- let's call it DeptA --  would really like to have (as in it better have it) is the ability for someone in DeptA to read the script and see what it will do. Currently we do this with .bat files. We hates the bat files. Nasty nasty bat files's. But if we ask DeptA to learn a new script language (nant, msbuild) they may be resistant.
Ideally the build tool of choice would be able kick out a list of actions without doing anything else. Along the lines of:

*

*Stop service ABC on server Z

*Stop service DEF on server Z

*Copy all files from
\server\dirA\dirB to \server2\dirC

*Start service ABC on server Z

*Start service DEF on server Z

*Run all scripts in dir
\server\dirA\dirC

Is it possible to do this with MSBuild? NAnt? Without me re-learning XSL?

A: If I was you I would actually blend MSBuild and MSDeploy. You should have your MSBuild script perform the actions like start/stop service etc. Then let MSDeploy to the file copy. With MSDeploy you can use the -whatif switch to indicate that you only want a report of the actions to be executed instead of actually executing it. MSBuild unfortunately doesn't offer such an option out of the box you will have to "build" that into your scripts. You can do this with properties and conditions. For example it might look something like this:
<Project ...>
    <PropertyGroup>
      <!--
          Create the property to use, and declare a default value.
          Here I've defaulted this to true because it is better to force the
          caller to explicitly specify when to perform the action instead of it
          being the default.
      -->
      <SimulateExecution Condition= '$(SimulateExecution)'==''>true</SimulateExecution>
    </PropertyGroup>

    <Target Name="Deploy">
        <Message Text="Deploy started" />

        <Message Text="Stop service ABC on server Z"/>
        <WindowsService ... Condition=" '$(SimulateExecution)'=='false' "/>

        <Message Text="Stop service DEF on server Z"/>
        <WindowsService ... Condition=" '$(SimulateExecution)'=='false' "/>

        <!-- Call MSDeploy with the Exec task. -->
        <PropertyGroup>
            <MSDeployCommand>...\msdeploy.exe YOUR_OPTIONS_HERE</MSDeployCommand>

            <!-- Append the -whatif to the command if this is just a simulation -->
            <MSDeployCommand Condition= '$(SimulateExecution)'=='false' ">$(MSDeployCommand) -whatif</MSDeployCommand>
        </PropertyGroup>

         <Exec Command="$(MSDeployCommand)" />

         ... More things here
    </Target>
</Project>

For the service actions you can use the WindowsService task from the MSBuild Extension Pack. You will have to fill  in the blanks there.
When you call MSDeploy you should just use the Exec task to invoke msdeploy.exe with your parameters. If you pass the -whatif it will not actually perform the actions, just report what it would have done. These will be logged to the msbuild log. So if you invoke msbuild.exe with /fl you will get those actions written out to a file. The only issue that I've seen when taking this approach is that for msdeploy.exe you many times have to use full paths (those without ..) which can sometimes be tricky so be wary of such paths.


text:
Q: I need multiple inheritance but I'm using Java I want to model a simple merchant website, with a Visitor, an Account, a Customer and an Administrator.
A Visitor can have a Basket.
A Visitor can become a Customer if it creates or provides Credentials.
A Customer and an Administrator are an Account with Credentials.
class Account {
    Credentials credentials;
    void logout();
    // other account management methods
}

class Admin extends Account {
}

class Visitor {
    Basket basket;
    // basket management methods
}

class Customer extends Visitor, Account {
    // needs a basket and credentials
}

I tried an Account interface, but account management methods have to be implemented both in Customer and Admin, and I don't want to duplicate that code. I saw that default implementation of interface methods exist in Java 8. But is there another way to achieve that without this hack?

A: You have to reconsider the design and favor composition over inheritance.
A simple rule - how to identify if you should use one or another: does the inheritance answer the question "is-a" or "has-a"?
Is Customer and Account? No. Customer is a User who MAY HAVE and Account.
Is customer a Visitor? Yes, he may be.
So you should extend your Customer from Visitor AND add an Account as a member of the class.
class Account {
    Credentials credentials;
    void logout();
    // other account management methods
}

class Admin {
     private Account account; // + Getters and setters
}

class Visitor {
    Basket basket;
    // basket management methods
}

class Customer extends Visitor {
    private Account account; // + Getters and setters
}

You can add an interface to make it even better in terms of SOLID:
interface Authenticable {
    Account getAccount();
    Account setAccount(Account account);
}

and make your Customer and Admin to implement it
class Customer extends Visitor implements Authenticable {
    private Account account;
    @Override
    Account getAccount(){return account};
    @Override
    Account setAccount(Account account){this.account = account};
}

If you still want to avoid duplicating Account getters and setters - just extend Admin from the Customer and override getBasket() - thow NotImplementedException()

A: you may need an abstract method to infrastructure the class

A: Java has no multiple inheritance like python. This is fact.
You can change Account from class into interface. And create a class with name 'AccountImpl' that implement Account interface. In every class that you want to define account management methods like Admin or Customer you must have a field of Account interface and initilize that with AccountImpl class. something like this:
interface Account { // account management methods }

class AccountImpl implements Account {
//implement account interface methods
}

class Admin {
    Account account;
    public Admin() {
       account = new AccountImpl();
}

class Customers extends Visitor {
    Account account;
    public Customers() {
       account = new AccountImpl();
}

For example if you want to logout you must say
`customer.getAccount().logOut();
This is good practice because you don't duplicate the implementation of Account and also maybe in the future you want make deference between some credential. In this way you just have to create new AccountImpl class.


text:
Q: Executing function when disconnecting bluetooth I'm having a problem involving my android app and an arduino board. I installed an app that searches for available bluetooth devices and connects to them, now I want when the devices disconnect a notification is sent to the mobile device ... Anyone know how to do this function ???
ConnectionThread:
 public class ConnectionThread extends Thread {

BluetoothSocket btSocket = null;
BluetoothServerSocket btServerSocket = null;
InputStream input = null;
OutputStream output = null;
String btDevAddress = null;
String myUUID = "00001101-0000-1000-8000-00805F9B34FB";
boolean server;
boolean running = false;

/*  Este construtor prepara o dispositivo para atuar como servidor.
 */
public ConnectionThread() {

    this.server = true;
}

/*  Este construtor prepara o dispositivo para atuar como cliente.
    Tem como argumento uma string contendo o endereço MAC do dispositivo
Bluetooth para o qual deve ser solicitada uma conexão.
 */
public ConnectionThread(String btDevAddress) {

    this.server = false;
    this.btDevAddress = btDevAddress;
}

/*  O método run() contem as instruções que serão efetivamente realizadas
em uma nova thread.
 */
public void run() {

    /*  Anuncia que a thread está sendo executada.
        Pega uma referência para o adaptador Bluetooth padrão.
     */
    this.running = true;
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    /*  Determina que ações executar dependendo se a thread está configurada
    para atuar como servidor ou cliente.
     */
    if(this.server) {

        /*  Servidor.
         */
        try {

            /*  Cria um socket de servidor Bluetooth.
                O socket servidor será usado apenas para iniciar a conexão.
                Permanece em estado de espera até que algum cliente
            estabeleça uma conexão.
             */
            btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord("AWC", UUID.fromString(myUUID));
            btSocket = btServerSocket.accept();

            /*  Se a conexão foi estabelecida corretamente, o socket
            servidor pode ser liberado.
             */
            if(btSocket != null) {

                btServerSocket.close();
            }

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }

    } else {

        /*  Cliente.
         */
        try {

            /*  Obtem uma representação do dispositivo Bluetooth com
            endereço btDevAddress.
                Cria um socket Bluetooth.
             */
            BluetoothDevice btDevice = btAdapter.getRemoteDevice(btDevAddress);
            btSocket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(myUUID));

            /*  Envia ao sistema um comando para cancelar qualquer processo
            de descoberta em execução.
             */
            btAdapter.cancelDiscovery();

            /*  Solicita uma conexão ao dispositivo cujo endereço é
            btDevAddress.
                Permanece em estado de espera até que a conexão seja
            estabelecida.
             */
            if (btSocket != null)
                btSocket.connect();

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }

    }

    /*  Pronto, estamos conectados! Agora, só precisamos gerenciar a conexão.
        ...
     */

    if(btSocket != null) {

        /*  Envia um código para a Activity principal informando que a
        a conexão ocorreu com sucesso.
         */
        toMainActivity("---S".getBytes());

        try {

            /*  Obtem referências para os fluxos de entrada e saída do
            socket Bluetooth.
             */
            input = btSocket.getInputStream();
            output = btSocket.getOutputStream();

            /*  Cria um byte array para armazenar temporariamente uma
            mensagem recebida.
                O inteiro bytes representará o número de bytes lidos na
            última mensagem recebida.
             */
            byte[] buffer = new byte[1024];
            int bytes;

            /*  Permanece em estado de espera até que uma mensagem seja
            recebida.
                Armazena a mensagem recebida no buffer.
                Envia a mensagem recebida para a Activity principal, do
            primeiro ao último byte lido.
                Esta thread permanecerá em estado de escuta até que
            a variável running assuma o valor false.
             */
            while(running) {

                bytes = input.read(buffer);
                toMainActivity(Arrays.copyOfRange(buffer, 0, bytes));

            }

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }
    }

}

/*  Utiliza um handler para enviar um byte array à Activity principal.
    O byte array é encapsulado em um Bundle e posteriormente em uma Message
antes de ser enviado.
 */
private void toMainActivity(byte[] data) {

    Message message = new Message();
    Bundle bundle = new Bundle();
    bundle.putByteArray("data", data);
    message.setData(bundle);
    MainActivity.handler.sendMessage(message);
}

/*  Método utilizado pela Activity principal para transmitir uma mensagem ao
 outro lado da conexão.
    A mensagem deve ser representada por um byte array.
 */
public void write(byte[] data) {

    if(output != null) {
        try {

            /*  Transmite a mensagem.
             */
            output.write(data);

        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {

        /*  Envia à Activity principal um código de erro durante a conexão.
         */
        toMainActivity("---N".getBytes());
    }
}

/*  Método utilizado pela Activity principal para encerrar a conexão
 */
public void cancel() {

    try {

        running = false;
        btServerSocket.close();
        btSocket.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    running = false;
}

Main Activity:
 public class MainActivity extends AppCompatActivity {

public static int ENABLE_BLUETOOTH = 1;
public static int SELECT_PAIRED_DEVICE = 2;
public static int SELECT_DISCOVERED_DEVICE = 3;

static TextView statusMessage;
static TextView textSpace;
ConnectionThread connect;

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

    statusMessage = (TextView) findViewById(R.id.statusMessage);
    textSpace = (TextView) findViewById(R.id.textSpace);

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter == null) {
        statusMessage.setText("Que pena! Hardware Bluetooth não está funcionando :(");
    } else {
        statusMessage.setText("Ótimo! Hardware Bluetooth está funcionando :)");
        if(!btAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH);
            statusMessage.setText("Solicitando ativação do Bluetooth...");

        } else {
            statusMessage.setText("Bluetooth já ativado :)");
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == ENABLE_BLUETOOTH) {
        if(resultCode == RESULT_OK) {
            statusMessage.setText("Bluetooth ativado :D");
        }
        else {
            statusMessage.setText("Bluetooth não ativado :(");
        }
    }
    else if(requestCode == SELECT_PAIRED_DEVICE || requestCode == SELECT_DISCOVERED_DEVICE) {
        if(resultCode == RESULT_OK) {
            statusMessage.setText("Você selecionou " + data.getStringExtra("btDevName") + "\n"
                    + data.getStringExtra("btDevAddress"));

            connect = new ConnectionThread(data.getStringExtra("btDevAddress"));
            connect.start();
        }
        else {
            statusMessage.setText("Nenhum dispositivo selecionado :(");
        }
    }
}

public void discoverDevices(View view) {

    Intent searchPairedDevicesIntent = new Intent(this, DiscoveredDevices.class);
    startActivityForResult(searchPairedDevicesIntent, SELECT_DISCOVERED_DEVICE);
}

public void enableVisibility(View view) {

    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30);
    startActivity(discoverableIntent);
}

public void waitConnection(View view) {

    connect = new ConnectionThread();
    connect.start();
}

public void sendMessage(View view) {

    EditText messageBox = (EditText) findViewById(R.id.editText_MessageBox);
    String messageBoxString = messageBox.getText().toString();
    byte[] data =  messageBoxString.getBytes();
    connect.write(data);
}

@SuppressLint("HandlerLeak")
public static Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray("data");
        String dataString= new String(data);

        if(dataString.equals("---N"))
            statusMessage.setText("Ocorreu um erro durante a conexão D:");
        else if(dataString.equals("---S"))
            statusMessage.setText("Conectado :D");
        else {

           // textSpace.setText(new String(data));
        }
    }
};
 ***function I want to perform***

public void alarme(){
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setContentTitle("My notification")
                    .setContentText("Hello World!");

    Intent resultIntent = new Intent(this, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, mBuilder.build());
}

}

A: I have solved this issue, Problem is when bluetooth connection is lost, then how you send notification ? So, solution is your android phone ping to bluetooth device everything 10 seconds or 5 seconds, bluetooth device will receive this ping and send response back to your android phone. if your phone gets response, then its working, if your phone does not get response. then you should show user that device is disconnected.


text:
Q: Delete all rows in a table with MySQL? I'm trying to create a simple chat application that posts people's messages, and that gives the user an option to "reset" the chat which will delete all messages from the database so the user can start over. The messages post okay, but the reset button just sends an empty post (instead of deleting all current posts). I'm wondering what I'm doing wrong:
if ( isset($_POST['reset']) ) {
    $sql = "DELETE FROM {$p}sample_chat WHERE chat = :CHA";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(':CHA' => $_POST['message']));
    header( 'Location: '.sessionize('index.php') ) ;
    return;
}

Per a comment below, I've updated my client side code to be:

<form id="chats" method="post">
<input type="text" size="60" name="message" />
<input type="submit" value="Chat"/>
<input type="submit" name="reset" value="Reset"/>
Launch chatlist.php
</form>

The code in its entirety, in case I've missed something/context is helpful:
<?php
require_once "../../config.php";
require_once $CFG->dirroot."/pdo.php";
require_once $CFG->dirroot."/lib/lms_lib.php";

// This is a very minimal index.php - just enough to launch
// chatlist.php with the PHPSESSIONID parameter
session_start();

// Retrieve the launch data if present
$LTI = requireData(array('user_id', 'result_id', 'role','link_id'));
$instructor = isset($LTI['role']) && $LTI['role'] == 1 ;
$p = $CFG->dbprefix;

if ( isset($_POST['message']) ) {
    $sql = "INSERT INTO {$p}sample_chat
    (link_id, user_id, chat, created_at)
    VALUES (:LI, :UID, :CHA, NOW() )
    ON DUPLICATE KEY
    UPDATE chat = :CHA, created_at = NOW()";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(
        ':LI' => $LTI['link_id'],
        ':UID' => $LTI['user_id'],
        ':CHA' => $_POST['message']));
    $messages = array();
    header( 'Location: '.sessionize('index.php') ) ;
    return;
}

if ( isset($_POST['reset']) ) {
    $sql = "DELETE FROM {$p}sample_chat WHERE chat = :CHA";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(':CHA' => $_POST['message']));
    header( 'Location: '.sessionize('index.php') ) ;
    return;
}

?>

<form id="chats" method="post">
<input type="text" size="60" name="message" />
<input type="submit" value="Chat"/>
<input type="submit" name="reset" value="Reset"/>
Launch chatlist.php
</form>

A: Major issue:
 $.getJSON('<?php echo(sessionize('chatlist.php')); ?>', function(data){
   ^^^--- using http GET

if ( isset($_POST['reset']) ) {
             ^^^^---expecting HTTP POST

.getJSON() is for GET requests only. If you want to use a POST, you'll have to use $.ajax() instead.

A: You are doing a GET request using ajax. Make a POST request. Add Type. For Example
$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

A: I suggests best thing you can do is: Use PHP REQUEST variable. Using it use can accept either post or get requests. i.e. For example:

if ( isset($_REQUEST['reset']) ) {
          /***Code to delete chat **/
}


text:
Q: What's the name of the algorithm to balance an acyclic graph? Algorithms class was a such a long time ago and I can't remember the name of the algorithm to balance an acyclic graph.
Let's start with a graph that looks like this:
        1
        |
        2
        |
        3
      /   \
     4     7
    / \    |
   5   6   8

The solution to balancing this out would be:
        2                             3
       /  \                         / |  \
      1    3                       2  4   7
          /  \        =>          /  / \  |
        4     7                  1  5   6 8
      /   \   |
     5     6  8

You rotate until the you have a root node whose branch's are the same length and your tree is at a minimum height.
What algorithm am I describing?

A: You might want to provide some more details in your description. Also, the example you give does not seem to be consistent (e.g. node 3 suddenly takes three children), whereas all other nodes seem to maintain at most two children.
Based on the little detail you provide, your rotation operations are similar to what's described in AVL tree rotations. See e.g. the wikipedia page for more details.


text:
Q: This site can't be reached docs/docker.github.io I ran
docker run -p 4000:4000 docs/docker.github.io

and the output shows
Docker docs are viewable at:
http://0.0.0.0:4000

however when I go to this address I get an error
 This site can't be reached

 The web page at http://0.0.0.0:4000/ might be temporarily down or it may
 have moved permanently to a new web address.
 ERR_ADDRESS_INVALID

A: What I found using Docker for Windows is that the references to localhost or 0.0.0.0 didn't work at all when I tried to access the application in the browser. It's using Docker Quickstart Terminal which runs a Linux image on Windows and it runs Docker inside that
This command provides the IP address of the Linux image
docker-machine ip

When I use that address on my Windows browser it works fine, for example:
http://192.168.99.100:4999/

A: 0.0.0.0 is a listener address that indicates all network interfaces on a machine, you don't connect to this address because it doesn't exist. Instead, you need to connect your browser to the IP address or name of the docker host. If you're running this locally, without docker-machine, that would be http://127.0.0.1:4000. With docker-machine, you can get the IP of the VM from the docker-machine ip output.


text:
Q: WinSCP .NET Assembly throws "The module was expected to contain an assembly manifest" I am trying to use the WinSCP within my C# project for some ftp automation.
I am using Visual Studio 2012 and am unsure on how to get it to work.
Things I have done so far:

*

*I copied the WinSCP.exe into my project folder.

*I imported a reference to the WinSCPnet.dll into my project

*I ran C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe Path/To/WINSCPnet.DLL /codebase /tlb
This is my code as of now:
using WinSCP;

static void Main(string[] args)
{
    try
    {
        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Ftp,
            HostName = "hostname.address.com",
            UserName = "Username",
            Password = "Password"
        };
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: {0}", e);

    }
}

When I run this in code I get the following exception:
Could not load file or assembly 'WinSCP, Version=1.0.7.3446, Culture=neutral,
PublicKeyToken=b5f19f5762436b89' or one of its dependencies. The module was expected to
contain an assembly manifest.

And Visual Studio's error is: BadImageFormatException was unhandled.
I am not exactly sure how to import WinSCP into my C# program and would appreciate some guidance here.
Conclusion
I was using 5.2.5 Beta and 32bit but my project was 64 bit

A: I suppose your project is 64-bit, while the distributed binary of WinSCP .NET assembly is only 32-bit. Either switch your project to 32-bit or build 64-bit version of the assembly from source code.
Also note that you do not need to register the assembly (regasm). That's for COM interop only. While you use it directly.


text:
Q: Append a tag box inside an image after clicking on it I'm trying to make a photo tag plugin for my website. I have long way to go. I know there are other actual plugins but I want to create my own here. The question is I was trying to make a box appear on a image after clicking it, it is not appearing, it is not appending on the image.

What is the problem with this code?

A: Interesting and difficult yet very simple solution
http://jsfiddle.net/e4tr7/5/
$("#imageHolder img").click(function (e) {
  var offset = $(this).offset();
  var position = {
    left: e.clientX - offset.left - 50,
    top: e.clientY - offset.top - 50
  }
  var append = $('

').draggable({containment: "parent"}).css({"position":"absolute","top":position.top,"left":position.left});
  $(this).parent().append(append);

});

A: Your example seems to work, see JSFiddle.
I moved the click function to the div, since the test.jpg image is not available. I also colored the divs to show it more clearly. Otherwise I left the rest of your code as is
$("#imageHolder").click(function(e){
  var imgBox = $(this);


text:
Q: Vim - Go to previous location Say I open a file in vim. I start on line 1 column 1 and hold down j until I am on line 14. Pressing :7CR puts me on line 7. I press yy to "yank".
How do I return to line 14? Using CTRL + o takes me back to the top of the file. ` ` gives me the same results.

A: <C-o> and <C-i> allow you to go down and up the jumplist. They work with "jump" commands but not with jjjjjjjjjjj.
To take advantage of this feature — and save a lot of time and keypresses in the process — I'd advise you to get into the habit of using better ways to navigate through your code : /?^$fFtTbBeEwW{} and so on.
And yes, use marks.

A: One more way: To jump back to another line, you can use ''. This works similar to an automatic mark, which is set for certain jump movements.

A: If you want to return to a previous location, first you have to mark that location using the mark (m) command, followed by any letter a-z or A-Z, like ma to mark a location as 'a'.
To return to that location you would enter `a.

A: Why not set a mark using ma for example, and then return to it later using `a or 'a?

A: Mark the line you were originally on using ma, then 'a to return there.

A: You can type 7G to jump to line#7, then type Ctrl-o to jump back.
:set showcmd to show what you have typed at the right bottom.

To yank line#7 (No cursor moving):
:7y

To paste line#7 below line#14:
:7t14


text:
Q: Raspberry PI 1B: Multiple "Push Buttons" I use a Raspi 1B which are connected 15 buttons + 1 led. Each button represents a letter box, the time press determines the contents of the box (letters, packages and special) and calls the appropriate bash script to send an email. Currently I have several python scripts (15, one for each button) that I will wish to merge into one script but I can not.
Here's what the script looks like (one of the 15 scripts):
#!/usr/bin/env python2.7

from time import sleep
import subprocess

import RPi.GPIO as GPIO

# GPIO 2 (pin 3)
CHANNEL = 2

# durees
colis = 2
special = 4

# GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(CHANNEL, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# LED
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,GPIO.LOW)

# fonction de gestion du bouton
def system_button(CHANNEL):

# variable de stockage du temps de pression
button_press_timer = 0

while True:
   if (GPIO.input(CHANNEL) == False) :
      button_press_timer += 0.2
         GPIO.output(18,GPIO.HIGH)

   else:
      if (button_press_timer > special) :
         print "special : ", button_press_timer
         subprocess.call("./Special.sh", shell=True)
         GPIO.output(18,GPIO.LOW)

      elif (button_press_timer > colis) :
         print "colis : ", button_press_timer
         subprocess.call("./Colis.sh", shell=True)
         GPIO.output(18,GPIO.LOW)

      elif (button_press_timer > 0.2):
         print "lettre : ", button_press_timer
         subprocess.call("./Lettre.sh", shell=True)
         GPIO.output(18,GPIO.LOW)

      button_press_timer = 0

   sleep(0.2)

GPIO.add_event_detect(CHANNEL, GPIO.FALLING, callback=system_button, bouncetime=200)

try:
while True:

   sleep (2)

except KeyboardInterrupt:

GPIO.cleanup()

GPIO.cleanup()

Thank you in advance for your assistance.


text:
Q: Wordpress links have become non-clickable My blog link was working well before. But today it seems that all the links of the subpages has become non-clickable.
In every wordpress sub pages, none of the links are clickable.. Just check it.. don't know what's the problem...
wordpress site url
When the site was created before it didn't have this kind of issue.. But today when I was checking I found this strange thing.
This problem wasn't before... Anyone help a bit.. I will be thankful..

A: If you use the element inspector in chrome, you'll see that an
 size is very big. This one's id is #social_comments_control .ui-widget-header which css is located in ur page's wp-content/plugins/social-comments/assets/css/social_comments.css so what comes to my mind is just to add this css to that element id in that stylesheet: overflow:hidden; or height:0; or just quit its html from the template.

A: The culprit are these classes and the id:

Just remove them like this and the links on the page will be clickable again:

Alternatively:
In case you want to keep the classes and the id, just simply remove the 'position:relative;' from #social_comments_nav and .ui-tabs.ui-tabs-nav which are defined in:
 /wp-content/plugins/social-comments/assets/css/social_comments.css

and the links will be clickable again.


text:
Q: What is stdole2.tlb stdole32.tlb contains all base type definitions, and every lib must import it, if we use MIDL. But when I created ATL DLL project, lib file looks like that
import "oaidl.idl";
import "ocidl.idl";

[
    uuid(4CA3ADAD-AE53-4D80-AF26-176BAF8223B1),
    version(1.0),
]
library FirstATLLib
{
    importlib("stdole2.tlb");
};

I can't google what is in stdole2.tlb? Does it contain stdole32.tlb? And what else? Can someone helps me to find out?

A: You can use Windows SDK COM/OLE Object Viewer to open the type library and see what is there inside:

It defines certain interfaces and type you can use in your type library, since you make them available through referencing stdole2.tlb.

A: stdole2.tlb is a newer version of stdole32.tlb. This is evident from the IDL exported using OleView:
From stdole2.tlb:
// typelib filename: stdole2.tlb

[
  uuid(00020430-0000-0000-C000-000000000046),
  version(2.0),
  helpstring("OLE Automation")
]
library stdole
{
...

From stdole32.tlb:
// typelib filename: stdole32.tlb

[
  uuid(00020430-0000-0000-C000-000000000046),
  version(1.0),
  helpstring("OLE Automation")
]
library stdole
{
...

This is confirmed by observing that they both have the same uuid but that stdole2 has a later version attribute.
Furthermore if you compare the IDL for both of them you can see specifically how the newer one differs from the first. Mainly it adds some attributes to a few interfaces, and also adds a bunch of new typedefs, interfaces, etc. (Too long to add here and not really needed to answer the question).
Curiously unlike a DLL there are no file attributes (Details tab of the Properties view in Windows Explorer) with version or other info.


text:
Q: Open a file with notepad and save it, using vbscript My problem is that I want to open a file in notepad and then save it from notepad, not manually but using vbscript (the reason I want this is to overcome some encoding issues). Until now I have found a relevant article which should solve my problem, but it doesn't work. It has this code:
Dim notepad, wndNotepad, strDesktop

Set notepad = Sys.Process("notepad")
Set wndNotepad = notepad.Window("Notepad")

' Open a file in Notepad
wndNotepad.MainMenu.Click("File|Open...")
notepad.Window("#32770", "Open").OpenFile "C:\Program Files\SmartBear\TestComplete 12\install.txt"

' Save the file to the desktop
strDesktop = WshShell.SpecialFolders("Desktop")
wndNotepad.MainMenu.Click "File|Save as..."
notepad.Window("#32770", "Save As").SaveFile strDesktop & "\install.txt"

The problem is that vbscript can't recognize the Sys in the second line (Sys.Process). I assume that in this line a process for notepad should be created (like here) and then something like an object of this process to be returned to the variable notepad (something I don't know if and how can be achived) in order to be used in the third line (notepad.Window("Notepad")).
If anyone has any idea how the code should be in order to work, I would really appreciate the help. Also any other suggestions on how to solve this problem (or any ideas about if it can actually be solved) are very welcome. Thank you for your time.
EDIT
As I said in the comments below, the above code needs the TestComplete software which is expensive. So if anyone has any idea for resolving my issue in another way (other software, other code, other programming language) I would be glad to learn it.

A: I think you need to copy a file from one path to another. Please refer the below code for copying Files,
Function CopyFile()
strSourceFile = "c:\.....\source.txt"
strDestFile = "c:\.....\dest.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file is read-only
If Not fso.GetFile(DestinationFile).Attributes And 1 Then
    'The file exists and is not read-only.  Safe to replace the file.
    fso.CopyFile strSourceFile, strDestFile, strOverWrite
Else
    'The file exists and is read-only.
    'Remove the read-only attribute
    fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
    'Replace the file
    fso.CopyFile strSourceFile, strDestFile, strOverWrite
    'Reapply the read-only attribute
    fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If

End Function


text:
Q: How do I compile gtypist-2.9.5 on Alpine Linux? GNU Typist is a well-known typing practice program for the terminal. I wanted to use it so I downloaded the .tar.gz from https://ftp.gnu.org/gnu/gtypist/?C=M;O=D. But when I untarred it and ran configure, it gives me the error
Error:  both library and header files for the ncursesw library are required to build this package.  See INSTALL file for further information. On Debian/Ubuntu you need to install libncursesw5-dev.

I already have ncurses and ncurses-dev installed (the branch is v3.15). I also tried installing ncurses5 and ncurses5-libs from branch v3.13 + ncurses-dev, but it shows me the same error. How do I fix this error?

A: Nevermind, I was being too pedantic with "everything must be managed by the package manager". In the configure file, the error was triggered by
if test -n "$HAVE_NCURSESW_H" -a -n "$HAVE_LIBNCURSESW";  then
   LIBS="-lncursesw $LIBS"
else
   echo -e "Error:  both library and header files for the ncursesw library\n"\
       "are required to build this package.  See INSTALL file for"\
       "further information. On Debian/Ubuntu you need to install libncursesw5-dev."
   exit 1;
fi

HAVE_NCURSESW_H is determined by these lines:
ac_fn_c_check_header_mongrel "$LINENO" "ncursesw/ncurses.h" "ac_cv_header_ncursesw_ncurses_h" "$ac_includes_default"
if test "x$ac_cv_header_ncursesw_ncurses_h" = xyes; then :
  HAVE_NCURSESW_H=1
fi

ac_fn_c_check_header_mongrel checks if a header exists.
So I created a folder named ncursesw in /usr/include (temporarily) and copied ncurses.h to the folder. Ran configure and everything worked perfectly after that.


text:
Q: TeaVM and WebAssembly - build errors I want to use Java code in the web. For this I want to convert Java to WASM and use this wasm-file in JavaScript. For converting Java to WebAssembly, I am using TeaVM.
First, I created an archetype with this command: mvn archetype:generate  -DarchetypeGroupId=org.teavm.flavour -DarchetypeArtifactId=teavm-flavour-application -DarchetypeVersion=0.2.0
In addition, I added these two dependencies (according to http://blog.dmitryalexandrov.net/webassembly-for-java-developers/):
   <dependency>
        <groupId>org.teavm</groupId>
        <artifactId>teavm-jso-apis</artifactId>
        <version>${teavm.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.teavm</groupId>
        <artifactId>teavm-interop</artifactId>
        <version>${teavm.version}</version>
    </dependency>

and added the following in the plugin section:
<targetType>WEBASSEMBLY</targetType>
<optimizationLevel>FULL</optimizationLevel>
<heapSize>8</heapSize>

My Java file:
@BindTemplate("templates/client.html")
public class Client extends ApplicationTemplate {
    private String userName = "ABC";

    public static void main(String[] args) {
        Client client = new Client();
        client.bind("application-content");
    }
    @Export(name = "getUserName")
    public String getUserName() {
        return userName;
    }
}

But when I am doing mvn clean package, I am getting to following error (but a wasm file is created):

my complete pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>my.company</groupId>
  <artifactId>java_wasm</artifactId>
  <version>1.0-SNAPSHOT</version>

  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <flavour.version>0.2.0</flavour.version>
    <teavm.version>0.6.0</teavm.version>
    <jackson.version>2.5.4</jackson.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.teavm</groupId>
      <artifactId>teavm-classlib</artifactId>
      <version>${teavm.version}</version>
    </dependency>
    <dependency>
      <groupId>org.teavm</groupId>
      <artifactId>teavm-metaprogramming-impl</artifactId>
      <version>${teavm.version}</version>
    </dependency>

    <dependency>
      <groupId>org.teavm.flavour</groupId>
      <artifactId>teavm-flavour-widgets</artifactId>
      <version>${flavour.version}</version>
    </dependency>
    <dependency>
      <groupId>org.teavm.flavour</groupId>
      <artifactId>teavm-flavour-rest</artifactId>
      <version>${flavour.version}</version>
    </dependency>
    <dependency>
        <groupId>org.teavm</groupId>
        <artifactId>teavm-jso-apis</artifactId>
        <version>${teavm.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.teavm</groupId>
        <artifactId>teavm-interop</artifactId>
        <version>${teavm.version}</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jackson.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>${java.version}</source>
          <target>${java.version}</target>
        </configuration>
      </plugin>

      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <webResources>
            <resource>
              <directory>${project.build.directory}/generated/js</directory>
            </resource>
          </webResources>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.teavm</groupId>
        <artifactId>teavm-maven-plugin</artifactId>
        <version>${teavm.version}</version>
        <executions>
          <execution>
            <id>web-client</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <targetDirectory>${project.build.directory}/generated/js/teavm</targetDirectory>
              <mainClass>my.company.Client</mainClass>
              <minifying>true</minifying>
              <debugInformationGenerated>true</debugInformationGenerated>
              <sourceMapsGenerated>true</sourceMapsGenerated>
              <sourceFilesCopied>true</sourceFilesCopied>
              <optimizationLevel>ADVANCED</optimizationLevel>
              <targetType>WEBASSEMBLY</targetType>
              <optimizationLevel>FULL</optimizationLevel>
              <heapSize>8</heapSize>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>

How can I create a complete WASM without errors? Thank you in advance!

A: Wasm backend of TeaVM does not support JSO interop layer. It also supports subset of features available in JavaScript backend. So there's no way to make TeaVM Flavour work in Wasm, instead your should prefer JavaScript target. If you want to learn how to deal with Wasm BE, you can take a look at example.
Wasm has proven to be extremely inappropriate to run Java, so I recommend to use JavaScript BE of TeaVM. Also, please note that official site (htts://teavm.org) lists links where you can get help (google groups, gitter, direct email). I don't follow StackOverflow questions about TeaVM and don't receive notifications from SO.


text:
Q: DRYing up my Rails belongs_to and has_many assosiations I'm working on an app that works out debts and who owes what to whom etc..
Currently it works like this:
create_table "debts", :force => true do |t|
  t.string   "amount"
  t.integer  "payer_id"
  t.integer  "payee_id"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
end

create_table "people", :force => true do |t|
  t.string   "name"
  t.integer  "bank"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
end

class Debt < ActiveRecord::Base
    attr_accessible :amount, :payee_id, :payer_id

    belongs_to :payee, :class_name => 'Person'
    belongs_to :payer, :class_name => 'Person'
 end

class Person < ActiveRecord::Base
    attr_accessible :amount, :payee_id, :payer_id

    has_many :debts_owed, :class_name => Debt, :foreign_key => "payee_id"
    has_many :debts_to_pay, :class_name => Debt, :foreign_key => "payer_id"
end

It's working but I know there must be a simpler way of representing multiple associations to the same model? I've been reading up on has_and_belongs_to_many which looks like the right thing but I'm lost to be honest.
Any help would be appreciated!
Thanks

A: I don't think a HABTM would help here.
HABTM is for situations where you need a many-to-many relationship, for example, tags. If I have a set of blog posts, I might want to be able to tag them. Blog posts can have many tags, and tags can be used on many blog posts.
That sort of relationship isn't happening in your case. I honestly don't believe there is a better way to set up the associations you have.

A: For just two lines, that's not too much repetition, BUT if you really wanted to, you could do something like this:
[:payee, :payer].each {|f| belongs_to(f, :class_name => 'Person') }

So that's one line instead of two, but it's probably less clear to read and maintain. It might be worth it if you had a few more lines using the same class_name though.


text:
Q: Check connection Redis I am using the Redis in Java using the Jedis client. I am creating a JedisPool and would like to know if the connection is successful, is there a way of doing this without fetching an object?

A: I have deployed a new method witch uses "ping" function from Jedis. This requires a new JedisPool independent for this purpose:
/**
 * Check if the current data base object is connected to the Redis Data Base.
 * @return True if is connected, false if not.
 * @since v0.3.0
 */
public boolean isConnected(){
    try{
        monitorDbObj.ping();
        return true;
    } catch (JedisConnectionException e){
        if(!this.connecting){
            connecting = true;  // Set the connecting flag True (trying to connect...).
            try{
                isConnected = connectDb();
            } catch (JedisConnectionException ex){
                isConnected = false;
            }
            connecting = false; // Set the connecting flag to False (connected).
        }
    } catch (JedisDataException e){
        LOGGER.info("Redis is busy loading the data set in memory.");
        connecting = false;
    }
    return false;

}
INFO: You can see the full class at this place: https://github.com/mami-project/KeyServer/blob/master/src/main/java/es/tid/keyserver/controllers/db/DataBase.java

A: You can attempt to get the Jedis resource from the JedisPool. A JedisConnectionException will be thrown if a connection has not been established:
JedisPool pool = new JedisPool(...);
try {
    Jedis jedis = pool.getResource();
    // Is connected
} catch (JedisConnectionException e) {
    // Not connected
}


text:
Q: how will select arrays i am having an o/p like this.this contains empty array values also,i want to get an array containing non zero values.
array
          0 => string 'Account' (length=7)
          1 => string 'Description: CURRENT' (length=20)
          2 => string 'A/C' (length=3)
          3 => string '-' (length=1)
          4 => string 'COLLECTION' (length=10)
          5 => string 'A/C' (length=3)

        array
     0 => string 'Branch' (length=6)
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string '' (length=0)
      4 => string '' (length=0)
      5 => string '' (length=0)
      6 => string '' (length=0)
      7 => string '' (length=0)
      8 => string '' (length=0)
      9 => string '' (length=0)
      10 => string '' (length=0)
      11 => string '' (length=0)
      12 => string '' (length=0)
      13 => string ':   SMART' (length=7)
      14 => string 'CITY' (length=4)
i want to get  an array(without empty fields)

 i want to get o/p like this $array=['Account','Description:,A/C,'Branch']

A: You can simply use array_filter as
$new_array = array_filter($old_array);


text:
Q: PyBytes_FromString returning a None object I was wondering if I could get some help. Say I've got the following function to serialize an object:
PyObject * CKKSwrapper::SerializeContext() {
    std::string s;
    std::ostringstream os(s);
    Serial::Serialize(m_cc, os, SerType::BINARY);

    const std::string tmp = os.str();
    const char *msg = tmp.c_str();
    std::cout << "Length of context: " << tmp.length() << "\n";
    return PyBytes_FromString(msg);
}

The Boost module file has
BOOST_PYTHON_MODULE (pycrypto) {
    class_<pycrypto::CKKSwrapper>("CKKSwrapper")
        .def("SerializeContext", &pycrypto::CKKSwrapper::SerializeContext,
             return_value_policy<manage_new_object>());

where I am managing the object.
However, when I call the method in Python, I get a None object, and the output is
import pycrypto
a = pycrypto.SerializeContext()

a is None and I get Length of context: X to my console


text:
Q: Hide View in @react-pdf/renderer If I want to hide a text on the last page of the pdf we do this:
<Text
   style={styles.paragraph}
   render={({ pageNumber, totalPages }) =>
   pageNumber === totalPages ? '' : 'Show this text'
   }
 />

I am trying to hide a view on the last page, let's suppose this is the View I want to hide on the last page
<View
   style={styles.paragraph}
   render={({ pageNumber, totalPages }) =>
   pageNumber === totalPages ? '' : 'Show this text'
   }
 />

But it's not working. Any ideas?

A: How about this?
{  pageNumber !== totalPages ?(
<View
   style={styles.paragraph}
   render={({ pageNumber, totalPages }) =>{ Your content here}
   }
 />
):null}


text:
Q: Openstack + Mongodb  + Elasticserach миграция Наверное, не так составил заголовок, но не знаю, как ещё.
В общем, какая проблема - человек сделал java rest сервис. Потом человек пропал, и возникла необходимость перейти на другой сервер. НО документации нет, и вообще неизвестно, какие ходы делал тот человек. Всё, что я выяснил, это - на сервере стоит openstack с виртуалкой, к которой прицеплены два тома - mongodb и elasticsearch. Код на сервер деплоится средствами jenkins. И потом как-то запускается rest сервис.
Может, у кого есть идеи, что почитать? Или кто-то уже сталкивался с подобными конфигурациями и может описать путь?


text:
Q: How to position ViewPager above RecyclerView? This xml layout has been populated by ViewPager and RecyclerView via an activity class, I want to position ViewPager on top and RecyclerView at the  bottom, I tired to use android:layout_below="@+id/awesomepager" in the LinearLayout of  RecyclerView but it doesn't work (it stays on top behind the toolbar[Deep blue color in the picture]), I also used android:layout_alignBottom="@+id/awesomepager" but that puts it inside the ViewPager at the bottom.
I basically want ViewPager and RecyclerView to be siblings , like this picture , black area to be ViewPager at the top and the green area to be RecyclerView at the bottom.

what is correct way to do this?
viewpager_with_toolbar_overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ProgressBar
        android:id="@+id/progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <android.support.v4.view.ViewPager
            android:id="@+id/awesomepager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:background="#068006"
            android:layout_below="@+id/awesomepager"
            >

        <android.support.v7.widget.RecyclerView
            android:id="@+id/episodesLIST"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:scrollbars="horizontal" />
    </LinearLayout>
    </RelativeLayout>
    <include layout="@layout/toolbar_layout" />
</FrameLayout>

Update:
If I define the hight of ViewPager the problem will be resolved , but when screen size changes lower part of the screen will be blank

A: I searched a lot and finally came up with a solution, first I changed RelativeLayout to LinearLayout and added android:orientation="vertical" to it,  then added android:layout_weight="1" to ViewPager.
Final version
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ProgressBar
        android:id="@+id/progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >
        <android.support.v4.view.ViewPager
            android:id="@+id/awesomepager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:background="#068006"
            android:layout_below="@+id/awesomepager"
            >

            <android.support.v7.widget.RecyclerView
                android:id="@+id/episodesLIST"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:scrollbars="horizontal" />
        </LinearLayout>

    </LinearLayout>

    <include layout="@layout/toolbar_layout" />

</FrameLayout>


text:
Q: How to select a value from a Dropdown in Protractor I want to select a value from a dropbox. The contents from dropbox do not have values or ID, instead, they have a title. This is the HTML for one of the contents and for the dropdown. The id below is from dropbox. With this information, I am just able to select the dropbox, not the values.
Select reason
<span class="select2-selection__rendered" id="select2-e5dt-container" role="textbox" title="01 - <Change of mind, back to stock>">01 - Change of mind, back to stock
<span class="select2-selection__rendered" id="select2-e5dt-container" role="textbox" title="04 - <Production Fault, to recovery>">04 - Production Fault, to recovery````

A: To solve this problem statement all you need to do is:

*

*Find the dropdown using element

*Click the dropdown

*Click the option

it("should select the dropdown." async () => {
    await $("span.select2-selection__placeholder").click();
    //add sleep to give a time for the options to reveal or use an explicit wait
    //here. I prefer the latter.
    await browser.sleep(1000)
    // click the option '01 - Change of mind, back to stock'
    await $$("span#select2-e5dt-container"").get(0).click();
});

Lemme know how it works out for you!

A: *

*Identify Drop Down and click on it

*Wait for DropDown options to be displayed (use ExpectedConditions.visibilityOf())
var EC = protractor.ExpectedConditions;
var filteroption = "Production Fault, to recovery";
this.DDOptions = element.all(by.css('[role="textbox"]'));

//Click on the Drop Down
// Wait for Drop Down options to be visible
browser.wait(EC.visibilityOf(this.DDOptions.get(0), 500, "DD option not visible timing out"));
this.DDOptions.filter(function (elem, index) {
    return elem.getText().then(function (text) {
      return text.toUpperCase() === filteroption.toUpperCase();
    });
  }).then(function (filteredElements) {
      filteredElements[0].click();
  });


text:
Q: Linux SoftLink to applications and execution I have created a softlink to an application using the following command:
ln -s sourcedir/Application somedir/ApplicationSoftLink

But I do not know how to start the application using the softlink. My understanding of a softlink is that it is the same as a shortcut in Windows, you just double-click the shortcut and the application will launch. However, when I tried to ./ApplicationSoftLink the application would not start.
Could someone please provide some assistance?

A: ln -s sourcedir/Application somedir/ApplicationSoftLink probably puts the wrong path in your symbolic link.
Try:
ln -s $PWD/sourcedir/Application somedir/ApplicationSoftLink

A: Were you in somedir when you tried running ./ApplicationSoftLink?
I think what you want to do is create the link in some directory in your path, so you don't have to say where the file is at all.  You can type
echo $PATH

to find out what's in your path.  /usr/local/bin is a good choice for things like this.

A: is sourcedir/Application executable?

when I tried to "./ApplicationSoftLink" the application would not
  start.

Is there any error message?
were you typing ./ApplicationSoftLink under "somedir"?
or try ln -s /absolute/path/sourcedir /absolute/path/you/want/somedir/myApp
then under somedir/myApp/  run ./Application


text:
Q: Why didn't Quria, Blade Transform, decide to introduce a Hive worm into its mind fluid? An excerpt from the Books of Sorrow, Verse 4:9 "open your eye : go into it":

Quria captured some worm larvae and began experimenting with them. Soon Quria, Blade Transform manifested religious tactics. By directing worship at the worms, Quria learned it could alter reality with mild ontopathogenic effects. Being an efficient machine, Quria manufactured a priesthood and ordered all its subminds to believe in worship. Then it set about abducting and killing dangerous organisms so it could bootstrap itself to Hive godhood. For some Vex reason, Quria never attempted to introduce worm larvae into its mind fluid.

Why would Quria not decide to combine the two? Its ability to quickly deduce the Sword Logic is a testament to its processing power and logical processes, so what was the reason for this decision? Was it concerned regarding the possibility of being overtaken by the Darkness associated with the worms, or was it something else?

A: Maybe it's because it didn't want to be inflicted with the same curse that the hive has, which is to endlessly feed their worms or be eaten by them.


text:
Q: rfft or irfft increasing wav file volume in python I have just started writing a program to manipulate some audio in python. Before I write any filtering functions, I wanted to do a test to compare the input signal to the output signal after having the input signal go through an rfft and irfft. For some reason the output file has an incredible amount of gain in it (50db!) compared to the input file, and I can't figure out why this is happening.
Here is the code:
from scipy.io.wavfile import read, write
from scipy.fftpack import rfft, irfft
import numpy as np

rate, input = read('5and10ksm.wav')
transformed = rfft(input)
output = irfft(transformed)
write('smaller.wav', rate, output)

Thanks!

A: scipy.fftpack.irfft returns an array of floats. Convert it to the dtype of your input file before writing it as wav file: output.astype(input.dtype).


text:
Q: Undefined method in model, but other method works I have a controller call a model for a user password reset flow. It calls two methods:
controller
Password.new(@user)
  .save_token_and_expiry
  .email_reset

model
module ModuleName
  class Password

    attr_accessor :token, :user

    def initialize(user)
      @token = SecureRandom.urlsafe_base64(ModuleName.configuration.reset_token_length, false)
      @user = user
    end

    def save_token_and_expiry
      User.find_by_email(@user['email'])
        .update_attributes(password_reset_token: @token, password_token_expiry: ModuleName.configuration.password_token_expiry)
    end

    def email_reset
      PasswordResetMailer.password_reset(@user, @token).deliver_now
    end
  end
end

output
NoMethodError (undefined method `email_reset' for true:TrueClass):

The first of which successfully executes, but it fails on the second.
Why is the second method returning an error?

A: Your save_token_and_expiry method returns true, on which you try to call email_reset method, which obviously fails. If you want to allow chaining like this, you can make save_token_and_expiry method return Password instance which it was called on:
def save_token_and_expiry
  User.find_by_email(@user['email'])
      .update_attributes(password_reset_token: @token, password_token_expiry: ModuleName.configuration.password_token_expiry)
  self
end

A: Rails is not so friendly for chaining calls. save_token_and_expiry returns you the result of last called action in it (update_attributes) and update_attributes doesn't return you the target it was called on, but just plain true/false. That's why you have such error. If you want to fix it you can rewrite your save_token_and_expiry method as:
def save_token_and_expiry
  User.find_by_email(@user['email']).update_attributes(password_reset_token: @token, password_token_expiry: ModuleName.configuration.password_token_expiry)
  self
end

A: You can change controller code:
@data = Password.new(@user)
@data.save_token_and_expiry
@data.email_reset


text:
Q: Edit text in C# console application? Is there a way to edit text in a C# console application? In other words, is it possible to place pre-defined text on the command line so that the user can modify the text and then re-submit it to the app?

A: Yes. You need to use method SetCursorPosition of Console. Example:
    Console.WriteLine("hello");
    Console.SetCursorPosition(4, 0);
    Console.WriteLine("      ");

It will display 'hell'
You need custom realization of ReadLine method which let you to edit n-symbols (default string) in Console and return string from a user. This is my example:
static string ReadLine(string Default)
{
    int pos = Console.CursorLeft;
    Console.Write(Default);
    ConsoleKeyInfo info;
    List<char> chars = new List<char> ();
    if (string.IsNullOrEmpty(Default) == false) {
        chars.AddRange(Default.ToCharArray());
    }

    while (true)
    {
        info = Console.ReadKey(true);
        if (info.Key == ConsoleKey.Backspace && Console.CursorLeft > pos)
        {
            chars.RemoveAt(chars.Count - 1);
            Console.CursorLeft -= 1;
            Console.Write(' ');
            Console.CursorLeft -= 1;

        }
        else if (info.Key == ConsoleKey.Enter) { Console.Write(Environment.NewLine); break; }
        //Here you need create own checking of symbols
        else if (char.IsLetterOrDigit(info.KeyChar))
        {
            Console.Write(info.KeyChar);
            chars.Add(info.KeyChar);
        }
    }
    return new string(chars.ToArray ());
}

This method will display string Default. Hope I understood your problem right (I doubt in it)

A: One thing that came to my mind is to...simulate keystrokes.
And a simple example using SendKeys:
static void Main(string[] args)
{
    Console.Write("Your editable text:");
    SendKeys.SendWait("hello"); //hello text will be editable :)
    Console.ReadLine();
}

NOTE: This works only on active window.


text:
Q: When we push on a wall, can we say work is being done on the atomic particles in contact with our hand? Since textbooks say work is act transfer of energy, it led me to think of the following assumption:
Work is being done on the the atoms in the wall, in contact with the hands, when we push (hard) on the wall.
When we push the wall, energy is being transferred as heat energy (due to friction between hand and wall) which increases the kinetic energy of the atomic particles on the wall, thus increasing the temperature of the area in contact.
I would appreciate if anyone could help me know whether I'm wrong in my assumption and why so.

A: Friction is a red herring here. You can do work on an object by pushing on it, even if there is no friction.
When you push on a spring, you do work by compressing the spring. The spring deforms (shortens) and the work that you do to deform the spring is stored as potential energy in the spring. The spring pushes back on you with a force that is proportional to its deformation (Hooke's law) and eventually this force equals the force with which you are pushing on the spring, and the spring stops deforming.
When you push on a fixed solid object such as a wall then you do work by compressing the bonds between the atoms and molecules in the wall. These bonds act like tiny springs and store potential energy. The deformation of the wall is very small, but it is real, and it is this deformation that leads to the wall "pushing back" on you.
Of course, if you push too hard and deform the interatomic bonds too much then something breaks !

A:
Work is being done on the the atoms in the wall, in contact with the
  hands, when we push (hard) on the wall.

At the macroscopic level the wall is considered a rigid body, and since the wall as a whole is not displaced, no work is done.
On the microscopic level you are doing work pushing on the wall by displacing layers of atoms in the wall (but mostly displaces the atoms of your hand). This in effect is stored as strain energy which, after you remove the force, is responsible for moving the atoms back to their original configuration.

When we push the wall, energy is being transferred as heat energy (due
  to friction between hand and wall) which increases the kinetic energy
  of the atomic particles on the wall, thus increasing the temperature
  of the area in contact.

Heat is energy transfer due solely to temperature difference. Any energy transfer by heat to the wall would be due to the temperature of our hand being greater than the wall.
An increase in temperature due to friction is actually energy transfer by friction work, not by heat. If you rub your hands together on a cold day to keep warm, you are doing friction work. It is the friction work that increases the temperature of your hands skin. In any event, simply pushing on a wall does not involve kinetic friction unless you rub your hands against the wall.

In any event, simply pushing on a wall does ..... the wall." Had I
  assumed that there is some frictional force between the hand and wall,
  which leads to increase in temperature of wall compared to initial
  condition, would it then be heat (transfer of thermal energy) or work
  done by friction (increase in the mechanical energy of the atoms in
  the wall in contact) or both?

It would be work transfer, not heat transfer. Consider compressing a gas. When you compress a gas its temperature rises. The temperature rise is not due to heat (energy transfer due to temperature difference) but due to work (force times displacement).
Now once the friction work increases the temperature of the surface of the wall (as well as your hand), it can be followed by heat transfer from the surface of the wall to the interior of the wall because the wall surface temperature is  higher than the interior temperature.

That leads me to another question : doesn't heat increases the
  mechanical energy(KE+PE) of the atoms/molecules too? Which would mean
  that heat is also a type work. Please correct me where I am wrong?

Yes, heat transfer can increase the KE and PE of the atoms/molecules of a substance (though we primarily consider it with respect to KE unless a material undergoes a phase change). But the mechanism is not the same as work. The mechanism is energy transfer due solely to temperature difference. Work is not energy transfer due to temperature difference. It is due to force times displacement.
That said, heat transfer can result in work and work transfer can result in heat.
If I expose a gas in a cylinder fitted with a piston to a body at a higher temperature than the gas, there will be heat transfer from that body to the gas increasing its temperature. The increase in temperature of the gas causes it to expand against the piston resulting in the gas doing work on its surroundings.
Likewise, if I compress the gas the work I do transfers energy to the gas increasing its temperature. Then you can have energy transfer from the gas to lower temperature surroundings by means of heat.
Hope this helps.


text:
Q: Failure when using setattr to add field to Django form class I'm trying to write use Django FormView and a bit of ingenuity to create a view which will allow me to get inputs from a user that will be fed to a function.  I'd like the code to be reusable, so I'd like to make a view that will be able to take a target function as a parameter and automagically create a form appropriate to that function.  There is more plumbing to be done, but the general idea would be:
class FormViewForFunction(FormView):
    template_name = '...'
    func = None

    def get_form_class(self):
        class _FunctionForm(forms.Form):
            pass

        a = inspect.getargspec(self.func)
        for argname in a['args']:
            setattr(_FunctionForm, argname, forms.CharField())
        return _FunctionForm

The idea would be that then you could set up something in your URLConf that used FormViewForFunction.as_view(func=***insert any function you want***) and you would wind up being presented with a form that was appropriate for specifying parameters for that function.  Let's not worry about what would happen on form submission.  For now I'm just stuck getting the form to generate properly.
With the code above, the form doesn't wind up having any fields!  What am I doing wrong?

A: form's fields are initialized during initialization, you should override the __init__ method and then append the fields to the self.fields dictionary

A: This should work:
class FormViewForFunction(FormView):
   template_name = '...'
   func = None

   def get_form_class(self):
       a = inspect.getargspec(self.func)
       class _FunctionForm(forms.Form):
           def __init__(self, *args, **kwargs):
               super(_FunctionForm, self).__init__(*args, **kwargs)
               for argname in a['args']:
                   self.fields[argname] = forms.CharField()
       return _FunctionForm


text:
Q: How to pass value of a select List to script? i have a problem with my code. I need to pass value from my pick list to a script. My app doesn't see value of that pick list. Have any solutions?

<apex:form >
<apex:outputLabel value="Type" />

<apex:selectList id="Lista" value ="{!type1}" size="1">
    <apex:selectOptions value="{!Types}"/>
</apex:selectList>

<apex:outputLabel value="First/Last Name" />

<apex:inputText value="{!searchText}" id="searchText"></apex:inputText>
<apex:commandButton value="change" onClick="change()"/>
</apex:form>

A: You can directly access apex variable in Javascript. This will work for you.

If you want the select value then you can do something like
<apex:selectList styleclass="Lista" value ="{!type1}" size="1">
    <apex:selectOptions value="{!Types}"/>
</apex:selectList>

var e = document.getElementsByClassName("Lista")[0];
var strUser = e.options[e.selectedIndex].value;

We are using class Name because in VF ID is generate dynamically so either you need to use dynamic Id selector or simply use the class Name.
Note: you can also use apex:repeat to iterate list in Javascript.


text:
Q: Search & Match in a text ignoring spaces I've indexed the text of PDF's files on my database, but sometimes the text is not clean and we have spaces between words:
var text = 'C or P ora te go V ernan C e report M ANA g EMENT bO A r D AND s u PE r V is O r y bO A r D C OMM i TTEE s The Management Board has not currently established any committees.';

I want make a front-end search engine for my users, but I need to know the START and END position of each search (Based on the original text, with spaces).
I can do that with a regex, for example if I do:
text.toLowerCase().search(/m ? a ? n ? a ? g ? e ? m ? e ? n ? t/);

I find the word "Management" on start position letter 36. Now, I want know the "End position" of the word (Because I don't know how much spaces are on the word, so I don't know how much letters), and I want the search to be multi-matches (To give me the start/end position of multiple results).
Can you help me with that? Again, it's very important for me to have the start/end position of each words based on the original text, removing spaces then search is not a good solution for me.
I'm also curious to know if I can do that without a regex.
Thank you!

A: This demo might help:
> text.toLowerCase().match(/m *a *n *a *g *e *m *e *n *t/)
[ 'm ana g ement',
  index: 36,
  input: 'c or p ora te go v ernan c e report m ana g ement bo a r d and s u pe r v is o r y bo a r d c omm i ttee s the management board has not currently established any committees.' ]

(I modified your regex to use ' *' between each letter, to match any number of spaces including 0. Your ' ? ' example would only match exactly 1 or 2 spaces between each letter.)
Using the .match method returns returns the captured expression and index (as seen above) if the regex is matched, otherwise null. You should be able to use this to do something along these lines:
const matches = text.toLowerCase().match(/m *a *n *a *g *e *m *e *n *t/);
if (matches) {
    const start = matches.index;
    const end = matches.index + matches[0].length - 1;
}