Programs & Examples On #Error suppression

What is the use of the @ symbol in PHP?

It suppresses errors.

See Error Control Operators in the manual:

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @...

Converting dd/mm/yyyy formatted string to Datetime

You can use "dd/MM/yyyy" format for using it in DateTime.ParseExact.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Here is a DEMO.

For more informations, check out Custom Date and Time Format Strings

anaconda - graphviz - can't import after installation

You can actually install both packages at the same time. For me:

conda install -c anaconda graphviz python-graphviz

did the trick.

Where can I find decent visio templates/diagrams for software architecture?

For SOA system architecture, I use the SOACP Visio stencil. It provides the symbols that are used in Thomas Erl's SOA book series.

I use the Visio Network and Database stencils to model most other requirements.

Check if a string is null or empty in XSLT

If there is a possibility that the element does not exist in the XML I would test both that the element is present and that the string-length is greater than zero:

<xsl:choose>
    <xsl:when test="categoryName and string-length(categoryName) &gt; 0">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

Java 8 stream reverse order

In all this I don't see the answer I would go to first.

This isn't exactly a direct answer to the question, but it's a potential solution to the problem.

Just build the list backwards in the first place. If you can, use a LinkedList instead of an ArrayList and when you add items use "Push" instead of add. The list will be built in the reverse order and will then stream correctly without any manipulation.

This won't fit cases where you are dealing with primitive arrays or lists that are already used in various ways but does work well in a surprising number of cases.

How to add a line to a multiline TextBox?

Append a \r\n to the string to put the text on a new line.

textBox1.Text += ("brown\r\n");
textBox1.Text += ("brwn");

This will produce the two entries on separate lines.

Intellij reformat on file save

This solution worked better for me:

  1. Make a macro (I used Organize Imports, Format Code, Save All)
  2. Assign it a keystroke (I overrode Ctrl+S)

Note: You will have to check the box "Do not show this message again" the first time for the organized imports, but it works as expected after that.

Step-by-step for IntelliJ 10.0:

  1. Code -> "Optimize Imports...", if a dialogue box appears, check the box that says "Do not show this message again.", then click "Run".
  2. Tools -> "Start Macro Recording"
  3. Code -> "Optimize Imports..."
  4. Code -> "Reformat Code..."
  5. File -> "Save all"
  6. Tools -> "Stop Macro Recording"
  7. Name the macro (something like "formatted save")
  8. In File -> Settings -> Keymap, select your macro located at "Main Menu -> Tools -> "formatted save"
  9. Click "Add Keyboard Shortcut", then perform the keystroke you want. If you choose Ctrl+S like me, it will ask you what to do with the previous Ctrl+S shortcut. Remove it. You can always reassign it later if you want.
  10. Enjoy!

For IntelliJ 11, replace

step 2. with: Edit -> Macros -> "Start Macro Recording"
step 6. with: Edit -> Macros -> "Stop Macro Recording"

Everything else remains the same.

IntelliJ 12

8. The Preferences contain the Keymap settings. Use the input field to filter the content, as shown in the screenshot.

Intellij / Preferences / Keymap / Macros

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

How to write some data to excel file(.xlsx)

Try this code

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    //Get a new workbook.
    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment =
        Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.
    string[,] saNames = new string[5, 2];

    saNames[0, 0] = "John";
    saNames[0, 1] = "Smith";
    saNames[1, 0] = "Tom";

    saNames[4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).
    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();

    oXL.Visible = false;
    oXL.UserControl = false;
    oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
    oXL.Quit();

    //...

jQuery get specific option tag text

I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:

So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:

var e = $('select[title="IntenalFieldName"] option:selected').text(); 

C++ - Decimal to binary converting

HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY


  #include<iostream>
    using namespace std;
    int main()
    {
        int input,rem,res,count=0,i=0;
        cout<<"Input number: ";
        cin>>input;`enter code here`
        int num=input;
        while(input > 0)
        {
            input=input/2;  
            count++;
        }

        int arr[count];

        while(num > 0)
        {
            arr[i]=num%2;
            num=num/2;  
            i++;
        }
        for(int i=count-1 ; i>=0 ; i--)
        {
            cout<<" " << arr[i]<<" ";
        }



        return 0;
    }

Convert a String In C++ To Upper Case

Boost string algorithms:

#include <boost/algorithm/string.hpp>
#include <string>

std::string str = "Hello World";

boost::to_upper(str);

std::string newstr = boost::to_upper_copy<std::string>("Hello World");

How to check file input size with jQuery?

If you want to use jQuery's validate you can by creating this method:

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param) 
});

You would use it:

$('#formid').validate({
    rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }},
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});

onNewIntent() lifecycle and registered listeners

Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.

OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.

You can invoke onNewIntent always by putting it into onCreate method like

@Override
public void onCreate(Bundle savedState){
    super.onCreate(savedState);
    onNewIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  //code
}

JQuery confirm dialog

Have you tried using the official JQueryUI implementation (not jQuery only) : ?

How does HttpContext.Current.User.Identity.Name know which usernames exist?

Assume a network environment where a "user" (aka you) has to logon. Usually this is a User ID (UID) and a Password (PW). OK then, what is your Identity, or who are you? You are the UID, and this gleans that "name" from your logon session. Simple! It should also work in an internet application that needs you to login, like Best Buy and others.

This will pull my UID, or "Name", from my session when I open the default page of the web application I need to use. Now, in my instance, I am part of a Domain, so I can use initial Windows authentication, and it needs to verify who I am, thus the 2nd part of the code. As for Forms Authentication, it would rely on the ticket (aka cookie most likely) sent to your workstation/computer. And the code would look like:

string id = HttpContext.Current.User.Identity.Name;

// Strip the domain off of the result
id = id.Substring(id.LastIndexOf(@"\", StringComparison.InvariantCulture) + 1);

Now it has my business name (aka UID) and can display it on the screen.

How do you right-justify text in an HTML textbox?

Apply style="text-align: right" to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.

Find the directory part (minus the filename) of a full path in access 97

vFilename="C:\Informes\Indicadores\Program\Ind_Cont_PRv.txt"

vDirFile = Replace(vFilename, Dir(vFileName, vbDirectory), "")

' Result=C:\Informes\Indicadores_Contraloria\Programa\Versiones anteriores\

Javascript/jQuery detect if input is focused

Did you try:

$(this).is(':focus');

Take a look at Using jQuery to test if an input has focus it features some more examples

Convert a tensor to numpy array in Tensorflow?

If you see there is a method _numpy(), e.g for an EagerTensor simply call the above method and you will get an ndarray.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I have try with the SCFRench and with the Ru Hasha on octave.

And finally it works: but I have done some modification

function message = makefuns
    assignin('base','fun1', @fun1);   % Ru Hasha
    assignin('base', 'fun2', @fun2);  % Ru Hasha
    message.fun1=@fun1;               % SCFrench
    message.fun2=@fun2;               % SCFrench
end

function y=fun1(x)
    y=x;
end

function z=fun2
    z=1;
end

Can be called in other 'm' file:

printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());

update:

I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).

Instagram API - How can I retrieve the list of people a user is following on Instagram

The REST API of Instagram has been discontinued. But you can use GraphQL to get the desired data. Here you can find an overview: https://developers.facebook.com/docs/instagram-api

Android soft keyboard covers EditText field

The above solution work perfectly but if you are using Fullscreen activity(translucent status bar) then these solutions might not work. so for fullscreen use this code inside your onCreate function on your Activity.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = getWindow();
        w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN , WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN );
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.TYPE_STATUS_BAR);
    }

Example:

  protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = getWindow();
        w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN , WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN );
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.TYPE_STATUS_BAR);
    }
    
    super.onCreate(savedInstanceState);

How to remove all callbacks from a Handler?

In my experience calling this worked great!

handler.removeCallbacksAndMessages(null);

In the docs for removeCallbacksAndMessages it says...

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Static variables in C++

A static variable declared in a header file outside of the class would be file-scoped in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.

A static class variable on the other hand is class-scoped and the same static variable is available to every compilation unit that includes the header containing the class with static variable.

How to check a string for a special character?

Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.

Use this method to detect special characters not including whitespaces:

import re

def detect_special_characer(pass_string): 
  regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
  if(regex.search(pass_string) == None): 
    res = False
  else: 
    res = True
  return(res)

Difference between npx and npm?

Simple Definition:

npm - Javascript package manager

npx - Execute npm package binaries

Asking the user for input until they give a valid response

Use try-except to handle the error and repeat it again:

while True:
    try:
        age = int(input("Please enter your age: "))
        if age >= 18:
            print("You are able to vote in the United States!")
        else:
            print("You are not able to vote in the United States.")
    except Exception as e:
        print("please enter number")

Set up an HTTP proxy to insert a header

