Programs & Examples On #Mac app store

For issues relating to deploying and maintaining an application in the Mac App Store.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

How to add hamburger menu in bootstrap

CSS only (no icon sets) Codepen

_x000D_
_x000D_
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
   <!-- <a class="navbar-brand" href="#">_x000D_
      <img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
      Bootstrap_x000D_
      </a> -->_x000D_
   <!-- https://stackoverflow.com/questions/26317679 -->_x000D_
   <a class="nav-link" href="#">_x000D_
      <div id="navBars">_x000D_
         <input type="checkbox" /><span></span>_x000D_
         <span></span>_x000D_
         <span></span>_x000D_
      </div>_x000D_
   </a>_x000D_
   <!-- /26317679 -->_x000D_
   <div class="collapse navbar-collapse" id="navbarNav">_x000D_
      <ul class="navbar-nav">_x000D_
         <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
         <li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
      </ul>_x000D_
   </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How can I set a dynamic model name in AngularJS?

To make the answer provided by @abourget more complete, the value of scopeValue[field] in the following line of code could be undefined. This would result in an error when setting subfield:

<textarea ng-model="scopeValue[field][subfield]"></textarea>

One way of solving this problem is by adding an attribute ng-focus="nullSafe(field)", so your code would look like the below:

<textarea ng-focus="nullSafe(field)" ng-model="scopeValue[field][subfield]"></textarea>

Then you define nullSafe( field ) in a controller like the below:

$scope.nullSafe = function ( field ) {
  if ( !$scope.scopeValue[field] ) {
    $scope.scopeValue[field] = {};
  }
};

This would guarantee that scopeValue[field] is not undefined before setting any value to scopeValue[field][subfield].

Note: You can't use ng-change="nullSafe(field)" to achieve the same result because ng-change happens after the ng-model has been changed, which would throw an error if scopeValue[field] is undefined.

Ruby value of a hash key?

I didn't understand your problem clearly but I think this is what you're looking for(Based on my understanding)

  person =   {"name"=>"BillGates", "company_name"=>"Microsoft", "position"=>"Chairman"}

  person.delete_if {|key, value| key == "name"} #doing something if the key == "something"

  Output: {"company_name"=>"Microsoft", "position"=>"Chairman"}

How to disable/enable select field using jQuery?

To be able to disable/enable selects first of all your selects need an ID or class. Then you could do something like this:

Disable:

$('#id').attr('disabled', 'disabled');

Enable:

$('#id').removeAttr('disabled');

Creating a batch file, for simple javac and java command execution

  1. open notepad

  2. write

    @echo off
    
    javac Main.java
    
    java Main
    

3.saveAs blahblah.bat

make sure that Main.java resides with your batch file and java path is set in env. variable

4 . double click on batch file, no need to open cmd explicitly tt will open itself on .bat execution

ASP.NET MVC - Getting QueryString values

Actually you can capture Query strings in MVC in two ways.....

public ActionResult CrazyMVC(string knownQuerystring)
{

  // This is the known query string captured by the Controller Action Method parameter above
  string myKnownQuerystring = knownQuerystring;

  // This is what I call the mysterious "unknown" query string
  // It is not known because the Controller isn't capturing it
  string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];

  return Content(myKnownQuerystring + " - " + myUnknownQuerystring);

}

This would capture both query strings...for example:

/CrazyMVC?knownQuerystring=123&unknownQuerystring=456

Output: 123 - 456

Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?

Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.

How to initialize an array in one step using Ruby?

To create such an array you could do:

array = ['1', '2', '3']

Dynamically update values of a chartjs chart

This is an example with ChartJs - 2.9.4

_x000D_
_x000D_
var maximumPoints = 5;// with this variable you can decide how many points are display on the chart
        function addData(chart, label, data) {
            chart.data.labels.push(label);
            chart.data.datasets.forEach((dataset) => {
                var d = data[0];
                dataset.data.push(d);
                data.shift();
            });


            var canRemoveData = false;
            chart.data.datasets.forEach((dataset) => {
                if (dataset.data.length > maximumPoints) {

                    if (!canRemoveData) {
                        canRemoveData = true;
                        chart.data.labels.shift();
                    }

                    dataset.data.shift();

                }

            });



            chart.update();
        }




        window.onload = function () {
            var canvas = document.getElementById('elm-chart'),
                ctx = canvas.getContext('2d');

            var myLineChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [
                        {
                            data: [],
                            label: 'Dataset-1',
                            backgroundColor: "#36a2eb88",
                            borderColor: "#36a2eb",
                        },
                        {
                            data: [],
                            label: 'Dataset-2',
                            backgroundColor: "#ff638488",
                            borderColor: "#ff6384",
                        }
                    ],

                },
                options: {
                    responsive: false,
                    maintainAspectRatio: false,
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });

            var index = 0;
            setInterval(function () {

                var data = [];
                myLineChart.data.datasets.forEach((dataset) => {
                    data.push(Math.random() * 100);
                });

                addData(myLineChart, index, data);
                index++;

            }, 1000);
        }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="elm-chart" width="640" height="480"></canvas>
_x000D_
_x000D_
_x000D_

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

HTTP Status 405 - Method Not Allowed Error for Rest API

I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure

So check for your server how it works and enable CORS. I didn't even need a browser plugin or proxy :)

Check if null Boolean is true results in exception

Boolean types can be null. You need to do a null check as you have set it to null.

if (bool != null && bool)
{
  //DoSomething
}                   

Read CSV file column by column

Reading a CSV file in very simple and common in Java. You actually don't require to load any extra third party library to do this for you. CSV (comma separated value) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g comma ",").

In order to read specific columns from the CSV file, there are several ways. Simplest of all is as below:

Code to read CSV without any 3rd party library

BufferedReader br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
    // use comma as separator
    String[] cols = line.split(cvsSplitBy);
    System.out.println("Coulmn 4= " + cols[4] + " , Column 5=" + cols[5]);
}

If you notice, nothing special is performed here. It is just reading a text file, and spitting it by a separator – ",".

Consider an extract from legacy country CSV data at GeoLite Free Downloadable Databases

"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"

Above code will output as below:

Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "TH" , Column 5="Thailand"

You can, in fact, put the columns in a Map and then get the values simply by using the key.

Shishir

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I was having the same issue implementing in Angular 9. These are the two steps I did:

  1. Change your YouTube URL from https://youtube.com/your_code to https://youtube.com/embed/your_code.

  2. And then pass the URL through DomSanitizer of Angular.

    import { Component, OnInit } from "@angular/core";
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Component({
      selector: "app-help",
      templateUrl: "./help.component.html",
      styleUrls: ["./help.component.scss"],
    })
    export class HelpComponent implements OnInit {
    
      youtubeVideoLink: any = 'https://youtube.com/embed/your_code'
    
      constructor(public sanitizer: DomSanitizer) {
        this.sanitizer = sanitizer;   
      }
    
      ngOnInit(): void {}
    
      getLink(){
        return this.sanitizer.bypassSecurityTrustResourceUrl(this.youtubeVideoLink);
      }
    
    }
    
    <iframe width="420" height="315" [src]="getLink()" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
    

Python conversion between coordinates

The existing answers can be simplified:

from numpy import exp, abs, angle

def polar2z(r,theta):
    return r * exp( 1j * theta )

def z2polar(z):
    return ( abs(z), angle(z) )

Or even:

polar2z = lambda r,?: r * exp( 1j * ? )
z2polar = lambda z: ( abs(z), angle(z) )

Note these also work on arrays!

rS, thetaS = z2polar( [z1,z2,z3] )
zS = polar2z( rS, thetaS )

Auto number column in SharePoint list

I had this issue with a custom list and while it's not possible to use the auto-generated ID column to create a calculated column, it is possible to use a workflow to do the heavy lifting.

I created a new workflow variable of type Number and set it to be the value of the ID column in the current item. Then it's simply a matter of calculating the custom column value and setting it - in my case I just needed the numbering to begin at 100,000.

enter image description here

How to return rows from left table not found in right table?

I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.

SELECT Column1
FROM TableA a
WHERE NOT EXISTS ( SELECT Column1
                   FROM Tableb b
                   WHERE a.Column1 = b.Column1
                 )

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

That worked for me,

Right Click on project -> "Run as Maven Test". This will automatically download the missing plugins and than Right Click on project ->"Update Maven project" it removes the error.

Splitting dataframe into multiple dataframes

Easy:

[v for k, v in df.groupby('name')]

C++ Calling a function from another class

    void CallFunction ()
    {   // <----- At this point the compiler knows
        //        nothing about the members of B.
        B b;
        b.bFunction();
    }

This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.

To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.

class A
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    { ... }
};

void A::CallFunction ()
{
    B b;
    b.bFunction();
}

Check that an email address is valid on iOS

Good cocoa function:

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
   BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
   NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
   NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
   return [emailTest evaluateWithObject:checkString];
}

Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/

And because categories are just better, you could also add an interface:

@interface NSString (emailValidation) 
  - (BOOL)isValidEmail;
@end

Implement

@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
  BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
  NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
  NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
  NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:self];
}
@end

And then utilize:

if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }

Android - get children inside a View?

I'm just going to provide this answer as an alternative @IHeartAndroid's recursive algorithm for discovering all child Views in a view hierarchy. Note that at the time of this writing, the recursive solution is flawed in that it will contains duplicates in its result.

For those who have trouble wrapping their head around recursion, here's a non-recursive alternative. You get bonus points for realizing this is also a breadth-first search alternative to the depth-first approach of the recursive solution.

private List<View> getAllChildrenBFS(View v) {
    List<View> visited = new ArrayList<View>();
    List<View> unvisited = new ArrayList<View>();
    unvisited.add(v);

    while (!unvisited.isEmpty()) {
        View child = unvisited.remove(0);
        visited.add(child);
        if (!(child instanceof ViewGroup)) continue;
        ViewGroup group = (ViewGroup) child;
        final int childCount = group.getChildCount();
        for (int i=0; i<childCount; i++) unvisited.add(group.getChildAt(i));
    }

    return visited;
}

A couple of quick tests (nothing formal) suggest this alternative is also faster, although that has most likely to do with the number of new ArrayList instances the other answer creates. Also, results may vary based on how vertical/horizontal the view hierarchy is.

Cross-posted from: Android | Get all children elements of a ViewGroup

macOS on VMware doesn't recognize iOS device

I met the same problem. I found the solution in the solution from kb.vmware.com.
It works for me by adding

usb.quirks.device0 = "0xvid:0xpid skip-refresh"

Detail as below:


