Programs & Examples On #Java server

DO NOT USE THIS TAG! "Java Server" is an incomplete term and makes therefore no sense as a tag and should be banned. Click "info" for alternate tags you're probably looking for.

How do you send a Firebase Notification to all devices via CURL?

Just make all users who log in subscribe to a specific topic, and then send a notification to that topic.

Maven2: Missing artifact but jars are in place

M2Eclipse sometimes does that. Select Project > Clean ... from the Menu and everything will be fine after the rebuild

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

Generate a UUID on iOS from Swift

You could also just use the NSUUID API:

let uuid = NSUUID()

If you want to get the string value back out, you can use uuid.UUIDString.

Note that NSUUID is available from iOS 6 and up.

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

Seriously, the top answer is not working for me. tried cxf.version 2.4.1 and 3.0.10. and generate absolute path with wsdlLocation every times.

My solution is to use the wsdl2java command in the apache-cxf-3.0.10\bin\ with -wsdlLocation classpath:wsdl/QueryService.wsdl.

Detail:

    wsdl2java -encoding utf-8 -p com.jeiao.boss.testQueryService -impl -wsdlLocation classpath:wsdl/testQueryService.wsdl http://127.0.0.1:9999/platf/testQueryService?wsdl

CSS, Images, JS not loading in IIS

Try removing the staticContent section from your web.config.

<system.webServer>
    <staticContent>
        ...
    </staticContent>
</system.webServer>

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

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.

Count multiple columns with group by in one query

    SELECT SUM(Output.count),Output.attr 
FROM
(
    SELECT COUNT(column1  ) AS count,column1 AS attr FROM tab1 GROUP BY column1 
    UNION ALL
    SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
    UNION ALL
    SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output

    GROUP BY attr 

Not equal string

With Equals() you can also use a Yoda condition:

if ( ! "-1".Equals(myString) )

Store an array in HashMap

Yes, the Map interface will allow you to store Arrays as values. Here's a very simple example:

int[] val = {1, 2, 3};
Map<String, int[]> map = new HashMap<String, int[]>();
map.put("KEY1", val);

Also, depending on your use case you may want to look at the Multimap support offered by guava.

Laravel Request getting current path with query string

Laravel 4.5

Just use

Request::fullUrl()

It will return the full url

You can extract the Querystring with str_replace

str_replace(Request::url(), '', Request::fullUrl())

Or you can get a array of all the queries with

Request::query()

Laravel >5.1

Just use

$request->fullUrl()

It will return the full url

You can extract the Querystring with str_replace

str_replace($request->url(), '',$request->fullUrl())

Or you can get a array of all the queries with

$request->query()

How to loop through all but the last item of a list?

This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:

zip(*(l[start:] for start in range(0, n)))

Examples:

l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

  • l[start:] generates a a list/generator starting from index start
  • *list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)

Note:

AFAIK, this code is as lazy as it can be. Not tested.

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);

How to use Java property files?

In Java 8 to get all your properties

public static Map<String, String> readPropertiesFile(String location) throws Exception {

    Map<String, String> properties = new HashMap<>();

    Properties props = new Properties();
    props.load(new FileInputStream(new File(location)));

    props.forEach((key, value) -> {
        properties.put(key.toString(), value.toString());
    });

    return properties;
}

How do I execute a program from Python? os.system fails due to spaces in path

subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.

import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

Angular 5 Service to read local .json file

I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".

Just call require:

const content = require('../../path_of_your.json');

The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrl property by template and the value by a require call to the actual HTML resource.

If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json:

"compilerOptions": {
  "types": ["node"],
  ...
},
...

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

I've work a little workarround without jquery. Not perfert but works fine (especially if you have a scroll-x in a scoll-y) https://github.com/pinadesign/overscroll/

Fell free to participate and improve it

How to compare times in Python?

You Can Use Timedelta fuction for x time increase comparision.

>>> import datetime 

>>> now = datetime.datetime.now()
>>> after_10_min = now + datetime.timedelta(minutes = 10)
>>> now > after_10_min 

False

Just A combination of these answers this And Roger

Displaying Image in Java

import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class DisplayImage {

    public static void main(String avg[]) throws IOException
    {
        DisplayImage abc=new DisplayImage();
    }

    public DisplayImage() throws IOException
    {
        BufferedImage img=ImageIO.read(new File("f://images.jpg"));
        ImageIcon icon=new ImageIcon(img);
        JFrame frame=new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setSize(200,300);
        JLabel lbl=new JLabel();
        lbl.setIcon(icon);
        frame.add(lbl);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

CSV parsing in Java - working example..?

There is a serious problem with using

String[] strArr=line.split(",");

in order to parse CSV files, and that is because there can be commas within the data values, and in that case you must quote them, and ignore commas between quotes.

There is a very very simple way to parse this:

/**
* returns a row of values as a list
* returns null if you are past the end of the input stream
*/
public static List<String> parseLine(Reader r) throws Exception {
    int ch = r.read();
    while (ch == '\r') {
        //ignore linefeed chars wherever, particularly just before end of file
        ch = r.read();
    }
    if (ch<0) {
        return null;
    }
    Vector<String> store = new Vector<String>();
    StringBuffer curVal = new StringBuffer();
    boolean inquotes = false;
    boolean started = false;
    while (ch>=0) {
        if (inquotes) {
            started=true;
            if (ch == '\"') {
                inquotes = false;
            }
            else {
                curVal.append((char)ch);
            }
        }
        else {
            if (ch == '\"') {
                inquotes = true;
                if (started) {
                    // if this is the second quote in a value, add a quote
                    // this is for the double quote in the middle of a value
                    curVal.append('\"');
                }
            }
            else if (ch == ',') {
                store.add(curVal.toString());
                curVal = new StringBuffer();
                started = false;
            }
            else if (ch == '\r') {
                //ignore LF characters
            }
            else if (ch == '\n') {
                //end of a line, break out
                break;
            }
            else {
                curVal.append((char)ch);
            }
        }
        ch = r.read();
    }
    store.add(curVal.toString());
    return store;
}

There are many advantages to this approach. Note that each character is touched EXACTLY once. There is no reading ahead, pushing back in the buffer, etc. No searching ahead to the end of the line, and then copying the line before parsing. This parser works purely from the stream, and creates each string value once. It works on header lines, and data lines, you just deal with the returned list appropriate to that. You give it a reader, so the underlying stream has been converted to characters using any encoding you choose. The stream can come from any source: a file, a HTTP post, an HTTP get, and you parse the stream directly. This is a static method, so there is no object to create and configure, and when this returns, there is no memory being held.

You can find a full discussion of this code, and why this approach is preferred in my blog post on the subject: The Only Class You Need for CSV Files.

How do I fetch lines before/after the grep result in bash?

Try this:

grep -i -A 10 "my_regex"

-A 10 means, print ten lines after match to "my_regex"

python 2.7: cannot pip on windows "bash: pip: command not found"

I had a similar problem running SciPy on my computer. There are two ways to fix this problem: 1. Yes you do need to cd into your python directory. 2. Sometimes you have to tell the computer explicitly what path to go through, you have to find the program you're using, open up the properties, and reroute the path it takes to run. 3. consult the manual: http://matplotlib.org/users/installing.html or http://www.scipy.org/install.html

the Scipy package is very finicky, and needs things spelled out in obnoxious detail.

How do I write dispatch_after GCD in Swift 3, 4, and 5?

A somewhat different flavour of the Accepted Answer.

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1 + .milliseconds(500) + 
.microseconds(500) + .nanoseconds(1000)) {
                print("Delayed by 0.1 second + 500 milliseconds + 500 microseconds + 
                      1000 nanoseconds)")
 }

How can I simulate an array variable in MySQL?

Try using FIND_IN_SET() function of MySql e.g.

SET @c = 'xxx,yyy,zzz';

SELECT * from countries 
WHERE FIND_IN_SET(countryname,@c);

Note: You don't have to SET variable in StoredProcedure if you are passing parameter with CSV values.

How to get the top position of an element?

$("#myTable").offset().top;

This will give you the computed offset (relative to document) of any object.

Reading HTTP headers in a Spring REST controller

Instead of taking the HttpServletRequest object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.

public class OAuth2ClientController {
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private HttpServletRequest request;

    @Autowired
    public OAuth2ClientController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("Content-Type"));

        return ResponseEntity.ok();
    }
}

How should I use Outlook to send code snippets?

If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.

With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.

Below is the summary of the style I have defined for emailing the code snippets.