If you have ruby on your system, how about a small Ruby Proxy using Sinatra (make sure to install the Sinatra Gem). This should be easier than setting up apache. The code can be found here.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`) 
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;

Why rgb and not cmy?

The basic colours are RGB not RYB. Yes most of the softwares use the traditional RGB which can be used to mix together to form any other color i.e. RGB are the fundamental colours (as defined in Physics & Chemistry texts).

The printer user CMYK (cyan, magenta, yellow, and black) coloring as said by @jcomeau_ictx. You can view the following article to know about RGB vs CMYK: RGB Vs CMYK

A bit more information from the extract about them:

Red, Green, and Blue are "additive colors". If we combine red, green and blue light you will get white light. This is the principal behind the T.V. set in your living room and the monitor you are staring at now. Additive color, or RGB mode, is optimized for display on computer monitors and peripherals, most notably scanning devices.

Cyan, Magenta and Yellow are "subtractive colors". If we print cyan, magenta and yellow inks on white paper, they absorb the light shining on the page. Since our eyes receive no reflected light from the paper, we perceive black... in a perfect world! The printing world operates in subtractive color, or CMYK mode.

Can an Option in a Select tag carry multiple values?

What about html data attributes? That's the easiest way. Reference from w3school

In your case

_x000D_
_x000D_
$('select').on('change', function() {_x000D_
  alert('value a is:' + $("select option:selected").data('valuea') +_x000D_
    '\nvalue b is:' + $("select option:selected").data('valueb')_x000D_
  )_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>_x000D_
<select name="Testing">_x000D_
  <option value="1" data-valuea="2010" data-valueb="2011"> One_x000D_
    <option value="2" data-valuea="2122" data-valueb="2123"> Two_x000D_
      <option value="3" data-valuea="0" data-valueb="1"> Three_x000D_
</select>
_x000D_
_x000D_
_x000D_

Android Split string

String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

You may want to remove the space to the second String:

separated[1] = separated[1].trim();

If you want to split the string with a special character like dot(.) you should use escape character \ before the dot

Example:

String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"

There are other ways to do it. For instance, you can use the StringTokenizer class (from java.util):

StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method

Create GUI using Eclipse (Java)

Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here

How do I get the entity that represents the current user in Symfony2?

$this->container->get('security.token_storage')->getToken()->getUser();

Best way to parse command-line parameters?

scopt/scopt

val parser = new scopt.OptionParser[Config]("scopt") {
  head("scopt", "3.x")

  opt[Int]('f', "foo") action { (x, c) =>
    c.copy(foo = x) } text("foo is an integer property")

  opt[File]('o', "out") required() valueName("<file>") action { (x, c) =>
    c.copy(out = x) } text("out is a required file property")

  opt[(String, Int)]("max") action { case ((k, v), c) =>
    c.copy(libName = k, maxCount = v) } validate { x =>
    if (x._2 > 0) success
    else failure("Value <max> must be >0") 
  } keyValueName("<libname>", "<max>") text("maximum count for <libname>")

  opt[Unit]("verbose") action { (_, c) =>
    c.copy(verbose = true) } text("verbose is a flag")

  note("some notes.\n")

  help("help") text("prints this usage text")

  arg[File]("<file>...") unbounded() optional() action { (x, c) =>
    c.copy(files = c.files :+ x) } text("optional unbounded args")

  cmd("update") action { (_, c) =>
    c.copy(mode = "update") } text("update is a command.") children(
    opt[Unit]("not-keepalive") abbr("nk") action { (_, c) =>
      c.copy(keepalive = false) } text("disable keepalive"),
    opt[Boolean]("xyz") action { (x, c) =>
      c.copy(xyz = x) } text("xyz is a boolean property")
  )
}
// parser.parse returns Option[C]
parser.parse(args, Config()) map { config =>
  // do stuff
} getOrElse {
  // arguments are bad, usage message will have been displayed
}

The above generates the following usage text:

scopt 3.x
Usage: scopt [update] [options] [<file>...]

  -f <value> | --foo <value>
        foo is an integer property
  -o <file> | --out <file>
        out is a required file property
  --max:<libname>=<max>
        maximum count for <libname>
  --verbose
        verbose is a flag
some notes.

  --help
        prints this usage text
  <file>...
        optional unbounded args

Command: update
update is a command.

  -nk | --not-keepalive
        disable keepalive    
  --xyz <value>
        xyz is a boolean property

This is what I currently use. Clean usage without too much baggage. (Disclaimer: I now maintain this project)

How to work with string fields in a C struct?

You could just use an even simpler typedef:

typedef char *string;

Then, your malloc would look like a usual malloc:

string s = malloc(maxStringLength);

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

You have to change the mamp Mysql Database port into 8889.

How to initialize a list of strings (List<string>) with many string values

You haven't really asked a question, but the code should be

List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"}; 

i.e. no trailing () after the list.

How to determine the installed webpack version

Just another way not mentioned yet:

If you installed it locally to a project then open up the node_modules folder and check your webpack module.

$cd /node_modules/webpack/package.json

Open the package.json file and look under version

enter image description here

C# getting its own class name

Use this

Let say Application Test.exe is running and function is foo() in form1 [basically it is class form1], then above code will generate below response.

string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;

This will return .

s1 = "TEST.form1"

for function name:

string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;

will return

s1 = foo 

Note if you want to use this in exception use :

catch (Exception ex)
{

    MessageBox.Show(ex.StackTrace );

}

How can I execute a PHP function in a form action?

In PHP functions will not be evaluated inside strings, because there are different rules for variables.

<?php
function name() {
  return 'Mark';
}

echo 'My name is: name()';   // Output: My name is name()
echo 'My name is: '. name(); // Output: My name is Mark

The action parameter to the tag in HTML should not reference the PHP function you want to run. Action should refer to a page on the web server that will process the form input and return new HTML to the user. This can be the same location as the PHP script that outputs the form, or some people prefer to make a separate PHP file to handle actions.

The basic process is the same either way:

  1. Generate HTML form to the user.
  2. User fills in the form, clicks submit.
  3. The form data is sent to the locations defined by action on the server.
  4. The script validates the data and does something with it.
  5. Usually a new HTML page is returned.

A simple example would be:

<?php
// $_POST is a magic PHP variable that will always contain
// any form data that was posted to this page.
// We check here to see if the textfield called 'name' had
// some data entered into it, if so we process it, if not we
// output the form.
if (isset($_POST['name'])) {
  print_name($_POST['name']);
}
else {
  print_form();
}

// In this function we print the name the user provided.
function print_name($name) {
  // $name should be validated and checked here depending on use.
  // In this case we just HTML escape it so nothing nasty should
  // be able to get through:
  echo 'Your name is: '. htmlentities($name);
}

// This function is called when no name was sent to us over HTTP.
function print_form() {
  echo '
    <form name="form1" method="post" action="">
    <p><label><input type="text" name="name" id="textfield"></label></p>
    <p><label><input type="submit" name="button" id="button" value="Submit"></label></p>
    </form>
  ';
}
?>

For future information I recommend reading the PHP tutorials: http://php.net/tut.php

There is even a section about Dealing with forms.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

In my case port 8080 are already use by my local xampp server during oracle installation software check un used port like pop window appear for me enter image description here

so for me url is http://127.0.0.1:8081/apex/f?p=4950:1:4076881202565564

How to declare a global variable in a .js file

Have you tried it?

If you do:

var HI = 'Hello World';

In global.js. And then do:

alert(HI);

In js1.js it will alert it fine. You just have to include global.js prior to the rest in the HTML document.

The only catch is that you have to declare it in the window's scope (not inside any functions).

You could just nix the var part and create them that way, but it's not good practice.

How to change href attribute using JavaScript after opening the link in a new window?

for example try this :

<a href="http://www.google.com" id="myLink1">open link 1</a><br/> <a href="http://www.youtube.com" id="myLink2">open link 2</a>



    document.getElementById("myLink1").onclick = function() {
    window.open(
    "http://www.facebook.com"
        );
        return false;
      };

      document.getElementById("myLink2").onclick = function() {
    window.open(
    "http://www.yahoo.com"
        );
        return false;
      };

JPA eager fetch does not join

If you use EclipseLink instead of Hibernate you can optimize your queries by "query hints". See this article from the Eclipse Wiki: EclipseLink/Examples/JPA/QueryOptimization.

There is a chapter about "Joined Reading".

Checking if a number is an Integer in Java

if you're talking floating point values, you have to be very careful due to the nature of the format.

the best way that i know of doing this is deciding on some epsilon value, say, 0.000001f, and then doing something like this:

boolean nearZero(float f)
{
    return ((-episilon < f) && (f <epsilon)); 
}

then

if(nearZero(z-(int)z))
{ 
    //do stuff
}

essentially you're checking to see if z and the integer case of z have the same magnitude within some tolerance. This is necessary because floating are inherently imprecise.

NOTE, HOWEVER: this will probably break if your floats have magnitude greater than Integer.MAX_VALUE (2147483647), and you should be aware that it is by necessity impossible to check for integral-ness on floats above that value.

How to find the foreach index?

I solved this way, when I had to use the foreach index and value in the same context:

$array = array('a', 'b', 'c');
foreach ($array as $letter=>$index) {

  echo $letter; //Here $letter content is the actual index
  echo $array[$letter]; // echoes the array value

}//foreach

MySQL date formats - difficulty Inserting a date

Put the date in single quotes and move the parenthesis (after the 'yes') to the end:

INSERT INTO custorder 
  VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
                        ^                                     ^
---parenthesis removed--|                and added here ------|

But you can always use dates without STR_TO_DATE() function, just use the (Y-m-d) '20120101' or '2012-01-01' format. Check the MySQL docs: Date and Time Literals

INSERT INTO custorder 
  VALUES ('Kevin', 'yes', '2012-01-01') ;

How to convert a String to Bytearray

If you are looking for a solution that works in node.js, you can use this:

var myBuffer = [];
var str = 'Stack Overflow';
var buffer = new Buffer(str, 'utf16le');
for (var i = 0; i < buffer.length; i++) {
    myBuffer.push(buffer[i]);
}

console.log(myBuffer);

android:layout_height 50% of the screen size

To make sure the height of a view is 50% of the screen then we can create two sub LinearLayouts in a LinearLayout. Each of the child LinearLayout should have "android:layout_weight" of 0.5 to cover half the screen

the parent LinearLAyout should have "android:orientation" set to vertical

.

.

here is code for your reference.... this code contains two buttons of height half the screen

<LinearLayout 
android:orientation="vertical"
android:layout_height="match_parent">

<LinearLayout

    android:layout_weight="0.5"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:padding="10dp"
        android:layout_weight="0.5"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="button1"
        android:id="@+id/button1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        />

    <Button
        android:padding="10dp"
        android:layout_weight="0.5"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="button2"
        android:id="@+id/button2"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        />

    </LinearLayout>

<LinearLayout

    android:layout_weight="0.5"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">


    </LinearLayout>
   </LinearLayout>

Good ways to sort a queryset? - Django

What about

import operator

auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))

In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

order_by(*fields)

By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.

Example:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.

Insert content into iFrame

This should do what you want:

$("#iframe").ready(function() {
    var body = $("#iframe").contents().find("body");
    body.append('Test');
});

Check this JSFiddle for working demo.

Edit: You can of course do it one line style:

$("#iframe").contents().find("body").append('Test');

composer laravel create project

No this step isn't equal to downloading the laravel.zip by using the command composer create-project laravel/laravel laravel you actually download the laravel project as well as dependent packages so its one step ahead.

If you are using windows environment you can solve the problem by deleting the composer environment variable you created to install the composer. And this command will run properly.

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

check gradle.properties and add android.useAndroidX=true or you can also add android.enableJetifier=true or you can comment it by #

worked for me

C++ Double Address Operator? (&&)

I believe that is is a move operator. operator= is the assignment operator, say vector x = vector y. The clear() function call sounds like as if it is deleting the contents of the vector to prevent a memory leak. The operator returns a pointer to the new vector.

This way,

std::vector<int> a(100, 10);
std::vector<int> b = a;
for(unsigned int i = 0; i < b.size(); i++)
{
    std::cout << b[i] << ' ';
}

Even though we gave vector a values, vector b has the values. It's the magic of the operator=()!

MSDN -- How to create a move constructor

Copying text to the clipboard using Java

The following class allows you to copy/paste a String to/from the clipboard.

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;

import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;

public class SystemClipboard
{
    public static void copy(String text)
    {
        Clipboard clipboard = getSystemClipboard();
        clipboard.setContents(new StringSelection(text), null);
    }

    public static void paste() throws AWTException
    {
        Robot robot = new Robot();

        int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
        robot.keyPress(controlKey);
        robot.keyPress(VK_V);
        robot.keyRelease(controlKey);
        robot.keyRelease(VK_V);
    }

    public static String get() throws Exception
    {
        Clipboard systemClipboard = getSystemClipboard();
        DataFlavor dataFlavor = DataFlavor.stringFlavor;

        if (systemClipboard.isDataFlavorAvailable(dataFlavor))
        {
            Object text = systemClipboard.getData(dataFlavor);
            return (String) text;
        }

        return null;
    }

    private static Clipboard getSystemClipboard()
    {
        Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        return defaultToolkit.getSystemClipboard();
    }
}

Alternative to deprecated getCellType

It looks that 3.15 offers no satisfying solution: either one uses the old style with Cell.CELL_TYPE_*, or we use the method getCellTypeEnum() which is marked as deprecated. A lot of disturbances for little add value...

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

What is this spring.jpa.open-in-view=true property in Spring Boot?

This property will register an OpenEntityManagerInViewInterceptor, which registers an EntityManager to the current thread, so you will have the same EntityManager until the web request is finished. It has nothing to do with a Hibernate SessionFactory etc.

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

HTML Upload MAX_FILE_SIZE does not appear to work

It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.

How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.

It seems that the built in upload support in PHP is one to use this field value.

Is there a Google Voice API?

Well... These are PHP. There is an sms one from google here.

And github has one here.

Another sms one is here. However, this one has a lot more code, so it may take up more space.

NSDictionary to NSArray?

Leaving aside the technical issues with the code you posted, you asked this:

To use this Dictionary Items in a Table View i have to transfer it to a NSArray, am i right?

The answer to which is: not necessarily. There's nothing intrinsic to the machinery of UITableView, UITableViewDataSource, or UITableViewDelegate that means that your data has to be in an array. You will need to implement various methods to tell the system how many rows are in your table, and what data appears in each row. Many people find it much more natural and efficient to answer those questions with an ordered data structure like an array. But there's no requirement that you do so. If you can write the code to implement those methods with the dictionary you started with, feel free!

Hive cast string to date dd-MM-yyyy

Let's say you have a column 'birth_day' in your table which is in string format, you should use the following query to filter using birth_day

date_Format(birth_day, 'yyyy-MM-dd')

You can use it in a query in the following way

select * from yourtable
where 
date_Format(birth_day, 'yyyy-MM-dd') = '2019-04-16';

How to change the status bar color in Android?

change the colorPrimaryDark to your desire color into the res/values/styles.xml file

    <resources>
        <color name="colorPrimary">#800000</color>
        <color name="colorPrimaryDark">#303F9F</color> //This Line
        <color name="colorAccent">#FF4081</color>
        <color name="red">#FF0000</color>
        <color name="white">#FFFFFF</color>
       <color name="cream">#fffdd0</color>
       <color name="burgundy">#800000</color>
    </resources>

Change the location of an object programmatically

Use either:

balancePanel.Left = optionsPanel.Location.X;

or

balancePanel.Location = new Point(optionsPanel.Location.X, balancePanel.Location.Y);

See the documentation of Location:

Because the Point class is a value type (Structure in Visual Basic, struct in Visual C#), it is returned by value, meaning accessing the property returns a copy of the upper-left point of the control. So, adjusting the X or Y properties of the Point returned from this property will not affect the Left, Right, Top, or Bottom property values of the control. To adjust these properties set each property value individually, or set the Location property with a new Point.

comparing two strings in ruby

var1 is a regular string, whereas var2 is an array, this is how you should compare (in this case):

puts var1 == var2[0]

Long Press in JavaScript?

Based on Maycow Moura's answer, I wrote this. It also ensures that the user didn't do a right click, which would trigger a long press and works on mobile devices. DEMO

var node = document.getElementsByTagName("p")[0];
var longpress = false;
var presstimer = null;
var longtarget = null;

var cancel = function(e) {
    if (presstimer !== null) {
        clearTimeout(presstimer);
        presstimer = null;
    }

    this.classList.remove("longpress");
};

var click = function(e) {
    if (presstimer !== null) {
        clearTimeout(presstimer);
        presstimer = null;
    }

    this.classList.remove("longpress");

    if (longpress) {
        return false;
    }

    alert("press");
};

var start = function(e) {
    console.log(e);

    if (e.type === "click" && e.button !== 0) {
        return;
    }

    longpress = false;

    this.classList.add("longpress");

    if (presstimer === null) {
        presstimer = setTimeout(function() {
            alert("long click");
            longpress = true;
        }, 1000);
    }

    return false;
};

node.addEventListener("mousedown", start);
node.addEventListener("touchstart", start);
node.addEventListener("click", click);
node.addEventListener("mouseout", cancel);
node.addEventListener("touchend", cancel);
node.addEventListener("touchleave", cancel);
node.addEventListener("touchcancel", cancel);

You should also include some indicator using CSS animations:

p {
    background: red;
    padding: 100px;
}

.longpress {
    -webkit-animation: 1s longpress;
            animation: 1s longpress;
}

@-webkit-keyframes longpress {
    0%, 20% { background: red; }
    100% { background: yellow; }
}

@keyframes longpress {
    0%, 20% { background: red; }
    100% { background: yellow; }
}

Java Ordered Map

The SortedMap interface (with the implementation TreeMap) should be your friend.

The interface has the methods:

  • keySet() which returns a set of the keys in ascending order
  • values() which returns a collection of all values in the ascending order of the corresponding keys

So this interface fulfills exactly your requirements. However, the keys must have a meaningful order. Otherwise you can used the LinkedHashMap where the order is determined by the insertion order.

How do I get the value of a textbox using jQuery?

Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.

You should not use <Link> outside a <Router>

Whenever you try to show a Link on a page thats outside the BrowserRouter you will get that error.

This error message is essentially saying that any component that is not a child of our <Router> cannot contain any React Router related components.

You need to migrate your component hierarchy to how you see it in the first answer above. For anyone else reviewing this post who may need to look at more examples.

Let's say you have a Header.jscomponent that looks like this:

import React from 'react';
import { Link } from 'react-router-dom';

const Header = () => {
    return (
        <div className="ui secondary pointing menu">
            <Link to="/" className="item">
                Streamy
            </Link>
            <div className="right menu">
                <Link to="/" className="item">
                    All Streams
                </Link>
            </div>
        </div>
    );
};

export default Header;

And your App.js file looks like this:

import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';

const App = () => {
  return (
    <div className="ui container">
      <Header />
      <BrowserRouter>
        <div>
        <Route path="/" exact component={StreamList} />
        <Route path="/streams/new" exact component={StreamCreate} />
        <Route path="/streams/edit" exact component={StreamEdit} />
        <Route path="/streams/delete" exact component={StreamDelete} />
        <Route path="/streams/show" exact component={StreamShow} />
        </div> 
      </BrowserRouter>
    </div>
  );
};

export default App;

Notice that the Header.js component is making use of the Link tag from react-router-dom but the componet was placed outside the <BrowserRouter>, this will lead to the same error as the one experience by the OP. In this case, you can make the correction in one move:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';

const App = () => {
  return (
    <div className="ui container">
      <BrowserRouter>
        <div>
        <Header />
        <Route path="/" exact component={StreamList} />
        <Route path="/streams/new" exact component={StreamCreate} />
        <Route path="/streams/edit" exact component={StreamEdit} />
        <Route path="/streams/delete" exact component={StreamDelete} />
        <Route path="/streams/show" exact component={StreamShow} />
        </div> 
      </BrowserRouter>
    </div>
  );
};

export default App;

Please review carefully and ensure you have the <Header /> or whatever your component may be inside of not only the <BrowserRouter> but also inside of the <div>, otherwise you will also get the error that a Router may only have one child which is referring to the <div> which is the child of <BrowserRouter>. Everything else such as Route and components must go within it in the hierarchy.

So now the <Header /> is a child of the <BrowserRouter> within the <div> tags and it can successfully make use of the Link element.

How to move the cursor word by word in the OS X Terminal

If you check Use option as meta key in the keyboard tab of the preferences, then the default emacs style commands for forward- and backward-word and ?F (Alt+F) and ?B (Alt+B) respectively.

I'd recommend reading From Bash to Z-Shell. If you want to increase your bash/zsh prowess!

Extract directory path and filename

dirname "/usr/home/theconjuring/music/song.mp3" will yield /usr/home/theconjuring/music.

Didn't Java once have a Pair class?

It does seem odd. I found this thread, also thinking I'd seen one in the past, but couldn't find it in Javadoc.

I can see the Java developers' point about using specialised classes, and that the presence of a generic Pair class could cause developers to be lazy (perish the thought!)

However, in my experience, there are undoubtedly times when the thing you're modelling really is just a pair of things and coming up with a meaningful name for the relationship between the two halves of the pair, is actually more painful than just getting on with it. So instead, we're left to create a 'bespoke' class of practically boiler-plate code - probably called 'Pair'.

This could be a slippery slope, but a Pair and a Triplet class would cover a very large proportion of the use-cases.

Access is denied when attaching a database

With me - Running on window 8 - RIght click SQL Server Manager Studio -> Run with admin. -> attach no problems

SQL Insert Query Using C#

I assume you have a connection to your database and you can not do the insert parameters using c #.

You are not adding the parameters in your query. It should look like:

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");

command.ExecuteNonQuery();

Updated:

using(SqlConnection connection = new SqlConnection(_connectionString))
{
    String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

    using(SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@id", "abc");
        command.Parameters.AddWithValue("@username", "abc");
        command.Parameters.AddWithValue("@password", "abc");
        command.Parameters.AddWithValue("@email", "abc");

        connection.Open();
        int result = command.ExecuteNonQuery();

        // Check Error
        if(result < 0)
            Console.WriteLine("Error inserting data into Database!");
    }
}

json.net has key method?

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

How to redirect the output of print to a TXT file

To redirect output for all prints, you can do this:

import sys
with open('c:\\goat.txt', 'w') as f:
    sys.stdout = f
    print "test"

pip not working in Python Installation in Windows 10

You may have to run cmd as administrator to perform these tasks. You can do it by right clicking on cmd icon and selecting run as administrator. It's worked for me.

Cross browser method to fit a child div to its parent's width

In case you want to use that padding space... then here's something:

http://jsfiddle.net/qD4zd/

All the colors are background colors.

How to add a where clause in a MySQL Insert statement?

INSERT INTO users (id,username, password) 
VALUES ('1','Jack','123')
ON DUPLICATE KEY UPDATE username='Jack',password='123'

This will work only if the id field is unique/pk (not composite PK though) Also, this will insert if no id of value 1 is found and update otherwise the record with id 1 if it does exists.

Rails 3: I want to list all paths defined in my rails application

Update

I later found that, there is an official way to see all the routes, by going to http://localhost:3000/rails/info/routes. Official docs: https://guides.rubyonrails.org/routing.html#listing-existing-routes


Though, it may be late, But I love the error page which displays all the routes. I usually try to go at /routes (or some bogus) path directly from the browser. Rails server automatically gives me a routing error page as well as all the routes and paths defined. That was very helpful :)

So, Just go to http://localhost:3000/routes enter image description here

How to write a Python module/package?

Make a file named "hello.py"

If you are using Python 2.x

def func():
    print "Hello"

If you are using Python 3.x

def func():
    print("Hello")

Run the file. Then, you can try the following:

>>> import hello
>>> hello.func()
Hello

If you want a little bit hard, you can use the following:

If you are using Python 2.x

def say(text):
    print text

If you are using Python 3.x

def say(text):
    print(text)

See the one on the parenthesis beside the define? That is important. It is the one that you can use within the define.

Text - You can use it when you want the program to say what you want. According to its name, it is text. I hope you know what text means. It means "words" or "sentences".

Run the file. Then, you can try the following if you are using Python 3.x:

>>> import hello
>>> hello.say("hi")
hi
>>> from hello import say
>>> say("test")
test

For Python 2.x - I guess same thing with Python 3? No idea. Correct me if I made a mistake on Python 2.x (I know Python 2 but I am used with Python 3)

Detect if string contains any spaces

var string  = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked: 
if(arr[i] === ' '){
   console.log(i);
}

I know regex can do the trick too!

Detect network connection type on Android

String active_network = ((ConnectivityManager)
    .getSystemService(Context.CONNECTIVITY_SERVICE))
    .getActiveNetworkInfo().getSubtypeName();

should get you the network name

Replace multiple strings with multiple other strings

by using prototype function we can replace easily by passing object with keys and values and replacable text

_x000D_
_x000D_
String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
 return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)
}

const data='hids dv sdc sd ${yathin} ${ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'${key}'))
_x000D_
_x000D_
_x000D_

Finding the median of an unsorted array

The answer is "No, one can't find the median of an arbitrary, unsorted dataset in linear time". The best one can do as a general rule (as far as I know) is Median of Medians (to get a decent start), followed by Quickselect. Ref: [https://en.wikipedia.org/wiki/Median_of_medians][1]

Concatenate a list of pandas dataframes together

Given that all the dataframes have the same columns, you can simply concat them:

import pandas as pd
df = pd.concat(list_of_dataframes)

How to select multiple files with <input type="file">?

New answer:

In HTML5 you can add the multiple attribute to select more than 1 file.

<input type="file" name="filefield" multiple="multiple">

Old answer:

You can only select 1 file per <input type="file" />. If you want to send multiple files you will have to use multiple input tags or use Flash or Silverlight.

How to disable all <input > inside a form with jQuery?

In older versions you could use attr. As of jQuery 1.6 you should use prop instead:

$("#target :input").prop("disabled", true);

To disable all form elements inside 'target'. See :input:

Matches all input, textarea, select and button elements.

If you only want the <input> elements:

$("#target input").prop("disabled", true);

What's the best way to store a group of constants that my program uses?

You probably could have them in a static class, with static read-only properties.

public static class Routes
{
    public static string SignUp => "signup";
}

Get elements by attribute when querySelectorAll is not available without using libraries?

Try this - I slightly changed the above answers:

var getAttributes = function(attribute) {
    var allElements = document.getElementsByTagName('*'),
        allElementsLen = allElements.length,
        curElement,
        i,
        results = [];

    for(i = 0; i < allElementsLen; i += 1) {
        curElement = allElements[i];

        if(curElement.getAttribute(attribute)) {
            results.push(curElement);
        }
    }

    return results;
};

Then,

getAttributes('data-foo');

How can I run a program from a batch file without leaving the console open after the program starts?

Loads of answers for this question already, but I am posting this to clarify something important, though this might not always be the case:

Start "C:\Program Files\someprog.exe"

Might cause issues in some windows versions as Start actually expects the first set of quotation marks to be a windows title. So it is best practice to first double quote a comment, or a blank comment:

Start "" "C:\Program Files\someprog.exe"

or

Start "Window Title" "C:\Program Files\someprog.exe"

How do I center an anchor element in CSS?

css cannot be directly applied for the alignment of the anchor tag. The css (text-align:center;) should be applied to the parent div/element for the alignment effect to take place on the anchor tag.

SSL Proxy/Charles and Android trouble

The top rated answers are working perfect (a bit old but still working), but I just want to mention that since Android N we all can configure your apps in order to have diff trust SSL certificates (for release , debug only and so on), including Charles SSL Proxy certificate (if you download the Charles certificate and put .pem file in your raw folder). More info can be found here: https://developer.android.com/training/articles/security-config.html

Also the official Charles documentation can be useful to setup this : https://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

Hope this will help to setup Charles inside your app project not on every single Android device.

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

Retrieve all values from HashMap keys in an ArrayList Java

Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.

Map <String, Object> map;
List<Object> list = new ArrayList<Object>(map.values());

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

HTML:

<div  ng-repeat="scannedDevice in ScanResult">
        <!--GridStarts-->
          <div >
              <img ng-src={{'./assets/img/PlaceHolder/Test.png'}} 
                   <!--Pass Param-->
                   ng-click="connectDevice(scannedDevice.id)"
                   altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}" 
                   onerror="this.src = $(this).attr('altSrc')">
           </div>    
 </div>

Java Script:

   //Global Variables
    var  ANGULAR_APP = angular.module('TestApp',[]);

    ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {

      //Variables
      $scope.ScanResult = [];

      //Pass Parameter
      $scope.connectDevice = function(deviceID) {
            alert("Connecting : "+deviceID );
        };
     }]);

Link to a section of a webpage

Simple:

Use <section>.

and use <a href="page.html#tips">Visit the Useful Tips Section</a>

w3school.com/html_links

JavaScript regex for alphanumeric string with length of 3-5 chars

You'd have to define alphanumerics exactly, but

/^(\w{3,5})$/ 

Should match any digit/character/_ combination of length 3-5.

If you also need the dash, make sure to escape it (\-) add it, like this: :

/^([\w\-]{3,5})$/ 

Also: the ^ anchor means that the sequence has to start at the beginning of the line (character string), and the $ that it ends at the end of the line (character string). So your value string mustn't contain anything else, or it won't match.

Why doesn't java.io.File have a close method?

A BufferedReader can be opened and closed but a File is never opened, it just represents a path in the filesystem.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

Flutter Countdown Timer

If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!

countDownTimer() async {
 int timerCount;
 for (int x = 5; x > 0; x--) {
   await Future.delayed(Duration(seconds: 1)).then((_) {
     setState(() {
       timerCount -= 1;
    });
  });
 }
}

How could I create a list in c++?

We are already in 21st century!! Don't try to implement the already existing data structures. Try to use the existing data structures.

Use STL or Boost library

Algorithm for solving Sudoku

Here is a much faster solution based on hari's answer. The basic difference is that we keep a set of possible values for cells that don't have a value assigned. So when we try a new value, we only try valid values and we also propagate what this choice means for the rest of the sudoku. In the propagation step, we remove from the set of valid values for each cell the values that already appear in the row, column, or the same block. If only one number is left in the set, we know that the position (cell) has to have that value.

This method is known as forward checking and look ahead (http://ktiml.mff.cuni.cz/~bartak/constraints/propagation.html).

The implementation below needs one iteration (calls of solve) while hari's implementation needs 487. Of course my code is a bit longer. The propagate method is also not optimal.

import sys
from copy import deepcopy

def output(a):
    sys.stdout.write(str(a))

N = 9

field = [[5,1,7,6,0,0,0,3,4],
         [2,8,9,0,0,4,0,0,0],
         [3,4,6,2,0,5,0,9,0],
         [6,0,2,0,0,0,0,1,0],
         [0,3,8,0,0,6,0,4,7],
         [0,0,0,0,0,0,0,0,0],
         [0,9,0,0,0,0,0,7,8],
         [7,0,3,4,0,0,5,6,0],
         [0,0,0,0,0,0,0,0,0]]

def print_field(field):
    if not field:
        output("No solution")
        return
    for i in range(N):
        for j in range(N):
            cell = field[i][j]
            if cell == 0 or isinstance(cell, set):
                output('.')
            else:
                output(cell)
            if (j + 1) % 3 == 0 and j < 8:
                output(' |')

            if j != 8:
                output(' ')
        output('\n')
        if (i + 1) % 3 == 0 and i < 8:
            output("- - - + - - - + - - -\n")

def read(field):
    """ Read field into state (replace 0 with set of possible values) """

    state = deepcopy(field)
    for i in range(N):
        for j in range(N):
            cell = state[i][j]
            if cell == 0:
                state[i][j] = set(range(1,10))

    return state

state = read(field)


def done(state):
    """ Are we done? """

    for row in state:
        for cell in row:
            if isinstance(cell, set):
                return False
    return True


def propagate_step(state):
    """
    Propagate one step.

    @return:  A two-tuple that says whether the configuration
              is solvable and whether the propagation changed
              the state.
    """

            new_units = False

    # propagate row rule
    for i in range(N):
        row = state[i]
        values = set([x for x in row if not isinstance(x, set)])
        for j in range(N):
            if isinstance(state[i][j], set):
                state[i][j] -= values
                if len(state[i][j]) == 1:
                    val = state[i][j].pop()
                    state[i][j] = val
                    values.add(val)
                    new_units = True
                elif len(state[i][j]) == 0:
                    return False, None

    # propagate column rule
    for j in range(N):
        column = [state[x][j] for x in range(N)]
        values = set([x for x in column if not isinstance(x, set)])
        for i in range(N):
            if isinstance(state[i][j], set):
                state[i][j] -= values
                if len(state[i][j]) == 1:
                    val = state[i][j].pop()
                    state[i][j] = val
                    values.add(val)
                    new_units = True
                elif len(state[i][j]) == 0:
                    return False, None

    # propagate cell rule
    for x in range(3):
        for y in range(3):
            values = set()
            for i in range(3 * x, 3 * x + 3):
                for j in range(3 * y, 3 * y + 3):
                    cell = state[i][j]
                    if not isinstance(cell, set):
                        values.add(cell)
            for i in range(3 * x, 3 * x + 3):
                for j in range(3 * y, 3 * y + 3):
                    if isinstance(state[i][j], set):
                        state[i][j] -= values
                        if len(state[i][j]) == 1:
                            val = state[i][j].pop()
                            state[i][j] = val
                            values.add(val)
                            new_units = True
                        elif len(state[i][j]) == 0:
                            return False, None

    return True, new_units

def propagate(state):
    """ Propagate until we reach a fixpoint """
    while True:
        solvable, new_unit = propagate_step(state)
        if not solvable:
            return False
        if not new_unit:
            return True


def solve(state):
    """ Solve sudoku """

    solvable = propagate(state)

    if not solvable:
        return None

    if done(state):
        return state

    for i in range(N):
        for j in range(N):
            cell = state[i][j]
            if isinstance(cell, set):
                for value in cell:
                    new_state = deepcopy(state)
                    new_state[i][j] = value
                    solved = solve(new_state)
                    if solved is not None:
                        return solved
                return None

print_field(solve(state))

Transitions on the CSS display property

You can get this to work the natural way you expected - using display - but you have to throttle the browser to get it to work, using either Javascript or as others have suggested a fancy trick with one tag inside another. I don't care for the inner tag as it further complicates CSS and dimensions, so here's the Javascript solution:

https://jsfiddle.net/b9chris/hweyecu4/17/

Starting with a box like:

<div id="box" class="hidden">Lorem</div>

A hidden box.

div.hidden {
    display: none;
}
#box {
    transition: opacity 1s;
}
    

We're going to use a trick found in a related q/a, checking offsetHeight to throttle the browser instantaneously:

https://stackoverflow.com/a/16575811/176877

First, a library formalizing the above trick:

$.fn.noTrnsn = function () {
    return this.each(function (i, tag) {
        tag.style.transition = 'none';
    });
};
$.fn.resumeTrnsn = function () {
    return this.each(function (i, tag) {
        tag.offsetHeight;    
        tag.style.transition = null;
    });
};

Next, we're going to use it to reveal a box, and fade it in:

$('#button').on('click', function() {
    var tag = $('#box');
    if (tag.hasClass('hidden'))
        tag.noTrnsn().removeClass('hidden')
        .css({ opacity: 0 })
        .resumeTrnsn().css({ opacity: 1 });
    else
        tag.css({ opacity: 0 });
});

This fades the box in and out. So, .noTrnsn() turns off transitions, then we remove the hidden class, which flips display from none to its default, block. We then set opacity to 0 to get ready for fading in. Now that we've set the stage, we turn transitions back on, with .resumeTrnsn(). And finally, kick off the transition by setting opacity to 1.

Without the library, both the change to display and the change to opacity would've gotten us undesirable results. If we simply removed the library calls, we'd get no transitions at all.

Note that the above does not set display to none again at the end of the fadeout animation. We can get fancier though. Let's do so with one that fades in and grows in height from 0.

Fancy!

https://jsfiddle.net/b9chris/hweyecu4/22/

#box {
    transition: height 1s, opacity 1s;
}

We're now transitioning both height and opacity. Note that we are not setting height, which means it is the default, auto. Conventionally this cannot be transitioned - moving from auto to a pixel value (like 0) will get you no transition. We're going to work around that with the library, and one more library method:

$.fn.wait = function (time, fn) {
    if (time)
        this.delay(time);
    if (!fn)
        return this;

    var _this = this;
    return this.queue(function (n) {
        fn.call(_this);
        n();
    });
};

This is a convenience method that lets us participate in jQuery's existing fx/animation queue, without requiring any of the animation framework that's now excluded in jQuery 3.x. I'm not going to explain how jQuery works, but suffice to say, the .queue() and .stop() plumbing that jQuery provides help us prevent our animations from stepping on each other.

Let's animate the slide down effect.

$('#button').on('click', function() {
    var tag = $('#box');
    if (tag.hasClass('hidden')) {
        // Open it
        // Measure it
        tag.stop().noTrnsn().removeClass('hidden').css({
            opacity: 0, height: 'auto'
        });
        var h = tag.height();
        tag.css({ height: 0 }).resumeTrnsn()
        // Animate it
        .css({ opacity: 1, height: h })
        .wait(1000, function() {
            tag.css({ height: 'auto' });
        });
    } else {
        // Close it
        // Measure it
        var h = tag.noTrnsn().height();
        tag.stop().css({ height: h })
        .resumeTrnsn()
        // Animate it
        .css({ opacity: 0, height: 0 })
        .wait(1000, function() {
            tag.addClass('hidden');
        });
    }
});

This code begins by checking on #box and whether it's currently hidden, by checking on its class. But it accomplishes more using the wait() library call, by adding the hidden class at the end of the slideout/fade animation, which you'd expect to find if it is in fact hidden - something the above simpler example could not do. This happens to also enable display/hiding the element over and over, which was a bug in the previous example, because the hidden class was never restored.

You can also see CSS and class changes being called after .noTrnsn() to generally set the stage for animations, including taking measurements, like measuring what will be the final height of #box without showing that to the user, before calling .resumeTrnsn(), and animating it from that fully-set stage to its goal CSS values.

Old Answer

https://jsfiddle.net/b9chris/hweyecu4/1/

You can have it transition on click with:

function toggleTransition() {
  var el = $("div.box1");

  if (el.length) {
    el[0].className = "box";
    el.stop().css({maxWidth: 10000}).animate({maxWidth: 10001}, 2000, function() {
        el[0].className = "box hidden";
    });
  } else {
    el = $("div.box");
    el[0].className = "box";
    el.stop().css({maxWidth: 10001}).animate({maxWidth: 10000}, 50, function() {
        el[0].className = "box box1";
    });
  }

  return el;
}

someTag.click(toggleTransition);

The CSS is what you'd guess:

.hidden {
    display: none;
}
.box {
    width: 100px;
    height: 100px;
    background-color: blue;
    color: yellow;
    font-size: 18px;
    left: 20px;
    top: 20px;
    position: absolute;
    -webkit-transform-origin: 0 50%;
    transform-origin: 0 50%;
    -webkit-transform: scale(.2);
    transform: scale(.2);
    -webkit-transition: transform 2s;
    transition: transform 2s;
}
.box1{
    -webkit-transform: scale(1);
    transform: scale(1);
}

The key is throttling the display property. By removing the hidden class and then waiting 50 ms, then starting the transition via the added class, we get it to appear and then expand like we wanted, instead of it just blipping onto the screen without any animation. Similar occurs going the other way, except we wait till the animation is over before applying hidden.

Note: I'm abusing .animate(maxWidth) here to avoid setTimeout race conditions. setTimeout is quick to introduce hidden bugs when you or someone else picks up code unaware of it. .animate() can easily be killed with .stop(). I'm just using it to put a 50 ms or 2000 ms delay on the standard fx queue where it's easy to find/resolve by other coders building on top of this.

Choosing a jQuery datagrid plugin?

A good plugin that I have used before is DataTables.

Multiple submit buttons in the same form calling different Servlets

    function gotofirst(){
        window.location = "firstServelet.java";
}
    function gotosecond(){
        window.location = "secondServelet.java";
}
<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" onclick="gotofirst()" value="FirstServlet">
    <input type="submit" onclick="gotosecond()" value="SecondServlet">
</form>

How to use BeanUtils.copyProperties?

There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.

One is

org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)

Another is

org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)

Pay attention to the opposite position of parameters.

Find all paths between two graph nodes

If you actually care about ordering your paths from shortest path to longest path then it would be far better to use a modified A* or Dijkstra Algorithm. With a slight modification the algorithm will return as many of the possible paths as you want in order of shortest path first. So if what you really want are all possible paths ordered from shortest to longest then this is the way to go.

If you want an A* based implementation capable of returning all paths ordered from the shortest to the longest, the following will accomplish that. It has several advantages. First off it is efficient at sorting from shortest to longest. Also it computes each additional path only when needed, so if you stop early because you dont need every single path you save some processing time. It also reuses data for subsequent paths each time it calculates the next path so it is more efficient. Finally if you find some desired path you can abort early saving some computation time. Overall this should be the most efficient algorithm if you care about sorting by path length.

import java.util.*;

public class AstarSearch {
    private final Map<Integer, Set<Neighbor>> adjacency;
    private final int destination;

    private final NavigableSet<Step> pending = new TreeSet<>();

    public AstarSearch(Map<Integer, Set<Neighbor>> adjacency, int source, int destination) {
        this.adjacency = adjacency;
        this.destination = destination;

        this.pending.add(new Step(source, null, 0));
    }

    public List<Integer> nextShortestPath() {
        Step current = this.pending.pollFirst();
        while( current != null) {
            if( current.getId() == this.destination )
                return current.generatePath();
            for (Neighbor neighbor : this.adjacency.get(current.id)) {
                if(!current.seen(neighbor.getId())) {
                    final Step nextStep = new Step(neighbor.getId(), current, current.cost + neighbor.cost + predictCost(neighbor.id, this.destination));
                    this.pending.add(nextStep);
                }
            }
            current = this.pending.pollFirst();
        }
        return null;
    }

    protected int predictCost(int source, int destination) {
        return 0; //Behaves identical to Dijkstra's algorithm, override to make it A*
    }

    private static class Step implements Comparable<Step> {
        final int id;
        final Step parent;
        final int cost;

        public Step(int id, Step parent, int cost) {
            this.id = id;
            this.parent = parent;
            this.cost = cost;
        }

        public int getId() {
            return id;
        }

        public Step getParent() {
            return parent;
        }

        public int getCost() {
            return cost;
        }

        public boolean seen(int node) {
            if(this.id == node)
                return true;
            else if(parent == null)
                return false;
            else
                return this.parent.seen(node);
        }

        public List<Integer> generatePath() {
            final List<Integer> path;
            if(this.parent != null)
                path = this.parent.generatePath();
            else
                path = new ArrayList<>();
            path.add(this.id);
            return path;
        }

        @Override
        public int compareTo(Step step) {
            if(step == null)
                return 1;
            if( this.cost != step.cost)
                return Integer.compare(this.cost, step.cost);
            if( this.id != step.id )
                return Integer.compare(this.id, step.id);
            if( this.parent != null )
                this.parent.compareTo(step.parent);
            if(step.parent == null)
                return 0;
            return -1;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Step step = (Step) o;
            return id == step.id &&
                cost == step.cost &&
                Objects.equals(parent, step.parent);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id, parent, cost);
        }
    }

   /*******************************************************
   *   Everything below here just sets up your adjacency  *
   *   It will just be helpful for you to be able to test *
   *   It isnt part of the actual A* search algorithm     *
   ********************************************************/

    private static class Neighbor {
        final int id;
        final int cost;

        public Neighbor(int id, int cost) {
            this.id = id;
            this.cost = cost;
        }

        public int getId() {
            return id;
        }

        public int getCost() {
            return cost;
        }
    }

    public static void main(String[] args) {
        final Map<Integer, Set<Neighbor>> adjacency = createAdjacency();
        final AstarSearch search = new AstarSearch(adjacency, 1, 4);
        System.out.println("printing all paths from shortest to longest...");
        List<Integer> path = search.nextShortestPath();
        while(path != null) {
            System.out.println(path);
            path = search.nextShortestPath();
        }
    }

    private static Map<Integer, Set<Neighbor>> createAdjacency() {
        final Map<Integer, Set<Neighbor>> adjacency = new HashMap<>();

        //This sets up the adjacencies. In this case all adjacencies have a cost of 1, but they dont need to.
        addAdjacency(adjacency, 1,2,1,5,1);         //{1 | 2,5}
        addAdjacency(adjacency, 2,1,1,3,1,4,1,5,1); //{2 | 1,3,4,5}
        addAdjacency(adjacency, 3,2,1,5,1);         //{3 | 2,5}
        addAdjacency(adjacency, 4,2,1);             //{4 | 2}
        addAdjacency(adjacency, 5,1,1,2,1,3,1);     //{5 | 1,2,3}

        return Collections.unmodifiableMap(adjacency);
    }

    private static void addAdjacency(Map<Integer, Set<Neighbor>> adjacency, int source, Integer... dests) {
        if( dests.length % 2 != 0)
            throw new IllegalArgumentException("dests must have an equal number of arguments, each pair is the id and cost for that traversal");

        final Set<Neighbor> destinations = new HashSet<>();
        for(int i = 0; i < dests.length; i+=2)
            destinations.add(new Neighbor(dests[i], dests[i+1]));
        adjacency.put(source, Collections.unmodifiableSet(destinations));
    }
}

The output from the above code is the following:

[1, 2, 4]
[1, 5, 2, 4]
[1, 5, 3, 2, 4]

Notice that each time you call nextShortestPath() it generates the next shortest path for you on demand. It only calculates the extra steps needed and doesnt traverse any old paths twice. Moreover if you decide you dont need all the paths and end execution early you've saved yourself considerable computation time. You only compute up to the number of paths you need and no more.

Finally it should be noted that the A* and Dijkstra algorithms do have some minor limitations, though I dont think it would effect you. Namely it will not work right on a graph that has negative weights.

Here is a link to JDoodle where you can run the code yourself in the browser and see it working. You can also change around the graph to show it works on other graphs as well: http://jdoodle.com/a/ukx

How to return XML in ASP.NET?

Below is the server side code that would call the handler and recieve the stream data and loads into xml doc

 Stream stream = null;
       **Create a web request with the specified URL**
        WebRequest myWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
        **Senda a web request and wait for response.**
        WebResponse webResponse = myWebRequest.GetResponse();
        **Get the stream object from response object**
        stream = webResponse.GetResponseStream();

       XmlDocument xmlDoc = new XmlDocument();
      **Load stream data into xml**
       xmlDoc.Load(stream);

Swift - How to hide back button in navigation item?

Put it in the viewDidLoad method

navigationItem.hidesBackButton = true 

How do I call an Angular.js filter with multiple arguments?

If you need two or more dealings with the filter, is possible to chain them:

{{ value | decimalRound: 2 | currencySimbol: 'U$' }} 
// 11.1111 becomes U$ 11.11

How to solve a pair of nonlinear equations using Python?

An alternative to fsolve is root:

import numpy as np
from scipy.optimize import root    

def your_funcs(X):

    x, y = X
    # all RHS have to be 0
    f = [x + y**2 - 4,
         np.exp(x) + x * y - 3]

    return f

sol = root(your_funcs, [1.0, 1.0])
print(sol.x)

This will print

[0.62034452 1.83838393]

If you then check

print(your_funcs(sol.x))

you obtain

[4.4508396968012676e-11, -1.0512035686360832e-11]

confirming that the solution is correct.

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

How do I get my Maven Integration tests to run

You should try using maven failsafe plugin. You can tell it to include a certain set of tests.

CertificateException: No name matching ssl.someUrl.de found

I created a method fixUntrustCertificate(), so when I am dealing with a domain that is not in trusted CAs you can invoke the method before the request. This code will gonna work after java1.4. This method applies for all hosts:

public void fixUntrustCertificate() throws KeyManagementException, NoSuchAlgorithmException{


        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }

            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // set the  allTrusting verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

Docker Networking - nginx: [emerg] host not found in upstream

My Workaround (after much trial and error):

  • In order to get around this issue, I had to get the full name of the 'upstream' Docker container, found by running docker network inspect my-special-docker-network and getting the full name property of the upstream container as such:

    "Containers": {
         "39ad8199184f34585b556d7480dd47de965bc7b38ac03fc0746992f39afac338": {
              "Name": "my_upstream_container_name_1_2478f2b3aca0",
    
  • Then used this in the NGINX my-network.local.conf file in the location block of the proxy_pass property: (Note the addition of the GUID to the container name):

    location / {
        proxy_pass http://my_upsteam_container_name_1_2478f2b3aca0:3000;
    

As opposed to the previously working, but now broken:

    location / {
        proxy_pass http://my_upstream_container_name_1:3000

Most likely cause is a recent change to Docker Compose, in their default naming scheme for containers, as listed here.

This seems to be happening for me and my team at work, with latest versions of the Docker nginx image:

  • I've opened issues with them on the docker/compose GitHub here

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

Make sure that your self-signed certificate matches your site URL. If it does not, you will continue to get a certificate error even after explicitly trusting the certificate in Internet Explorer 8 (I don't have Internet Explorer 7, but Firefox will trust the certificate regardless of a URL mismatch).

If this is the problem, the red "Certificate Error" box in Internet Explorer 8 will show "Mismatched Address" as the error after you add your certificate. Also, "View Certificates" has an Issued to: label which shows what URL the certificate is valid against.

How to display 3 buttons on the same line in css

You need to float all the buttons to left and make sure its width to fit within outer container.

CSS:

.btn{

   float:left;
}

HTML:

    <button type="submit" class="btn" onClick="return false;" >Save</button>
    <button type="submit" class="btn" onClick="return false;">Publish</button>
    <button class="btn">Back</button>

How do I capture the output of a script if it is being ran by the task scheduler?

To supplement @user2744787's answer, here is a screenshot to show how to use cmd with arguments in a Scheduled Task:

Scheduled Task cmd output to logfile

Program/script: cmd

Add arguments: /c run_with_default_port.bat > IMQuantWebServices.log

Center div on the middle of screen

2018: CSS3

div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);
}

This is even shorter. For more information see this: CSS: Centering Things

Disable scrolling in webview?

I haven't tried this as I have yet to encounter this problem, but perhaps you could overrive the onScroll function?

@Override
public void scrollTo(int x, int y){
super.scrollTo(0,y);
}

How do I get console input in javascript?

In plain JavaScript, simply use response = readline() after printing a prompt.

In Node.js, you'll need to use the readline module: const readline = require('readline')

Git fetch remote branch

With this simple command:

git checkout -b 'your_branch' origin/'remote branch'

How to search if dictionary value contains certain string with Python

For me, this also worked:

def search(myDict, search1):
    search.a=[]
    for key, value in myDict.items():
        if search1 in value:
            search.a.append(key)

search(myDict, 'anyName')
print(search.a)
  • search.a makes the list a globally available
  • if a match of the substring is found in any value, the key of that value will be appended to a

Command failed due to signal: Segmentation fault: 11

In my case, I was trying to extend a CoreData class with a helper method that could work on all of its subclasses:

extension ExampleCoreDataClass {
   static func insert() -> Self {
   ...

I got no warnings about this, but when I tried to compile it the segmentation fault appeared.

After struggling for a while I used a protocol extension instead and this resolved the error:

extension NSFetchRequestResult where Self: ExampleCoreDataClass {
   static func insert() -> Self {
   ...

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This is not a new answer but will help somebody who's not sure how to set primary key for their table. Use this in a new query and run. This will set UniqueID column as primary key.

USE [YourDatabaseName]
GO

Alter table  [dbo].[YourTableNname]
Add Constraint PK_YourTableName_UniqueID Primary Key Clustered (UniqueID);
GO

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SELECT convert(datetime, '23/07/2009', 103)

Java Byte Array to String to Byte Array

You can't just take the returned string and construct a string from it... it's not a byte[] data type anymore, it's already a string; you need to parse it. For example :

String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]";      // response from the Python script

String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];

for (int i=0, len=bytes.length; i<len; i++) {
   bytes[i] = Byte.parseByte(byteValues[i].trim());     
}

String str = new String(bytes);

** EDIT **

You get an hint of your problem in your question, where you say "Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...", because 91 is the byte value for [, so [91, 45, ... is the byte array of the string "[-45, 1, 16, ..." string.

The method Arrays.toString() will return a String representation of the specified array; meaning that the returned value will not be a array anymore. For example :

byte[] b1 = new byte[] {97, 98, 99};

String s1 = Arrays.toString(b1);
String s2 = new String(b1);

System.out.println(s1);        // -> "[97, 98, 99]"
System.out.println(s2);        // -> "abc";

As you can see, s1 holds the string representation of the array b1, while s2 holds the string representation of the bytes contained in b1.

Now, in your problem, your server returns a string similar to s1, therefore to get the array representation back, you need the opposite constructor method. If s2.getBytes() is the opposite of new String(b1), you need to find the opposite of Arrays.toString(b1), thus the code I pasted in the first snippet of this answer.

Should I use px or rem value units in my CSS?

I've found the best way to program the font sizes of a website are to define a base font size for the body and then use em's (or rem's) for every other font-size I declare after that. That's personal preference I suppose, but it's served me well and also made it very easy to incorporate a more responsive design.

As far as using rem units go, I think it's good to find a balance between being progressive in your code, but to also offer support for older browsers. Check out this link about browser support for rem units, that should help out a good amount on your decision.

Any way to generate ant build.xml file automatically from Eclipse?

Right-click on an Eclipse project then "Export" then "General" then "Ant build files". I don't think it is possible to customise the output format though.

Remove multiple items from a Python list in just one statement

You Can use this -

Suppose we have a list, l = [1,2,3,4,5]

We want to delete last two items in a single statement

del l[3:]

We have output:

l = [1,2,3]

Keep it Simple

Auto-increment primary key in SQL tables

Right-click on the table in SSMS, 'Design' it, and click on the id column. In the properties, set the identity to be seeded @ e.g. 1 and to have increment of 1 - save and you're done.

How to list all the files in android phone by using adb shell?

Open cmd type adb shell then press enter. Type ls to view files list.

Why does python use 'else' after for and while loops?

I agree, it's more like an 'elif not [condition(s) raising break]'.

I know this is an old thread, but I am looking into the same question right now, and I'm not sure anyone has captured the answer to this question in the way I understand it.

For me, there are three ways of "reading" the else in For... else or While... else statements, all of which are equivalent, are:

  1. else == if the loop completes normally (without a break or error)
  2. else == if the loop does not encounter a break
  3. else == else not (condition raising break) (presumably there is such a condition, or you wouldn't have a loop)

So, essentially, the "else" in a loop is really an "elif ..." where '...' is (1) no break, which is equivalent to (2) NOT [condition(s) raising break].

I think the key is that the else is pointless without the 'break', so a for...else includes:

for:
    do stuff
    conditional break # implied by else
else not break:
    do more stuff

So, essential elements of a for...else loop are as follows, and you would read them in plainer English as:

for:
    do stuff
    condition:
        break
else: # read as "else not break" or "else not condition"
    do more stuff

As the other posters have said, a break is generally raised when you are able to locate what your loop is looking for, so the else: becomes "what to do if target item not located".

Example

You can also use exception handling, breaks, and for loops all together.

for x in range(0,3):
    print("x: {}".format(x))
    if x == 2:
        try:
            raise AssertionError("ASSERTION ERROR: x is {}".format(x))
        except:
            print(AssertionError("ASSERTION ERROR: x is {}".format(x)))
            break
else:
    print("X loop complete without error")

Result

x: 0
x: 1
x: 2
ASSERTION ERROR: x is 2
----------
# loop not completed (hit break), so else didn't run

Example

Simple example with a break being hit.

for y in range(0,3):
    print("y: {}".format(y))
    if y == 2: # will be executed
        print("BREAK: y is {}\n----------".format(y))
        break
else: # not executed because break is hit
    print("y_loop completed without break----------\n")

Result

y: 0
y: 1
y: 2
BREAK: y is 2
----------
# loop not completed (hit break), so else didn't run

Example

Simple example where there no break, no condition raising a break, and no error are encountered.

for z in range(0,3):
     print("z: {}".format(z))
     if z == 4: # will not be executed
         print("BREAK: z is {}\n".format(y))
         break
     if z == 4: # will not be executed
         raise AssertionError("ASSERTION ERROR: x is {}".format(x))
else:
     print("z_loop complete without break or error\n----------\n")

Result

z: 0
z: 1
z: 2
z_loop complete without break or error
----------

How do you get the length of a string?

HTML

<div class="selector">Text mates</div>

SCRIPT

alert(jQuery('.selector').text().length);

RESULT

10

regular expression for anything but an empty string

You can do one of two things:

  • match against ^\s*$; a match means the string is "empty"
    • ^, $ are the beginning and end of string anchors respectively
    • \s is a whitespace character
    • * is zero-or-more repetition of
  • find a \S; an occurrence means the string is NOT "empty"
    • \S is the negated version of \s (note the case difference)
    • \S therefore matches any non-whitespace character

References

Related questions

Getting key with maximum value in dictionary?

I got here looking for how to return mydict.keys() based on the value of mydict.values(). Instead of just the one key returned, I was looking to return the top x number of values.

This solution is simpler than using the max() function and you can easily change the number of values returned:

stats = {'a':1000, 'b':3000, 'c': 100}

x = sorted(stats, key=(lambda key:stats[key]), reverse=True)
['b', 'a', 'c']

If you want the single highest ranking key, just use the index:

x[0]
['b']

If you want the top two highest ranking keys, just use list slicing:

x[:2]
['b', 'a']

How do I run msbuild from the command line using Windows SDK 7.1?

To enable msbuild in Command Prompt, you simply have to add the directory of the msbuild.exe install on your machine to the PATH environment variable.

You can access the environment variables by:

  1. Right clicking on Computer
  2. Click Properties
  3. Then click Advanced system settings on the left navigation bar
  4. On the next dialog box click Environment variables
  5. Scroll down to PATH
  6. Edit it to include your path to the framework (don't forget a ";" after the last entry in here).

For reference, my path was C:\Windows\Microsoft.NET\Framework\v4.0.30319

Path Updates:

As of MSBuild 12 (2013)/VS 2013/.NET 4.5.1+ and onward MSBuild is now installed as a part of Visual Studio.

For VS2015 the path was %ProgramFiles(x86)%\MSBuild\14.0\Bin

For VS2017 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin

For VS2019 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin

ReactJS Two components communicating

If you want to explore options of communicating between components and feel like it is getting harder and harder, then you might consider adopting a good design pattern: Flux.

It is simply a collection of rules that defines how you store and mutate application wide state, and use that state to render components.

There are many Flux implementations, and Facebook's official implementation is one of them. Although it is considered the one that contains most boilerplate code, but it is easier to understand since most of the things are explicit.

Some of Other alternatives are flummox fluxxor fluxible and redux.

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
  <select>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <button type="submit">Submit POST Data</button>
</form>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

gridview data export to excel in asp.net

Instead of doing all these.. cant you use a simpler approach as shown below.

Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
            Response.ContentType = "application/excel";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

You can get the entire walkthrough here

Select distinct values from a large DataTable column

All credit to Rajeev Kumar's answer, but I received a list of anonymous type that evaluated to string, which was not as easy to iterate over. Updating the code as below helped to return a List that was more easy to manipulate (or, for example, drop straight into a foreach block).

var distinctIds = datatable.AsEnumerable().Select(row => row.Field<string>("id")).Distinct().ToList();

Perform .join on value in array of objects

Well you can always override the toString method of your objects:

var arr = [
    {name: "Joe", age: 22, toString: function(){return this.name;}},
    {name: "Kevin", age: 24, toString: function(){return this.name;}},
    {name: "Peter", age: 21, toString: function(){return this.name;}}
];

var result = arr.join(", ");
//result = "Joe, Kevin, Peter"

Split string into strings by length?

My solution

   st =' abs de fdgh  1234 556 shg shshh'
   print st

   def splitStringMax( si, limit):
    ls = si.split()
    lo=[]
    st=''
    ln=len(ls)
    if ln==1:
        return [si]
    i=0
    for l in ls:
        st+=l
        i+=1
        if i <ln:
            lk=len(ls[i])
            if (len(st))+1+lk < limit:
                st+=' '
                continue
        lo.append(st);st=''
    return lo

   ############################

   print  splitStringMax(st,7)
   # ['abs de', 'fdgh', '1234', '556', 'shg', 'shshh']
    print  splitStringMax(st,12)

   # ['abs de fdgh', '1234 556', 'shg shshh']

How to dismiss notification after action has been clicked

I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.

You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.

Also if you start a broadcast receiver from the button, the notification drawer doesn't close.

I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.

I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.

Lua - Current time in milliseconds

If your environment is Windows and you have access to system commands, you can get time of centiseconds precision with io.popen(command):

local handle = io.popen("echo %time%")
local result = handle:read("*a")
handle:close()

The result will hold string of hh:mm:ss.cc format: (with trailing line break)

"19:56:53.90\n"

Note, it's in local timesone, so you probably want to extract only the .cc part and combine it with epoch seconds from os.time().

Concatenating bits in VHDL

Here is an example of concatenation operator:

architecture EXAMPLE of CONCATENATION is
   signal Z_BUS : bit_vector (3 downto 0);
   signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
   Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;

How to implement HorizontalScrollView like Gallery?

I have created a horizontal ListView in every row of ListView if you want single You can do the following

Here I am just creating horizontalListView of Thumbnail of Videos Like this

enter image description here

The idea is just continuously add the ImageView to the child of LinearLayout in HorizontalscrollView

Note: remember to fire .removeAllViews(); before next time load other wise it will add duplicate child

Cursor mImageCursor = db.getPlaylistVideoImage(playlistId);
mVideosThumbs.removeAllViews();
if (mImageCursor != null && mImageCursor.getCount() > 0) {
    for (int index = 0; index < mImageCursor.getCount(); index++) {
        mImageCursor.moveToPosition(index);
        ImageView iv = (ImageView) imageViewInfalter.inflate(
            R.layout.image_view, null);
                    name = mImageCursor.getString(mImageCursor
                    .getColumnIndex("LogoDefaultName"));
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
                    if (logoFile.exists()) {    
                Uri uri = Uri.fromFile(logoFile);
                iv.setImageURI(uri);                    
            }
            iv.setScaleType(ScaleType.FIT_XY);
            mVideosThumbs.addView(iv);
    }
    mImageCursor.close();
    mImageCursor = null;
    } else {
        ImageView iv = (ImageView) imageViewInfalter.inflate(
                    R.layout.image_view, null);
        String name = "";
        File logoFile;
        name = mImageCursor.getString(mImageCursor
                    .getColumnIndex("LogoMediumName"));
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
        if (logoFile.exists()) {
            Uri uri = Uri.fromFile(logoFile);
            iv.setImageURI(uri);
            }
        }

My xml for HorizontalListView

<HorizontalScrollView
    android:id="@+id/horizontalScrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/linearLayoutTitle"
    android:background="@drawable/shelf"
    android:paddingBottom="@dimen/Playlist_TopBottom_margin"
    android:paddingLeft="@dimen/playlist_RightLeft_margin"
    android:paddingRight="@dimen/playlist_RightLeft_margin"
    android:paddingTop="@dimen/Playlist_TopBottom_margin" >

    <LinearLayout
        android:id="@+id/linearLayoutVideos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left|center_vertical"
        android:orientation="horizontal" >
    </LinearLayout>
</HorizontalScrollView>

and Also my Image View as each child

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"


  android:id="@+id/imageViewThumb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginRight="20dp"
    android:adjustViewBounds="true"
    android:background="@android:color/transparent"
    android:contentDescription="@string/action_settings"
    android:cropToPadding="true"
    android:maxHeight="200dp"
    android:maxWidth="240dp"
    android:padding="@dimen/playlist_image_padding"
    android:scaleType="centerCrop"
    android:src="@drawable/loading" />

To learn More you can follow the following links which have some easy samples

  1. http://www.dev-smart.com/?p=34
  2. Horizontal ListView in Android?

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

!python 'script.py'

replace script.py with your real file name, DON'T forget ''

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

NSAttributedString add text alignment

As NSAttributedString is primarily used with Core Text on iOS, you have to use CTParagraphStyle instead of NSParagraphStyle. There is no mutable variant.

For example:

CTTextAlignment alignment = kCTCenterTextAlignment;

CTParagraphStyleSetting alignmentSetting;
alignmentSetting.spec = kCTParagraphStyleSpecifierAlignment;
alignmentSetting.valueSize = sizeof(CTTextAlignment);
alignmentSetting.value = &alignment;

CTParagraphStyleSetting settings[1] = {alignmentSetting};

size_t settingsCount = 1;
CTParagraphStyleRef paragraphRef = CTParagraphStyleCreate(settings, settingsCount);
NSDictionary *attributes = @{(__bridge id)kCTParagraphStyleAttributeName : (__bridge id)paragraphRef};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Hello World" attributes:attributes];

How to uninstall Golang?

For Windows 10:

  1. Go to Apps in the Settings App.
  2. Look for Go Programming Language * in the list and uninstall it.
  3. Remove C:\Go\bin from your PATH environment variable (only if you don't plan on installing another version of golang)

What was the strangest coding standard rule that you were forced to follow?

Back in the 80's/90's, I worked for an aircraft simulator company that used FORTRAN. Our FORTRAN compiler had a limit of 8 characters for variable names. The company's coding standards reserved the first three of them for Hungarian-notation style info. So we had to try and create meaningful variable names with just 5 characters!

Why is division in Ruby returning an integer instead of decimal value?

It’s doing integer division. You can make one of the numbers a Float by adding .0:

9.0 / 5  #=> 1.8
9 / 5.0  #=> 1.8

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

I'm not sure about HQL, but in JPA you just call the query's setParameter with the parameter and collection.

Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);

where names is the collection of names you're searching for

Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");

How to add an onchange event to a select box via javascript?

replace:

transport_select.onChange = function(){toggleSelect(transport_select_id);};

with:

transport_select.onchange = function(){toggleSelect(transport_select_id);};

on'C'hange >> on'c'hange


You can use addEventListener too.

How to convert a String to CharSequence?

CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.

So, just as you use InterfaceName i = new ItsImplementation(), you can use CharSequence cs = new String("string") or simply CharSequence cs = "string";

How to solve npm install throwing fsevents warning on non-MAC OS?

fsevents is dealt differently in mac and other linux system. Linux system ignores fsevents whereas mac install it. As the above error message states that fsevents is optional and it is skipped in installation process.

You can run npm install --no-optional command in linux system to avoid above warning.

Further information

https://github.com/npm/npm/issues/14185

https://github.com/npm/npm/issues/5095

Load data from txt with pandas

You can use it which is most helpful.

df = pd.read_csv(('data.txt'), sep="\t", skiprows=[0,1], names=['FromNode','ToNode'])

When to use If-else if-else over switch statements and vice versa

This depends very much on the specific case. Preferably, I think one should use the switch over the if-else if there are many nested if-elses.

The question is how much is many?

Yesterday I was asking myself the same question:

public enum ProgramType {
    NEW, OLD
}

if (progType == OLD) {
    // ...
} else if (progType == NEW) {
    // ...
}

if (progType == OLD) {
    // ...
} else {
    // ...
}

switch (progType) {
case OLD:
    // ...
    break;
case NEW:
    // ...
    break;
default:
    break;
}

In this case, the 1st if has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.

I ended up choosing the switch because it just reads better.

CSS Font Border?

I created a comparison of all the solutions mentioned here to have a quick overview:

<h1>with mixin</h1>
<h2>with text-shadow</h2>
<h3>with css text-stroke-width</h3>

https://codepen.io/Grienauer/pen/GRRdRJr

How to download a file from my server using SSH (using PuTTY on Windows)

If your server have a http service you can compress your directory and download the compressed file.

Compress:

tar -zcvf archive-name.tar.gz -C directory-name .

Download throught your browser:

http://the-server-ip/archive-name.tar.gz

If you don't have direct access to the server ip, do a ssh tunnel throught putty, and forward the 80 port in some local port, and you can download the file.

What key shortcuts are to comment and uncomment code?

This is how I did it,

Menu ToolsOptions on the EnvironmentKeyboard window

One can alter the default shortcuts following the below steps

  • Select Edit.CommentSelection in the listbox
  • Click on "Remove" button
  • Select "Text Editor" option in the dropdown under "Use new shortcut in:"
  • Press your own shortcut in the textbox under "Press shortcut keys:" Example: Pressing Ctrl+E and then C will give you Ctrl+E, C
  • Click on "Assign" button
  • Repeat the same for Edit.UnCommentSelection (Ctrl+E, U)

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

How to programmatically set the SSLContext of a JAX-WS client?

This one was a hard nut to crack, so for the record:

To solve this, it required a custom KeyManager and a SSLSocketFactory that uses this custom KeyManager to access the separated KeyStore. I found the base code for this KeyStore and SSLFactory on this excellent blog entry: how-to-dynamically-select-a-certificate-alias-when-invoking-web-services

Then, the specialized SSLSocketFactory needs to be inserted into the WebService context:

service = getWebServicePort(getWSDLLocation());
BindingProvider bindingProvider = (BindingProvider) service; 
bindingProvider.getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", getCustomSocketFactory()); 

Where the getCustomSocketFactory() returns a SSLSocketFactory created using the method mentioned above. This would only work for JAX-WS RI from the Sun-Oracle impl built into the JDK, given that the string indicating the SSLSocketFactory property is proprietary for this implementation.

At this stage, the JAX-WS service communication is secured through SSL, but if you are loading the WSDL from the same secure server () then you'll have a bootstrap problem, as the HTTPS request to gather the WSDL will not be using the same credentials than the Web Service. I worked around this problem by making the WSDL locally available (file:///...) and dynamically changing the web service endpoint: (a good discussion on why this is needed can be found in this forum)

bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, webServiceLocation); 

Now the WebService gets bootstrapped and is able to communicate through SSL with the server counterpart using a named (alias) Client-Certificate and mutual authentication. ?

Dealing with HTTP content in HTTPS pages

I realise that this is an old thread but one option is just to remove the http: part from the image URL so that 'http://some/image.jpg' becomes '//some/image.jpg'. This will also work with CDNs

Command line to remove an environment variable from the OS level configuration

setx FOOBAR ""

just causes the value of FOOBAR to be a null string. (Although, it shows with the set command with the "" so maybe double-quotes is the string.)

I used:

set FOOBAR=

and then FOOBAR was no longer listed in the set command. (Log-off was not required.)

Windows 7 32 bit, using the command prompt, non-administrator is what I used. (Not cmd or Windows + R, which might be different.)

BTW, I did not see the variable I created anywhere in the registry after I created it. I'm using RegEdit not as administrator.

Find out which remote branch a local branch is tracking

The local branches and their remotes.

git branch -vv 

All branches and tracking remotes.

git branch -a -vv

See where the local branches are explicitly configured for push and pull.

git remote show {remote_name}

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.

Assign null to a SqlParameter

The accepted answer suggests making use of a cast. However, most of the SQL types have a special Null field which can be used to avoid this cast.

For example, SqlInt32.Null "Represents a DBNull that can be assigned to this instance of the SqlInt32 class."

int? example = null;
object exampleCast = (object) example ?? DBNull.Value;
object exampleNoCast = example ?? SqlInt32.Null;

How do I insert datetime value into a SQLite database?

You have to change the format of the date string you are supplying in order to be able to insert it using the STRFTIME function. Reason being, there is no option for a month abbreviation:

%d  day of month: 00
%f  fractional seconds: SS.SSS
%H  hour: 00-24
%j  day of year: 001-366
%J  Julian day number
%m  month: 01-12
%M  minute: 00-59
%s  seconds since 1970-01-01
%S  seconds: 00-59
%w  day of week 0-6 with sunday==0
%W  week of year: 00-53
%Y  year: 0000-9999
%%  % 

The alternative is to format the date/time into an already accepted format:

  1. YYYY-MM-DD
  2. YYYY-MM-DD HH:MM
  3. YYYY-MM-DD HH:MM:SS
  4. YYYY-MM-DD HH:MM:SS.SSS
  5. YYYY-MM-DDTHH:MM
  6. YYYY-MM-DDTHH:MM:SS
  7. YYYY-MM-DDTHH:MM:SS.SSS
  8. HH:MM
  9. HH:MM:SS
  10. HH:MM:SS.SSS
  11. now

Reference: SQLite Date & Time functions

Some projects cannot be imported because they already exist in the workspace error in Eclipse

This warning means you just deleted project from navigator, but the project is present in the working set. Or else your working set has project with same name, so go to work-space directory and delete the project which has the same name and import again.

How to make Bootstrap 4 cards the same height in card-columns?

You can either put the classes on the "row" or the "column"? Won't be visible on the cards (border) if you use it on the row. https://v4-alpha.getbootstrap.com/utilities/flexbox/#align-items

<div class="container">
    <div class="row">
          <div class="col-lg-4 d-flex align-items-stretch">

Some of the other answers here seem 'wacky'. Why would use a min-height or even worse a fixed height?

I thought this issue (equal heights) was part of the reason for progression away from floating block divs?

How to autosize a textarea using Prototype?

One refinement to some of these answers is to let CSS do more of the work.

The basic route seems to be:

  1. Create a container element to hold the textarea and a hidden div
  2. Using Javascript, keep the textarea’s contents synced with the div’s
  3. Let the browser do the work of calculating the height of that div
  4. Because the browser handles rendering / sizing the hidden div, we avoid explicitly setting the textarea’s height.

_x000D_
_x000D_
document.addEventListener('DOMContentLoaded', () => {_x000D_
    textArea.addEventListener('change', autosize, false)_x000D_
    textArea.addEventListener('keydown', autosize, false)_x000D_
    textArea.addEventListener('keyup', autosize, false)_x000D_
    autosize()_x000D_
}, false)_x000D_
_x000D_
function autosize() {_x000D_
    // Copy textarea contents to div browser will calculate correct height_x000D_
    // of copy, which will make overall container taller, which will make_x000D_
    // textarea taller._x000D_
    textCopy.innerHTML = textArea.value.replace(/\n/g, '<br/>')_x000D_
}
_x000D_
html, body, textarea {_x000D_
    font-family: sans-serif;_x000D_
    font-size: 14px;_x000D_
}_x000D_
_x000D_
.textarea-container {_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.textarea-container > div, .textarea-container > textarea {_x000D_
    word-wrap: break-word; /* make sure the div and the textarea wrap words in the same way */_x000D_
    box-sizing: border-box;_x000D_
    padding: 2px;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.textarea-container > textarea {_x000D_
    overflow: hidden;_x000D_
    position: absolute;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.textarea-container > div {_x000D_
    padding-bottom: 1.5em; /* A bit more than one additional line of text. */ _x000D_
    visibility: hidden;_x000D_
}
_x000D_
<div class="textarea-container">_x000D_
    <textarea id="textArea"></textarea>_x000D_
    <div id="textCopy"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I reference tables in Excel using VBA?

The OP asked, is it possible to reference a table, not how to add a table. So the working equivalent of

Sheets("Sheet1").Table("A_Table").Select

would be this statement:

Sheets("Sheet1").ListObjects("A_Table").Range.Select

or to select parts (like only the data in the table):

Dim LO As ListObject
Set LO = Sheets("Sheet1").ListObjects("A_Table")
LO.HeaderRowRange.Select        ' Select just header row
LO.DataBodyRange.Select         ' Select just data cells
LO.TotalsRowRange.Select        ' Select just totals row

For the parts, you may want to test for the existence of the header and totals rows before selecting them.

And seriously, this is the only question on referencing tables in VBA in SO? Tables in Excel make so much sense, but they're so hard to work with in VBA!

How do you get the current page number of a ViewPager for Android?

getCurrentItem(), doesn't actually give the right position for the first and the last page I fixed it adding this code:

public void CalcPostion() {    
    current = viewPager.getCurrentItem();

    if ((last == current) && (current != 1) && (current != 0)) {
        current = current + 1;
        viewPager.setCurrentItem(current);
    }
    if ((last == 1) && (current == 1)) {
        last = 0;
        current = 0;
    }
    display();
    last = current;
}

Where do I get servlet-api.jar from?

You may want to consider using Java EE, which includes the javax.servlet.* packages. If you require a specific version of the servlet api, for instance to target a specific web application server, you will probably want the Java EE version which matches, see this version table.

JavaScript and getElementById for multiple elements with the same ID

As others have stated, you shouldn't have the same ID more than once in your HTML, however... elements with an ID are attached to the document object and to window on Internet Explorer. Refer to:

Do DOM tree elements with ids become global variables?

If more than one element with the same ID exists in your HTML, this property is attached as an array. I'm sorry, but I don't know where to look if this is the standard behavior or at least you get the same behavior between browsers, which I doubt.

Xpath for href element

This works properly try this code-

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

JavaScript + Unicode regexes

If you are using Babel then Unicode support is already available.

I also released a plugin which transforms your source code such that you can write regular expressions like /^\p{L}+$/. These will then be transformed into something that browsers understand.

Here is the project page of the plugin:

babel-plugin-utf-8-regex

DISTINCT clause with WHERE

Try:

SELECT * FROM table GROUP BY email

  • This returns all rows with a unique email taken by the first ID appearance (if that makes sense)
  • I assume this is what you were looking since I had about the same question but none of these answers worked for me.

How to unlock a file from someone else in Team Foundation Server

If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.

RestTemplate: How to send URL and query parameters together

An issue with the answer from Michal Foksa is that it adds the query parameters first, and then expands the path variables. If query parameter contains parenthesis, e.g. {foobar}, this will cause an exception.

The safe way is to expand the path variables first, and then add the query parameters:

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
        .buildAndExpand(params)
        .toUri();
uri = UriComponentsBuilder
        .fromUri(uri)
        .queryParam("name", "myName")
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

Uninstall Eclipse under OSX?

  1. From terminal, find all eclipse directories with

    sudo find / -iname "Eclipse"

  2. Delete those directories with rm command.

SQL - Update multiple records in one query

Execute the below code if you want to update all record in all columns:

update config set column1='value',column2='value'...columnN='value';

and if you want to update all columns of a particular row then execute below code:

update config set column1='value',column2='value'...columnN='value' where column1='value'

ASP.NET MVC 3 - redirect to another action

You have to write this code instead of return View(); :

return RedirectToAction("ActionName", "ControllerName");

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

if the document.domain property is set in the parent page, Internet Explorer gives me an "Access is denied"

Sigh. Yeah, it's an IE issue (bug? difficult to say as there is no documented standard for this kind of unpleasantness). When you create a srcless iframe it receives a document.domain from the parent document's location.host instead of its document.domain. At that point you've pretty much lost as you can't change it.

A horrendous workaround is to set src to a javascript: URL (urgh!):

 iframe.src= "javascript:'<html><body><p>Hello<\/p><script>do things;<\/script>'";

But for some reason, such a document is unable to set its own document.domain from script in IE (good old “unspecified error”), so you can't use that to regain a bridge between the parent(*). You could use it to write the whole document HTML, assuming the widget doesn't need to talk to its parent document once it's instantiated.

However iframe JavaScript URLs don't work in Safari, so you'd still need some kind of browser-sniffing to choose which method to use.

*: For some other reason, you can, in IE, set document.domain from a second document, document.written by the first document. So this works:

if (isIE)
    iframe.src= "javascript:'<script>window.onload=function(){document.write(\\'<script>document.domain=\\\""+document.domain+"\\\";<\\\\/script>\\');document.close();};<\/script>'";

At this point the hideousness level is too high for me, I'm out. I'd do the external HTML like David said.

Using Mockito to test abstract classes

Mocking frameworks are designed to make it easier to mock out dependencies of the class you are testing. When you use a mocking framework to mock a class, most frameworks dynamically create a subclass, and replace the method implementation with code for detecting when a method is called and returning a fake value.

When testing an abstract class, you want to execute the non-abstract methods of the Subject Under Test (SUT), so a mocking framework isn't what you want.

Part of the confusion is that the answer to the question you linked to said to hand-craft a mock that extends from your abstract class. I wouldn't call such a class a mock. A mock is a class that is used as a replacement for a dependency, is programmed with expectations, and can be queried to see if those expectations are met.

Instead, I suggest defining a non-abstract subclass of your abstract class in your test. If that results in too much code, than that may be a sign that your class is difficult to extend.

An alternative solution would be to make your test case itself abstract, with an abstract method for creating the SUT (in other words, the test case would use the Template Method design pattern).

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You should avoid setting LD_LIBRARY_PATH in your .bashrc. See "Why LD_LIBRARY_PATH is bad" for more information.

Use the linker option -rpath while linking so that the dynamic linker knows where to find libsync.so during runtime.

gcc ... -Wl,-rpath /path/to/library -L/path/to/library -lsync -o sync_test

EDIT:

Another way would be to use a wrapper like this

#!/bin/bash

LD_LIBRARY_PATH=/path/to/library sync_test "$@"

If sync_test starts any other programs, they might end up using the libs in /path/to/library which may or may not be intended.

New lines (\r\n) are not working in email body

' '   

space was missing in my case, when a blank space added ' \r\n' started to work

How to change text color of cmd with windows batch script every 1 second

@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F 31 32 33 34 35 36 37 41 42 43 44 45 46 90 91 92 93 94 95 96 97 100 101 102 103 104 105 106 107 
for %%x in (%NUM%) do ( 
    for %%y in (%NUM%) do (
        color %%x%%y
cls
echo Himel Sarkar
        timeout 1 >nul
    )
)

pause

How is using OnClickListener interface different via XML and Java code?

using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener then add the variable Button button1; then add this to your onCreate()

button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);

when you implement OnClickListener you need to add the inherited method onClick() where you will handle your clicks

Python3 project remove __pycache__ folders and .pyc files

Why not just use rm -rf __pycache__? Run git add -A afterwards to remove them from your repository and add __pycache__/ to your .gitignore file.

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

How do I delete specific lines in Notepad++?

This is the most common feature of Notepad++ that I use to update my code.

All you need to do is:

  • Select common string that is present in all lines.
  • Press Ctrl + F
  • In the Mark tab, paste the recurring string and check the Bookmark line checkbox.
  • Click on Mark All
  • Now go to menu SearchBookmarkRemove Bookmarked Lines

You can refer to this link for pictorial explanation.

http://www.downloadorinstall.com/best-notepad-tips-and-tricks-for-faster-work-and-development/

Uninstall Django completely

Got it solved. I missed to delete the egg_info files of all previous Django versions. Removed them from /usr/local/lib/python2.7/dist-packages. Also from /usr/lib/python2.7/dist-packages (if any present here)

sudo pip freeze| grep Django
sudo pip show -f Django
sudo pip search Django | more +/^Django

All above commands should not show Django version to verify clean uninstallation.