To add quirks:
  1. Shut down the virtual machine and quit Workstation/Fusion.

    Caution: Do not skip this step.
     
  2. Open the vmware.log file within the virtual machine bundle. For more information, see Locating a virtual machine bundle in VMware Workstation/Fusion (1007599).
  3. In the Filter box at the top of the Console window, enter the name of the device manufacturer.

    For example, if you enter the name Apple, you see a line that looks similar to:

    vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:8240 path:13/7/2 speed:full family:hid]



    The line has the name of the USB device and its vid and pid information. Make a note of the vid and pid values.
     

  4. Open the .vmx file using a text editor. For more information, see Editing the .vmx file for your Workstation/Fusion virtual machine (1014782).
  5. Add this line to the .vmx file, replacing vid and pid with the values noted in Step 2, each prefixed by the number 0 and the letter x .

    usb.quirks.device0 = "0xvid:0xpid skip-reset"

    For example, for the Apple device found in step 2, this line is:

    usb.quirks.device0 = "0x05ac:0x8240 skip-reset"
     

  6. Save the .vmx file.
  7. Re-open Workstation/Fusion. The edited .vmx file is reloaded with the changes.
  8. Start the virtual machine, and connect the device.
  9. If the issue is not resolved, replace the quirks line added in Step 4 with one of these lines, in the order provided, and repeat Steps 5 to 8:
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
usb.quirks.device0 = "0xvid:0xpid skip-setconfig"
usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"

Notes:

  • Use one of these lines at a time. If one does not work, replace it with another one in the list. Do not add more than one of these in the .vmx file at a time.
  • The last line uses all three quirks in combination. Use this only if the other three lines do not work.

Refer this to see in detail.

How to do something before on submit?

You can use onclick to run some JavaScript or jQuery code before submitting the form like this:

<script type="text/javascript">
    beforeSubmit = function(){
        if (1 == 1){
            //your before submit logic
        }        
        $("#formid").submit();            
    }
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />

Could not load file or assembly Exception from HRESULT: 0x80131040

What worked for me immediately was:

  • I located bin folder (picture below shows).

  • moved all dll in other folder for safety.

  • then rebuild ed the project.

  • after solved the issue, deleted old dll files.

Open file location

Python3 project remove __pycache__ folders and .pyc files

Please just go to your terminal then type:

$rm __pycache__

and it will be removed.

C# - Simplest way to remove first occurrence of a substring from another string

string myString = sourceString.Remove(sourceString.IndexOf(removeString),removeString.Length);

EDIT: @OregonGhost is right. I myself would break the script up with conditionals to check for such an occurence, but I was operating under the assumption that the strings were given to belong to each other by some requirement. It is possible that business-required exception handling rules are expected to catch this possibility. I myself would use a couple of extra lines to perform conditional checks and also to make it a little more readable for junior developers who may not take the time to read it thoroughly enough.

Specify a Root Path of your HTML directory for script links?

You can use ResolveUrl

<link type="text/css" rel="stylesheet" href="<%=Page.ResolveUrl("~/Content/table-sorter.css")%>" />

Find document with array that contains a specific value

Incase of lookup_food_array is array.

match_stage["favoriteFoods"] = {'$elemMatch': {'$in': lookup_food_array}}

Incase of lookup_food_array is string.

match_stage["favoriteFoods"] = {'$elemMatch': lookup_food_string}

You seem to not be depending on "@angular/core". This is an error

Faced the same Issue. While running ngserve you should be in the apps directory. To confirm(on GIT BASH : you will have (master) after the directory path at gitbash prompt, if you are at app directory.)

How to invoke bash, run commands inside the new shell, and then give control back to user?

With accordance with the answer by daveraja, here is a bash script which will solve the purpose.

Consider a situation if you are using C-shell and you want to execute a command without leaving the C-shell context/window as follows,

Command to be executed: Search exact word 'Testing' in current directory recursively only in *.h, *.c files

grep -nrs --color -w --include="*.{h,c}" Testing ./

Solution 1: Enter into bash from C-shell and execute the command

bash
grep -nrs --color -w --include="*.{h,c}" Testing ./
exit

Solution 2: Write the intended command into a text file and execute it using bash

echo 'grep -nrs --color -w --include="*.{h,c}" Testing ./' > tmp_file.txt
bash tmp_file.txt

Solution 3: Run command on the same line using bash

bash -c 'grep -nrs --color -w --include="*.{h,c}" Testing ./'

Solution 4: Create a sciprt (one-time) and use it for all future commands

alias ebash './execute_command_on_bash.sh'
ebash grep -nrs --color -w --include="*.{h,c}" Testing ./

The script is as follows,

#!/bin/bash
# =========================================================================
# References:
# https://stackoverflow.com/a/13343457/5409274
# https://stackoverflow.com/a/26733366/5409274
# https://stackoverflow.com/a/2853811/5409274
# https://stackoverflow.com/a/2853811/5409274
# https://www.linuxquestions.org/questions/other-%2Anix-55/how-can-i-run-a-command-on-another-shell-without-changing-the-current-shell-794580/
# https://www.tldp.org/LDP/abs/html/internalvariables.html
# https://stackoverflow.com/a/4277753/5409274
# =========================================================================

# Enable following line to see the script commands
# getting printing along with their execution. This will help for debugging.
#set -o verbose

E_BADARGS=85

if [ ! -n "$1" ]
then
  echo "Usage: `basename $0` grep -nrs --color -w --include=\"*.{h,c}\" Testing ."
  echo "Usage: `basename $0` find . -name \"*.txt\""
  exit $E_BADARGS
fi  

# Create a temporary file
TMPFILE=$(mktemp)

# Add stuff to the temporary file
#echo "echo Hello World...." >> $TMPFILE

#initialize the variable that will contain the whole argument string
argList=""
#iterate on each argument
for arg in "$@"
do
  #if an argument contains a white space, enclose it in double quotes and append to the list
  #otherwise simply append the argument to the list
  if echo $arg | grep -q " "; then
   argList="$argList \"$arg\""
  else
   argList="$argList $arg"
  fi
done

#remove a possible trailing space at the beginning of the list
argList=$(echo $argList | sed 's/^ *//')

# Echoing the command to be executed to tmp file
echo "$argList" >> $TMPFILE

# Note: This should be your last command
# Important last command which deletes the tmp file
last_command="rm -f $TMPFILE"
echo "$last_command" >> $TMPFILE

#echo "---------------------------------------------"
#echo "TMPFILE is $TMPFILE as follows"
#cat $TMPFILE
#echo "---------------------------------------------"

check_for_last_line=$(tail -n 1 $TMPFILE | grep -o "$last_command")
#echo $check_for_last_line

#if tail -n 1 $TMPFILE | grep -o "$last_command"
if [ "$check_for_last_line" == "$last_command" ]
then
  #echo "Okay..."
  bash $TMPFILE
  exit 0
else
  echo "Something is wrong"
  echo "Last command in your tmp file should be removing itself"
  echo "Aborting the process"
  exit 1
fi

Specify sudo password for Ansible

You can pass variable on the command line via --extra-vars "name=value". Sudo password variable is ansible_sudo_pass. So your command would look like:

ansible-playbook playbook.yml -i inventory.ini --user=username \
                              --extra-vars "ansible_sudo_pass=yourPassword"

Update 2017: Ansible 2.2.1.0 now uses var ansible_become_pass. Either seems to work.

Parse RSS with jQuery

jQuery Feeds is a nice option, it has a built-in templating system and uses the Google Feed API, so it has cross-domain support.

How do I create a batch file timer to execute / call another batch throughout the day

I did it by writing a little C# app that just wakes up to launch periodic tasks -- don't know if it is doable from a batch file without downloading extensions to support a sleep command. (For my purposes the Windows scheduler didn't work because the apps launched had no graphics context available.)

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

Stretch background image css?

CSS3: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm

.style1 {
  ...
  background-size: 100%;
}

You can specify just width or height with:

background-size: 100% 50%;

Which will stretch it 100% of the width and 50% of the height.


Browser support: http://caniuse.com/#feat=background-img-opts

How to insert element into arrays at specific position?

array_slice() can be used to extract parts of the array, and the union array operator (+) can recombine the parts.

$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

This example:

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

gives:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)

How to use Google App Engine with my own naked domain (not subdomain)?

[Update April 2016] This answer is now outdated, custom naked domain mapping is supported, see Lawrence Mok's answer.

I have figured it out!

First off: it is impossible to link something like mydomain.com with your appspot app. This is considered a naked domain, which is not supported by Google App Engine (anymore). Strictly speaking, the answer to my question has to be "impossible". Read on...

All you can do is add subdomains pointing to your app, e.g myappid.mydomain.com. The key to get your top level domain linked to your app is to realize that www is a subdomain like any other!

myappid.mydomain.com is treated exactly the same as www.mydomain.com!

Here are the steps:

  1. Go to appengine.google.com, open your app
  2. Administration > Versions > Add Domain... (your domain has to be linked to your Google Apps account, follow the steps to do that including the domain verification.)
  3. Go to www.google.com/a/yourdomain.com
  4. Dashboard > your app should be listed here. Click on it.
  5. myappid settings page > Web address > Add new URL
  6. Simply enter www and click Add
  7. Using your domain hosting provider's web interface, add a CNAME for www for your domain and point to ghs.googlehosted.com

Now you have www.mydomain.com linked to your app.

I wished this would have been more obvious in the documentation...Good luck!

How to setup FTP on xampp

XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.

Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :

  1. Open a new Linux terminal and ensure you are logged in as root.

  2. Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.

groupadd ftp

  1. Add your account (in this example, susan) to the new group. Add other users if needed.

usermod -a -G ftp susan

  1. Change the ownership and permissions of the htdocs/ subdirectory of the XAMPP installation directory (typically, /opt/lampp) so that it is writable by the the new ftp group.

cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs

  1. Ensure that proFTPD is running in the XAMPP control panel.

You can now transfer files to the XAMPP server using the steps below:

  1. Start an FTP client like winSCP or FileZilla and enter connection details as below.

If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.

Use "21" as the port.

Enter your Linux username and password as your FTP credentials.

Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.

  1. Transfer the file from your home directory to the server using normal FTP transfer conventions. If you’re using a graphical FTP client, you can usually drag and drop the file from one directory to the other. If you’re using a command-line FTP client, you can use the FTP PUT command.

Once the file is successfully transferred, you should be able to see it in action.

Creating a copy of an object in C#

There's already a question about this, you could perhaps read it

Deep cloning objects

There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.

class A
{
  private int attr

  public int Attr
  {
     get { return attr; }
     set { attr = value }
  }

  public A()
  {
  }

  public A(A p)
  {
     this.attr = p.Attr;
  }  
}

This would be an example, copying the member 'Attr' when building the new object.

Change icon on click (toggle)