Do not check spelling or grammar, Border:
Box: (Single solid line, Orange,  0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

I had to use Take(n) method, then transform to list, Worked like a charm:

    var listTest = (from x in table1
                     join y in table2
                     on x.field1 equals y.field1
                     orderby x.id descending
                     select new tempList()
                     {
                         field1 = y.field1,
                         active = x.active
                     }).Take(10).ToList();

What does Java option -Xmx stand for?

C:\java -X

    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.

The -X options are non-standard and subject to change without notice.

String to HtmlDocument

You could try with OpenNew and then with Write but that's a bit strange use of that class. More info on MSDN.

smooth scroll to top

Hmm comment function off for me,

try this

_x000D_
_x000D_
$(document).ready(function(){
    $("#top").hide();
    $(function toTop() {
        $(window).scroll(function () {
            if ($(this).scrollTop() > 100) {
                $('#top').fadeIn();
            } else {
                $('#top').fadeOut();
            }
        });

        $('#top').click(function () {
            $('body,html').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    });         
            
            
    
    });
_x000D_
#top {
  float:right;
  width:39px;
  margin-top:-35px; 
}
#top {
    transition: all 0.5s ease 0s;
    -moz-transition: all 0.5s ease 0s;
    -webkit-transition: all 0.5s ease 0s;
    -o-transition: all 0.5s ease 0s;
    opacity: 0.5;
    display:none;
    cursor: pointer;
}
#top:hover {
    opacity: 1;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="top" onclick="toTop()"><img src="to_top.png" alt="no pic "/> klick to top</div>
_x000D_
_x000D_
_x000D_

How to convert CSV file to multiline JSON?

How about using Pandas to read the csv file into a DataFrame (pd.read_csv), then manipulating the columns if you want (dropping them or updating values) and finally converting the DataFrame back to JSON (pd.DataFrame.to_json).

Note: I haven't checked how efficient this will be but this is definitely one of the easiest ways to manipulate and convert a large csv to json.

enumerate() for dictionary in python

dict1={'a':1, 'b':'banana'}

To list the dictionary in Python 2.x:

for k,v in dict1.iteritems():
        print k,v 

In Python 3.x use:

for k,v in dict1.items():
        print(k,v)
# a 1
# b banana

Finally, as others have indicated, if you want a running index, you can have that too:

for i  in enumerate(dict1.items()):
   print(i)  

 # (0, ('a', 1))
 # (1, ('b', 'banana'))

But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use OrderedDict instead.

ArrayList filter

In , they introduced the method removeIf which takes a Predicate as parameter.

So it will be easy as:

List<String> list = new ArrayList<>(Arrays.asList("How are you",
                                                  "How you doing",
                                                  "Joe",
                                                  "Mike"));
list.removeIf(s -> !s.contains("How"));

qmake: could not find a Qt installation of ''

You could check path to qmake using which qmake.

Consider install qt4-default or qt5-default depends what version of qt you want use.

You could also use qtchooser - a wrapper used to select between Qt development binary versions.

When to use .First and when to use .FirstOrDefault with LINQ?

Others have very well described the difference between First() and FirstOrDefault(). I want to take a further step in interpreting the semantics of these methods. In my opinion FirstOrDefault is being overused a lot. In the majority of the cases when you’re filtering data you would either expect to get back a collection of elements matching the logical condition or a single unique element by its unique identifier – such as a user, book, post etc... That’s why we can even get as far as saying that FirstOrDefault() is a code smell not because there is something wrong with it but because it’s being used way too often. This blog post explores the topic in details. IMO most of the times SingleOrDefault() is a much better alternative so watch out for this mistake and make sure you use the most appropriate method that clearly represents your contract and expectations.

mailto link multiple body lines

This is what I do, just add \n and use encodeURIComponent

Example

var emailBody = "1st line.\n 2nd line \n 3rd line";

emailBody = encodeURIComponent(emailBody);

href = "mailto:[email protected]?body=" + emailBody;

Check encodeURIComponent docs

How can I switch to another branch in git?

Useful commands to work in daily life:

git checkout -b "branchname" ->  creates new branch
git branch                   ->  lists all branches
git checkout "branchname"    ->  switches to your branch
git push origin "branchname" ->  Pushes to your branch
git add */filename           -> Stages *(All files) or by given file name
git commit -m "commit message" -> Commits staged files
git push                     -> Pushes to your current branch

If you want to merge to dev from feature branch, First check out dev branch with command "git branch dev/develop" Then enter merge commadn "git merge featurebranchname"

handling dbnull data in vb.net

I think this should be much easier to use:

select ISNULL(sum(field),0) from tablename

Copied from: http://www.codeproject.com/Questions/736515/How-do-I-avoide-Conversion-from-type-DBNull-to-typ

find without recursion

If you look for POSIX compliant solution:

cd DirsRoot && find . -type f -print -o -name . -o -prune

-maxdepth is not POSIX compliant option.

Checking if an input field is required using jQuery

A little bit of a more complete answer, inspired by the accepted answer:

$( '#form_id' ).submit( function( event ) {
        event.preventDefault();

        //validate fields
        var fail = false;
        var fail_log = '';
        var name;
        $( '#form_id' ).find( 'select, textarea, input' ).each(function(){
            if( ! $( this ).prop( 'required' )){

            } else {
                if ( ! $( this ).val() ) {
                    fail = true;
                    name = $( this ).attr( 'name' );
                    fail_log += name + " is required \n";
                }

            }
        });

        //submit if fail never got set to true
        if ( ! fail ) {
            //process form here.
        } else {
            alert( fail_log );
        }

});

In this case we loop all types of inputs and if they are required, we check if they have a value, and if not, a notice that they are required is added to the alert that will run.

Note that this, example assumes the form will be proceed inside the positive conditional via AJAX or similar. If you are submitting via traditional methods, move the second line, event.preventDefault(); to inside the negative conditional.

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

Where you have written the code

public class Main {
    public static void main(String args[])
    {
        Calculate obj = new Calculate(1,2,'+');
        obj.getAnswer();
    }
}

Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.

Simple dynamic breadcrumb

This may be overkill for a simple breadcrumb, but it's worth a shot. I remember having this issue a long time ago when I first started, but I never really solved it. That is, until I just decided to write this up now. :)

I have documented as best I can inline, at the bottom are 3 possible use cases. Enjoy! (feel free to ask any questions you may have)

<?php

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' &raquo; ', $home = 'Home') {
    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array("<a href=\"$base\">$home</a>");

    // Find out the index for the last value in our path array
    $last = end(array_keys($path));

    // Build the rest of the breadcrumbs
    foreach ($path AS $x => $crumb) {
        // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
        $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));

        // If we are not on the last index, then display an <a> tag
        if ($x != $last)
            $breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
        // Otherwise, just display the title (minus)
        else
            $breadcrumbs[] = $title;
    }

    // Build our temporary array (pieces of bread) into one big string :)
    return implode($separator, $breadcrumbs);
}

?>

<p><?= breadcrumbs() ?></p>
<p><?= breadcrumbs(' > ') ?></p>
<p><?= breadcrumbs(' ^^ ', 'Index') ?></p>

Regex - how to match everything except a particular pattern

My answer here might solve your problem as well:

https://stackoverflow.com/a/27967674/543814

  • Instead of Replace, you would use Match.
  • Instead of group $1, you would read group $2.
  • Group $2 was made non-capturing there, which you would avoid.

Example:

Regex.Match("50% of 50% is 25%", "(\d+\%)|(.+?)");

The first capturing group specifies the pattern that you wish to avoid. The last capturing group captures everything else. Simply read out that group, $2.

What is the advantage of using heredoc in PHP?

Some IDEs highlight the code in heredoc strings automatically - which makes using heredoc for XML or HTML visually appealing.

I personally like it for longer parts of i.e. XML since I don't have to care about quoting quote characters and can simply paste the XML.

Convert a Unicode string to a string in Python (containing extra symbols)

Well, if you're willing/ready to switch to Python 3 (which you may not be due to the backwards incompatibility with some Python 2 code), you don't have to do any converting; all text in Python 3 is represented with Unicode strings, which also means that there's no more usage of the u'<text>' syntax. You also have what are, in effect, strings of bytes, which are used to represent data (which may be an encoded string).

http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

(Of course, if you're currently using Python 3, then the problem is likely something to do with how you're attempting to save the text to a file.)

making a paragraph in html contain a text from a file

I would use javascript for this.

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
  if (txtFile.readyState === 4 && txtFile.status == 200) {
     allText = txtFile.responseText;
  }
document.getElementById('your div id').innerHTML = allText;

This is just a code sample, would need tweaking for all browsers, etc.

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

boundingRectWithSize for NSAttributedString returning wrong size

I didn't have luck with any of these suggestions. My string contained unicode bullet points and I suspect they were causing grief in the calculation. I noticed UITextView was handling the drawing fine, so I looked to that to leverage its calculation. I did the following, which is probably not as optimal as the NSString drawing methods, but at least it's accurate. It's also slightly more optimal than initialising a UITextView just to call -sizeThatFits:.

NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(width, CGFLOAT_MAX)];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[layoutManager addTextContainer:textContainer];

NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:formattedString];
[textStorage addLayoutManager:layoutManager];

const CGFloat formattedStringHeight = ceilf([layoutManager usedRectForTextContainer:textContainer].size.height);

Delete duplicate records from a SQL table without a primary key

there are two columns in the a table ID and name where names are repeating with different IDs so for that you may use this query: . .

DELETE FROM dbo.tbl1
WHERE id NOT IN (
     Select MIN(Id) AS namecount FROM tbl1
     GROUP BY Name
)

CSS3 Rotate Animation

Here this should help you

The below jsfiddle link will help you understand how to rotate a image.I used the same one to rotate the dial of a clock.

http://jsfiddle.net/xw89p/

var rotation = function (){
   $("#image").rotate({
      angle:0, 
      animateTo:360, 
      callback: rotation,
      easing: function (x,t,b,c,d){       
          return c*(t/d)+b;
      }
   });
}
rotation();

Where: • t: current time,

• b: begInnIng value,

• c: change In value,

• d: duration,

• x: unused

No easing (linear easing): function(x, t, b, c, d) { return b+(t/d)*c ; }

else & elif statements not working in Python

indentation is important in Python. Your if else statement should be within triple arrow (>>>), In Mac python IDLE version 3.7.4 elif statement doesn't comes with correct indentation when you go on next line you have to shift left to avoid syntax error.

enter image description here

Place API key in Headers or URL

I would not put the key in the url, as it does violate this loose 'standard' that is REST. However, if you did, I would place it in the 'user' portion of the url.

eg: http://[email protected]/myresource/myid

This way it can also be passed as headers with basic-auth.

jQuery - Getting the text value of a table cell in the same row as a clicked element

This will also work

$(this).parent().parent().find('td').text()

.htaccess redirect www to non-www with SSL/HTTPS

Certificate must cover both www and non-www https. Some provider's certs cover both for www.xxxx.yyy, but only one for xxxx.yyy.

Turn on rewrites:

RewriteEngine On

Make all http use https:

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://xxx.yyy/$1 [L,R=301]

Make only www https use the non-www https:

RewriteCond %{SERVER_PORT} 443
RewriteCond %{HTTP_HOST} ^www[.].+$
RewriteRule ^(.*)$ https://xxxx.yyy/$1 [L,R=301]

Cannot be processing non-www https, otherwise a loop occurs.

In [L,R=301]:

  1. L = If the rule was processed, don't process any more.
  2. R=301 = Tells browser/robot to do a permanent redirect.

More generic

A more generic approach -- not port-dependant -- is:

RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ https://xxxx.yyy/$1 [R=301,QSA]

to make any url with www drop it.

RewriteCond %{HTTPS} !on
RewriteCond %{HTTPS} !1
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteRule ^(.*)$ https://xxxx.yyy/$1 [R=301,QSA]

to force any non-https url, even for those system downstream from load-balancers that drop https, use https.

Note that I have not tested the forwarded options, so would appreciate feedback on any issues with them. Those lines could be left out if your system is not behind a load-balancer.

TO HTTP_HOST or not

You can use ${HTTP_HOST} to be part of the URL in the RewriteRule, or you can use your explicit canonical domain name text (xxxx.yyy above).

Specifying the domain name explicitly ensures that no slight-of-hand character-bending means are used in the user-supplied URL to possibly trick your site into doing something it might not be prepared for, or at least ensures that the proper domain name appears in the address bar, regardless of which URL string opened the page.

It might even help convert punycode-encoded domains to show the proper unicode characters in the address bar.

How do I prevent Conda from activating the base environment by default?

There're 3 ways to achieve this after conda 4.6. (The last method has the highest priority.)

  1. Use sub-command conda config to change the setting.

    conda config --set auto_activate_base false
    
  2. In fact, the former conda config sub-command is changing configuration file .condarc. We can modify .condarc directly. Add following content into .condarc under your home directory,

    # auto_activate_base (bool)
    #   Automatically activate the base environment during shell
    #   initialization. for `conda init`
    auto_activate_base: false
    
  3. Set environment variable CONDA_AUTO_ACTIVATE_BASE in the shell's init file. (.bashrc for bash, .zshrc for zsh)

    CONDA_AUTO_ACTIVATE_BASE=false
    

    To convert from the condarc file-based configuration parameter name to the environment variable parameter name, make the name all uppercase and prepend CONDA_. For example, conda’s always_yes configuration parameter can be specified using a CONDA_ALWAYS_YES environment variable.

    The environment settings take precedence over corresponding settings in .condarc file.

References

Compiling a java program into an executable

We have found Jsmooth to be well-working and easily scriptable with ant under Linux. You may want to use one-jar (also easily scriptable with ant under Linux) to collect a multifile application in a single jar first.

We primarily needed the easy deployment of the EXE combined with the "hey, you need Java version X, go here to download" facilities.

(but what you most likely need is the "Runnable jar" / "Executable jar" facility in standard Java).