Here is a very easy way of doing that

 $(function () {
    $(".glyphicon").unbind('click');
    $(".glyphicon").click(function (e) {
        $(this).toggleClass("glyphicon glyphicon-chevron-up glyphicon glyphicon-chevron-down");
});

Hope this helps :D

How to copy a dictionary and only edit the copy

While dict.copy() and dict(dict1) generates a copy, they are only shallow copies. If you want a deep copy, copy.deepcopy(dict1) is required. An example:

>>> source = {'a': 1, 'b': {'m': 4, 'n': 5, 'o': 6}, 'c': 3}
>>> copy1 = x.copy()
>>> copy2 = dict(x)
>>> import copy
>>> copy3 = copy.deepcopy(x)
>>> source['a'] = 10  # a change to first-level properties won't affect copies
>>> source
{'a': 10, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy1
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy2
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy3
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> source['b']['m'] = 40  # a change to deep properties WILL affect shallow copies 'b.m' property
>>> source
{'a': 10, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy1
{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy2
{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy3  # Deep copy's 'b.m' property is unaffected
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}

Regarding shallow vs deep copies, from the Python copy module docs:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Java List.contains(Object with field value equal to x)

If you need to perform this List.contains(Object with field value equal to x) repeatedly, a simple and efficient workaround would be:

List<field obj type> fieldOfInterestValues = new ArrayList<field obj type>;
for(Object obj : List) {
    fieldOfInterestValues.add(obj.getFieldOfInterest());
}

Then the List.contains(Object with field value equal to x) would be have the same result as fieldOfInterestValues.contains(x);

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

import numpy as np

mean_data = np.array([
[6.0, 315.0, 4.8123788544375692e-06],
[6.5, 0.0, 2.259217450023793e-06],
[6.5, 45.0, 9.2823565008402673e-06],
[6.5, 90.0, 8.309270169336028e-06],
[6.5, 135.0, 6.4709418114245381e-05],
[6.5, 180.0, 1.7227922423558414e-05],
[6.5, 225.0, 1.2308522579848724e-05],
[6.5, 270.0, 2.6905672894824344e-05],
[6.5, 315.0, 2.2727114437176048e-05]])

R = mean_data[:,0]
print R
print R.shape

EDIT

The reason why you had an invalid index error is the lack of a comma between mean_data and the values you wanted to add.

Also, np.append returns a copy of the array, and does not change the original array. From the documentation :

Returns : append : ndarray

A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

So you have to assign the np.append result to an array (could be mean_data itself, I think), and, since you don't want a flattened array, you must also specify the axis on which you want to append.

With that in mind, I think you could try something like

mean_data = np.append(mean_data, [[ur, ua, np.mean(data[samepoints,-1])]], axis=0)

Do have a look at the doubled [[ and ]] : I think they are necessary since both arrays must have the same shape.

How do I run a batch file from my Java Application?

Batch files are not an executable. They need an application to run them (i.e. cmd).

On UNIX, the script file has shebang (#!) at the start of a file to specify the program that executes it. Double-clicking in Windows is performed by Windows Explorer. CreateProcess does not know anything about that.

Runtime.
   getRuntime().
   exec("cmd /c start \"\" build.bat");

Note: With the start \"\" command, a separate command window will be opened with a blank title and any output from the batch file will be displayed there. It should also work with just `cmd /c build.bat", in which case the output can be read from the sub-process in Java if desired.

Python logging not outputting anything

Maybe try this? It seems the problem is solved after remove all the handlers in my case.

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

logging.basicConfig(filename='output.log', level=logging.INFO)

Decompile Python 2.7 .pyc

Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc

For example:

git clone https://github.com/zrax/pycdc   
cd pycdc
make  
./bin/pycdc Example.pyc > Example.py

Replace Div Content onclick

Try This:

I think that you want something like this.

HTML:

<div id="1">
    My Content 1
</div>

<div id="2" style="display:none;">
    My Dynamic Content
</div>
<button id="btnClick">Click me!</button>

jQuery:

$('#btnClick').on('click',function(){
if($('#1').css('display')!='none'){
$('#2').show().siblings('div').hide();
}else if($('#2').css('display')!='none'){
    $('#1').show().siblings('div').hide();
}
});


JsFiddle:
http://jsfiddle.net/ha6qp7w4/1113/ <--- see this I hope You want something like this.

C# Test if user has write access to a folder

For example for all users (Builtin\Users), this method works fine - enjoy.

public static bool HasFolderWritePermission(string destDir)
{
   if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
   try
   {
      DirectorySecurity security = Directory.GetAccessControl(destDir);
      SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
      foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
      {
          if(rule.IdentityReference == users)
          {
             FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
             if(rights.AccessControlType == AccessControlType.Allow)
             {
                    if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
             }
          }
       }
       return false;
    }
    catch
    {
        return false;
    }
}

Check whether a string contains a substring

Another possibility is to use regular expressions which is what Perl is famous for:

if ($mystring =~ /s1\.domain\.com/) {
   print qq("$mystring" contains "s1.domain.com"\n);
}

The backslashes are needed because a . can match any character. You can get around this by using the \Q and \E operators.

my $substring = "s1.domain.com";
    if ($mystring =~ /\Q$substring\E/) {
   print qq("$mystring" contains "$substring"\n);
}

Or, you can do as eugene y stated and use the index function. Just a word of warning: Index returns a -1 when it can't find a match instead of an undef or 0.

Thus, this is an error:

my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
    print qq("$mystring" doesn't contains "$substring"\n";
} 

This will be wrong if s1.domain.com is at the beginning of your string. I've personally been burned on this more than once.

Build Eclipse Java Project from Command Line

This question contains some useful links on headless builds, but they are mostly geared towards building plugins. I'm not sure how much of it can be applied to pure Java projects.

Access-Control-Allow-Origin Multiple Origin Domains?

Only a single origin can be specified for the Access-Control-Allow-Origin header. But you can set the origin in your response according to the request. Also don't forget to set the Vary header. In PHP I would do the following:

    /**
     * Enable CORS for the passed origins.
     * Adds the Access-Control-Allow-Origin header to the response with the origin that matched the one in the request.
     * @param array $origins
     * @return string|null returns the matched origin or null
     */
    function allowOrigins($origins)
    {
        $val = $_SERVER['HTTP_ORIGIN'] ?? null;
        if (in_array($val, $origins, true)) {
            header('Access-Control-Allow-Origin: '.$val);
            header('Vary: Origin');

            return $val;
        }

        return null;
    }

  if (allowOrigins(['http://localhost', 'https://localhost'])) {
      echo your response here, e.g. token
  }

How to specify table's height such that a vertical scroll bar appears?

to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link

Simple Popup by using Angular JS

Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.

Created an angular directive called modal and used in html. Explanation:-

HTML

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>

On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.

JS

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

UPDATE

<!doctype html>
<html ng-app="mymodal">


<body>

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <!-- Scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <!-- App -->
    <script>
        var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
          scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

    </script>
</body>
</html>

UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is

<modal>

Other values are 'A' for attribute

<div modal>

'C' for class (not preferable in our case because modal is already a class in bootstrap.css)

<div class="modal">

Why doesn't Mockito mock static methods?

As an addition to the Gerold Broser's answer, here an example of mocking a static method with arguments:

class Buddy {
  static String addHello(String name) {
    return "Hello " + name;
  }
}

...

@Test
void testMockStaticMethods() {
  assertThat(Buddy.addHello("John")).isEqualTo("Hello John");

  try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
    theMock.when(() -> Buddy.addHello("John")).thenReturn("Guten Tag John");
    assertThat(Buddy.addHello("John")).isEqualTo("Guten Tag John");
  }

  assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
}

"Post Image data using POSTMAN"

The accepted answer works if you set the JSON as a key/value pair in the form-data panel (See the image hereunder)

enter image description here

Nevertheless, I am wondering if it is a very clean way to design an API. If it is mandatory for you to upload both image and JSON in a single call maybe it is ok but if you could separate the routes (one for image uploading, the other for JSON body with a proper content-type header), it seems better.

Delete rows containing specific strings in R

You can use it in the same datafram (df) using the previously provided code

df[!grepl("REVERSE", df$Name),]

or you might assign a different name to the datafram using this code

df1<-df[!grepl("REVERSE", df$Name),]

Animate scroll to ID on page load

try with following code. make elements with class name page-scroll and keep id name to href of corresponding links

$('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

How to create a dotted <hr/> tag?

hr {
    border: 1px dotted #ff0000;
    border-style: none none dotted; 
    color: #fff; 
    background-color: #fff;
}

Try this

Assign keyboard shortcut to run procedure

Write a vba proc like:

Sub E_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\e1.wav", 0)
    Range("AG" & (ActiveCell.Row)).Select 'go to column AG in the same row
End Sub

then go to developer tab, macros, select the macro, click options, then add a shortcut letter or button.

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

SELECT * FROM TABLE
WHERE DATE BETWEEN '09/16/2010 05:00:00' and '09/21/2010 09:00:00'

How to run travis-ci locally

tl;dr Use image specified at https://docs.travis-ci.com/user/common-build-problems/#troubleshooting-locally-in-a-docker-image in combination with https://github.com/travis-ci/travis-build#use-as-addon-for-travis-cli.


EDIT 2019-12-06

#troubleshooting-locally-in-a-docker-image section was replaced by #running-builds-in-debug-mode which also describes how to SSH to the job running in the debug mode.

EDIT 2019-07-26

#troubleshooting-locally-in-a-docker-image section is no longer part of the docs; here's why


Though, it's still in git history: https://github.com/travis-ci/docs-travis-ci-com/pull/2193.

Look for (quite old, couldn't find newer) image versions at: https://travis-ci.org/travis-ci/docs-travis-ci-com/builds/230889063#L661.



I wanted to inspect why one of the tests in my build failed with an error I din't get locally.

Worked.

What actually worked was using the image specified at Troubleshooting Locally in a Docker Image docs page. In my case it was travisci/ci-garnet:packer-1512502276-986baf0.

I was able to add travise compile following steps described at https://github.com/travis-ci/travis-build#use-as-addon-for-travis-cli.

dm@z580:~$ docker run --name travis-debug -dit travisci/ci-garnet:packer-1512502276-986baf0 /sbin/init
dm@z580:~$ docker images
REPOSITORY                       TAG                          IMAGE ID            CREATED             SIZE
travisci/ci-garnet               packer-1512502276-986baf0    6cbda6a950d3        11 months ago       10.2GB
dm@z580:~$ docker exec -it travis-debug bash -l
root@912e43dbfea4:/# su - travis
travis@912e43dbfea4:~$ cd builds/
travis@912e43dbfea4:~/builds$ git clone https://github.com/travis-ci/travis-build
travis@912e43dbfea4:~/builds$ cd travis-build
travis@912e43dbfea4:~/builds/travis-build$ mkdir -p ~/.travis
travis@912e43dbfea4:~/builds/travis-build$ ln -s $PWD ~/.travis/travis-build
travis@912e43dbfea4:~/builds/travis-build$ gem install bundler
travis@912e43dbfea4:~/builds/travis-build$ bundle install --gemfile ~/.travis/travis-build/Gemfile
travis@912e43dbfea4:~/builds/travis-build$ bundler binstubs travis
travis@912e43dbfea4:~/builds/travis-build$ cd ..
travis@912e43dbfea4:~/builds$ git clone --depth=50 --branch=master https://github.com/DusanMadar/PySyncDroid.git DusanMadar/PySyncDroid
travis@912e43dbfea4:~/builds$ cd DusanMadar/PySyncDroid/
travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$ ~/.travis/travis-build/bin/travis compile > ci.sh
travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$ sed -i 's,--branch\\=\\\x27\\\x27,--branch\\=master,g' ci.sh
travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$ bash ci.sh

Everything from .travis.yml was executed as expected (dependencies installed, tests ran, ...).

Note that before running bash ci.sh I had to change --branch\=\'\'\ to --branch\=master\ (see the second to last sed -i ... command) in ci.sh.

If that doesn't work the command bellow will help to identify the target line number and you can edit the line manually.

travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$ cat ci.sh | grep -in branch
840:    travis_cmd git\ clone\ --depth\=50\ --branch\=\'\'\ https://github.com/DusanMadar/PySyncDroid.git\ DusanMadar/PySyncDroid --echo --retry --timing
889:export TRAVIS_BRANCH=''
899:export TRAVIS_PULL_REQUEST_BRANCH=''
travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$

Didn't work.

Followed the accepted answer for this question but didn't find the image (travis-ci-garnet-trusty-1512502259-986baf0) mentioned by instance at https://hub.docker.com/u/travisci/.

Build worker version points to travis-ci/worker commit and its travis-worker-install references quay.io/travisci/ as image registry. So I tried it.

dm@z580:~$ docker run -it -u travis quay.io/travisci/travis-python /bin/bash
travis@370c23a773c9:/$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 12.04.5 LTS
Release:    12.04
Codename:   precise
travis@370c23a773c9:/$
dm@z580:~$ docker images 
REPOSITORY                       TAG                          IMAGE ID            CREATED             SIZE
quay.io/travisci/travis-python   latest                       753a216d776c        3 years ago         5.36GB

Definitely not Trusty (Ubuntu 14.04) and not small either.

Selenium and xPath - locating a link by containing text

I think the problem is here:

[contains(text()='Some text')]

To break this down,

  1. The [] are a conditional that operates on each individual node in that node set -- each span node in your case. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  2. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  3. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order.

You should try to change this to

[text()[contains(.,'Some text')]]

  1. The outer [] are a conditional that operates on each individual node in that node set text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.

  2. The inner [] are a conditional that operates on each node in that node set.

  3. contains is a function that operates on a string. Here it is passed an individual text node (.).

How to Get enum item name from its value

How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc."

On some older C code (quite some time ago), I found code analogous to:

std::string weekEnumToStr(int n)
{
   std::string s("unknown");
   switch (n)
   {
   case 0: { s = "Mon"; } break;
   case 1: { s = "Tue"; } break;
   case 2: { s = "Wed"; } break;
   case 3: { s = "Thu"; } break;
   case 4: { s = "Fri"; } break;
   case 5: { s = "Sat"; } break;
   case 6: { s = "Sun"; } break;
   }
   return s;
}

Con: This establishes a "pathological dependency" between the enumeration values and the function... meaning if you change the enum you must change the function to match. I suppose this is true even for a std::map.

I vaguely remember we found a utility to generate the function code from the enum code. The enum table length had grown to several hundred ... and at some point it is maybe a sound choice to write code to write code.


Note -

in an embedded system enhancement effort, my team replaced many tables (100+?) of null-terminated-strings used to map enum int values to their text strings.

The problem with the tables was that a value out of range was often not noticed because many of these tables were gathered into one region of code / memory, such that a value out-of-range reached past the named table end(s) and returned a null-terminated-string from some subsequent table.

Using the function-with-switch statement also allowed us to add an assert in the default clause of the switch. The asserts found several more coding errors during test, and our asserts were tied into a static-ram-system-log our field techs could search.

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

Sql Server : How to use an aggregate function like MAX in a WHERE clause

yes you need to use a having clause after the Group by clause , as the where is just to filter the data on simple parameters , but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

How should a model be structured in MVC?

More oftenly most of the applications will have data,display and processing part and we just put all those in the letters M,V and C.

Model(M)-->Has the attributes that holds state of application and it dont know any thing about V and C.

View(V)-->Has displaying format for the application and and only knows about how-to-digest model on it and does not bother about C.

Controller(C)---->Has processing part of application and acts as wiring between M and V and it depends on both M,V unlike M and V.

Altogether there is separation of concern between each. In future any change or enhancements can be added very easily.

Android emulator: could not get wglGetExtensionsStringARB error

For me changing the Emulated Performance setting to "Store a snapshot for faster startup" and unchecking "Use Host GPU" fixed the problem.

Best way to test for a variable's existence in PHP; isset() is clearly broken

Object properties can be checked for existence by property_exists

Example from a unit test:

function testPropertiesExist()
{
    $sl =& $this->system_log;
    $props = array('log_id',
                   'type',
                   'message',
                   'username',
                   'ip_address',
                   'date_added');

    foreach($props as $prop) {
        $this->assertTrue(property_exists($sl, $prop),
                           "Property <{$prop}> exists");
    }
}

IE9 jQuery AJAX with CORS returns "Access is denied"

Building on the solution by MoonScript, you could try this instead:

https://github.com/intuit/xhr-xdr-adapter/blob/master/src/xhr-xdr-adapter.js

The benefit is that since it's a lower level solution, it will enable CORS (to the extent possible) on IE 8/9 with other frameworks, not just with jQuery. I've had success using it with AngularJS, as well as jQuery 1.x and 2.x.

Download and install an ipa from self hosted url on iOS

More simply you can utilize DropBox for this. The steps basically remain the same. You can do the following-:

1) upload your .ipa to dropBox, Share the link for this .ipa

2) Paste the shared link for .ipa in your manifest.plist file , Upload manifest file in DropBox again share the link for this .plist file

3)paste the link for this Plist in your index.html file with a suitable tag.

Share this index.html file with anybody who can tap on the URL and download. or you can directly hit the URL instead.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Must be used convert, not cast:

SELECT
 CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
 COLLATE Cyrillic_General_CI_AI

(http://blog.sqlpositive.com/2010/03/using-convert-with-collate-to-strip-accents-from-unicode-strings/)

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

You need to set M2 and M2_HOME. I was facing same problem and issue was I had put one extra space in PATH variable after semicolon. Just removed space from path and it worked. (Windows 7 machine)

Regarding Java switch statements - using return and omitting breaks in each case

If you're going to have a method that just runs the switch and then returns some value, then sure this way works. But if you want a switch with other stuff in a method then you can't use return or the rest of the code inside the method will not execute. Notice in the tutorial how it has a print after the code? Yours would not be able to do this.

Convert NSDate to NSString

+(NSString*)date2str:(NSDate*)myNSDateInstance onlyDate:(BOOL)onlyDate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (onlyDate) {
        [formatter setDateFormat:@"yyyy-MM-dd"];
    }else{
        [formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    }

    //Optionally for time zone conversions
    //   [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

    NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
    return stringFromDate;
}

+(NSDate*)str2date:(NSString*)dateStr{
    if ([dateStr isKindOfClass:[NSDate class]]) {
        return (NSDate*)dateStr;
    }

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    return date;
}

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

This is the most simple way you can do it since you can't clear $_POST data by refreshing the page but by leaving the page and coming back to it again.

This will be on the page you would want to clear $_POST data.

<a class="btn" href="clear_reload.php"> Clear</a> // button to 'clear' data

Now create clear_reload.php.

clear_reload.php:

<?php
header("Location: {$_SERVER['HTTP_REFERER']}");
?>

The "clear" button will direct you to this clear_reload.php page, which will redirect you back to the same page you were at.

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

How can I export the schema of a database in PostgreSQL?

pg_dump -d <databasename> -h <hostname> -p <port> -n <schemaname> -f <location of the dump file>

Please notice that you have sufficient privilege to access that schema. If you want take backup as specific user add user name in that command preceded by -U

How do I ignore all files in a folder with a Git repository in Sourcetree?

After beating my head on this for at least an hour, I offer this answer to try to expand on the comments some others have made. To ignore a folder/directory, do the following: if you don't have a .gitignore file in the root of your project (that name exactly ".gitignore"), create a dummy text file in the folder you want to exclude. Inside of Source Tree, right click on it and select Ignore. You'll get a popup that looks like this.

enter image description here

Select "Everything underneath" and select the folder you want to ignore from the drop-down list. This will create a .gitignore file in your root directory and put the folder specification in it.

If you do have a .gitignore folder already in your root folder, you could follow the same approach above, or you can just edit the .gitignore file and add the folder you want to exclude. It's just a text file. Note that it uses forward slashes in path names rather than backslashes, as we Windows users are accustomed to. I tried creating a .gitignore text file by hand in Windows Explorer, but it didn't let me create a file without a name (i.e. with only the extension).

Note that adding the .gitignore and the file specification will have no effect on files that are already being tracked. If you're already tracking these, you'll have to stop tracking them. (Right-click on the folder or file and select Stop Tracking.) You'll then see them change from having a green/clean or amber/changed icon to a red/removed icon. On your next commit the files will be removed from the repository and thereafter appear with a blue/ignored icon. Another contributor asked why Ignore was disabled for particular files and I believe it was because he was trying to ignore a file that was already being tracked. You can only ignore a file that has a blue question mark icon.

break out of if and foreach

A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.

Example:

// Setup a counter
$ImageCounter = 0;

// Increment through repeater fields
while ( condition ):
  $ImageCounter++;

   // Only print the first while instance
   if ($ImageCounter == 1) {
    echo 'It worked just once';
   }

// Close while statement
endwhile;

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.

Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.

Is there any way to wait for AJAX response and halt execution?

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

Why do people say that Ruby is slow?

Obviously, talking about speed Ruby loses. Even though benchmark tests suggest that Ruby is not so much slower than PHP. But in return, you are getting easy-to-maintain DRY code, the best out of all frameworks in various languages.

For a small project, you wont feel any slowness (I mean until like <50K users) given that no complex calculations are used in the code, just the mainstream stuff.

For a bigger project, paying for resources pays off and is cheaper than developer wages. In addition, writing code on RoR turns out to be much faster than any other.

In 2014 this magnitude of speed difference you're talking about is for most websites insignificant.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

This expression 12-4-2005 is a calculated int and the value is -1997. You should do like this instead '2005-04-12' with the ' before and after.

Python debugging tips

PyDev

PyDev has a pretty good interactive debugger. It has watch expressions, hover-to-evaluate, thread and stack listings and (almost) all the usual amenities you expect from a modern visual debugger. You can even attach to a running process and do remote debugging.

Like other visual debuggers, though, I find it useful mostly for simple problems, or for very complicated problems after I've tried everything else. I still do most of the heavy lifting with logging.

Submit a form using jQuery

For information
if anyone use

$('#formId').submit();

Do not something like this

<button name = "submit">

It took many hours to find me that submit() won't work like this.

How do I merge a git tag onto a branch

Just complementing the answer.

Merging the last tag on a branch:

git checkout my-branch
git merge $(git describe --tags $(git rev-list --tags --max-count=1))

Inspired by https://gist.github.com/rponte/fdc0724dd984088606b0

NULL value for int in Update statement

Provided that your int column is nullable, you may write:

UPDATE dbo.TableName
SET TableName.IntColumn = NULL
WHERE <condition>

Proper way to set response status and JSON content in a REST API made with nodejs and express

try {
  var data = {foo: "bar"};
  res.json(JSON.stringify(data));
}
catch (e) {
  res.status(500).json(JSON.stringify(e));
}

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

Here's a solution using a negative lookahead (not supported in all regex engines):

^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$

Test that it works as expected:

import re
tests = [
   ('a', True),
   ('_', False),
   ('zz', True),
   ('a0', True),
   ('A_', False),
   ('a0_b', True),
   ('a__b', False),
   ('a_1_c', True),
]

regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
   is_match = re.match(regex, test[0]) is not None
   if is_match != test[1]:
       print "fail: "  + test[0]

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

IllegalMonitorStateException on wait() call

Not sure if this will help somebody else out or not but this was the key part to fix my problem in user "Tom Hawtin - tacklin"'s answer above:

synchronized (lock) {
    makeWakeupNeeded();
    lock.notifyAll();
}

Just the fact that the "lock" is passed as an argument in synchronized() and it is also used in "lock".notifyAll();

Once I made it in those 2 places I got it working

Jquery, set value of td in a table?

Try the code below :

$('#detailInfo').html('your value')

in_array() and multidimensional array

what about array_search? seems it quite faster than foreach according to https://gist.github.com/Ocramius/1290076 ..

if( array_search("Irix", $a) === true) 
{
    echo "Got Irix";
}

PermissionError: [Errno 13] in python

For me, I was writing to a file that is opened in Excel.

Python Accessing Nested JSON Data

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

print j['state']
print j['places'][1]['post code']

How do I convert a number to a letter in Java?

for(int i=0;i<ar.length();i++) {
            char ch = ar.charAt(i);
                    System.out.println((char)(ch+16));;
        }

how to stop a running script in Matlab

Consider having multiple matlab sessions. Keep the main session window (the pretty one with all the colours, file manager, command history, workspace, editor etc.) for running stuff that you know will terminate.

Stuff that you are experimenting with, say you are messing with ode suite and you get lots of warnings: matrix singular, because you altered some parameter and didn't predict what would happen, run in a separate session:

dos('matlab -automation -r &')

You can kill that without having to restart the whole of Matlab.

How to check if pytorch is using the GPU?

To check if there is a GPU available:

torch.cuda.is_available()

If the above function returns False,

  1. you either have no GPU,
  2. or the Nvidia drivers have not been installed so the OS does not see the GPU,
  3. or the GPU is being hidden by the environmental variable CUDA_VISIBLE_DEVICES. When the value of CUDA_VISIBLE_DEVICES is -1, then all your devices are being hidden. You can check that value in code with this line: os.environ['CUDA_VISIBLE_DEVICES']

If the above function returns True that does not necessarily mean that you are using the GPU. In Pytorch you can allocate tensors to devices when you create them. By default, tensors get allocated to the cpu. To check where your tensor is allocated do:

# assuming that 'a' is a tensor created somewhere else
a.device  # returns the device where the tensor is allocated

Note that you cannot operate on tensors allocated in different devices. To see how to allocate a tensor to the GPU, see here: https://pytorch.org/docs/stable/notes/cuda.html

Similarity String Comparison in Java

Theoretically, you can compare edit distances.

Rename Files and Directories (Add Prefix)

On my system, I don't have the rename command. Here is a simple one liner. It finds all the HTML files recursively and adds prefix_ in front of their names:

for f in $(find . -name '*.html'); do mv "$f" "$(dirname "$f")/prefix_$(basename "$f")"; done

Oracle Insert via Select from multiple tables where one table may not have a row

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
   ts.tax_status_id, 
   ( select r.recipient_id
     from recipient r
     where r.recipient_code = ?
   )
from tax_status ts
where ts.tax_status_code = ?

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

I should add: You should not be putting your dll's into \system32\ anyway! Modify your code, modify your installer... find a home for your bits that is NOT anywhere under c:\windows\

For example, your installer puts your dlls into:

\program files\<your app dir>\

or

\program files\common files\<your app name>\

(Note: The way you actually do this is to use the environment var: %ProgramFiles% or %ProgramFiles(x86)% to find where Program Files is.... you do not assume it is c:\program files\ ....)

and then sets a registry tag :

HKLM\software\<your app name>
-- dllLocation

The code that uses your dlls reads the registry, then dynamically links to the dlls in that location.

The above is the smart way to go.

You do not ever install your dlls, or third party dlls into \system32\ or \syswow64. If you have to statically load, you put your dlls in your exe dir (where they will be found). If you cannot predict the exe dir (e.g. some other exe is going to call your dll), you may have to put your dll dir into the search path (avoid this if at all poss!)

system32 and syswow64 are for Windows provided files... not for anyone elses files. The only reason folks got into the bad habit of putting stuff there is because it is always in the search path, and many apps/modules use static linking. (So, if you really get down to it, the real sin is static linking -- this is a sin in native code and managed code -- always always always dynamically link!)

Adding ID's to google map markers

JavaScript is a dynamic language. You could just add it to the object itself.

var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};

Also, because all v3 objects extend MVCObject(). You can use:

marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");

Python not working in command prompt?

Kalle posted a link to a page that has this video on it, but it's done on XP. If you use Windows 7:

  1. Press the windows key.
  2. Type "system env". Press enter.
  3. Press alt + n
  4. Press alt + e
  5. Press right, and then ; (that's a semicolon)
  6. Without adding a space, type this at the end: C:\Python27
  7. Hit enter twice. Hit esc.
  8. Use windows key + r to bring up the run dialog. Type in python and press enter.

Duplicate AssemblyVersion Attribute

I had the same error and it was underlining the Assembly Vesrion and Assembly File Version so reading Luqi answer I just added them as comments and the error was solved

// AssemblyVersion is the CLR version. Change this only when making breaking    changes
//[assembly: AssemblyVersion("3.1.*")]
// AssemblyFileVersion should ideally be changed with each build, and should help identify the origin of a build
//[assembly: AssemblyFileVersion("3.1.0.0")]

XML Serialize generic list of serializable objects

I think it's best if you use methods with generic arguments, like the following :

public static void SerializeToXml<T>(T obj, string fileName)
{
    using (var fileStream = new FileStream(fileName, FileMode.Create))
    { 
        var ser = new XmlSerializer(typeof(T)); 
        ser.Serialize(fileStream, obj);
    }
}

public static T DeserializeFromXml<T>(string xml)
{
    T result;
    var ser = new XmlSerializer(typeof(T));
    using (var tr = new StringReader(xml))
    {
        result = (T)ser.Deserialize(tr);
    }
    return result;
}

JBoss default password

I suggest visit Add digest auth in jmx-console and read oficial documentation for Configure admin consoles, you can add more security to your JBoss AS console and at these link explains where are the role and user/pass files that you need to change this information for your server and how you can change them. Also I recommend you quit all consoles that you don't use because they can affect to application server's performance. Also there are others links about securing jmx-console that could help you, search in jboss as community site for them (I can't put them here for my actual reputation,sorry). Never you should has the password in plain text over conf/props/ files.

Sorry for my bad English and I hope my answer be useful for you.

SQL Statement using Where clause with multiple values

Try this:

select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2

The number in the having should match the amount of people. If you also need the Status to be Complete use this where clause instead of the previous one:

where personName in ('Ryan', 'Holly') and status = 'Complete'

Web API optional parameters

you need only set default value to parameters(you do not need the Route attribute):

public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

Can't operator == be applied to generic types in C#?

Well in my case I wanted to unit-test the equality operator. I needed call the code under the equality operators without explicitly setting the generic type. Advises for EqualityComparer were not helpful as EqualityComparer called Equals method but not the equality operator.

Here is how I've got this working with generic types by building a LINQ. It calls the right code for == and != operators:

/// <summary>
/// Gets the result of "a == b"
/// </summary>
public bool GetEqualityOperatorResult<T>(T a, T b)
{
    // declare the parameters
    var paramA = Expression.Parameter(typeof(T), nameof(a));
    var paramB = Expression.Parameter(typeof(T), nameof(b));
    // get equality expression for the parameters
    var body = Expression.Equal(paramA, paramB);
    // compile it
    var invokeEqualityOperator = Expression.Lambda<Func<T, T, bool>>(body, paramA, paramB).Compile();
    // call it
    return invokeEqualityOperator(a, b);
}

/// <summary>
/// Gets the result of "a =! b"
/// </summary>
public bool GetInequalityOperatorResult<T>(T a, T b)
{
    // declare the parameters
    var paramA = Expression.Parameter(typeof(T), nameof(a));
    var paramB = Expression.Parameter(typeof(T), nameof(b));
    // get equality expression for the parameters
    var body = Expression.NotEqual(paramA, paramB);
    // compile it
    var invokeInequalityOperator = Expression.Lambda<Func<T, T, bool>>(body, paramA, paramB).Compile();
    // call it
    return invokeInequalityOperator(a, b);
}

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

I was getting the same error, You can fix through one of this method:

  1. If you don't have any nested module

    a. Import the CommonModule in your App module

    b. Import your Component where you are adding the *ngFor in the App Module, define in declarations

// file App.modules.ts
@NgModule({
  declarations: [
    LoginComponent // declarations of your component
  ],
  imports: [
    BrowserModule
    DemoMaterialModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
    ApiService, 
    CookieService, 
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ApiInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})

c. If you are using the separate module file for routing then Import the CommonModule in your Routing module else Import the CommonModule in your App module

// file app.routing.modules.ts
import { LoginComponent } from './login/login.component';
import { CommonModule } from "@angular/common";

const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent }
];

@NgModule({
  imports: [RouterModule,RouterModule.forRoot(routes), CommonModule],
  exports: [RouterModule]
})
  1. If you have nested module then perform the 1st step in that particular module

In my case, the 2nd method solved my issue.
Hope this will help you

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

A Context is:

  • an abstract class whose implementation is provided by the Android system.
  • It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

The remote certificate is invalid according to the validation procedure

Even shorter version of the solution from Dominic Zukiewicz:

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.

Difference between jQuery’s .hide() and setting CSS to display: none

Looking at the jQuery code, this is what happens:

hide: function( speed, easing, callback ) {
    if ( speed || speed === 0 ) {
        return this.animate( genFx("hide", 3), speed, easing, callback);

    } else {
        for ( var i = 0, j = this.length; i < j; i++ ) {
            var display = jQuery.css( this[i], "display" );

            if ( display !== "none" ) {
                jQuery.data( this[i], "olddisplay", display );
            }
        }

        // Set the display of the elements in a second loop
        // to avoid the constant reflow
        for ( i = 0; i < j; i++ ) {
            this[i].style.display = "none";
        }

        return this;
    }
},

CSS vertical alignment text inside li

line-height is how you vertically align text. It is pretty standard and I don't consider it a "hack". Just add line-height: 100px to your ul.catBlock li and it will be fine.

In this case you may have to add it to ul.catBlock li a instead since all of the text inside the li is also inside of an a. I have seen some weird things happen when you do this, so try both and see which one works.

Create an application setup in visual studio 2013

I will tell , how i solved almost similar problem. I developed a application using VS 2013 and tried to create wizard for it failed to do. Later i installed premium VS and tried and failed.

at last i used "ClickOnce" and it worked fine.

So i believe here also , "CLICKONCE" would help you.

How to import Swagger APIs into Postman?

I work on PHP and have used Swagger 2.0 to document the APIs. The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.

Sample document

{
    "swagger": "2.0",
    "info": {
    "title": "Company Admin Panel",
        "description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
        "contact": {
        "email": "[email protected]"
        },
        "version": "1.0.0"
    },
    "host": "localhost/cv_admin/api",
    "schemes": [
    "http"
],
    "paths": {
    "/getCustomerByEmail.php": {
        "post": {
            "summary": "List the details of customer by the email.",
                "consumes": [
                "string",
                "application/json",
                "application/x-www-form-urlencoded"
            ],
                "produces": [
                "application/json"
            ],
                "parameters": [
                    {
                        "name": "email",
                        "in": "body",
                        "description": "Customer email to ge the data",
                        "required": true,
                        "schema": {
                        "properties": {
                            "id": {
                                "properties": {
                                    "abc": {
                                        "properties": {
                                            "inner_abc": {
                                                "type": "number",
                                                    "default": 1,
                                                    "example": 123
                                                }
                                            },
                                            "type": "object"
                                        },
                                        "xyz": {
                                        "type": "string",
                                            "default": "xyz default value",
                                            "example": "xyz example value"
                                        }
                                    },
                                    "type": "object"
                                }
                            }
                        }
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "Email required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getCustomerById.php": {
        "get": {
            "summary": "List the details of customer by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Customer ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getShipmentById.php": {
        "get": {
            "summary": "List the details of shipment by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Shipment ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the shipment"
                    },
                    "404": {
                    "description": "Shipment does not exist"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        }
    },
    "definitions": {

    }
}

This can be imported into Postman as follow.

  1. Click on the 'Import' button in the top left corner of Postman UI.
  2. You will see multiple options to import the API doc. Click on the 'Paste Raw Text'.
  3. Paste the JSON format in the text area and click import.
  4. You will see all your APIs as 'Postman Collection' and can use it from the Postman.

Importing the JSON into Postman

Imported APIs

You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.

This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.

<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;

SQL Server 2008- Get table constraints

I tried to edit the answer provided by marc_s however it wasn't accepted for some reason. It formats the sql for easier reading, includes the schema and also names the Default name so that this can easily be pasted into other code.

  SELECT SchemaName = s.Name,
         TableName = t.Name,
         ColumnName = c.Name,
         DefaultName = dc.Name,
         DefaultDefinition = dc.Definition
    FROM sys.schemas                s
    JOIN sys.tables                 t   on  t.schema_id          = s.schema_id
    JOIN sys.default_constraints    dc  on  dc.parent_object_id  = t.object_id 
    JOIN sys.columns                c   on  c.object_id          = dc.parent_object_id
                                        and c.column_id          = dc.parent_column_id
ORDER BY s.Name, t.Name, c.name

How do I install package.json dependencies in the current directory using npm

In my case I need to do

sudo npm install  

my project is inside /var/www so I also need to set proper permissions.

Working with TIFFs (import, export) in Python using numpy

I recommend using the python bindings to OpenImageIO, it's the standard for dealing with various image formats in the vfx world. I've ovten found it more reliable in reading various compression types compared to PIL.

import OpenImageIO as oiio
input = oiio.ImageInput.open ("/path/to/image.tif")

CSS Classes & SubClasses

The class you apply on the div can be used to as a reference point to style elements with that div, for example.

<div class="area1">
    <table>
        <tr>
                <td class="item">Text Text Text</td>
                <td class="item">Text Text Text</td>
        </tr>
    </table>
</div>


.area1 { border:1px solid black; }

.area1 td { color:red; } /* This will effect any TD within .area1 */

To be super semantic you should move the class onto the table.

    <table class="area1">
        <tr>
                <td>Text Text Text</td>
                <td>Text Text Text</td>
        </tr>
    </table>

Can I remove the URL from my print css, so the web address doesn't print?

In Firefox, https://bug743252.bugzilla.mozilla.org/attachment.cgi?id=714383 (view page source :: tag HTML).

In your code, replace <html> with <html moznomarginboxes mozdisallowselectionprint>.

In others browsers, I don't know, but you can view http://www.mintprintables.com/print-tips/header-footer-windows/

jQuery callback on image load (even when the image is cached)

Just re-add the src argument on a separate line after the img oject is defined. This will trick IE into triggering the lad-event. It is ugly, but it is the simplest workaround I've found so far.

jQuery('<img/>', {
    src: url,
    id: 'whatever'
})
.load(function() {
})
.appendTo('#someelement');
$('#whatever').attr('src', url); // trigger .load on IE

Android - running a method periodically using postDelayed() call

You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity

Get number days in a specified month using JavaScript?

Date.prototype.monthDays= function(){
    var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
    return d.getDate();
}

Failed to execute 'createObjectURL' on 'URL':

My code was broken because I was using a deprecated technique. It used to be this:

video.src = window.URL.createObjectURL(localMediaStream);
video.play();

Then I replaced that with this:

video.srcObject = localMediaStream;
video.play();

That worked beautifully.

EDIT: Recently localMediaStream has been deprecated and replaced with MediaStream. The latest code looks like this:

video.srcObject = new MediaStream();

References:

  1. Deprecated technique: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
  2. Modern deprecated technique: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
  3. Modern technique: https://developer.mozilla.org/en-US/docs/Web/API/MediaStream

Check whether a value is a number in JavaScript or jQuery

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

Change div height on button click

Just remove the "px" in the style.height assignation, like:

<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200px"> </button>

Should be

<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200">Click Me!</button>

jQuery and TinyMCE: textarea value doesn't submit

Before submitting the form, call tinyMCE.triggerSave();

Font-awesome, input type 'submit'

You can use font awesome utf cheatsheet

<input type="submit" class="btn btn-success" value="&#xf011; Login"/>

here is the link for the cheatsheet http://fortawesome.github.io/Font-Awesome/cheatsheet/

Python 3 Building an array of bytes

agf's bytearray solution is workable, but if you find yourself needing to build up more complicated packets using datatypes other than bytes, you can try struct.pack(). http://docs.python.org/release/3.1.3/library/struct.html

ORA-01861: literal does not match format string

A simple view like this was giving me the ORA-01861 error when executed from Entity Framework:

create view myview as 
select * from x where x.initialDate >= '01FEB2021'

Just did something like this to fix it:

create view myview as 
select * from x where x.initialDate >= TO_DATE('2021-02-01', 'YYYY-MM-DD')

I think the problem is EF date configuration is not the same as Oracle's.

Twitter bootstrap float div right

This does the trick, without the need to add an inline style

<div class="row-fluid">
    <div class="span6">
        <p>text left</p>
    </div>
    <div class="span6">
        <div class="pull-right">
            <p>text right</p>
        </div>
    </div>
</div>

The answer is in nesting another <div> with the "pull-right" class. Combining the two classes won't work.

How to modify list entries during for loop?

You can do something like this:

a = [1,2,3,4,5]
b = [i**2 for i in a]

It's called a list comprehension, to make it easier for you to loop inside a list.

How to edit default dark theme for Visual Studio Code?

tldr

You can get the colors for any theme (including the builtin ones) by switching to the theme then choosing Developer > Generate Color Theme From Current Settings from the command palette.

Details

  1. Switch to the builtin theme you wish to modify by selecting Preferences: Color Theme from the command palette then choosing the theme.

  2. Get the colors for that theme by choosing Developer > Generate Color Theme From Current Settings from the command palette. Save the file with the suffix -color-theme.jsonc.
    The color-theme part will enable color picker widgets when editing the file and jsonc sets the filetype to JSON with comments.

  3. From the command palette choose Preferences: Open Settings (JSON) to open your settings.json file. Then add your desired changes to either the workbench.colorCustomizations or tokenColorCustomizations section.

    • To restrict the settings to just this theme, use an associative arrays where the key is the theme name in brackets ([]) and the value is an associative array of settings.
    • The theme name can be found in settings.json at workbench.colorTheme.

For example, the following customizes the theme listed as Dark+ (default dark) from the Color Theme list. It sets the editor background to near black and the syntax highlighting for comments to a dim gray.

// settings.json
"workbench.colorCustomizations": {
    "[Default Dark+]": {
        "editor.background": "#19191f"
    }
},
"editor.tokenColorCustomizations": {
    "[Default Dark+]": {
        "comments": "#5F6167"
    }
},

How to request a random row in SQL?

In late, but got here via Google, so for the sake of posterity, I'll add an alternative solution.

Another approach is to use TOP twice, with alternating orders. I don't know if it is "pure SQL", because it uses a variable in the TOP, but it works in SQL Server 2008. Here's an example I use against a table of dictionary words, if I want a random word.

SELECT TOP 1
  word
FROM (
  SELECT TOP(@idx)
    word 
  FROM
    dbo.DictionaryAbridged WITH(NOLOCK)
  ORDER BY
    word DESC
) AS D
ORDER BY
  word ASC

Of course, @idx is some randomly-generated integer that ranges from 1 to COUNT(*) on the target table, inclusively. If your column is indexed, you'll benefit from it too. Another advantage is that you can use it in a function, since NEWID() is disallowed.

Lastly, the above query runs in about 1/10 of the exec time of a NEWID()-type of query on the same table. YYMV.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

how to delete all commit history in github?

If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

git init
git remote add origin [email protected]:user/repo

now commit your current version of code

git add *
git commit -am 'message'

and finally force the update to GitHub:

git push -f origin master

However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

Is there way to use two PHP versions in XAMPP?

I just want to share my new finding: https://laragon.org/docs/index.html

I just used it for 1 hour and it looks promising.

  • You can add and switch PHP versions,
  • it has one-click installers for Wordpress, laravel, etc
  • it autocreates vhosts with the name of each app (eg. appname.test)
  • you can select your current htdocs folder as the root www folder
  • you just add other PHP versions extracting them in folders and selecting them from a list
  • it auto reload apache after each change
  • adding phpMyAdmin is as easy as download it and put it in {LARAGON_DIR}\etc\apps\phpMyAdmin, etc...

Laragon DOCS

How to add another PHP version to Laragon

How to add phpMyAdmin to Laragon


I'm not affiliated in any way with Laragon. Just found it on Google looking for "XAMPP Windows alteratives"

"git rebase origin" vs."git rebase origin/master"

You can make a new file under [.git\refs\remotes\origin] with name "HEAD" and put content "ref: refs/remotes/origin/master" to it. This should solve your problem.

It seems that clone from an empty repos will lead to this. Maybe the empty repos do not have HEAD because no commit object exist.

You can use the

git log --remotes --branches --oneline --decorate

to see the difference between each repository, while the "problem" one do not have "origin/HEAD"

Edit: Give a way using command line
You can also use git command line to do this, they have the same result

git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master

How do I set cell value to Date and apply default Excel date format?

To know the format string used by Excel without having to guess it: create an excel file, write a date in cell A1 and format it as you want. Then run the following lines:

FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);

Then copy-paste the resulting string, remove the backslashes (for example d/m/yy\ h\.mm;@ becomes d/m/yy h.mm;@) and use it in the http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells code:

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

How to center absolute div horizontally using CSS?

Although above answers are correct but to make it simple for newbies, all you need to do is set margin, left and right. following code will do it provided that width is set and position is absolute:

margin: 0 auto;
left: 0;
right: 0;

Demo:

_x000D_
_x000D_
.centeredBox {_x000D_
    margin: 0 auto;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
   _x000D_
   _x000D_
   /** Position should be absolute */_x000D_
    position: absolute;_x000D_
    /** And box must have a width, any width */_x000D_
    width: 40%;_x000D_
    background: #faebd7;_x000D_
   _x000D_
   }
_x000D_
<div class="centeredBox">Centered Box</div>
_x000D_
_x000D_
_x000D_

Can you recommend a free light-weight MySQL GUI for Linux?

I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.

There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.

Get pixel color from canvas, on mousemove

Quick Answer

context.getImageData(x, y, 1, 1).data; returns an rgba array. e.g. [50, 50, 50, 255]


Here's a version of @lwburk's rgbToHex function that takes the rgba array as an argument.

function rgbToHex(rgb){
  return '#' + ((rgb[0] << 16) | (rgb[1] << 8) | rgb[2]).toString(16);
};

How to read a text file from server using JavaScript?

It looks like XMLHttpRequest has been replaced by the Fetch API. Google published a good introduction that includes this example doing what you want:

fetch('./api/some.json')
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

However, you probably want to call response.text() instead of response.json().

call a function in success of datatable ajax call

The success option of ajax should not be altered because DataTables uses it internally to execute the table draw when the data load is complete. The recommendation is used "dataSrc" to alter the received data.

OkHttp Post Body as JSON

Another approach is by using FormBody.Builder().
Here's an example of callback:

Callback loginCallback = new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        try {
            Log.i(TAG, "login failed: " + call.execute().code());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // String loginResponseString = response.body().string();
        try {
            JSONObject responseObj = new JSONObject(response.body().string());
            Log.i(TAG, "responseObj: " + responseObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.i(TAG, "loginResponseString: " + loginResponseString);
    }
};

Then, we create our own body:

RequestBody formBody = new FormBody.Builder()
        .add("username", userName)
        .add("password", password)
        .add("customCredential", "")
        .add("isPersistent", "true")
        .add("setCookie", "true")
        .build();

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(this)
        .build();
Request request = new Request.Builder()
        .url(loginUrl)
        .post(formBody)
        .build();

Finally, we call the server:

client.newCall(request).enqueue(loginCallback);

Add line break to ::after or ::before pseudo-element content

For people who will going to look for 'How to change dynamically content on pseudo element adding new line sign" here's answer

Html chars like &#13;&#10; will not work appending them to html using JavaScript because those characters are changed on document render

Instead you need to find unicode representation of this characters which are U+000D and U+000A so we can do something like

_x000D_
_x000D_
var el = document.querySelector('div');_x000D_
var string = el.getAttribute('text').replace(/, /, '\u000D\u000A');_x000D_
el.setAttribute('text', string);
_x000D_
div:before{_x000D_
   content: attr(text);_x000D_
   white-space: pre;_x000D_
}
_x000D_
<div text='I want to break it in javascript, after comma sign'></div> 
_x000D_
_x000D_
_x000D_

Hope this save someones time, good luck :)

Group by month and year in MySQL

You are grouping by month only, you have to add YEAR() to the group by

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

This happened to me when I upgraded. I had to downgrade back.

react-redux ^5.0.6 ? ^7.1.3

Calculate date from week number

I improved a little on Thomas' solution with an override:

   public static DateTime FirstDateOfWeek(int year, int weekOfYear)
    {
      return Timer.FirstDateOfWeekOfMonth(year, 1, weekOfYear);
    }

    public static DateTime FirstDateOfWeekOfMonth(int year, int month, 
    int weekOfYear)
    {
      DateTime dtFirstDayOfMonth = new DateTime(year, month, 1);

       //I also commented out this part:
      /*
      if (firstWeek <= 1)
      {
        weekOfYear -= 1;
      }
      */

Otherwise the date was preceding by one week..

Thank you Thomas, great help.

Normalizing a list of numbers in Python

try:

normed = [i/sum(raw) for i in raw]

normed
[0.25, 0.5, 0.25]

How to put Google Maps V2 on a Fragment using ViewPager

For the issue of getting a NullPointerException when we change the Tabs in a FragmentTabHost you just need to add this code to your class which has the TabHost. I mean the class where you initialize the tabs. This is the code :

/**** Fix for error : Activity has been destroyed, when using Nested tabs 
 * We are actually detaching this tab fragment from the `ChildFragmentManager`
 * so that when this inner tab is viewed back then the fragment is attached again****/

import java.lang.reflect.Field;

@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

py2exe - generate single executable file

I recently used py2exe to create an executable for post-review for sending reviews to ReviewBoard.

This was the setup.py I used

from distutils.core import setup
import py2exe

setup(console=['post-review'])

It created a directory containing the exe file and the libraries needed. I don't think it is possible to use py2exe to get just a single .exe file. If you need that you will need to first use py2exe and then use some form of installer to make the final executable.

One thing to take care of is that any egg files you use in your application need to be unzipped, otherwise py2exe can't include them. This is covered in the py2exe docs.

TimeStamp on file name using PowerShell

Thanks for the above script. One little modification to add in the file ending correctly. Try this ...

$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**

Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat

How to hide the title bar for an Activity in XML with existing custom theme

This Solved my problem

In manifest my activity:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

In style under "AppTheme" name:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme"
        parent="Theme.AppCompat.Light.NoActionBar">
        **<item name="windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>**
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

make: Nothing to be done for `all'

Remove the hello file from your folder and try again.

The all target depends on the hello target. The hello target first tries to find the corresponding file in the filesystem. If it finds it and it is up to date with the dependent files—there is nothing to do.

How to convert array values to lowercase in PHP?

You can also use a combination of array_flip() and array_change_key_case(). See this post

Why do you have to link the math library in C?

I would guess that it is a way to make apps which don't use it at all perform slightly better. Here's my thinking on this.

x86 OSes (and I imagine others) need to store FPU state on context switch. However, most OSes only bother to save/restore this state after the app attempts to use the FPU for the first time.

In addition to this, there is probably some basic code in the math library which will set the FPU to a sane base state when the library is loaded.

So, if you don't link in any math code at all, none of this will happen, therefore the OS doesn't have to save/restore any FPU state at all, making context switches slightly more efficient.

Just a guess though.

EDIT: in response to some of the comments, the same base premise still applies to non-FPU cases (the premise being that it was to make apps which didn't make use libm perform slightly better).

For example, if there is a soft-FPU which was likley in the early days of C. Then having libm separate could prevent a lot of large (and slow if it was used) code from unnecessarily being linked in.

In addition, if there is only static linking available, then a similar argument applies that it would keep executable sizes and compile times down.

How to edit/save a file through Ubuntu Terminal

Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

My httpd.conf is empty

It seems to me, that it is by design that this file is empty.

A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf

So, you should have a look for /etc/apache2/apache2.conf

Sum of values in an array using jQuery

You don't need jQuery. You can do this using a for loop:

var total = 0;
for (var i = 0; i < someArray.length; i++) {
    total += someArray[i] << 0;
}

Related:

How to perform grep operation on all files in a directory?

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

Should I return EXIT_SUCCESS or 0 from main()?

This is a never ending story that reflect the limits (an myth) of "interoperability and portability over all".

What the program should return to indicate "success" should be defined by who is receiving the value (the Operating system, or the process that invoked the program) not by a language specification.

But programmers likes to write code in "portable way" and hence they invent their own model for the concept of "operating system" defining symbolic values to return.

Now, in a many-to-many scenario (where many languages serve to write programs to many system) the correspondence between the language convention for "success" and the operating system one (that no one can grant to be always the same) should be handled by the specific implementation of a library for a specific target platform.

But - unfortunatly - these concept where not that clear at the time the C language was deployed (mainly to write the UNIX kernel), and Gigagrams of books where written by saying "return 0 means success", since that was true on the OS at that time having a C compiler.

From then on, no clear standardization was ever made on how such a correspondence should be handled. C and C++ has their own definition of "return values" but no-one grant a proper OS translation (or better: no compiler documentation say anything about it). 0 means success if true for UNIX - LINUX and -for independent reasons- for Windows as well, and this cover 90% of the existing "consumer computers", that - in the most of the cases - disregard the return value (so we can discuss for decades, bu no-one will ever notice!)

Inside this scenario, before taking a decision, ask these questions: - Am I interested to communicate something to my caller about my existing? (If I just always return 0 ... there is no clue behind the all thing) - Is my caller having conventions about this communication ? (Note that a single value is not a convention: that doesn't allow any information representation)

If both of this answer are no, probably the good solution is don't write the main return statement at all. (And let the compiler to decide, in respect to the target is working to).

If no convention are in place 0=success meet the most of the situations (and using symbols may be problematic, if they introduce a convention).

If conventions are in place, ensure to use symbolic constants that are coherent with them (and ensure convention coherence, not value coherence, between platforms).

Run batch file from Java code

Following is worked for me

File dir = new File("E:\\test");
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","test.bat");
        pb.directory(dir);
        Process p = pb.start();

.Contains() on a list of custom class objects

If you are using .NET 3.5 or newer you can use LINQ extension methods to achieve a "contains" check with the Any extension method:

if(CartProducts.Any(prod => prod.ID == p.ID))

This will check for the existence of a product within CartProducts which has an ID matching the ID of p. You can put any boolean expression after the => to perform the check on.

This also has the benefit of working for LINQ-to-SQL queries as well as in-memory queries, where Contains doesn't.

Why do I need 'b' to encode a string with Base64?

If the data to be encoded contains "exotic" characters, I think you have to encode in "UTF-8"

encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))

How does one add keyboard languages and switch between them in Linux Mint 16?

Go to menu , search for Regional Settings. Switch to Keyboard layouts tab. Click Options button. Search for Key(s) to change layout. There isn't a default one so you have to tick the combination you like. Enjoy.

Circular gradient in android

I always find images helpful when learning a new concept, so this is a supplemental answer.

enter image description here

The %p means a percentage of the parent, that is, a percentage of the narrowest dimension of whatever view we set our drawable on. The images above were generated by changing the gradientRadius in this code

my_gradient_drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="radial"
        android:gradientRadius="10%p"
        android:startColor="#f6ee19"
        android:endColor="#115ede" />
</shape>

Which can be set on a view's background attribute like this

<View
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:background="@drawable/my_gradient_drawable"/>

Center

You can change the center of the radius with

android:centerX="0.2"
android:centerY="0.7"

where the decimals are fractions of the width and height for x and y respectively.

enter image description here

Documentation

Here are some notes from the documentation explaining things a little more.

android:gradientRadius

Radius of the gradient, used only with radial gradient. May be an explicit dimension or a fractional value relative to the shape's minimum dimension.

May be a floating point value, such as "1.2".

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

May be a fractional value, which is a floating point number appended with either % or %p, such as "14.5%". The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container.

Proxies with Python 'Requests' module

If you'd like to persisist cookies and session data, you'd best do it like this:

import requests

proxies = {
    'http': 'http://user:[email protected]:3128',
    'https': 'https://user:[email protected]:3128',
}

# Create the session and set the proxies.
s = requests.Session()
s.proxies = proxies

# Make the HTTP request through the session.
r = s.get('http://www.showmemyip.com/')

Vertical Align Center in Bootstrap 4

Important! Vertical center is relative to the height of the parent

If the parent of the element you're trying to center has no defined height, none of the vertical centering solutions will work!

Now, onto vertical centering...

Bootstrap 5 (Updated 2020)

Bootstrap 5 is still flexbox based so vertical centering works the same way as Bootstrap 4. For example align-items-center and justify-content-center can used on the flexbox parent (row or d-flex). https://codeply.com/p/0VM5MJ7Had

Bootstrap 4

You can use the new flexbox & size utilities to make the container full-height and display: flex. These options don't require extra CSS (except that the height of the container (ie:html,body) must be 100%).

Option 1 align-self-center on flexbox child

<div class="container d-flex h-100">
    <div class="row justify-content-center align-self-center">
     I'm vertically centered
    </div>
</div>

https://codeply.com/go/fFqaDe5Oey

Option 2 align-items-center on flexbox parent (.row is display:flex; flex-direction:row)

<div class="container h-100">
    <div class="row align-items-center h-100">
        <div class="col-6 mx-auto">
            <div class="jumbotron">
                I'm vertically centered
            </div>
        </div>
    </div>
</div>

enter image description here

https://codeply.com/go/BumdFnmLuk

Option 3 justify-content-center on flexbox parent (.card is display:flex;flex-direction:column)

<div class="container h-100">
    <div class="row align-items-center h-100">
        <div class="col-6 mx-auto">
            <div class="card h-100 border-primary justify-content-center">
                <div>
                    ...card content...
                </div>
            </div>
        </div>
    </div>
</div>

https://codeply.com/go/3gySSEe7nd


More on Bootstrap 4 Vertical Centering

Now that Bootstrap 4 offers flexbox and other utilities, there are many approaches to vertical alignment. http://www.codeply.com/go/WG15ZWC4lf

1 - Vertical Center Using Auto Margins:

Another way to vertically center is to use my-auto. This will center the element within it's container. For example, h-100 makes the row full height, and my-auto will vertically center the col-sm-12 column.

<div class="row h-100">
    <div class="col-sm-12 my-auto">
        <div class="card card-block w-25">Card</div>
    </div>
</div>

Vertical Center Using Auto Margins Demo

my-auto represents margins on the vertical y-axis and is equivalent to:

margin-top: auto;
margin-bottom: auto;

2 - Vertical Center with Flexbox:

vertical center grid columns

Since Bootstrap 4 .row is now display:flex you can simply use align-self-center on any column to vertically center it...

       <div class="row">
           <div class="col-6 align-self-center">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

or, use align-items-center on the entire .row to vertically center align all col-* in the row...

       <div class="row align-items-center">
           <div class="col-6">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

Vertical Center Different Height Columns Demo

See this Q/A to center, but maintain equal height


3 - Vertical Center Using Display Utils:

Bootstrap 4 has display utils that can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

<div class="row h-50">
    <div class="col-sm-12 h-100 d-table">
        <div class="card card-block d-table-cell align-middle">
            I am centered vertically
        </div>
    </div>
</div>

Vertical Center Using Display Utils Demo

More examples
Vertical center image in <div>
Vertical center .row in .container
Vertical center and bottom in <div>
Vertical center child inside parent
Vertical center full screen jumbotron


Important! Did I mention height?

Remember vertical centering is relative to the height of the parent element. If you want to center on the entire page, in most cases, this should be your CSS...

body,html {
  height: 100%;
}

Or use min-height: 100vh (min-vh-100 in Bootstrap 4.1+) on the parent/container. If you want to center a child element inside the parent. The parent must have a defined height.

Also see:
Vertical alignment in bootstrap 4
Bootstrap 4 Center Vertical and Horizontal Alignment

Setting a width and height on an A tag

You need to make your anchor display: block or display: inline-block; and then it will accept the width and height values.

Ruby 'require' error: cannot load such file

For those who are absolutely sure their relative path is correct, my problem was that my files did not have the .rb extension! (Even though I used RubyMine to create the files and selected that they were Ruby files on creation.)

Double check the file extensions on your file!

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

The exception clearly identifies some .NET 2.0.50727 component was included in .NET 4.0. In App.config file use this:

<startup useLegacyV2RuntimeActivationPolicy="true" /> 

It solved my problem

Convert float to string with precision & number of decimal digits specified?

A typical way would be to use stringstream:

#include <iomanip>
#include <sstream>

double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();

See fixed

Use fixed floating-point notation

Sets the floatfield format flag for the str stream to fixed.

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

and setprecision.


For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.

Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:

#include <array>
#include <charconv>

double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
                               std::chars_format::fixed, 2);
if (ec == std::errc{}) {
    std::string s(buffer.data(), ptr);
    // ....
}
else {
    // error handling
}

How to move all HTML element children to another parent using JavaScript?

DEMO

Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.

var newParent = document.getElementById('new-parent');
var oldParent = document.getElementById('old-parent');

while (oldParent.childNodes.length > 0) {
    newParent.appendChild(oldParent.childNodes[0]);
}

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

How do you round to 1 decimal place in Javascript?

To complete the Best Answer:

var round = function ( number, precision )
{
    precision = precision || 0;
    return parseFloat( parseFloat( number ).toFixed( precision ) );
}

The input parameter number may "not" always be a number, in this case .toFixed does not exist.

How do I search for files in Visual Studio Code?

Other answers don't mention this command is named workbench.action.quickOpen.

You can use this to search the Keyboard Shortcuts menu located in Preferences.

On MacOS the default keybinding is cmd ? + P.

(Coming from Sublime Text, I always change this to cmd ? + T)

How do JavaScript closures work?

To understand closures you have to get down to the program and literally execute as if you are the run time. Let's look at this simple piece of code:

Enter image description here

JavaScript runs the code in two phases:

  • Compilation Phase // JavaScript is not a pure interpreted language
  • Execution Phase

When JavaScript goes through the compilation phase it extract out the declarations of variables and functions. This is called hoisting. Functions encountered in this phase are saved as text blobs in memory also known as lambda. After compilation JavaScript enters the execution phase where it assigns all the values and runs the function. To run the function it prepares the execution context by assigning memory from the heap and repeating the compilation and execution phase for the function. This memory area is called scope of the function. There is a global scope when execution starts. Scopes are the key in understanding closures.

In this example, in first go, variable a is defined and then f is defined in the compilation phase. All undeclared variables are saved in the global scope. In the execution phase f is called with an argument. f's scope is assigned and the compilation and execution phase is repeated for it.

Arguments are also saved in this local scope for f. Whenever a local execution context or scope is created it contain a reference pointer to its parent scope. All variable access follows this lexical scope chain to find its value. If a variable is not found in the local scope it follows the chain and find it in its parent scope. This is also why a local variable overrides variables in the parent scope. The parent scope is called the "Closure" for local a scope or function.

Here when g's scope is being set up it got a lexical pointer to its parents scope of f. The scope of f is the closure for g. In JavaScript, if there is some reference to functions, objects or scopes if you can reach them somehow, it will not get garbage collected. So when myG is running, it has a pointer to scope of f which is its closure. This area of memory will not get garbage collected even f has returned. This is a closure as far as the runtime is concerned.

SO WHAT IS A CLOSURE?

  • It is an implicit, permanent link between a function and its scope chain...
  • A function definition's (lambda) hidden [[scope]] reference.
  • Holds the scope chain (preventing garbage collection).
  • It is used and copied as the "outer environment reference" anytime the function is run.

IMPLICIT CLOSURE

var data = "My Data!";
setTimeout(function() {
  console.log(data); // Prints "My Data!"
}, 3000);

EXPLICIT CLOSURES

function makeAdder(n) {
  var inc = n;
  var sum = 0;
  return function add() {
    sum = sum + inc;
    return sum;
  };
}

var adder3 = makeAdder(3);

A very interesting talk on closures and more is Arindam Paul - JavaScript VM internals, EventLoop, Async and ScopeChains.

Should I Dispose() DataSet and DataTable?

Datasets implement IDisposable thorough MarshalByValueComponent, which implements IDisposable. Since datasets are managed there is no real benefit to calling dispose.

How to completely hide the navigation bar in iPhone / HTML5

Simple javascript document navigation to "#" will do it.

window.onload = function()
{
document.location.href = "#";
}

This will force the navigation bar to remove itself on load.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Try to import

java.util.List;

instead of

java.awt.List;

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

Make sure that all these libs are in your class path:

compile(group: 'com.sun.jersey', name: 'jersey-core',        version: '1.19.4') 
compile(group: 'com.sun.jersey', name: 'jersey-server',      version: '1.19.4') 
compile(group: 'com.sun.jersey', name: 'jersey-servlet',     version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-json',        version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-client',      version: '1.19.4')
compile(group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl',   version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-jaxrs',      version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-xc',         version: '1.9.2')

Add "Pojo Mapping" and "Jackson Provider" to the jersey client config:

ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
clientConfig.getClasses().add(JacksonJsonProvider.class);

This solve to me!

ClientResponse response = null;

response = webResource
        .type(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON)
        .get(ClientResponse.class);


if (response.getStatus() == Response.Status.OK.getStatusCode()) {

    MyClass myclass = response.getEntity(MyClass.class);
    System.out.println(myclass);
}

How can I make a checkbox readonly? not disabled?

You can easily do this by css. HTML :

<form id="aform" name="aform" method="POST">
    <input name="chkBox_1" type="checkbox" checked value="1" readonly />
    <br/>
    <input name="chkBox_2" type="checkbox" value="1" readonly />
    <br/>
    <input id="submitBttn" type="button" value="Submit">
</form>

CSS :

input[type="checkbox"][readonly] {
  pointer-events: none;
}

Demo

Equivalent of *Nix 'which' command in PowerShell?

Here is an actual *nix equivalent, i.e. it gives *nix-style output.

Get-Command <your command> | Select-Object -ExpandProperty Definition

Just replace with whatever you're looking for.

PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe

When you add it to your profile, you will want to use a function rather than an alias because you can't use aliases with pipes:

function which($name)
{
    Get-Command $name | Select-Object -ExpandProperty Definition
}

Now, when you reload your profile you can do this:

PS C:\> which notepad
C:\Windows\system32\notepad.exe

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

had the same issue. I had imported a newer version of json library (deleted the old one - but not removed it from the build path). Resolved it by removing the reference to the old one from the build path

Rounding a double to turn it into an int (java)

public static int round(double d) {
    if (d > 0) {
        return (int) (d + 0.5);
    } else {
        return (int) (d - 0.5);
    }
}

How to make a hyperlink in telegram without using bots?

On Telegram Desktop for macOS, the shortcuts differ. You can right-click a highlighted text, then hover over Transformations to see the available options:

macOS Telegram Desktop Formatting Shortcuts

HTTP Error 500.30 - ANCM In-Process Start Failure

I looked at the Windows Logs under Application. It displayed the error message and stack trace. I found out I was missing a folder called node_modules. I created that folder and that fixed it.

I did not make any changes to web.config or the project file. My .NETCoreApp version was 3.1

How to format a number as percentage in R?

The tidyverse version is this:

> library(dplyr)
> library(scales)

> set.seed(1)
> m <- runif(5)
> dt <- as.data.frame(m)

> dt %>% mutate(perc=percent(m,accuracy=0.001))
          m    perc
1 0.2655087 26.551%
2 0.3721239 37.212%
3 0.5728534 57.285%
4 0.9082078 90.821%
5 0.2016819 20.168%

Looks tidy as usual.

Get refresh token google api

Found out by adding this to your url parameters

approval_prompt=force

Update:

Use access_type=offline&prompt=consent instead.

approval_prompt=force no longer works https://github.com/googleapis/oauth2client/issues/453