How to save a pandas DataFrame table as a png

The best solution to your problem is probably to first export your dataframe to HTML and then convert it using an HTML-to-image tool. The final appearance could be tweaked via CSS.

Popular options for HTML-to-image rendering include:


Let us assume we have a dataframe named df. We can generate one with the following code:

import string
import numpy as np
import pandas as pd


np.random.seed(0)  # just to get reproducible results from `np.random`
rows, cols = 5, 10
labels = list(string.ascii_uppercase[:cols])
df = pd.DataFrame(np.random.randint(0, 100, size=(5, 10)), columns=labels)
print(df)
#     A   B   C   D   E   F   G   H   I   J
# 0  44  47  64  67  67   9  83  21  36  87
# 1  70  88  88  12  58  65  39  87  46  88
# 2  81  37  25  77  72   9  20  80  69  79
# 3  47  64  82  99  88  49  29  19  19  14
# 4  39  32  65   9  57  32  31  74  23  35

Using WeasyPrint

This approach uses a pip-installable package, which will allow you to do everything using the Python ecosystem. One shortcoming of weasyprint is that it does not seem to provide a way of adapting the image size to its content. Anyway, removing some background from an image is relatively easy in Python / PIL, and it is implemented in the trim() function below (adapted from here). One also would need to make sure that the image will be large enough, and this can be done with CSS's @page size property.

The code follows:

import weasyprint as wsp
import PIL as pil


def trim(source_filepath, target_filepath=None, background=None):
    if not target_filepath:
        target_filepath = source_filepath
    img = pil.Image.open(source_filepath)
    if background is None:
        background = img.getpixel((0, 0))
    border = pil.Image.new(img.mode, img.size, background)
    diff = pil.ImageChops.difference(img, border)
    bbox = diff.getbbox()
    img = img.crop(bbox) if bbox else img
    img.save(target_filepath)


img_filepath = 'table1.png'
css = wsp.CSS(string='''
@page { size: 2048px 2048px; padding: 0px; margin: 0px; }
table, td, tr, th { border: 1px solid black; }
td, th { padding: 4px 8px; }
''')
html = wsp.HTML(string=df.to_html())
html.write_png(img_filepath, stylesheets=[css])
trim(img_filepath)

table_weasyprint


Using wkhtmltopdf/wkhtmltoimage

This approach uses an external open source tool and this needs to be installed prior to the generation of the image. There is also a Python package, pdfkit, that serves as a front-end to it (it does not waive you from installing the core software yourself), but I will not use it.

wkhtmltoimage can be simply called using subprocess (or any other similar means of running an external program in Python). One would also need to output to disk the HTML file.

The code follows:

import subprocess


df.to_html('table2.html')
subprocess.call(
    'wkhtmltoimage -f png --width 0 table2.html table2.png', shell=True)

table_wkhtmltoimage

and its aspect could be further tweaked with CSS similarly to the other approach.


Parse JSON in C#

Your data class doesn't match the JSON object. Use this instead:

[DataContract]
public class GoogleSearchResults
{
    [DataMember]
    public ResponseData responseData { get; set; }
}

[DataContract]
public class ResponseData
{
    [DataMember]
    public IEnumerable<Results> results { get; set; }
}

[DataContract]
public class Results
{
    [DataMember]
    public string unescapedUrl { get; set; }

    [DataMember]
    public string url { get; set; }

    [DataMember]
    public string visibleUrl { get; set; }

    [DataMember]
    public string cacheUrl { get; set; }

    [DataMember]
    public string title { get; set; }

    [DataMember]
    public string titleNoFormatting { get; set; }

    [DataMember]
    public string content { get; set; }
}

Also, you don't have to instantiate the class to get its type for deserialization:

public static T Deserialise<T>(string json)
{
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        var serialiser = new DataContractJsonSerializer(typeof(T));
        return (T)serialiser.ReadObject(ms);
    }
}

How to directly execute SQL query in C#?

IMPORTANT NOTE: You should not concatenate SQL queries unless you trust the user completely. Query concatenation involves risk of SQL Injection being used to take over the world, ...khem, your database.

If you don't want to go into details how to execute query using SqlCommand then you could call the same command line like this:

string userInput = "Brian";
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format(@"sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS  
     -s ; -W -w 100 -Q "" SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName,
     tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '{0}' """, userInput);

process.StartInfo = startInfo;
process.Start();

Just ensure that you escape each double quote " with ""

How can I output a UTF-8 CSV in PHP that Excel will read properly?

How about just outputting for Excel itself? This is an excellent class that allows you to generate XLS files server-side. I use it frequently for clients who can't "figure out" csv's and so far have never had a complaint. It also allows some extra formatting (shading, rowheights, calculations, etc) that csv won't ever do.

PHP checkbox set to check based on database value

Add this code inside your input tag

<?php if ($tag_1 == 'yes') echo "checked='checked'"; ?>

What is a MIME type?

A MIME type is a label used to identify a type of data. It is used so software can know how to handle the data. It serves the same purpose on the Internet that file extensions do on Microsoft Windows.

So if a server says "This is text/html" the client can go "Ah, this is an HTML document, I can render that internally", while if the server says "This is application/pdf" the client can go "Ah, I need to launch the FoxIt PDF Reader plugin that the user has installed and that has registered itself as the application/pdf handler."

You'll most commonly find them in the headers of HTTP messages (to describe the content that an HTTP server is responding with or the formatting of the data that is being POSTed in a request) and in email headers (to describe the message format and attachments).

How to programmatically set cell value in DataGridView?

I tried a lot of methods, and the only one which worked was UpdateCellValue:

dataGridView.Rows[rowIndex].Cells[columnIndex].Value = "New Value";
dataGridView.UpdateCellValue(columnIndex, rowIndex);

I hope to have helped. =)

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

Returning a promise in an async function in TypeScript

It's complicated.

First of all, in this code

const p = new Promise((resolve) => {
    resolve(4);
});

the type of p is inferred as Promise<{}>. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p should be Promise<number>.

Then, Promise<{}> is compatible with Promise<number>, because basically the only property a promise has is then method, and then is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1.

But the purpose of async is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2 because {} is obvioulsy not compatible with number.

So the async behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:

const whatever2 = async (): Promise<number> => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

Table Height 100% inside Div element

You need to have a height in the div <div style="overflow:hidden"> else it doesnt know what 100% is.

jQuery: how to find first visible input/select/textarea excluding buttons?

You may try below code...

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('form').find('input[type=text],textarea,select').filter(':visible:first').focus();_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>_x000D_
<form>_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
    _x000D_
<input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

To capture several parameters using the same name, I modified the while loop in Tomalak's method like this:

  while (match = re.exec(url)) {
    var pName = decode(match[1]);
    var pValue = decode(match[2]);
    params[pName] ? params[pName].push(pValue) : params[pName] = [pValue];
  }

input: ?firstname=george&lastname=bush&firstname=bill&lastname=clinton

returns: {firstname : ["george", "bill"], lastname : ["bush", "clinton"]}

Firebase TIMESTAMP to date and Time

timestamp is an object

_x000D_
_x000D_
timestamp= {nanoseconds: 0,_x000D_
seconds: 1562524200}_x000D_
_x000D_
console.log(new Date(timestamp.seconds*1000))
_x000D_
_x000D_
_x000D_

"R cannot be resolved to a variable"?

When other solutions fail, select your project and delete it. MAKE SURE YOU DO NOT REMOVE FILES FROM DISK.

Then use file>import>existing android code into workspace, and select the location of your project.

Splitting dataframe into multiple dataframes

Easy:

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

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

OK!

The code below is written using ES6 syntaxes but could just as easily be written in ES5 or even less. ES6 is not a requirement to create a "mechanism to loop x times"


If you don't need the iterator in the callback, this is the most simple implementation

_x000D_
_x000D_
const times = x => f => {_x000D_
  if (x > 0) {_x000D_
    f()_x000D_
    times (x - 1) (f)_x000D_
  }_x000D_
}_x000D_
_x000D_
// use it_x000D_
times (3) (() => console.log('hi'))_x000D_
_x000D_
// or define intermediate functions for reuse_x000D_
let twice = times (2)_x000D_
_x000D_
// twice the power !_x000D_
twice (() => console.log('double vision'))
_x000D_
_x000D_
_x000D_

If you do need the iterator, you can use a named inner function with a counter parameter to iterate for you

_x000D_
_x000D_
const times = n => f => {_x000D_
  let iter = i => {_x000D_
    if (i === n) return_x000D_
    f (i)_x000D_
    iter (i + 1)_x000D_
  }_x000D_
  return iter (0)_x000D_
}_x000D_
_x000D_
times (3) (i => console.log(i, 'hi'))
_x000D_
_x000D_
_x000D_


Stop reading here if you don't like learning more things ...

But something should feel off about those...

  • single branch if statements are ugly — what happens on the other branch ?
  • multiple statements/expressions in the function bodies — are procedure concerns being mixed ?
  • implicitly returned undefined — indication of impure, side-effecting function

"Isn't there a better way ?"

There is. Let's first revisit our initial implementation

// times :: Int -> (void -> void) -> void
const times = x => f => {
  if (x > 0) {
    f()               // has to be side-effecting function
    times (x - 1) (f)
  }
}

Sure, it's simple, but notice how we just call f() and don't do anything with it. This really limits the type of function we can repeat multiple times. Even if we have the iterator available, f(i) isn't much more versatile.

What if we start with a better kind of function repetition procedure ? Maybe something that makes better use of input and output.

Generic function repetition

_x000D_
_x000D_
// repeat :: forall a. Int -> (a -> a) -> a -> a_x000D_
const repeat = n => f => x => {_x000D_
  if (n > 0)_x000D_
    return repeat (n - 1) (f) (f (x))_x000D_
  else_x000D_
    return x_x000D_
}_x000D_
_x000D_
// power :: Int -> Int -> Int_x000D_
const power = base => exp => {_x000D_
  // repeat <exp> times, <base> * <x>, starting with 1_x000D_
  return repeat (exp) (x => base * x) (1)_x000D_
}_x000D_
_x000D_
console.log(power (2) (8))_x000D_
// => 256
_x000D_
_x000D_
_x000D_

Above, we defined a generic repeat function which takes an additional input which is used to start the repeated application of a single function.

// repeat 3 times, the function f, starting with x ...
var result = repeat (3) (f) (x)

// is the same as ...
var result = f(f(f(x)))

Implementing times with repeat

Well this is easy now; almost all of the work is already done.

_x000D_
_x000D_
// repeat :: forall a. Int -> (a -> a) -> a -> a_x000D_
const repeat = n => f => x => {_x000D_
  if (n > 0)_x000D_
    return repeat (n - 1) (f) (f (x))_x000D_
  else_x000D_
    return x_x000D_
}_x000D_
_x000D_
// times :: Int -> (Int -> Int) -> Int _x000D_
const times = n=> f=>_x000D_
  repeat (n) (i => (f(i), i + 1)) (0)_x000D_
_x000D_
// use it_x000D_
times (3) (i => console.log(i, 'hi'))
_x000D_
_x000D_
_x000D_

Since our function takes i as an input and returns i + 1, this effectively works as our iterator which we pass to f each time.

We've fixed our bullet list of issues too

  • No more ugly single branch if statements
  • Single-expression bodies indicate nicely separated concerns
  • No more useless, implicitly returned undefined

JavaScript comma operator, the

In case you're having trouble seeing how the last example is working, it depends on your awareness of one of JavaScript's oldest battle axes; the comma operator – in short, it evaluates expressions from left to right and returns the value of the last evaluated expression

(expr1 :: a, expr2 :: b, expr3 :: c) :: c

In our above example, I'm using

(i => (f(i), i + 1))

which is just a succinct way of writing

(i => { f(i); return i + 1 })

Tail Call Optimisation

As sexy as the recursive implementations are, at this point it would be irresponsible for me to recommend them given that no JavaScript VM I can think of supports proper tail call elimination – babel used to transpile it, but it's been in "broken; will reimplement" status for well over a year.

repeat (1e6) (someFunc) (x)
// => RangeError: Maximum call stack size exceeded

As such, we should revisit our implementation of repeat to make it stack-safe.

The code below does use mutable variables n and x but note that all mutations are localized to the repeat function – no state changes (mutations) are visible from outside of the function

_x000D_
_x000D_
// repeat :: Int -> (a -> a) -> (a -> a)_x000D_
const repeat = n => f => x =>_x000D_
  {_x000D_
    let m = 0, acc = x_x000D_
    while (m < n)_x000D_
      (m = m + 1, acc = f (acc))_x000D_
    return acc_x000D_
  }_x000D_
_x000D_
// inc :: Int -> Int_x000D_
const inc = x =>_x000D_
  x + 1_x000D_
_x000D_
console.log (repeat (1e8) (inc) (0))_x000D_
// 100000000
_x000D_
_x000D_
_x000D_

This is going to have a lot of you saying "but that's not functional !" – I know, just relax. We can implement a Clojure-style loop/recur interface for constant-space looping using pure expressions; none of that while stuff.

Here we abstract while away with our loop function – it looks for a special recur type to keep the loop running. When a non-recur type is encountered, the loop is finished and the result of the computation is returned

_x000D_
_x000D_
const recur = (...args) =>_x000D_
  ({ type: recur, args })_x000D_
  _x000D_
const loop = f =>_x000D_
  {_x000D_
    let acc = f ()_x000D_
    while (acc.type === recur)_x000D_
      acc = f (...acc.args)_x000D_
    return acc_x000D_
  }_x000D_
_x000D_
const repeat = $n => f => x =>_x000D_
  loop ((n = $n, acc = x) =>_x000D_
    n === 0_x000D_
      ? acc_x000D_
      : recur (n - 1, f (acc)))_x000D_
      _x000D_
const inc = x =>_x000D_
  x + 1_x000D_
_x000D_
const fibonacci = $n =>_x000D_
  loop ((n = $n, a = 0, b = 1) =>_x000D_
    n === 0_x000D_
      ? a_x000D_
      : recur (n - 1, b, a + b))_x000D_
      _x000D_
console.log (repeat (1e7) (inc) (0)) // 10000000_x000D_
console.log (fibonacci (100))        // 354224848179262000000
_x000D_
_x000D_
_x000D_

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.

Remove a folder from git tracking

To forget directory recursively add /*/* to the path:

git update-index --assume-unchanged wordpress/wp-content/uploads/*/*

Using git rm --cached is not good for collaboration. More details here: How to stop tracking and ignore changes to a file in Git?

Load a Bootstrap popover content with AJAX. Is this possible?

Works ok for me:

$('a.popup-ajax').popover({
    "html": true,
    "content": function(){
        var div_id =  "tmp-id-" + $.now();
        return details_in_popup($(this).attr('href'), div_id);
    }
});

function details_in_popup(link, div_id){
    $.ajax({
        url: link,
        success: function(response){
            $('#'+div_id).html(response);
        }
    });
    return '<div id="'+ div_id +'">Loading...</div>';
}

Get a random boolean in python?

random.choice([True, False])

would also work.

How to Use -confirm in PowerShell

Read-Host is one example of a cmdlet that -Confirm does not have an effect on.-Confirm is one of PowerShell's Common Parameters specifically a Risk-Mitigation Parameter which is used when a cmdlet is about to make a change to the system that is outside of the Windows PowerShell environment. Many but not all cmdlets support the -Confirm risk mitigation parameter.

As an alternative the following would be an example of using the Read-Host cmdlet and a regular expression test to get confirmation from a user:

$reply = Read-Host -Prompt "Continue?[y/n]"
if ( $reply -match "[yY]" ) { 
    # Highway to the danger zone 
}

The Remove-Variable cmdlet is one example that illustrates the usage of the -confirm switch.

Remove-Variable 'reply' -Confirm

Additional References: CommonParameters, Write-Host, Read-Host, Comparison Operators, Regular Expressions, Remove-Variable

RegEx to parse or validate Base64 data

Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com line. In Perl, say, something like

my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;

say decode_base64($sanitized_str);

might be what you want. It produces

This is simple ASCII Base64 for StackOverflow exmaple.

mongo - couldn't connect to server 127.0.0.1:27017

This is an old question, but, as a newbie I figured I'd add that (using Webstorm) you need to click on Mongo Explorer (tab on far right hand side of your window). From there:

-Click settings. -Click browse button (looks like a button with "..." on it). -Go to Program Files > MongoDB > Server > 3.4 > bin > mongo.exe (your version maybe different than 3.4) -After that, click the green plus sign on the right. A window will open -Enter a name in "Label" slot. -Click apply.

You should now be connected. Entering "mongod" in the terminal isn't enough. You have to do the above steps also.

My apologies in advance to those of you who aren't using Webstorm! Not sure about the steps using other IDE's.

Is there an auto increment in sqlite?

What you do is correct, but the correct syntax for 'auto increment' should be without space:

CREATE TABLE people (id integer primary key autoincrement, first_name string, last_name string);

(Please also note that I changed your varchars to strings. That's because SQLite internally transforms a varchar into a string, so why bother?)

then your insert should be, in SQL language as standard as possible:

INSERT INTO people(id, first_name, last_name) VALUES (null, 'john', 'doe');

while it is true that if you omit id it will automatically incremented and assigned, I personally prefer not to rely on automatic mechanisms which could change in the future.

A note on autoincrement: although, as many pointed out, it is not recommended by SQLite people, I do not like the automatic reuse of ids of deleted records if autoincrement is not used. In other words, I like that the id of a deleted record will never, ever appear again.

HTH

Initial bytes incorrect after Java AES/CBC decryption

The IV that your using for decryption is incorrect. Replace this code

//Decrypt cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);

With this code

//Decrypt cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(encryptCipher.getIV());
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);

And that should solve your problem.


Below includes an example of a simple AES class in Java. I do not recommend using this class in production environments, as it may not account for all of the specific needs of your application.

import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AES 
{
    public static byte[] encrypt(final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
    {       
        return AES.transform(Cipher.ENCRYPT_MODE, keyBytes, ivBytes, messageBytes);
    }

    public static byte[] decrypt(final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
    {       
        return AES.transform(Cipher.DECRYPT_MODE, keyBytes, ivBytes, messageBytes);
    }

    private static byte[] transform(final int mode, final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        final SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        final IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        byte[] transformedBytes = null;

        try
        {
            final Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

            cipher.init(mode, keySpec, ivSpec);

            transformedBytes = cipher.doFinal(messageBytes);
        }        
        catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) 
        {
            e.printStackTrace();
        }
        return transformedBytes;
    }

    public static void main(final String[] args) throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        //Retrieved from a protected local file.
        //Do not hard-code and do not version control.
        final String base64Key = "ABEiM0RVZneImaq7zN3u/w==";

        //Retrieved from a protected database.
        //Do not hard-code and do not version control.
        final String shadowEntry = "AAECAwQFBgcICQoLDA0ODw==:ZtrkahwcMzTu7e/WuJ3AZmF09DE=";

        //Extract the iv and the ciphertext from the shadow entry.
        final String[] shadowData = shadowEntry.split(":");        
        final String base64Iv = shadowData[0];
        final String base64Ciphertext = shadowData[1];

        //Convert to raw bytes.
        final byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        final byte[] ivBytes = Base64.getDecoder().decode(base64Iv);
        final byte[] encryptedBytes = Base64.getDecoder().decode(base64Ciphertext);

        //Decrypt data and do something with it.
        final byte[] decryptedBytes = AES.decrypt(keyBytes, ivBytes, encryptedBytes);

        //Use non-blocking SecureRandom implementation for the new IV.
        final SecureRandom secureRandom = new SecureRandom();

        //Generate a new IV.
        secureRandom.nextBytes(ivBytes);

        //At this point instead of printing to the screen, 
        //one should replace the old shadow entry with the new one.
        System.out.println("Old Shadow Entry      = " + shadowEntry);
        System.out.println("Decrytped Shadow Data = " + new String(decryptedBytes, StandardCharsets.UTF_8));
        System.out.println("New Shadow Entry      = " + Base64.getEncoder().encodeToString(ivBytes) + ":" + Base64.getEncoder().encodeToString(AES.encrypt(keyBytes, ivBytes, decryptedBytes)));
    }
}

Note that AES has nothing to do with encoding, which is why I chose to handle it separately and without the need of any third party libraries.

Parse JSON String to JSON Object in C#.NET

Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

There is a System.Json.dll you should add to your project References.

-Jesse

Running conda with proxy

You can configure a proxy with conda by adding it to the .condarc, like

proxy_servers:
    http: http://user:[email protected]:8080
    https: https://user:[email protected]:8080

Then in cmd Anaconda Power Prompt (base) PS C:\Users\user> run:

conda update -n root conda

Getting the last element of a list

In Python, how do you get the last element of a list?

To just get the last element,

  • without modifying the list, and
  • assuming you know the list has a last element (i.e. it is nonempty)

pass -1 to the subscript notation:

>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

Explanation

Indexes and slices can take negative integers as arguments.

I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python", -1 references the last element, the character, 'n':

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

Assignment via iterable unpacking

This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable - not just lists):

>>> *head, last = a_list
>>> last
'three'

The variable name, head is bound to the unnecessary newly created list:

>>> head
['zero', 'one', 'two']

If you intend to do nothing with that list, this would be more apropos:

*_, last = a_list

Or, really, if you know it's a list (or at least accepts subscript notation):

last = a_list[-1]

In a function

A commenter said:

I wish Python had a function for first() and last() like Lisp does... it would get rid of a lot of unnecessary lambda functions.

These would be quite simple to define:

def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

Or use operator.itemgetter:

>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

In either case:

>>> last(a_list)
'three'
>>> first(a_list)
'zero'

Special cases

If you're doing something more complicated, you may find it more performant to get the last element in slightly different ways.

If you're new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together. If you change your algorithm in one place, it may have an unintended impact on another line of code.

I try to provide caveats and conditions as completely as I can, but I may have missed something. Please comment if you think I'm leaving a caveat out.

Slicing

A slice of a list returns a new list - so we can slice from -1 to the end if we are going to want the element in a new list:

>>> a_slice = a_list[-1:]
>>> a_slice
['three']

This has the upside of not failing if the list is empty:

>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

Whereas attempting to access by index raises an IndexError which would need to be handled:

>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

But again, slicing for this purpose should only be done if you need:

  • a new list created
  • and the new list to be empty if the prior list was empty.

for loops

As a feature of Python, there is no inner scoping in a for loop.

If you're performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:

>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...     
>>> item
'three'

This is not semantically the last thing in the list. This is semantically the last thing that the name, item, was bound to.

>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

Thus this should only be used to get the last element if you

  • are already looping, and
  • you know the loop will finish (not break or exit due to errors), otherwise it will point to the last element referenced by the loop.

Getting and removing it

We can also mutate our original list by removing and returning the last element:

>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

But now the original list is modified.

(-1 is actually the default argument, so list.pop can be used without an index argument):

>>> a_list.pop()
'two'

Only do this if

  • you know the list has elements in it, or are prepared to handle the exception if it is empty, and
  • you do intend to remove the last element from the list, treating it like a stack.

These are valid use-cases, but not very common.

Saving the rest of the reverse for later:

I don't know why you'd do it, but for completeness, since reversed returns an iterator (which supports the iterator protocol) you can pass its result to next:

>>> next(reversed([1,2,3]))
3

So it's like doing the reverse of this:

>>> next(iter([1,2,3]))
1

But I can't think of a good reason to do this, unless you'll need the rest of the reverse iterator later, which would probably look more like this:

reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

and now:

>>> use_later
[2, 1]
>>> last_element
3

How would I run an async Task<T> method synchronously?

Surprised no one mentioned this:

public Task<int> BlahAsync()
{
    // ...
}

int result = BlahAsync().GetAwaiter().GetResult();

Not as pretty as some of the other methods here, but it has the following benefits:

  • it doesn't swallow exceptions (like Wait)
  • it won't wrap any exceptions thrown in an AggregateException (like Result)
  • works for both Task and Task<T> (try it out yourself!)

Also, since GetAwaiter is duck-typed, this should work for any object that is returned from an async method (like ConfiguredAwaitable or YieldAwaitable), not just Tasks.


edit: Please note that it's possible for this approach (or using .Result) to deadlock, unless you make sure to add .ConfigureAwait(false) every time you await, for all async methods that can possibly be reached from BlahAsync() (not just ones it calls directly). Explanation.

// In BlahAsync() body
await FooAsync(); // BAD!
await FooAsync().ConfigureAwait(false); // Good... but make sure FooAsync() and
                                        // all its descendants use ConfigureAwait(false)
                                        // too. Then you can be sure that
                                        // BlahAsync().GetAwaiter().GetResult()
                                        // won't deadlock.

If you're too lazy to add .ConfigureAwait(false) everywhere, and you don't care about performance you can alternatively do

Task.Run(() => BlahAsync()).GetAwaiter().GetResult()

set initial viewcontroller in appdelegate - swift

I worked out a solution on Xcode 6.4 in swift. 

// I saved the credentials on a click event to phone memory

    @IBAction func gotobidderpage(sender: AnyObject) {
 if (usernamestring == "bidder" && passwordstring == "day303")
        {
            rolltype = "1"

NSUserDefaults.standardUserDefaults().setObject(usernamestring, forKey: "username")
NSUserDefaults.standardUserDefaults().setObject(passwordstring, forKey: "password")
NSUserDefaults.standardUserDefaults().setObject(rolltype, forKey: "roll")


            self.performSegueWithIdentifier("seguetobidderpage", sender: self)
}


// Retained saved credentials in app delegate.swift and performed navigation after condition check


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

let usernamestring = NSUserDefaults.standardUserDefaults().stringForKey("username")
let passwordstring = NSUserDefaults.standardUserDefaults().stringForKey("password")
let rolltypestring = NSUserDefaults.standardUserDefaults().stringForKey("roll")

        if (usernamestring == "bidder" && passwordstring == "day303" && rolltypestring == "1")
        {

            // Access the storyboard and fetch an instance of the view controller
            var storyboard = UIStoryboard(name: "Main", bundle: nil)
            var viewController: BidderPage = storyboard.instantiateViewControllerWithIdentifier("bidderpageID") as! BidderPage

            // Then push that view controller onto the navigation stack
            var rootViewController = self.window!.rootViewController as! UINavigationController
            rootViewController.pushViewController(viewController, animated: true)
        }

        // Override point for customization after application launch.
        return true
    }



Hope it helps !

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

How to sort a collection by date in MongoDB?

With mongoose I was not able to use 'toArray', and was getting the error: TypeError: Collection.find(...).sort(...).toArray is not a function. The toArray function exists on the Cursor class from the Native MongoDB NodeJS driver (reference).

Also sort accepts only one parameter, so you can't pass your function inside it.

This worked for me (as answered by Emil):

collection.find().sort('-date').exec(function(error, result) {
  // Your code
})

What does @@variable mean in Ruby?

@ and @@ in modules also work differently when a class extends or includes that module.

So given

module A
    @a = 'module'
    @@a = 'module'

    def get1
        @a          
    end     

    def get2
        @@a         
    end     

    def set1(a) 
        @a = a      
    end     

    def set2(a) 
        @@a = a     
    end     

    def self.set1(a)
        @a = a      
    end     

    def self.set2(a)
        @@a = a     
    end     
end 

Then you get the outputs below shown as comments

class X
    extend A

    puts get1.inspect # nil
    puts get2.inspect # "module"

    @a = 'class' 
    @@a = 'class' 

    puts get1.inspect # "class"
    puts get2.inspect # "module"

    set1('set')
    set2('set')

    puts get1.inspect # "set" 
    puts get2.inspect # "set" 

    A.set1('sset')
    A.set2('sset')

    puts get1.inspect # "set" 
    puts get2.inspect # "sset"
end 

class Y
    include A

    def doit
        puts get1.inspect # nil
        puts get2.inspect # "module"

        @a = 'class'
        @@a = 'class'

        puts get1.inspect # "class"
        puts get2.inspect # "class"

        set1('set')
        set2('set')

        puts get1.inspect # "set"
        puts get2.inspect # "set"

        A.set1('sset')
        A.set2('sset')

        puts get1.inspect # "set"
        puts get2.inspect # "sset"
    end
end

Y.new.doit

So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

An even easier solution, just iterate through all popovers and hide if not this.

$(document).on('click', '.popup-marker', function() {
    $(this).popover('toggle')
})

$(document).bind('click touchstart', function(e) {
    var target = $(e.target)[0];
    $('.popup-marker').each(function () {
        // hide any open popovers except for the one we've clicked
        if (!$(this).is(target)) {
            $(this).popover('hide');
        }
    });
});

Dynamically updating css in Angular 2

you can achive this by calling a function also

<div [style.width.px]="getCustomeWidth()"></div>

  getCustomeWidth() {
    //do what ever you want here
    return customeWidth;
  }

z-index not working with fixed positioning

When elements are positioned outside the normal flow, they can overlap other elements.

according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp

scroll image with continuous scrolling using marquee tag

You cannot scroll images continuously using the HTML marquee tag - it must have JavaScript added for the continuous scrolling functionality.

There is a JavaScript plugin called crawler.js available on the dynamic drive forum for achieving this functionality. This plugin was created by John Davenport Scheuer and has been modified over time to suit new browsers.

I have also implemented this plugin into my blog to document all the steps to use this plugin. Here is the sample code:

<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="assets/js/crawler.js" type="text/javascript" ></script>
</head>

<div id="mycrawler2" style="margin-top: -3px; " class="productswesupport">
    <img src="assets/images/products/ie.png" />
    <img src="assets/images/products/browser.png" />
    <img src="assets/images/products/chrome.png" />
    <img src="assets/images/products/safari.png" />
</div>

Here is the plugin configration:

marqueeInit({
    uniqueid: 'mycrawler2',
    style: {
    },
    inc: 5, //speed - pixel increment for each iteration of this marquee's movement
    mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
    moveatleast: 2,
    neutral: 150,
    savedirection: true,
    random: true
});

How to add a touch event to a UIView?

Seems quite simple these days. This is the Swift version.

let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
    view.addGestureRecognizer(tap)

@objc func viewTapped(recognizer: UIGestureRecognizer)
{
    //Do what you need to do!
}

Carriage Return\Line feed in Java

Encapsulate your writer to provide char replacement, like this:

public class WindowsFileWriter extends Writer {

    private Writer writer;

    public WindowsFileWriter(File file) throws IOException {
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
        } catch (UnsupportedEncodingException e) {
            writer = new FileWriter(logfile);
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
    }

    @Override
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }

}

Unbound classpath container in Eclipse

For those using sdkman, this helped me.

Use Case:
I was using identifier 8.0.202-amzn
I decided to install Azul Zulu as follows: sdk install java 13.0.2-zulu

Error: And then i got this unbound error.

Solution:
1. Right-click on your project in Eclipse/STS
2. Choose Build Path > Configure Build Path...
3. Under Libraries, remove the JRE Library, for my case 8.0.202-amzn
4. Under Libraries, click on Modulepath > Add Library...
5. Choose JRE System Library, click Next
6. Choose Alternate JRE, click on Installed JREs...
7. Your previous configured value should be there
8. If it is there, edit it, if it is not there, add one
9. Make sure the name is: 13.0.2-zulu
10. And the location(JRE home) is: /Users/jumping_monkey/.sdkman/candidates/java/current
11. Click Apply and close
12. Click Finish
13. Voila!

You will see JRE System Library [13.0.2-zulu] in your Project Explorer and all errors gone

Bravo!

Finding all positions of substring in a larger string in C#

I noticed that at least two proposed solutions don't handle overlapping search hits. I didn't check the one marked with the green checkmark. Here is one that handles overlapping search hits:

    public static List<int> GetPositions(this string source, string searchString)
    {
        List<int> ret = new List<int>();
        int len = searchString.Length;
        int start = -1;
        while (true)
        {
            start = source.IndexOf(searchString, start +1);
            if (start == -1)
            {
                break;
            }
            else
            {
                ret.Add(start);
            }
        }
        return ret;
    }

Ignore cells on Excel line graph

There are many cases in which gaps are desired in a chart.

I am currently trying to make a plot of flow rate in a heating system vs. the time of day. I have data for two months. I want to plot only vs. the time of day from 00:00 to 23:59, which causes lines to be drawn between 23:59 and 00:01 of the next day which extend across the chart and disturb the otherwise regular daily variation.

Using the NA() formula (in German NV()) causes Excel to ignore the cells, but instead the previous and following points are simply connected, which has the same problem with lines across the chart.

The only solution I have been able to find is to delete the formulas from the cells which should create the gaps.

Using an IF formula with "" as its value for the gaps makes Excel interpret the X-values as string labels (shudder) for the chart instead of numbers (and makes me swear about the people who wrote that requirement).

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Colon (:) in Python list index

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.

jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });

I was then able to use the JObject.Parse(jsonResult) and everything worked.

How can I catch an error caused by mail()?

PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

How to randomly pick an element from an array

You can use the Random generator to generate a random index and return the element at that index:

//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];

Finding the mode of a list

Python 3.4 includes the method statistics.mode, so it is straightforward:

>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
 3

You can have any type of elements in the list, not just numeric:

>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
 'red'

Is there any sizeof-like method in Java?

The Java Native Access library is typically used for calling native shared libraries from Java. Within this library there exist methods for determining the size of Java objects:

The getNativeSize(Class cls) method and its overloads will provide the size for most classes.

Alternatively, if your classes inherit from JNA's Structure class the calculateSize(boolean force) method will be available.

How to redirect DNS to different ports

Possible solutions:

  1. Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.

  2. If you use AWS you can use the load balancer to redirect the request to specific port based on the host.

C++ correct way to return pointer to array from function

Your code as it stands is correct but I am having a hard time figuring out how it could/would be used in a real world scenario. With that said, please be aware of a few caveats when returning pointers from functions:

  • When you create an array with syntax int arr[5];, it's allocated on the stack and is local to the function.
  • C++ allows you to return a pointer to this array, but it is undefined behavior to use the memory pointed to by this pointer outside of its local scope. Read this great answer using a real world analogy to get a much clear understanding than what I could ever explain.
  • You can still use the array outside the scope if you can guarantee that memory of the array has not be purged. In your case this is true when you pass arr to test().
  • If you want to pass around pointers to a dynamically allocated array without worrying about memory leaks, you should do some reading on std::unique_ptr/std::shared_ptr<>.

Edit - to answer the use-case of matrix multiplication

You have two options. The naive way is to use std::unique_ptr/std::shared_ptr<>. The Modern C++ way is to have a Matrix class where you overload operator * and you absolutely must use the new rvalue references if you want to avoid copying the result of the multiplication to get it out of the function. In addition to having your copy constructor, operator = and destructor, you also need to have move constructor and move assignment operator. Go through the questions and answers of this search to gain more insight on how to achieve this.

Edit 2 - answer to appended question

int* test (int a[5], int b[5]) {
    int *c = new int[5];
    for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
    return c;
}

If you are using this as int *res = test(a,b);, then sometime later in your code, you should call delete []res to free the memory allocated in the test() function. You see now the problem is it is extremely hard to manually keep track of when to make the call to delete. Hence the approaches on how to deal with it where outlined in the answer.

How to find NSDocumentDirectory in Swift?

More convenient Swift 3 method:

let documentsUrl = FileManager.default.urls(for: .documentDirectory, 
                                             in: .userDomainMask).first!

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

In my case what solved this problem was simply to Close Eclipse and opening it again...However I am still not sure why this happened or why it worked. I was having problems Cleaning my project (it said it could not Delete certain file) and this solved it :):

For loop in Oracle SQL

You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.

With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.

http://www.dba-oracle.com/t_with_clause.htm

http://www.orafaq.com/node/55

It requires some effort though. Don't be afraid to post a concrete example.

Using simple pseudo table DUAL helps too.

MySQL Workbench not displaying query results

Update manually from mysql website

Here's a solution for Ubuntu 15.04 users running Mysql Workbench 6.2.3.

I was able to resolve the issue of missing results in the Mysql workbench by just upgrading mysql-workbench to version 6.3.3 from http://dev.mysql.com/downloads/workbench/. You will need to download the one marked for Ubuntu 14.10. An install via Ubuntu software center resolved the issue. Hope this helps.

NSString with \n or line break

In Swift 3, its much simpler

let stringA = "Terms and Conditions"
let stringB = "Please read the instructions"

yourlabel.text =  "\(stringA)\n\(stringB)"

or if you are using a textView

yourtextView.text =  "\(stringA)\n\(stringB)"

Maven project.build.directory

It points to your top level output directory (which by default is target):

https://web.archive.org/web/20150527103929/http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide

EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:

http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html#resource-filtering-sect-project-properties

If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.

    project.build.sourceDirectory
    project.build.scriptSourceDirectory
    project.build.testSourceDirectory
    project.build.outputDirectory
    project.build.testOutputDirectory
    project.build.directory

sourceDirectory, scriptSourceDirectory, and testSourceDirectory provide access to the source directories for the project. outputDirectory and testOutputDirectory provide access to the directories where Maven is going to put bytecode or other build output. directory refers to the directory which contains all of these output directories.

Update a table using JOIN in SQL Server?

I had the same issue.. and you don't need to add a physical column.. cuz now you will have to maintain it.. what you can do is add a generic column in the select query:

EX:

select tb1.col1, tb1.col2, tb1.col3 ,
( 
select 'Match' from table2 as tbl2
where tbl1.col1 = tbl2.col1 and tab1.col2 = tbl2.col2
)  
from myTable as tbl1

How to create a property for a List<T>

T must be defined within the scope in which you are working. Therefore, what you have posted will work if your class is generic on T:

public class MyClass<T>
{
    private List<T> newList;

    public List<T> NewList
    {
        get{return newList;}
        set{newList = value;}
    }
}

Otherwise, you have to use a defined type.

EDIT: Per @lKashef's request, following is how to have a List property:

private List<int> newList;

public List<int> NewList
{
    get{return newList;}
    set{newList = value;}
}

This can go within a non-generic class.

Edit 2: In response to your second question (in your edit), I would not recommend using a list for this type of data handling (if I am understanding you correctly). I would put the user settings in their own class (or struct, if you wish) and have a property of this type on your original class:

public class UserSettings
{
 string FirstName { get; set; }
 string LastName { get; set; }
 // etc.
}

public class MyClass
{
 string MyClassProperty1 { get; set; }
 // etc.

 UserSettings MySettings { get; set; }
}

This way, you have named properties that you can reference instead of an arbitrary index in a list. For example, you can reference MySettings.FirstName as opposed to MySettingsList[0].

Let me know if you have any further questions.

EDIT 3: For the question in the comments, your property would be like this:

public class MyClass
{
    public List<KeyValuePair<string, string>> MySettings { get; set; } 
}

EDIT 4: Based on the question's edit 2, following is how I would use this:

public class MyClass
{
    // note that this type of property declaration is called an "Automatic Property" and
    // it means the same thing as you had written (the private backing variable is used behind the scenes, but you don't see it)
    public List<KeyValuePair<string, string> MySettings { get; set; } 
}

public class MyConsumingClass
{
    public void MyMethod
    {
        MyClass myClass = new MyClass();
        myClass.MySettings = new List<KeyValuePair<string, string>>();
        myClass.MySettings.Add(new KeyValuePair<string, string>("SomeKeyValue", "SomeValue"));

        // etc.
    }
}

You mentioned that "the property still won't appear in the object's instance," and I am not sure what you mean. Does this property not appear in IntelliSense? Are you sure that you have created an instance of MyClass (like myClass.MySettings above), or are you trying to access it like a static property (like MyClass.MySettings)?

Convert comma separated string of ints to int array

If you don't want to have the current error handling behaviour, it's really easy:

return text.Split(',').Select(x => int.Parse(x));

Otherwise, I'd use an extra helper method (as seen this morning!):

public static int? TryParseInt32(string text)
{
    int value;
    return int.TryParse(text, out value) ? value : (int?) null;
}

and:

return text.Split(',').Select<string, int?>(TryParseInt32)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or if you don't want to use the method group conversion:

return text.Split(',').Select(t => t.TryParseInt32(t)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or in query expression form:

return from t in text.Split(',')
       select TryParseInt32(t) into x
       where x.HasValue
       select x.Value;

ResourceDictionary in a separate assembly

For UWP:

<ResourceDictionary Source="ms-appx:///##Namespace.External.Assembly##/##FOLDER##/##FILE##.xaml" />

No server in Eclipse; trying to install Tomcat

You have probably installed Eclipse for Java Developers instead of Eclipse IDE for Enterprise Java Developers, server tab and some other are not available.

You don't have to uninstall. Just rerun eclipse-inst-win64.exe and choose Java EE IDE

JAVA EE IDE Installation

How to pass multiple parameters in json format to a web service using jquery?

This is a stab in the dark, but maybe do you need to wrap your JSON arguments; like say something like this:

data: "{'Ids':[{'Id1':'2'},{'Id2':'2'}]}"

Make sure your JSON is properly formed?

IOException: The process cannot access the file 'file path' because it is being used by another process

Using FileShare fixed my issue of opening file even if it is opened by another process.

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}

Correct format specifier to print pointer or address?

You can use %x or %X or %p; all of them are correct.

  • If you use %x, the address is given as lowercase, for example: a3bfbc4
  • If you use %X, the address is given as uppercase, for example: A3BFBC4

Both of these are correct.

If you use %x or %X it's considering six positions for the address, and if you use %p it's considering eight positions for the address. For example:

How can I see the specific value of the sql_mode?

It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:

mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
|            |
+------------+
1 row in set (0.00 sec)

mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode                                                                                                           |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

PHP: HTTP or HTTPS?

This can get more complicated depending on where PHP sits in your environment, since your question is quite broad. This may depend on whether there's a load-balancer and how it's configured. Here are are a few related questions:

Initializing select with AngularJS and ng-repeat

As suggested you need to use ng-options and unfortunately I believe you need to reference the array element for a default (unless the array is an array of strings).

http://jsfiddle.net/FxM3B/3/

The JavaScript:

function AppCtrl($scope) {


    $scope.operators = [
        {value: 'eq', displayName: 'equals'},
        {value: 'neq', displayName: 'not equal'}
     ]

    $scope.filterCondition={
        operator: $scope.operators[0]
    }
}

The HTML:

<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator.value}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.displayName for operator in operators">
</select>
</body>

form_for but to post to a different action

The following works for me:

form_for @user, :url => {:action => "YourActionName"}

Gradle task - pass arguments to Java application

You need to pass them as args to the task using project properties, something like:

args = [project.property('h')]

added to your task definition (see the dsl docs)

Then you can run it as:

gradle -Ph run

Calculating distance between two points, using latitude longitude?

The Java code given by Dommer above gives slightly incorrect results but the small errors add up if you are processing say a GPS track. Here is an implementation of the Haversine method in Java which also takes into account height differences between two points.

/**
 * Calculate distance between two points in latitude and longitude taking
 * into account height difference. If you are not interested in height
 * difference pass 0.0. Uses Haversine method as its base.
 * 
 * lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters
 * el2 End altitude in meters
 * @returns Distance in Meters
 */
public static double distance(double lat1, double lat2, double lon1,
        double lon2, double el1, double el2) {

    final int R = 6371; // Radius of the earth

    double latDistance = Math.toRadians(lat2 - lat1);
    double lonDistance = Math.toRadians(lon2 - lon1);
    double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
            + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
            * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = R * c * 1000; // convert to meters

    double height = el1 - el2;

    distance = Math.pow(distance, 2) + Math.pow(height, 2);

    return Math.sqrt(distance);
}

How to extract elements from a list using indices in Python?

I think you're looking for this:

elements = [10, 11, 12, 13, 14, 15]
indices = (1,1,2,1,5)

result_list = [elements[i] for i in indices]    

Change the jquery show()/hide() animation?

Use slidedown():

$("test").slideDown("slow");

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

<hr> tag in Twitter Bootstrap not functioning correctly?

You may want one of these, so to correspond to the Bootstrap layout:

<div class="col-xs-12">
    <hr >
</div>

<!-- or -->

<div class="col-xs-12">
    <hr style="border-style: dashed; border-top-width: 2px;">
</div>

<!-- or -->

<div class="col-xs-12">
    <hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>

Without a DIV grid element included, layout may brake on different devices.

How to pass html string to webview on android

To load your data in WebView. Call loadData() method of WebView

webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

MySQL timestamp select date range

SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'

window.location.href and window.open () methods in JavaScript

  • window.open will open a new browser with the specified URL.

  • window.location.href will open the URL in the window in which the code is called.

Note also that window.open() is a function on the window object itself whereas window.location is an object that exposes a variety of other methods and properties.

Open files in 'rt' and 'wt' modes

t indicates for text mode

https://docs.python.org/release/3.1.5/library/functions.html#open

on linux, there's no difference between text mode and binary mode, however, in windows, they converts \n to \r\n when text mode.

http://www.cygwin.com/cygwin-ug-net/using-textbinary.html

What is the difference between "expose" and "publish" in Docker?

EXPOSE is used to map local port container port ie : if you specify expose in docker file like

EXPOSE 8090

What will does it will map localhost port 8090 to container port 8090

How do I check (at runtime) if one class is a subclass of another?

The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.

Set textarea width to 100% in bootstrap modal

Try add min-width: 100% to style of your textarea:

<textarea class="form-control" style="min-width: 100%"></textarea>

Android: making a fullscreen application

in my case all works fine. See in logcat. Maybe logcat show something that can help you to resolve your problem

Anyway you can try do it programmatically:

 public class ActivityName extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // remove title
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.main);
        }
 }

Are PostgreSQL column names case-sensitive?

The column names which are mixed case or uppercase have to be double quoted in PostgresQL. So best convention will be to follow all small case with underscore.

Use VBA to Clear Immediate Window?

I tested this code based on all the comments above. Seems to work flawlessly. Comments?

Sub ResetImmediate()  
        Debug.Print String(5, "*") & " Hi there mom. " & String(5, "*") & vbTab & "Smile"  
        Application.VBE.Windows("Immediate").SetFocus  
        Application.SendKeys "^g ^a {DEL} {HOME}"  
        DoEvents  
        Debug.Print "Bye Mom!"  
End Sub

Previously used the Debug.Print String(200, chr(10)) which takes advantage of the Buffer overflow limit of 200 lines. Didn't like this method much but it works.

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to remove all white spaces from a given text file

I think you may use sed to wipe out the space while not losing some infomation like changing to another line.

cat hello.txt | sed '/^$/d;s/[[:blank:]]//g'

Appending output of a Batch file To log file

Instead of using ">" to redirect like this:

java Foo > log

use ">>" to append normal "stdout" output to a new or existing file:

java Foo >> log

However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:

java Foo >> log 2>&1 

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

As the others mentioned you can change the SubSystem to Console and the error will go away.

Or if you want to keep the Windows subsystem you can just hint at what your entry point is, because you haven't defined ___tmainCRTStartup. You can do this by adding the following to Properties -> Linker -> Command line:

/ENTRY:"mainCRTStartup"

This way you get rid of the console window.

Pytorch tensor to numpy array

This worked for me:

np_arr = torch_tensor.cpu().detach().numpy()

Refreshing data in RecyclerView and keeping its scroll position

I use this one.^_^

// Save state
private Parcelable recyclerViewState;
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();

// Restore state
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);

It is simpler, hope it will help you!

Update Row if it Exists Else Insert Logic with Entity Framework

If you are working with attached object (object loaded from the same instance of the context) you can simply use:

if (context.ObjectStateManager.GetObjectStateEntry(myEntity).State == EntityState.Detached)
{
    context.MyEntities.AddObject(myEntity);
}

// Attached object tracks modifications automatically

context.SaveChanges();

If you can use any knowledge about the object's key you can use something like this:

if (myEntity.Id != 0)
{
    context.MyEntities.Attach(myEntity);
    context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
    context.MyEntities.AddObject(myEntity);
}

context.SaveChanges();

If you can't decide existance of the object by its Id you must exectue lookup query:

var id = myEntity.Id;
if (context.MyEntities.Any(e => e.Id == id))
{
    context.MyEntities.Attach(myEntity);
    context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
    context.MyEntities.AddObject(myEntity);
}

context.SaveChanges();

What is the iOS 5.0 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

iPad:

Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3

How to get column values in one comma separated value

Try the following Query:

select distinct Users,
 STUFF(
        (
        select ', ' + d.Department FROM @temp d
        where t.Users=d.Users
group by d.Department for xml path('')
        ), 1, 2, '') as Departments
 from @temp t

Implementation:

Declare @temp Table(
ID int,
Users varchar(50),
Department varchar(50)
)
insert into @temp
(ID,Users,Department)
values
(1,'User1','Admin')
insert into @temp
(ID,Users,Department)
values
(2,'User1','Accounts')
insert into @temp
(ID,Users,Department)
values
(3,'User2','Finance')
insert into @temp
(ID,Users,Department)
values
(4,'User3','Sales')
insert into @temp
(ID,Users,Department)
values
(5,'User3','Finance')

 select distinct Users,
 STUFF(
        (
        select ', ' + d.Department FROM @temp d
        where t.Users=d.Users
group by d.Department for xml path('')
        ), 1, 2, '') as Departments

 from @temp t

Result will be:

enter image description here

How do I create a HTTP Client Request with a cookie?

The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

How To Launch Git Bash from DOS Command Line?

I used the info above to help create a more permanent solution. The following will create the alias sh that you can use to open Git Bash:

echo @start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login > %systemroot%\sh.bat

How to test whether a service is running from the command line

Let's go back to the old school of batch programing on windows

net start | find "Service Name"

This will work everywhere...

How to print a groupby object

Simply do:

grouped_df = df.groupby('A')

for key, item in grouped_df:
    print(grouped_df.get_group(key), "\n\n")

This also works,

grouped_df = df.groupby('A')    
gb = grouped_df.groups

for key, values in gb.iteritems():
    print(df.ix[values], "\n\n")

For selective key grouping: Insert the keys you want inside the key_list_from_gb, in following, using gb.keys(): For Example,

gb = grouped_df.groups
gb.keys()

key_list_from_gb = [key1, key2, key3]

for key, values in gb.items():
    if key in key_list_from_gb:
        print(df.ix[values], "\n")

How to get text of an element in Selenium WebDriver, without including child element text?

You don't have to do a replace, you can get the length of the children text and subtract that from the overall length, and slice into the original text. That should be substantially faster.

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

AngularJS: how to implement a simple file upload with multipart form?

You can use the simple/lightweight ng-file-upload directive. It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
  $scope.onFileSelect = function($files) {
  Upload.upload({
    url: 'my/upload/url',
    file: $files,            
  }).progress(function(e) {
  }).then(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  }); 

}];

how to reset <input type = "file">

Works for dynamic controls too.

Javascript

<input type="file" onchange="FileValidate(this)" />

function FileValidate(object) {
    if ((object.files[0].size / 1024 / 1024) > 1) {   //greater than 1 MB         
        $(object).val('');
    }     
}

JQuery

<input type="file" class="UpoloadFileSize">

$(document).ready(function () {

    $('.UpoloadFileSize').bind('change', function () {                
        if ((this.files[0].size / 1024000) > 1.5) { //greater than 1.5 MB
            $(this).val('');
            alert('Size exceeded !!');
        }
    });

});

TypeError: 'undefined' is not a function (evaluating '$(document)')

 ;(function($){
        // your code
    })(jQuery);

Place your js code inside the closure above , it should solve the problem.

MySQL INNER JOIN select only one row from second table

You can try this:

SELECT u.*, p.*
FROM users AS u LEFT JOIN (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY userid ORDER BY [Date] DESC) AS RowNo
    FROM payments  
) AS p ON u.userid = p.userid AND p.RowNo=1

best practice to generate random token for forgot password

This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16));

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

ERROR: Google Maps API error: MissingKeyMapError

As per Google recent announcement, usage of the Google Maps APIs now requires a key. If you are using the Google Maps API on localhost or your domain was not active prior to June 22nd, 2016, it will require a key going forward. Please see the Google Maps APIs documentation to get a key and add it to your application.

How to use HTML to print header and footer on every printed page of a document?

I have been searching for years for a solution and found this post on how to print a footer that works on multiple pages without overlapping page content.

My requirement was IE8, so far I have found that this does not work in Chrome. [update]As of 1 March 2018, it works in Chrome as well

This example uses tables and the tfoot element by setting the css style:

tfoot {display: table-footer-group;}

UNC path to a folder on my local computer

I had to:

How do I reload a page without a POSTDATA warning in Javascript?

If you use GET method instead of POST then we can't the form filed values. If you use window.opener.location.href = window.opener.location.href; then we can fire the db and we can get the value but only thing is the JSP is not refreshing eventhough the scriplet having the form values.

How to check Oracle patches are installed?

Here is an article on how to check and or install new patches :


To find the OPatch tool setup your database enviroment variables and then issue this comand:

cd $ORACLE_HOME/OPatch 
> pwd
/oracle/app/product/10.2.0/db_1/OPatch

To list all the patches applies to your database use the lsinventory option:

[oracle@DCG023 8828328]$ opatch lsinventory
Oracle Interim Patch Installer version 11.2.0.3.4
Copyright (c) 2012, Oracle Corporation. All rights reserved.

Oracle Home : /u00/product/11.2.0/dbhome_1
Central Inventory : /u00/oraInventory
from : /u00/product/11.2.0/dbhome_1/oraInst.loc
OPatch version : 11.2.0.3.4
OUI version : 11.2.0.1.0
Log file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/opatch2013-11-13_13-55-22PM_1.log
Lsinventory Output file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/lsinv/lsinventory2013-11-13_13-55-22PM.txt


Installed Top-level Products (1):
Oracle Database 11g 11.2.0.1.0
There are 1 products installed in this Oracle Home.

Interim patches (1) :
Patch 8405205 : applied on Mon Aug 19 15:18:04 BRT 2013
Unique Patch ID: 11805160
Created on 23 Sep 2009, 02:41:32 hrs PST8PDT
Bugs fixed:
8405205

OPatch succeeded.

To list the patches using sql :

select * from registry$history;

Magento: get a static block as html in a phtml file

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my_static_block_name')->toHtml() ?>

and use this link for more http://www.justwebdevelopment.com/blog/how-to-call-static-block-in-magento/

Redirect non-www to www in .htaccess

I have tested all the above solutions but not working for me, i have tried to remove the http:// and won't redirect also removed the www it redirect well, so i get confused, specially i am running all my sites under https://

So i have combined some codes together and came up with perfect solution for both http:// and https:// and www and non-www.

# HTTPS forced
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
# Redirect to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
</IfModule>

Hope this can help someone :)

How to handle button clicks using the XML onClick within Fragments

The problem I think is that the view is still the activity, not the fragment. The fragments doesn't have any independent view of its own and is attached to the parent activities view. Thats why the event ends up in the Activity, not the fragment. Its unfortunate, but I think you will need some code to make this work.

What I've been doing during conversions is simply adding a click listener that calls the old event handler.

for instance:

final Button loginButton = (Button) view.findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(final View v) {
        onLoginClicked(v);
    }
});

Can RDP clients launch remote applications and not desktops

This is called RemoteApp. To use it you need to install Terminal Services, which is now called Remote Desktop Services.

https://social.technet.microsoft.com/wiki/contents/articles/10817.publishing-remoteapps-in-windows-server-2012.aspx

How to Install pip for python 3.7 on Ubuntu 18?

I used apt-get to install python3.7 in ubuntu18.04. The installations are as follows.

  1. install python3.7
sudo apt-get install python3.7 
  1. install pip3. It should be noted that this may install pip3 for python3.6.
sudo apt-get install python3-pip 
  1. change the default of python3 for python3.7. This is where the magic is, which will make the pip3 refer to python3.7.
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1

Hope it works for you.

Convert string to nullable type (int, double, etc...)

There is no way around this. Nullable, as well as your method, is constrained to using only value types as it's argument. String is a reference type and hence is incompatible with this declaration.

Find unused code

Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.

How to convert an address into a Google Maps Link (NOT MAP)

Also, anyone wanting to manually URLENCODE the address: http://code.google.com/apis/maps/documentation/webservices/index.html#BuildingURLs

You can use that to create specific rules that meet GM standards.

Does mobile Google Chrome support browser extensions?

Some extensions like blocksite use the accessibility service API to deploy extension like features to Chrome on Android. Might be worth a look through the play store. Otherwise, Firefox is your best bet, though many extensions don't work on mobile for some reason.

https://play.google.com/store/apps/details?id=co.blocksite&hl=en_US

Remove trailing comma from comma-separated string

This method is in BalusC's StringUtil class. his blog

i use it very often and will trim any string of any value:

/**
 * Trim the given string with the given trim value.
 * @param string The string to be trimmed.
 * @param trim The value to trim the given string off.
 * @return The trimmed string.
 */
public static String trim(String string, String trim) {
    if (string == null) {
        return null;
    }

    if (trim.length() == 0) {
        return string;
    }

    int start = 0;
    int end = string.length();
    int length = trim.length();

    while (start + length <= end && string.substring(
            start, start + length).equals(trim)) {
        start += length;
    }
    while (start + length <= end && string.substring(
            end - length, end).equals(trim)) {
        end -= length;
    }

    return string.substring(start, end);
}

ex:

trim("1, 2, 3, ", ", ");

Get selected value from combo box in C# WPF

XAML:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="19,123,0,0" Name="comboBox1" VerticalAlignment="Top" Width="33" ItemsSource="{Binding}" AllowDrop="True" AlternationCount="1">
    <ComboBoxItem Content="1" Name="ComboBoxItem1" />
    <ComboBoxItem Content="2" Name="ComboBoxItem2" />
    <ComboBoxItem Content="3" Name="ComboBoxItem3" />
</ComboBox>

C#:

if (ComboBoxItem1.IsSelected)
{
    // Your code
}
else if (ComboBoxItem2.IsSelected)
{
    // Your code
}
else if(ComboBoxItem3.IsSelected)
{
    // Your code
}

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

You can also use some existing API's like GroupDocs.Viewer which can convert your document into image or html and then you will be able to display it in your own application.

sql ORDER BY multiple values in specific order?

You can use a LEFT JOIN with a "VALUES ('f',1),('p',2),('a',3),('i',4)" and use the second column in your order-by expression. Postgres will use a Hash Join which will be much faster than a huge CASE if you have a lot of values. And it is easier to autogenerate.

If this ordering information is fixed, then it should have its own table.

How to catch exception output from Python subprocess.check_output()?

I don't think the accepted solution handles the case where the error text is reported on stderr. From my testing the exception's output attribute did not contain the results from stderr and the docs warn against using stderr=PIPE in check_output(). Instead, I would suggest one small improvement to J.F Sebastian's solution by adding stderr support. We are, after all, trying to handle errors and stderr is where they are often reported.

from subprocess import Popen, PIPE

p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0: 
   print("bitcoin failed %d %s %s" % (p.returncode, output, error))

What is the current choice for doing RPC in Python?

There are some attempts at making SOAP work with python, but I haven't tested it much so I can't say if it is good or not.

SOAPy is one example.

How to call multiple JavaScript functions in onclick event?

onclick="doSomething();doSomethingElse();"

But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

How can I check if PostgreSQL is installed or not via Linux script?

There is no single simple way to do it, because PostgreSQL might be installed and set up in many different ways:

  • Installed from source in a user home directory
  • Installed from source into /opt or /usr/local, manually started or started by an init script
  • Installed from distributor rpm / deb packages and started via init script
  • Installed from 3rd party rpm / deb packages and started via init script
  • Installed from packages but not set to start
  • Client installed, connecting to a server on a different computer
  • Installed and running but not on the default PATH or default port

You can't rely on psql being on the PATH. You can't rely on there being only one psql on the system (multiple versions might be installed in different ways). You can't do it based on port, as there's no guarantee it's on port 5432, or that there aren't multiple versions.

Prompt the user and ask them.

Returning a value from thread?

Simply use the delegate approach.

int val;
Thread thread = new Thread(() => { val = Multiply(1, 2); });
thread.Start();

Now make Multiply function that will work on another thread:

int Multiply(int x, int y)
{
    return x * y;
}

FTP/SFTP access to an Amazon S3 Bucket

Or spin Linux instance for SFTP Gateway in your AWS infrastructure that saves uploaded files to your Amazon S3 bucket.

Supported by Thorntech

How to solve PHP error 'Notice: Array to string conversion in...'

When you have many HTML inputs named C[] what you get in the POST array on the other end is an array of these values in $_POST['C']. So when you echo that, you are trying to print an array, so all it does is print Array and a notice.

To print properly an array, you either loop through it and echo each element, or you can use print_r.

Alternatively, if you don't know if it's an array or a string or whatever, you can use var_dump($var) which will tell you what type it is and what it's content is. Use that for debugging purposes only.

turn typescript object into json string

TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:

  • JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
  • JSON.stringify() method converts a JavaScript object or value to a JSON string.

Example:

_x000D_
_x000D_
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';_x000D_
_x000D_
_x000D_
const JSobj = JSON.parse(jsonString);_x000D_
_x000D_
console.log(JSobj);_x000D_
console.log(typeof JSobj);_x000D_
_x000D_
const JSON_string = JSON.stringify(JSobj);_x000D_
_x000D_
console.log(JSON_string);_x000D_
console.log(typeof JSON_string);
_x000D_
_x000D_
_x000D_

How do you run a SQL Server query from PowerShell?

Invoke-Sqlcmd -Query "sp_who" -ServerInstance . -QueryTimeout 3

Looping through list items with jquery

You can use each for this:

$('#productList li').each(function(i, li) {
  var $product = $(li);  
  // your code goes here
});

That being said - are you sure you want to be updating the values to be +1 each time? Couldn't you just find the count and then set the values based on that?

Gradients on UIView and UILabels On iPhone

You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

Inheriting from a template class in c++

#include<iostream>

using namespace std;

template<class t> 
class base {
protected:
    t a;
public:
    base(t aa){
        a = aa;
        cout<<"base "<<a<<endl;
    }
};

template <class t> 
class derived: public base<t>{
    public:
        derived(t a): base<t>(a) {
        }
        //Here is the method in derived class 
    void sampleMethod() {
        cout<<"In sample Method"<<endl;
    }
};

int main() {
    derived<int> q(1);
    // calling the methods
    q.sampleMethod();
}

How can I symlink a file in Linux?

To the original question:


'ln -s '+basebuild+'/IpDome-kernel/kernel /home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal'

This will indeed create a symbolic link (-s) from the file/directory:

<basebuild>/IpDome-kernel/kernel

to your new link

/home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal

Here's a few ways to help you remember:

First, there's the man page for ln. You can access this via searching "man ln" in google, or just open a terminal window and type man ln and you'll get the same information. The man page clearly states:

ln [OPTION]... [-T] TARGET LINK_NAME (1st form)


If having to search or read through a man page every time isn't for you, maybe you'll have an easier time remembering that all nix commands work the same way:

cp /file/that/exists /location/for/new/file
mv /file/that/exists /location/its/moving/to
ln /file/that/exists /the/new/link

cp copies a file that currently exists (the first argument) to a new file (the second argument).
mv moves a file that currently exists (the first argument) to a new place (the second argument)

Likewise ln links a file that currently exists (the first argument) to a new link (the second argument)*


The final option I would like to suggest is you can create your own man pages that are easy to read and easy (for you) to find/remember. Just make a simple shell script that gives you the hint you need. For example?:

In your .bash_aliases file you can place something like:

commandsfx() {
    echo "Symlink:  ln -s /path/to/file /path/to/symlink"
    echo "Copy:     cp /file/to/copy /destination/to/send/copy"
}

alias 'cmds'=commandsfx

Then when you need it, from the command line just type cmds and you'll get back the proper syntax in a way you can quickly read and understand it. You can make these functions as advanced as you'd like to get what what information you need, it's up to you. You could even make them interactive so you just have to follow the prompts.. something like:

makesymlink() {
    echo "Symlink name:"
    read sym
    echo "File to link to:"
    read fil
    ln -s $fil $sym
}

alias 'symlink'=makesymlink

* - well obviously they can all take different parameters and do different things and can work on files as well as directories... but the premise is the same
? - examples using the bash shell

Remove spaces from std::string in C++

The best thing to do is to use the algorithm remove_if and isspace:

remove_if(str.begin(), str.end(), isspace);

Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:

template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
    T dest = beg;
    for (T itr = beg;itr != end; ++itr)
        if (!pred(*itr))
            *(dest++) = *itr;
    return dest;
}

Javascript - Get Image height

...but... wouldn't it be better to adjust the image size on the server side rather than transmitting the bytes to the browser and doing it there?

When I say adjust the image size, I don't mean set the height and width in the HTML image tag. If you do that, you are still shipping a large number of bytes from server to client. I mean, actually manipulate the image itself server side.

I have .NET C# code here that takes that approach, but there must be a php way to do it too: http://ifdefined.com/www/gallery.html

Also, by doing it server side, that opens up the possibility of doing the adjustment just once and then saving the adjusted image, which would be very fast.

Can I configure a subdomain to point to a specific port on my server

If you wish to use 2 subdomains to other ports, you can use Minecraft's proxy server (it means BungeeCord, Waterfall, Travertine...), and bind subdomain to specifiend in config.yml server. To do that you have to setup your servers in BungeeCord's config:

servers:
  pvp:
    motd: 'A Minecraft Server PVP'
    address: localhost:25566
    restricted: false
  skyblock:
    motd: 'A Minecraft Server SkyBlock'
    address: localhost:25567
    restricted: false

Remember! Ports must be diffrent than default Minecraft's port (it means 25565), because we will use this port to our proxy. sub1.domain.com and sub2.domain.com we have to bind to server where you have these servers. Now, we have to bind subdomains in your Bungee server:

listeners:
    forced_hosts:
      sub1.domain.com: pvp
      sub2.domain.com: skyblock
      domain.com: pvp // You can bind other domains to same servers.

Remember to change force_default_server to true, and change host to 0.0.0.0:25565 Example of BungeeCord's config.yml with some servers: https://pastebin.com/tA9ktZ6f Now you can connect to your pvp server on sub1.domain.com and connect to skyblock on sub2.domain.com. Don't worry, BungeeCord takes only 0,5GB of RAM for 500 players.