Programs & Examples On #Web search

What to use now Google News API is deprecated?

I'm running into the same issue with one of my own apps. So far I've found the only non-deprecated way to access Google News data is through their RSS feeds. They have a feed for each section and also a useful search function. However, these are only for noncommercial use.

As for viable alternatives I'll be trying out these two services: Feedzilla, Daylife

Is there a short cut for going back to the beginning of a file by vi editor?

In command mode: : + 1 will take you to first line

How do you push a tag to a remote repository using Git?

To expand on Trevor's answer, you can push a single tag or all of your tags at once.

Push a Single Tag

git push <remote> <tag>

This is a summary of the relevant documentation that explains this (some command options omitted for brevity):

git push [[<repository> [<refspec>…]]

<refspec>...

The format of a <refspec> parameter is…the source ref <src>, followed by a colon :, followed by the destination ref <dst>

The <dst> tells which ref on the remote side is updated with this push…If :<dst> is omitted, the same ref as <src> will be updated…

tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.

Push All of Your Tags at Once

git push --tags <remote>
# Or
git push <remote> --tags

Here is a summary of the relevant documentation (some command options omitted for brevity):

git push [--all | --mirror | --tags] [<repository> [<refspec>…]]

--tags

All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.

How can strip whitespaces in PHP's variable?

$string = str_replace(" ", "", $string);

I believe preg_replace would be looking for something like [:space:]

Java: How to stop thread?

You can create a boolean field and check it inside run:

public class Task implements Runnable {

   private volatile boolean isRunning = true;

   public void run() {

     while (isRunning) {
         //do work
     }
   }

   public void kill() {
       isRunning = false;
   }

}

To stop it just call

task.kill();

This should work.

How can I get the class name from a C++ object?

Do you want [classname] to be 'one' and [objectname] to be 'A'?

If so, this is not possible. These names are only abstractions for the programmer, and aren't actually used in the binary code that is generated. You could give the class a static variable classname, which you set to 'one' and a normal variable objectname which you would assign either directly, through a method or the constructor. You can then query these methods for the class and object names.

Hibernate table not mapped error in HQL query

The exception message says:

Books is not mapped [SELECT COUNT(*) FROM Books]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]

Books is not mapped. That is, that there is no mapped type called Books.

And indeed, there isn't. Your mapped type is called Book. It's mapped to a table called Books, but the type is called Book. When you write HQL (or JPQL) queries, you use the names of the types, not the tables.

So, change your query to:

select count(*) from Book

Although I think it may need to be

select count(b) from Book b

If HQL doesn't support the * notation.

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

You can use a specific php Version when running Composer

If, like me, for some reason, you are using PHP 32 bits even though your computer is 64 bits, this will always limit the amount of memory allocated to Composer. I solved my problem this way:

  • Install a 64 bits php version somewhere on your computer (let's say in C:/php64)
  • In composer (using cygwin in my case), run:

COMPOSER_MEMORY_LIMIT=-1 C:/php64/php.exe ../composer.phar update

ng-change get new value and original value

With an angular {{expression}} you can add the old user or user.id value to the ng-change attribute as a literal string:

<select ng-change="updateValue(user, '{{user.id}}')" 
        ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>

On ngChange, the 1st argument to updateValue will be the new user value, the 2nd argument will be the literal that was formed when the select-tag was last updated by angular, with the old user.id value.

Convert a bitmap into a byte array

I believe you may simply do:

ImageConverter converter = new ImageConverter();
var bytes = (byte[])converter.ConvertTo(img, typeof(byte[]));

Convert Unix timestamp into human readable date using MySQL

Need a unix timestamp in a specific timezone?

Here's a one liner if you have quick access to the mysql cli:

mysql> select convert_tz(from_unixtime(1467095851), 'UTC', 'MST') as 'local time';

+---------------------+
| local time          |
+---------------------+
| 2016-06-27 23:37:31 |
+---------------------+

Replace 'MST' with your desired timezone. I live in Arizona thus the conversion from UTC to MST.

Open a URL in a new tab (and not a new window)

function openTab(url) {
  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  link.remove();
}

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

I got this since I had a comment in a file I was adding to my JS, really awkward reason to what was going on - though when clicking on the VM file that's pre-rendered and catches the error, you'll find out what exactly the error was, in my case it was simply uncommenting some code I was using.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

Edit:

If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):

Exception from HRESULT: 0x800A03EC

and/or

Old format or invalid type library

SOLUTION 1:


To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.

//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
  oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
  System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}

SOLUTION 2:


Another solution that could work, create a 1033 directory under Microsoft Office\Office11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.

Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:

yourRange.Value2 = "10/10/09"

Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:

October 10, 2009 September 10, 2009 October 9, 2010

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

How to prevent downloading images and video files from my website?

Insert a transparent gif 1px x 1px just inside the <body> tag:

<body><img src="route-to-images/blim.gif" class="blimover">

Then style it with this:

.blimover {
  width: 100% !important;
  height: 100% !important;
  z-index: 1000 !important;
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
}

This will remove any click functionality from a page, but it sure stops people stealing any content!

You can apply the same to a <div>, <section>, <article> etc, just name accordingly and prevent your copy and/or images being ripped.

Nothing stops a screengrab though ... ...

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

Avoid Adding duplicate elements to a List C#

If you want to save distinct values into a collection you could try HashSet Class. It will automatically remove the duplicate values and save your coding time. :)

How can I get a count of the total number of digits in a number?

int i = 855865264;
int NumLen = i.ToString().Length;

Setting the height of a SELECT in IE

You can use a replacement: jQuery Chosen. It looks pretty awesome.

Getting started with OpenCV 2.4 and MinGW on Windows 7

This isn't working for me. I spent few days following every single tutorial I found on net and finally i compiled my own binaries. Everyting is described here: OpenVC 2.4.5, eclipse CDT Juno, MinGW error 0xc0000005

After many trials and errors I decided to follow this tutorial and to compile my own binaries as it seems that too many people are complaining that precompiled binaries are NOT working for them. Eclipse CDT Juno was already installed.

My procedure was as follows:

  1. Download and install MinGW and add to the system PATH with c:/mingw/bin
  2. Download cmake from http://www.cmake.org and install it
  3. Download OpenCV2.4.5 Windows version
  4. Install/unzip Opencv to C:\OpenCV245PC\ (README,index.rst and CMakeLists.txt are there with all subfolders)
  5. Run CMake GUI tool, then
  6. Choose C:\OpenCV245PC\ as source
  7. Choose the destination, C:\OpenCV245MinGW\x86 where to build the binaries
  8. Press Configure button, choose MinGW Makefiles as the generator. There are some red highlights in the window, choose options as you need.
  9. Press the Configure button again. Configuring is now done.
  10. Press the Generate button.
  11. Exit the program when the generating is done.
  12. Exit the Cmake program.
  13. Run the command line mode (cmd.exe) and go to the destination directory C:\OpenCV245MinGW\x86
  14. Type "mingw32-make". You will see a progress of building binaries. If the command is not found, you must make sure that the system PATH is added with c:/mingw/bin. The build continues according the chosen options to a completion.
  15. In Windows system PATH (My Computer > Right button click > Properties > Advanced > Environment Variables > Path) add the destination's bin directory, C:\OpenCV245MinGW\x86\bin
  16. RESTART COMPUTER
  17. Go to the Eclipse CDT IDE, create a C++ program using the sample OpenCV code (You can use code from top of this topic).
  18. Go to Project > Properties > C/C++ Build > Settings > GCC C++ Compiler > Includes, and add the source OpenCV folder "C:\OpenCV245PC\build\include"
  19. Go to Project > Properties > C/C++ Build > Settings > MinGW C++ Linker > Libraries, and add to the Libraries (-l) ONE BY ONE (this could vary from project to project, you can add all of them if you like or some of them just the ones that you need for your project): opencv_calib3d245 opencv_contrib245 opencv_core245 opencv_features2d245 opencv_flann245 opencv_gpu245 opencv_highgui245 opencv_imgproc245 opencv_legacy245 opencv_ml245 opencv_nonfree245 opencv_objdetect245 opencv_photo245 opencv_stitching245 opencv_video245 opencv_videostab245
  20. Add the built OpenCV library folder, "C:\OpenCV245MinGW\x86\lib" to Library search path (-L).

You can use this code to test your setup:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{

Mat img = imread("c:/lenna.png", CV_LOAD_IMAGE_COLOR);

namedWindow("MyWindow", CV_WINDOW_AUTOSIZE);
imshow("MyWindow", img);

waitKey(0);
return 0;
}

Don't forget to put image to the C:/ (or wherever you might find suitable, just be sure that eclipse have read acess.

How to get a random number between a float range?

Use random.uniform(a, b):

>>> random.uniform(1.5, 1.9)
1.8733202628557872

What characters are forbidden in Windows and Linux directory names?

The easy way to get Windows to tell you the answer is to attempt to rename a file via Explorer and type in / for the new name. Windows will popup a message box telling you the list of illegal characters.

A filename cannot contain any of the following characters:
    \ / : * ? " < > | 

https://support.microsoft.com/en-us/kb/177506

Querying data by joining two tables in two database on different servers

From a practical enterprise perspective, the best practice is to make a mirrored copy of the database table in your database, and then just have a task/proc update it with delta's every hour.

Full Screen DialogFragment in Android

This is what you need to set to fragment:

/* theme is optional, I am using leanback... */
setStyle(STYLE_NORMAL, R.style.AppTheme_Leanback);

In your case:

DialogFragment newFragment = new DetailsDialogFragment();
newFragment.setStyle(STYLE_NORMAL, R.style.AppTheme_Leanback);
newFragment.show(ft, "dialog");

And why? Because DialogFragment (when not told explicitly), will use its inner styles that will wrap your custom layout in it (no fullscreen, etc.).

And layout? No hacky way needed, this is working just fine:

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

Enjoy

How do you get assembler output from C/C++ source in gcc?

Well, as everyone said, use -S option. If you use -save-temps option, you can also get preprocessed file(.i), assembly file(.s) and object file(*.o). (get each of them by using -E, -S, and -c.)

How to concatenate strings in a Windows batch file?

Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:

@echo off
setlocal enabledelayedexpansion
set myvar=the list: 
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%

Also consider the following restriction (MSDN):

The maximum individual environment variable size is 8192bytes.

How does one get started with procedural generation?

(More than 10 years later ...)

Procedural generation only means that code is used to generate the data instead of it being hand made. For example if you want to generate a forest with various trees you are not going to design each tree by hand, thus coding is more efficient to generate the variations. It could be the generation of the tree graphics, size, structure, placement ...

In general there is some kind of interation with a few rules, in addition to that you can add some randomness and logic of your own, combine all of these techniques ... Anything somewhat chaotic but not too chaotic can yield interesting results.

Here are a few notable techniques:

A few games famous for their procedural generation:

Video tutorial about Procedural Landmass Generation.

Conference on procedural content generation for games, has a lot of videos on the topic: everythingprocedural

Have fun.

How to determine whether an object has a given property in JavaScript

includes

Object.keys(x).includes('y');

The Array.prototype.includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

and

Object.keys() returns an array of strings that represent all the enumerable properties of the given object.

.hasOwnProperty() and the ES6+ .? -optional-chaining like: if (x?.y) are very good 2020+ options as well.

How do I replace a character at a particular index in JavaScript?

If you want to replace characters in string, you should create mutable strings. These are essentially character arrays. You could create a factory:

  function MutableString(str) {
    var result = str.split("");
    result.toString = function() {
      return this.join("");
    }
    return result;
  }

Then you can access the characters and the whole array converts to string when used as string:

  var x = MutableString("Hello");
  x[0] = "B"; // yes, we can alter the character
  x.push("!"); // good performance: no new string is created
  var y = "Hi, "+x; // converted to string: "Hi, Bello!"

Reading a text file using OpenFileDialog in windows forms

for this approach, you will need to add system.IO to your references by adding the next line of code below the other references near the top of the c# file(where the other using ****.** stand).

using System.IO;

this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))

both should be quite easy to understand and use.


    string pathToFile = "";//to save the location of the selected object
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(theDialog.FileName.ToString());
            pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object

        }

        if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
        {
            //method1
            string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
            string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();

            //method2
            string text = "";
            using(StreamReader sr =new StreamReader(pathToFile))
            {
                text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
            }
        }
    }

To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.


to add the data to your class you can use the constructor to add the data like:

  public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
        {
            EmployeeNum = EMPLOYEENUM;
            Name = NAME;
            Address = ADRESS;
            Wage = WAGE;
            Hours = HOURS;
        }

or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).

How do you decompile a swf file

Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text

Create a date from day month and year with T-SQL

SQL Server 2012 has a wonderful and long-awaited new DATEFROMPARTS function (which will raise an error if the date is invalid - my main objection to a DATEADD-based solution to this problem):

http://msdn.microsoft.com/en-us/library/hh213228.aspx

DATEFROMPARTS(ycolumn, mcolumn, dcolumn)

or

DATEFROMPARTS(@y, @m, @d)

How can I convince IE to simply display application/json rather than offer to download it?

Above solution was missing thing, and below code should work in every situation:

Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.  
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;  

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/x-json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

Just save it file json.reg, and run to modify your registry.

How to reliably open a file in the same directory as a Python script

I'd do it this way:

from os.path import abspath, exists

f_path = abspath("fooabar.txt")

if exists(f_path):
    with open(f_path) as f:
        print f.read()

The above code builds an absolute path to the file using abspath and is equivalent to using normpath(join(os.getcwd(), path)) [that's from the pydocs]. It then checks if that file actually exists and then uses a context manager to open it so you don't have to remember to call close on the file handle. IMHO, doing it this way will save you a lot of pain in the long run.

Bat file to run a .exe at the command prompt

it is very simple code for executing notepad bellow code type into a notepad and save to extension .bat Exapmle:notepad.bat

start "c:\windows\system32" notepad.exe   

(above code "c:\windows\system32" is path where you kept your .exe program and notepad.exe is your .exe program file file)

enjoy!

How to escape double quotes in JSON

When and where to use \\\" instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.

If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\" is the one you're looking for.

However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

<script>
  var text="{";
  text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
  text += "}";
  var obj=JSON.parse(text);
</script>

+1: since it's a JavaScript text string, a double backslash double quote \\" would work too; because the double quote does not need escaped within a single quoted string eg '\"' and '"' result in the same JS string.

Large Numbers in Java

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package.

Example:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);

Change background color for selected ListBox item

<UserControl.Resources>
    <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Transparent"/>
        </Style.Resources>
    </Style>
</UserControl.Resources> 

and

<ListBox ItemsSource="{Binding Path=FirstNames}"
         ItemContainerStyle="{StaticResource myLBStyle}">  

You just override the style of the listboxitem (see the: TargetType is ListBoxItem)

How to change the MySQL root account password on CentOS7?

What version of mySQL are you using? I''m using 5.7.10 and had the same problem with logging on as root

There is 2 issues - why can't I log in as root to start with, and why can I not use 'mysqld_safe` to start mySQL to reset the root password.

I have no answer to setting up the root password during installation, but here's what you do to reset the root password

Edit the initial root password on install can be found by running

grep 'temporary password' /var/log/mysqld.log

http://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html


  1. systemd is now used to look after mySQL instead of mysqld_safe (which is why you get the -bash: mysqld_safe: command not found error - it's not installed)

  2. The user table structure has changed.

So to reset the root password, you still start mySQL with --skip-grant-tables options and update the user table, but how you do it has changed.

1. Stop mysql:
systemctl stop mysqld

2. Set the mySQL environment option 
systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

3. Start mysql usig the options you just set
systemctl start mysqld

4. Login as root
mysql -u root

5. Update the root user password with these mysql commands
mysql> UPDATE mysql.user SET authentication_string = PASSWORD('MyNewPassword')
    -> WHERE User = 'root' AND Host = 'localhost';
mysql> FLUSH PRIVILEGES;
mysql> quit

*** Edit ***
As mentioned my shokulei in the comments, for 5.7.6 and later, you should use 
   mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
Or you'll get a warning

6. Stop mysql
systemctl stop mysqld

7. Unset the mySQL envitroment option so it starts normally next time
systemctl unset-environment MYSQLD_OPTS

8. Start mysql normally:
systemctl start mysqld

Try to login using your new password:
7. mysql -u root -p

Reference

As it says at http://dev.mysql.com/doc/refman/5.7/en/mysqld-safe.html,

Note

As of MySQL 5.7.6, for MySQL installation using an RPM distribution, server startup and shutdown is managed by systemd on several Linux platforms. On these platforms, mysqld_safe is no longer installed because it is unnecessary. For more information, see Section 2.5.10, “Managing MySQL Server with systemd”.

Which takes you to http://dev.mysql.com/doc/refman/5.7/en/server-management-using-systemd.html where it mentions the systemctl set-environment MYSQLD_OPTS= towards the bottom of the page.

The password reset commands are at the bottom of http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

How to get multiple selected values from select box in JSP?

It would seem overkill but Spring Forms handles this elegantly. That is of course if you are already using Spring MVC and you want to take advantage of the Spring Forms feature.

// jsp form
    <form:select path="friendlyNumber" items="${friendlyNumberItems}" />

    // the command class
    public class NumberCmd {
      private String[] friendlyNumber;
    }

    // in your Spring MVC controller submit method
    @RequestMapping(method=RequestMethod.POST)
    public String manageOrders(@ModelAttribute("nbrCmd") NumberCmd nbrCmd){

       String[] selectedNumbers = nbrCmd.getFriendlyNumber();

    }

How to access elements of a JArray (or iterate over them)

Update - I verified the below works. Maybe the creation of your JArray isn't quite right.

[TestMethod]
    public void TestJson()
    {
        var jsonString = @"{""trends"": [
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              },
              {
                ""name"": ""#HNCJ"",
                ""url"": ""http://twitter.com/search?q=%23HNCJ"",
                ""promoted_content"": null,
                ""query"": ""%23HNCJ"",
                ""events"": null
              },
              {
                ""name"": ""Boston"",
                ""url"": ""http://twitter.com/search?q=Boston"",
                ""promoted_content"": null,
                ""query"": ""Boston"",
                ""events"": null
              },
              {
                ""name"": ""#prayforboston"",
                ""url"": ""http://twitter.com/search?q=%23prayforboston"",
                ""promoted_content"": null,
                ""query"": ""%23prayforboston"",
                ""events"": null
              },
              {
                ""name"": ""#TheMrsCarterShow"",
                ""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
                ""promoted_content"": null,
                ""query"": ""%23TheMrsCarterShow"",
                ""events"": null
              },
              {
                ""name"": ""#Raw"",
                ""url"": ""http://twitter.com/search?q=%23Raw"",
                ""promoted_content"": null,
                ""query"": ""%23Raw"",
                ""events"": null
              },
              {
                ""name"": ""Iran"",
                ""url"": ""http://twitter.com/search?q=Iran"",
                ""promoted_content"": null,
                ""query"": ""Iran"",
                ""events"": null
              },
              {
                ""name"": ""#gaa"",
                ""url"": ""http://twitter.com/search?q=%23gaa"",
                ""promoted_content"": null,
                ""query"": ""gaa"",
                ""events"": null
              },
              {
                ""name"": ""Facebook"",
                ""url"": ""http://twitter.com/search?q=Facebook"",
                ""promoted_content"": null,
                ""query"": ""Facebook"",
                ""events"": null
              }]}";

        var twitterObject = JToken.Parse(jsonString);
        var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;


        foreach (var item in trendsArray.Children())
        {
            var itemProperties = item.Children<JProperty>();
            //you could do a foreach or a linq here depending on what you need to do exactly with the value
            var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
            var myElementValue = myElement.Value; ////This is a JValue type
        }
    }

So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.

foreach(var item in yourJArray.Children())
{
    var itemProperties = item.Children<JProperty>();
    //you could do a foreach or a linq here depending on what you need to do exactly with the value
    var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
    var myElementValue = myElement.Value; ////This is a JValue type
}

specifying goal in pom.xml

You need to set the path of maven under Global setting like MAVEN_HOME

/user/share/maven

and make sure the workbench have permission of read, write and delete "777"

Turn off textarea resizing

It can done easy by just using html draggable attribute

<textarea name="mytextarea" draggable="false"></textarea>

Default value is true.

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

I've learned that error messages like this are usually right. When it couldn't POSSIBLY (in your mind) be what the error being reported says, you go hunting for a problem in another area...only to find out hours later that the original error message was indeed right.

Since you're using Eclipse, I think Thilo has it right The most likely reason you are getting this message is because one of your projects is compiling 1.6 classes. It doesn't matter if you only have a 1.5 JRE on the system, because Eclipse has its own compiler (not javac), and only needs a 1.5 JRE to compile 1.6 classes. It may be weird, and a setting needs to be unchecked to allow this, but I just managed to do it.

For the project in question, check the Project Properties (usually Alt+Enter), Java Compiler section. Here's an image of a project configured to compile 1.6, but with only a 1.5 JRE.

enter image description here

Creating the checkbox dynamically using JavaScript?

   /* worked for me  */
     <div id="divid"> </div>
     <script type="text/javascript">
         var hold = document.getElementById("divid");
         var checkbox = document.createElement('input');
         checkbox.type = "checkbox";
         checkbox.name = "chkbox1";
         checkbox.id = "cbid";
         var label = document.createElement('label');
         var tn = document.createTextNode("Not A RoBot");
         label.htmlFor="cbid";
         label.appendChild(tn); 
         hold.appendChild(label);
         hold.appendChild(checkbox);
      </script>  

Array of Matrices in MATLAB

Use cell arrays. This has an advantage over 3D arrays in that it does not require a contiguous memory space to store all the matrices. In fact, each matrix can be stored in a different space in memory, which will save you from Out-of-Memory errors if your free memory is fragmented. Here is a sample function to create your matrices in a cell array:

function result = createArrays(nArrays, arraySize)
    result = cell(1, nArrays);
    for i = 1 : nArrays
        result{i} = zeros(arraySize);
    end
end

To use it:

myArray = createArrays(requiredNumberOfArrays, [500 800]);

And to access your elements:

myArray{1}(2,3) = 10;

If you can't know the number of matrices in advance, you could simply use MATLAB's dynamic indexing to make the array as large as you need. The performance overhead will be proportional to the size of the cell array, and is not affected by the size of the matrices themselves. For example:

myArray{1} = zeros(500, 800);
if twoRequired, myArray{2} = zeros(500, 800); end

Is there a difference between x++ and ++x in java?

The Question is already answered, but allow me to add from my side too.

First of all ++ means increment by one and -- means decrement by one.

Now x++ means Increment x after this line and ++x means Increment x before this line.

Check this Example

class Example {
public static void main (String args[]) {
      int x=17,a,b;
      a=x++;
      b=++x;
      System.out.println(“x=” + x +“a=” +a);
      System.out.println(“x=” + x + “b=” +b);
      a = x--;
      b = --x;
      System.out.println(“x=” + x + “a=” +a);
      System.out.println(“x=” + x + “b=” +b);
      }
}

It will give the following output:

x=19 a=17
x=19 b=19
x=18 a=19
x=17 b=17

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Open this Link and select follow the instructions google servers blocks any attempts from unknown servers so once you click on captcha check every thing will be fine

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Using find command in bash script

If you want to loop over what you "find", you should use this:

find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
    printf '%s\n' "$file"
done

Source: https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;
     });
  };

  //initial load
  $scope.loadData();
}

then in your markup

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="loadData()">Refresh</button>
</div>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });
};

Then you could use that in your view or whatever you'd want to do.

Android emulator: could not get wglGetExtensionsStringARB error

When you create the emulator, you need to choose properties CPU/ABI is Intel Atom (installed it in SDK manager )

In PowerShell, how can I test if a variable holds a numeric value?

Testing if a value is numeric or a string representation of a numeric value.

function Test-Number 
{
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0)]
        [ValidatePattern("^[\d\.]+$")]
        $Number
    )

    $Number -is [ValueType] -or [Double]::TryParse($Number,[ref]$null)
}

Testing if a value is numeric.

function Test-Number 
{
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0)]
        [ValidatePattern("^[\d\.]+$")]
        $Number
    )

    $Number -is [ValueType]
}

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

Making TextView scrollable on Android

In my case.Constraint Layout.AS 2.3.

Code implementation:

YOUR_TEXTVIEW.setMovementMethod(new ScrollingMovementMethod());

XML:

android:scrollbars="vertical"
android:scrollIndicators="right|end"

How to clear form after submit in Angular 2?

To reset the complete form upon submission, you can use reset() in Angular. The below example is implemented in Angular 8. Below is a Subscribe form where we are taking email as an input.

<form class="form" id="subscribe-form" data-response-message-animation="slide-in-left" #subscribeForm="ngForm"
(ngSubmit)="subscribe(subscribeForm.value); subscribeForm.reset()">
<div class="input-group">
   <input type="email" name="email" id="sub_email" class="form-control rounded-circle-left"
      placeholder="Enter your email" required ngModel #email="ngModel" email>
   <div class="input-group-append">
      <button class="btn btn-rounded btn-dark" type="submit" id="register"
         [disabled]="!subscribeForm.valid">Register</button>
   </div>
</div>
</form>

Refer official doc: https://angular.io/guide/forms#show-and-hide-validation-error-messages.

Editing an item in a list<T>

You don't need to use linq since List<T> provides the methods to do this:

int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
    lst[index] = new Class1() { ... };
}

Bootstrap 4 align navbar items to the right

use the flex-row-reverse class

<nav class="navbar navbar-toggleable-md navbar-light">
    <div class="container">
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false"
          aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="#">
            <i class="fa fa-hospital-o fa-2x" aria-hidden="true"></i>
        </a>
        <div class="collapse navbar-collapse flex-row-reverse" id="navbarNavAltMarkup">
            <ul class="navbar-nav">
                <li><a class="nav-item nav-link active" href="#" style="background-color:#666">Home <span class="sr-only">(current)</span></a</li>
                <li><a class="nav-item nav-link" href="#">Doctors</a></li>
                <li><a class="nav-item nav-link" href="#">Specialists</a></li>
                <li><a class="nav-item nav-link" href="#">About</a></li>
            </ul>
        </div>
    </div>
</nav>

How to enable directory listing in apache web server

See if you are able to access/list the '/icons/' directory. This is useful to test the behavior of Directory in Apache.

for eg : You might be having below config by default in your httpd.conf file.So hit the url : IP:Port/icons/ and see if it list the icons or not.You can also try by putting the 'directory/folder' inside the 'var/www/icons'.

Alias /icons/ "/var/www/icons/"

<Directory "/var/www/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
</Directory>

If it does works then you can crosscheck or modify your custom directory configuration with '' configuration.

Android: How to enable/disable option menu item on button click?

How to update the current menu in order to enable or disable the items when an AsyncTask is done.

In my use case I needed to disable my menu while my AsyncTask was loading data, then after loading all the data, I needed to enable all the menu again in order to let the user use it.

This prevented the app to let users click on menu items while data was loading.

First, I declare a state variable , if the variable is 0 the menu is shown, if that variable is 1 the menu is hidden.

private mMenuState = 1; //I initialize it on 1 since I need all elements to be hidden when my activity starts loading.

Then in my onCreateOptionsMenu() I check for this variable , if it's 1 I disable all my items, if not, I just show them all

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_galeria_pictos, menu);

        if(mMenuState==1){
            for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(false);
            }
        }else{
             for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(true);
            }
        }

        return super.onCreateOptionsMenu(menu);
    }

Now, when my Activity starts, onCreateOptionsMenu() will be called just once, and all my items will be gone because I set up the state for them at the start.

Then I create an AsyncTask Where I set that state variable to 0 in my onPostExecute()

This step is very important!

When you call invalidateOptionsMenu(); it will relaunch onCreateOptionsMenu();

So, after setting up my state to 0, I just redraw all the menu but this time with my variable on 0 , that said, all the menu will be shown after all the asynchronous process is done, and then my user can use the menu.

 public class LoadMyGroups extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mMenuState = 1; //you can set here the state of the menu too if you dont want to initialize it at global declaration. 

        }

        @Override
        protected Void doInBackground(Void... voids) {
           //Background work

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            mMenuState=0; //We change the state and relaunch onCreateOptionsMenu
            invalidateOptionsMenu(); //Relaunch onCreateOptionsMenu

        }
    }

Results

enter image description here

How do I write a bash script to restart a process if it dies?

I've used the following script with great success on numerous servers:

pid=`jps -v | grep $INSTALLATION | awk '{print $1}'`
echo $INSTALLATION found at PID $pid 
while [ -e /proc/$pid ]; do sleep 0.1; done

notes:

  • It's looking for a java process, so I can use jps, this is much more consistent across distributions than ps
  • $INSTALLATION contains enough of the process path that's it's totally unambiguous
  • Use sleep while waiting for the process to die, avoid hogging resources :)

This script is actually used to shut down a running instance of tomcat, which I want to shut down (and wait for) at the command line, so launching it as a child process simply isn't an option for me.

How to include file in a bash shell script

In my situation, in order to include color.sh from the same directory in init.sh, I had to do something as follows.

. ./color.sh

Not sure why the ./ and not color.sh directly. The content of color.sh is as follows.

RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`

Making use of File color.sh does not error but, the color do not display. I have tested this in Ubuntu 18.04 and the Bash version is:

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

.htaccess rewrite subdomain to directory

For any sub domain request, use this:

RewriteEngine on 
RewriteCond %{HTTP_HOST} !^www\.band\.s\.co 
RewriteCond %{HTTP_HOST} ^(.*)\.band\.s\.co 
RewriteCond %{REQUEST_URI} !^/([a-zA-Z0-9-z\-]+) 
RewriteRule ^(.*)$ /%1/$1 [L] 

Just make some folder same as sub domain name you need. Folder must be exist like this: domain.com/sub for sub.domain.com.

Count number of times value appears in particular column in MySQL

select email, count(*) as c FROM orders GROUP BY email

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How can I pass a parameter to a Java Thread?

You need to pass the parameter in the constructor to the Runnable object:

public class MyRunnable implements Runnable {

   public MyRunnable(Object parameter) {
       // store parameter for later user
   }

   public void run() {
   }
}

and invoke it thus:

Runnable r = new MyRunnable(param_value);
new Thread(r).start();

Downloading folders from aws s3, cp or sync?

You've many options to do that, but the best one is using the AWS CLI.

Here's a walk-through:

  1. Download and install AWS CLI in your machine:

  2. Configure AWS CLI:

enter image description here

Make sure you input valid access and secret keys, which you received when you created the account.

  1. Sync the S3 bucket using:

     aws s3 sync s3://yourbucket/yourfolder /local/path
    

In the above command, replace the following fields:

  • yourbucket/yourfolder >> your S3 bucket and the folder that you want to download.
  • /local/path >> path in your local system where you want to download all the files.

How to control the width and height of the default Alert Dialog in Android?

I think tir38's answer is the cleanest solution. Have in mind that if you are using android.app.AlerDialog and holo themes your style should look like this

<style name="WrapEverythingDialog" parent=[holo theme ex. android:Theme.Holo.Dialog]>
    <item name="windowMinWidthMajor">0dp</item>
    <item name="windowMinWidthMinor">0dp</item>
</style>

And if using support.v7.app.AlertDialog or androidx.appcompat.app.AlertDialog with AppCompat theme your style should look like this

<style name="WrapEverythingDialog" parent=[Appcompat theme ex. Theme.AppCompat.Light.Dialog.Alert]>
    <item name="android:windowMinWidthMajor">0dp</item>
    <item name="android:windowMinWidthMinor">0dp</item>
</style>

How to read file with async/await properly?

This is TypeScript version of @Joel's answer. It is usable after Node 11.0:

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(data);
}

Intellij Cannot resolve symbol on import

I had a similar issue with my imported Maven project. In one module, it cannot resolve symbol on import for part of the other module (yes, part of that module can be resolved).

I changed "Maven home directory" to a newer version solved my issue.

Update: Good for 1 hour, back to broken status...

Alter Table Add Column Syntax

Just remove COLUMN from ADD COLUMN

ALTER TABLE Employees
  ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
        PK_Employees PRIMARY KEY CLUSTERED 
        (
          EmployeeID
        ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

How to get the current URL within a Django template?

In Django 3, you want to use url template tag:

{% url 'name-of-your-user-profile-url' possible_context_variable_parameter %}

For an example, see the documentation

Is there a common Java utility to break a list into batches?

With Java 9 you can use IntStream.iterate() with hasNext condition. So you can simplify the code of your method to this:

public static <T> List<List<T>> getBatches(List<T> collection, int batchSize) {
    return IntStream.iterate(0, i -> i < collection.size(), i -> i + batchSize)
            .mapToObj(i -> collection.subList(i, Math.min(i + batchSize, collection.size())))
            .collect(Collectors.toList());
}

Using {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, the result of getBatches(numbers, 4) will be:

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

How to check if a particular service is running on Ubuntu

run

ps -ef | grep name-related-to-process

above command will give all the details like pid, start time about the process.

like if you want all java realted process give java or if you have name of process place the name

Which keycode for escape key with jQuery

Try with the keyup event:

$(document).keyup(function(e) {
  if (e.keyCode === 13) $('.save').click();     // enter
  if (e.keyCode === 27) $('.cancel').click();   // esc
});

Python add item to the tuple

>>> x = (u'2',)
>>> x += u"random string"

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", )  # concatenate a one-tuple instead
>>> x
(u'2', u'random string')

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

This is because gcc calls many other executables to complete the processing of the input, and cc1 is not in the included path.

On shell type whereis cc1. If cc1 is found, it's better go ahead and create a softlink in the directory of gcc; otherwise, cc1 is not installed and you have to install gcc-c++ using the package manager.

std::enable_if to conditionally compile a member function

The boolean needs to depend on the template parameter being deduced. So an easy way to fix is to use a default boolean parameter:

template< class T >
class Y {

    public:
        template < bool EnableBool = true, typename = typename std::enable_if<( std::is_same<T, double>::value && EnableBool )>::type >
        T foo() {
            return 10;
        }

};

However, this won't work if you want to overload the member function. Instead, its best to use TICK_MEMBER_REQUIRES from the Tick library:

template< class T >
class Y {

    public:
        TICK_MEMBER_REQUIRES(std::is_same<T, double>::value)
        T foo() {
            return 10;
        }

        TICK_MEMBER_REQUIRES(!std::is_same<T, double>::value)
        T foo() {
            return 10;
        }

};

You can also implement your own member requires macro like this(just in case you don't want to use another library):

template<long N>
struct requires_enum
{
    enum class type
    {
        none,
        all       
    };
};


#define MEMBER_REQUIRES(...) \
typename requires_enum<__LINE__>::type PrivateRequiresEnum ## __LINE__ = requires_enum<__LINE__>::type::none, \
class=typename std::enable_if<((PrivateRequiresEnum ## __LINE__ == requires_enum<__LINE__>::type::none) && (__VA_ARGS__))>::type

Running a simple shell script as a cronjob

The easiest way would be to use a GUI:

For Gnome use gnome-schedule (universe)

sudo apt-get install gnome-schedule 

For KDE use kde-config-cron

It should be pre installed on Kubuntu

But if you use a headless linux or don´t want GUI´s you may use:

crontab -e

If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:

*     *     *     *     *  YOURCOMMAND
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- Day in Week (0 to 7) (Sunday is 0 and 7)
|     |     |     +------- Month (1 to 12)
|     |     +--------- Day in Month (1 to 31)
|     +----------- Hour (0 to 23)
+------------- Minute (0 to 59)

There are some shorts, too (if you don´t want the *):

@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year

If you want to use the shorts as cron (because they don´t work or so):

@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *

Replace Div Content onclick

Try This:

I think that you want something like this.

HTML:

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

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

jQuery:

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


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

How to create a Calendar table for 100 years in Sql

This SQL Server User Defined Function resolves the problem efficiently.No recursion, no complex loops. It takes a very short time to generate.

ALTER FUNCTION [GA].[udf_GenerateCalendar]
(
     @StartDate  DATE        -- StartDate
   , @EndDate    DATE        -- EndDate
)
RETURNS @Results TABLE 
       (
           Date       DATE 
       )
AS

/**********************************************************
Purpose:   Generate a sequence of dates based on StartDate and EndDate 
***********************************************************/

BEGIN

    DECLARE @counter INTEGER = 1 

    DECLARE @days table(
        day INTEGER NOT NULL 
    )

    DECLARE @months table(
        month INTEGER NOT NULL 
    )

    DECLARE @years table(
        year INTEGER NOT NULL 
    )

    DECLARE @calendar table(
        Date DATE NOT NULL 
    )


    -- Populate generic days 
    SET @counter = 1 
    WHILE @counter <= 31 
    BEGIN 
        INSERT INTO @days 
        SELECT @counter dia 

        SELECT @counter = @counter + 1 
    END 

    -- Populate generic months 
    SET @counter = 1 
    WHILE @counter <= 12 
    BEGIN 
        INSERT INTO @months 
        SELECT @counter month 

        SELECT @counter = @counter + 1 
    END 

    -- Populate generic years 
    SET @counter = YEAR(@StartDate) 
    WHILE @counter <= YEAR(@EndDate) 
    BEGIN 
        INSERT INTO @years 
        SELECT @counter year 

        SELECT @counter = @counter + 1 
    END 

    INSERT @calendar (Date) 
    SELECT Date 
    FROM ( 
        SELECT 
            CONVERT(Date, [Date], 102) AS Date 
        FROM ( 
            SELECT 
                CAST(
                    y.year * 10000 
                    + m.month * 100 
                    + d.day 
                    AS VARCHAR(8)) AS Date 
            FROM @days d, @months m, @years y 
            WHERE 
                ISDATE(CAST(
                    y.year * 10000 
                    + m.month * 100 
                    + d.day 
                    AS VARCHAR(8)) 
                    ) = 1 
        ) A 
    ) A 

    INSERT @Results (Date) 
    SELECT Date 
    FROM @calendar 
    WHERE Date BETWEEN @StartDate AND @EndDate

   RETURN 
/*
DECLARE @StartDate DATE = '2015-08-01'
DECLARE @EndDate   DATE = '2015-08-31'
select * from [GA].[udf_GenerateCalendar](@StartDate, @EndDate)
*/
END

How to set the color of "placeholder" text?

For Firefox use:

 input:-moz-placeholder { color: #aaa; }
 textarea:-moz-placeholder { color: #aaa;}

For all other browsers (Chrome, IE, Safari), just use:

 .placeholder { color: #aaa; }

What is a good Hash Function?

A good hash function has the following properties:

  1. Given a hash of a message it is computationally infeasible for an attacker to find another message such that their hashes are identical.

  2. Given a pair of message, m' and m, it is computationally infeasible to find two such that that h(m) = h(m')

The two cases are not the same. In the first case, there is a pre-existing hash that you're trying to find a collision for. In the second case, you're trying to find any two messages that collide. The second task is significantly easier due to the birthday "paradox."

Where performance is not that great an issue, you should always use a secure hash function. There are very clever attacks that can be performed by forcing collisions in a hash. If you use something strong from the outset, you'll secure yourself against these.

Don't use MD5 or SHA-1 in new designs. Most cryptographers, me included, would consider them broken. The principle source of weakness in both of these designs is that the second property, which I outlined above, does not hold for these constructions. If an attacker can generate two messages, m and m', that both hash to the same value they can use these messages against you. SHA-1 and MD5 also suffer from message extension attacks, which can fatally weaken your application if you're not careful.

A more modern hash such as Whirpool is a better choice. It does not suffer from these message extension attacks and uses the same mathematics as AES uses to prove security against a variety of attacks.

Hope that helps!

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

Try marginTop in place of margin-top, eg:

$("#ActionBox").css("marginTop", foo);

Git Clone from GitHub over https with two-factor authentication

To everyone struggling, what worked for me was creating personal access token and then using it as a username AND password (in the prompt that opened).

Split page vertically using CSS

Here is the flex-box approach:

CSS

 .parent {
  display:flex;
  height:100vh;
  }
  .child{
    flex-grow:1;
  }
  .left{
    background:#ddd;
  }
  .center{
    background:#666;
  }

  .right{
    background:#999;
  }

HTML

<div class="parent">
    <div class="child left">Left</div>
    <div class="child center">Center</div>
    <div class="child right">Right</div>
</div>

You can try the same in js fiddle.

can't multiply sequence by non-int of type 'float'

Because growthRates is a sequence (you're even iterating it!) and you multiply it by (1 + 0.01), which is obviously a float (1.01). I guess you mean for growthRate in growthRates: ... * growthrate?

How to sort multidimensional array by column?

You can use list.sort with its optional key parameter and a lambda expression:

>>> lst = [
...     ['John',2],
...     ['Jim',9],
...     ['Jason',1]
... ]
>>> lst.sort(key=lambda x:x[1])
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>

This will sort the list in-place.


Note that for large lists, it will be faster to use operator.itemgetter instead of a lambda:

>>> from operator import itemgetter
>>> lst = [
...     ['John',2],
...     ['Jim',9],
...     ['Jason',1]
... ]
>>> lst.sort(key=itemgetter(1))
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>

Link entire table row?

Use the ::before pseudo element. This way only you don't have to deal with Javascript or creating links for each cell. Using the following table structure

<table>
  <tr>
    <td><a href="http://domain.tld" class="rowlink">Cell</a></td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table>

all we have to do is create a block element spanning the entire width of the table using ::before on the desired link (.rowlink) in this case.

table {
  position: relative;
}

.rowlink::before {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 1.5em; /* don't forget to set the height! */
}

demo

The ::before is highlighted in red in the demo so you can see what it's doing.

Can't use method return value in write context

The alternative way to check if an array is empty could be:

count($array)>0

It works for me without that error

How to run a C# application at Windows startup?

I did not find any of the above code worked. Maybe that's because my app is running .NET 3.5. I don't know. The following code worked perfectly for me. I got this from a senior level .NET app developer on my team.

Write(Microsoft.Win32.Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\", "WordWatcher", "\"" + Application.ExecutablePath.ToString() + "\"");
public bool Write(RegistryKey baseKey, string keyPath, string KeyName, object Value)
{
    try
    {
        // Setting 
        RegistryKey rk = baseKey;
        // I have to use CreateSubKey 
        // (create or open it if already exits), 
        // 'cause OpenSubKey open a subKey as read-only 
        RegistryKey sk1 = rk.CreateSubKey(keyPath);
        // Save the value 
        sk1.SetValue(KeyName.ToUpper(), Value);

        return true;
    }
    catch (Exception e)
    {
        // an error! 
        MessageBox.Show(e.Message, "Writing registry " + KeyName.ToUpper());
        return false;
    }
}

How to define hash tables in Bash?

This is what I was looking for here:

declare -A hashmap
hashmap["key"]="value"
hashmap["key2"]="value2"
echo "${hashmap["key"]}"
for key in ${!hashmap[@]}; do echo $key; done
for value in ${hashmap[@]}; do echo $value; done
echo hashmap has ${#hashmap[@]} elements

This did not work for me with bash 4.1.5:

animals=( ["moo"]="cow" )

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

Edit:

This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx


You can use this ObjectFilter:

    public class ObjectFilter : ActionFilterAttribute {

    public string Param { get; set; }
    public Type RootType { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
            object o =
            new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
            filterContext.ActionParameters[Param] = o;
        }

    }
}

You can then apply it to your controller methods like so:

    [ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
    public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }

So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.

Response Content type as CSV

Using text/csv is the most appropriate type.

You should also consider adding a Content-Disposition header to the response. Often a text/csv will be loaded by a Internet Explorer directly into a hosted instance of Excel. This may or may not be a desirable result.

Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");

The above will cause a file "Save as" dialog to appear which may be what you intend.

How do I show a console output/window in a forms application?

You can any time switch between type of applications, to console or windows. So, you will not write special logic to see the stdout. Also, when running application in debugger, you will see all the stdout in output window. You might also just add a breakpoint, and in breakpoint properties change "When Hit...", you can output any messages, and variables. Also you can check/uncheck "Continue execution", and your breakpoint will become square shaped. So, the breakpoint messages without changhing anything in the application in the debug output window.

brew install mysql on macOS

If mysql is already installed

Stop mysql completely.

  1. mysql.server stop <-- may need editing based on your version
  2. ps -ef | grep mysql <-- lists processes with mysql in their name
  3. kill [PID] <-- kill the processes by PID

Remove files. Instructions above are good. I'll add:

  1. sudo find /. -name "*mysql*"
  2. Using your judgement, rm -rf these files. Note that many programs have drivers for mysql which you do not want to remove. For example, don't delete stuff in a PHP install's directory. Do remove stuff in its own mysql directory.

Install

Hopefully you have homebrew. If not, download it.

I like to run brew as root, but I don't think you have to. Edit 2018: you can't run brew as root anymore

  1. sudo brew update
  2. sudo brew install cmake <-- dependency for mysql, useful
  3. sudo brew install openssl <-- dependency for mysql, useful
  4. sudo brew info mysql <-- skim through this... it gives you some idea of what's coming next
  5. sudo brew install mysql --with-embedded; say done <-- Installs mysql with the embedded server. Tells you when it finishes (my install took 10 minutes)

Afterwards

  1. sudo chown -R mysql /usr/local/var/mysql/ <-- mysql wouldn't work for me until I ran this command
  2. sudo mysql.server start <-- once again, the exact syntax may vary
  3. Create users in mysql (http://dev.mysql.com/doc/refman/5.7/en/create-user.html). Remember to add a password for the root user.

Push git commits & tags simultaneously

Maybe this helps someone:

git tag 0.0.1                    # creates tag locally     
git push origin 0.0.1            # pushes tag to remote

git tag --delete 0.0.1           # deletes tag locally    
git push --delete origin 0.0.1   # deletes remote tag

How can I get the line number which threw exception?

I tried using the solution By @davy-c but had an Exception "System.FormatException: 'Input string was not in a correct format.'", this was due to there still being text past the line number, I modified the code he posted and came up with:

int line = Convert.ToInt32(objErr.ToString().Substring(objErr.ToString().IndexOf("line")).Substring(0, objErr.ToString().Substring(objErr.ToString().IndexOf("line")).ToString().IndexOf("\r\n")).Replace("line ", ""));

This works for me in VS2017 C#.

How do you run a Python script as a service in Windows?

The simplest way to achieve this is to use native command sc.exe:

sc create PythonApp binPath= "C:\Python34\Python.exe --C:\tmp\pythonscript.py"

References:

  1. https://technet.microsoft.com/en-us/library/cc990289(v=ws.11).aspx
  2. When creating a service with sc.exe how to pass in context parameters?

What are NDF Files?

An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.

How to use \n new line in VB msgbox() ...?

Add a vbNewLine as:

"text1" & vbNewLine & "text2"

How can I express that two values are not equal to eachother?

Just put a '!' in front of the boolean expression

How do I get the APK of an installed app without root access?

I found a way to get the APK's package name in a non-root device. it's not so elegant, but works all the time.

Step 1: on your device, open the target APK

Step 2: on PC cmd window, type this commands:

 adb shell dumpsys activity a > dump.txt

because the output of this command is numerous, redirect to a file is recommended.

Step 3: open this dump.txt file with any editor.

for device befor Android 4.4:
the beginning of the file would be looked like this:

ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)  
  Main stack:  
  * TaskRecord{41aa9ed0 #4 A com.tencent.mm U 0}  
    numActivities=1 rootWasReset=true userId=0  
    affinity=com.tencent.mm  
    intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10600000 cmp=com.tencent.mm/.ui.LauncherUI}  
    realActivity=com.tencent.mm/.ui.LauncherUI  
    askedCompatMode=false  
    lastThumbnail=null lastDescription=null  
    lastActiveTime=19915965 (inactive for 10s)  
    * Hist #9: ActivityRecord{41ba1a30 u0 com.tencent.mm/.ui.LauncherUI}  
        packageName=com.tencent.mm processName=com.tencent.mm 

the package name is in the 3rd line, com.tencent.mm for this example.

for Android 4.4 and later:
the dumpsys output has changed a little. try search "Stack #1", the package name would be very close below it.

Also, search "baseDir", you will find the full path of the apk file!

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

I faced this issue too. I was using jquery.poptrox.min.js for image popping and zooming and I received an error which said:

“Uncaught TypeError: a.indexOf is not a function” error.

This is because indexOf was not supported in 3.3.1/jquery.min.js so a simple fix to this is to change it to an old version 2.1.0/jquery.min.js.

This fixed it for me.

Create a .csv file with values from a Python list

Here is a secure version of Alex Martelli's:

import csv

with open('filename', 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)

How do I redirect in expressjs while passing some context?

The easiest way I have found to pass data between routeHandlers to use next() no need to mess with redirect or sessions. Optionally you could just call your homeCtrl(req,res) instead of next() and just pass the req and res

var express  = require('express');
var jade     = require('jade');
var http     = require("http");


var app    = express();
var server = http.createServer(app);

/////////////
// Routing //
/////////////

// Move route middleware into named
// functions
function homeCtrl(req, res) {

    // Prepare the context
    var context = req.dataProcessed;
    res.render('home.jade', context);
}

function categoryCtrl(req, res, next) {

    // Process the data received in req.body
    // instead of res.redirect('/');
    req.dataProcessed = somethingYouDid;
    return next();
    // optionally - Same effect
    // accept no need to define homeCtrl
    // as the last piece of middleware
    // return homeCtrl(req, res, next);
}

app.get('/', homeCtrl);

app.post('/category', categoryCtrl, homeCtrl);

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:

$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie

$cfg['Servers'][$i]['user'] = 'root'; // MySQL user

$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password

Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:

$cfg['Servers'][$i]['AllowRoot']     = TRUE;        // true = allow root login

This way you have your root password set.

Mergesort with Python

After implementing different versions of solution, I finally made a trade-off to achieve these goals based on CLRS version.

Goal

  • not using list.pop() to iterate values
  • not creating a new list for saving result, modifying the original one instead
  • not using float('inf') as sentinel values
def mergesort(A, p, r):
    if(p < r):
        q = (p+r)//2
        mergesort(A, p, q)
        mergesort(A, q+1, r)
        merge(A, p, q, r)
def merge(A, p, q, r):
    L = A[p:q+1]
    R = A[q+1:r+1]
    i = 0
    j = 0
    k = p
    while i < len(L) and j < len(R):
        if(L[i] < R[j]):
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
        k += 1
    if i < len(L):
        A[k:r+1] = L[i:]
if __name__ == "__main__":
    items = [6, 2, 9, 1, 7, 3, 4, 5, 8]
    mergesort(items, 0, len(items)-1)
    print items
    assert items == [1, 2, 3, 4, 5, 6, 7, 8, 9]

Reference

[1] Book: CLRS

[2] https://github.com/gzc/CLRS/blob/master/C02-Getting-Started/exercise_code/merge-sort.py

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

The answer marked will help you eliminate the error but it will not get MVC working. The answer to the problem is to add this line to the web.config file in system.webServer:

<modules runAllManagedModulesForAllRequests="true" />

Why is Git better than Subversion?

I like Git because it actually helps communication developer to developer on a medium to large team. As a distributed version control system, through its push/pull system, it helps developers to create a source code eco-system which helps to manage a large pool of developers working on a single project.

For example say you trust 5 developers and only pull codes from their repository. Each of those developers has their own trust network from where they pull codes. Thus the development is based on that trust fabric of developers where code responsibility is shared among the development community.

Of course there are other benefits which are mentioned in other answers here.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Definitely summing the Counter()s is the most pythonic way to go in such cases but only if it results in a positive value. Here is an example and as you can see there is no c in result after negating the c's value in B dictionary.

In [1]: from collections import Counter

In [2]: A = Counter({'a':1, 'b':2, 'c':3})

In [3]: B = Counter({'b':3, 'c':-4, 'd':5})

In [4]: A + B
Out[4]: Counter({'d': 5, 'b': 5, 'a': 1})

That's because Counters were primarily designed to work with positive integers to represent running counts (negative count is meaningless). But to help with those use cases,python documents the minimum range and type restrictions as follows:

  • The Counter class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you could store anything in the value field.
  • The most_common() method requires only that the values be orderable.
  • For in-place operations such as c[key] += 1, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for update() and subtract() which allow negative and zero values for both inputs and outputs.
  • The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.
  • The elements() method requires integer counts. It ignores zero and negative counts.

So for getting around that problem after summing your Counter you can use Counter.update in order to get the desire output. It works like dict.update() but adds counts instead of replacing them.

In [24]: A.update(B)

In [25]: A
Out[25]: Counter({'d': 5, 'b': 5, 'a': 1, 'c': -1})

How to set the maxAllowedContentLength to 500MB while running on IIS7?

IIS v10 (but this should be the same also for IIS 7.x)

Quick addition for people which are looking for respective max values

Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

Is there a 'foreach' function in Python 3?

Other examples:

Python Foreach Loop:

array = ['a', 'b']
for value in array:
    print(value)
    # a
    # b

Python For Loop:

array = ['a', 'b']
for index in range(len(array)):
    print("index: %s | value: %s" % (index, array[index]))
    # index: 0 | value: a
    # index: 1 | value: b

How to use Switch in SQL Server

This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

I think your issue may be in the url pattern. Changing

<servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
</servlet-mapping>

and

<form action="/Register" method="post">

may fix your problem

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

Did you init a local Git repository, into which this remote is supposed to be added?

Does your local directory have a .git folder?

Try git init.

Python, creating objects

when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.

class Student:
     def __init__(self):

# creating an object....

   student1=Student()

Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..

class Student:
      def __init__(self,name,age):
            self.name=value
            self.age=value

 # creating an object.......

     student2=Student("smith",25)

What does "where T : class, new()" mean?

class & new are 2 constraints on the generic type parameter T.
Respectively they ensure:

class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

new

The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

Their combination means that the type T must be a Reference Type (can't be a Value Type), and must have a parameterless constructor.

Example:

struct MyStruct { } // structs are value types

class MyClass1 { } // no constructors defined, so the class implicitly has a parameterless one

class MyClass2 // parameterless constructor explicitly defined
{
    public MyClass2() { }
}

class MyClass3 // only non-parameterless constructor defined
{
    public MyClass3(object parameter) { }
}

class MyClass4 // both parameterless & non-parameterless constructors defined
{
    public MyClass4() { }
    public MyClass4(object parameter) { }
}

interface INewable<T>
    where T : new()
{
}

interface INewableReference<T>
    where T : class, new()
{
}

class Checks
{
    INewable<int> cn1; // ALLOWED: has parameterless ctor
    INewable<string> n2; // NOT ALLOWED: no parameterless ctor
    INewable<MyStruct> n3; // ALLOWED: has parameterless ctor
    INewable<MyClass1> n4; // ALLOWED: has parameterless ctor
    INewable<MyClass2> n5; // ALLOWED: has parameterless ctor
    INewable<MyClass3> n6; // NOT ALLOWED: no parameterless ctor
    INewable<MyClass4> n7; // ALLOWED: has parameterless ctor

    INewableReference<int> nr1; // NOT ALLOWED: not a reference type
    INewableReference<string> nr2; // NOT ALLOWED: no parameterless ctor
    INewableReference<MyStruct> nr3; // NOT ALLOWED: not a reference type
    INewableReference<MyClass1> nr4; // ALLOWED: has parameterless ctor
    INewableReference<MyClass2> nr5; // ALLOWED: has parameterless ctor
    INewableReference<MyClass3> nr6; // NOT ALLOWED: no parameterless ctor
    INewableReference<MyClass4> nr7; // ALLOWED: has parameterless ctor
}

Simple way to measure cell execution time in ipython notebook

you may also want to look in to python's profiling magic command %prunwhich gives something like -

def sum_of_lists(N):
    total = 0
    for i in range(5):
        L = [j ^ (j >> i) for j in range(N)]
        total += sum(L)
    return total

then

%prun sum_of_lists(1000000)

will return

14 function calls in 0.714 seconds  

Ordered by: internal time      

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    5    0.599    0.120    0.599    0.120 <ipython-input-19>:4(<listcomp>)
    5    0.064    0.013    0.064    0.013 {built-in method sum}
    1    0.036    0.036    0.699    0.699 <ipython-input-19>:1(sum_of_lists)
    1    0.014    0.014    0.714    0.714 <string>:1(<module>)
    1    0.000    0.000    0.714    0.714 {built-in method exec}

I find it useful when working with large chunks of code.

Objective-C for Windows

You can get an objective c compiler that will work with Windows and play nice with Visual Studio 2008\2010 here.

open-c flite

Just download the latest source. You don't need to build all of CF-Lite there is a solution called objc.sln. You will need to fix a few of the include paths but then it will build just fine. There is even a test project included so you can see some objective-c .m files being compiled and working in visual studio. One sad thing is it only works with Win32 not x64. There is some assembly code that would need to be written for x64 for it to support that.

Angular File Upload

Here is a working example for file upload to api:

Step 1: HTML Template (file-upload.component.html)

Define simple input tag of type file. Add a function to (change)-event for handling choosing files.

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">
</div>

Step 2: Upload Handling in TypeScript (file-upload.component.ts)

Define a default variable for selected file.

fileToUpload: File = null;

Create function which you use in (change)-event of your file input tag:

handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
}

If you want to handle multifile selection, than you can iterate through this files array.

Now create file upload function by calling you file-upload.service:

uploadFileToActivity() {
    this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
        console.log(error);
      });
  }

Step 3: File-Upload Service (file-upload.service.ts)

By uploading a file via POST-method you should use FormData, because so you can add file to http request.

postFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

So, This is very simple working example, which I use everyday in my work.

Run react-native application on iOS device directly from command line?

Just wanted to add something to Kamil's answer

After following the steps, I still got an error,

error Could not find device with the name: "....'s Xr"

After removing special characters from the device name (Go to Settings -> General -> About -> Name)

Eg: '

It Worked !

Hope this will help someone who faced similar issue.

Tested with - react-native-cli: 2.0.1 | react-native: 0.59.8 | VSCode 1.32 | Xcode 10.2.1 | iOS 12.3

The tilde operator in Python

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

Installing R with Homebrew

Working on El Capitan 10.11.1, the steps I followed are

brew install cask    
brew tap homebrew/science    
brew install r

Copying text to the clipboard using Java

For JavaFx based applications.

        //returns System Clipboard
        final Clipboard clipboard = Clipboard.getSystemClipboard();
        // ClipboardContent provides flexibility to store data in different formats
        final ClipboardContent content = new ClipboardContent();
        content.putString("Some text");
        content.putHtml("<b>Some</b> text");
        //this will be replaced by previous putString
        content.putString("Some different text");
        //set the content to clipboard
        clipboard.setContent(content);
       // validate before retrieving it
        if(clipboard.hasContent(DataFormat.HTML)){
            System.out.println(clipboard.getHtml());
        }
        if(clipboard.hasString()){
            System.out.println(clipboard.getString());
        }

ClipboardContent can save multiple data in several data formats like(html,url,plain text,image).

For more information see official documentation

Apache VirtualHost 403 Forbidden

I just spent several hours on this stupid problem

First, change permissions using this in terminal

find htdocs -type f -exec chmod 664 {} + -o -type d -exec chmod 775 {} +

I don't know what the difference is between 664 and 775 I did both 775 like this Also htdocs needs the directory path for instance for me it was

/usr/local/apache2/htdocs 

find htdocs -type f -exec chmod 775 {} + -o -type d -exec chmod 775 {} +

This is the other dumb thing too

make sure that your image src link is your domain name for instance

src="http://www.fakedomain.com/images/photo.png"

Be sure to have

EnableSendfile off in httpd.conf file
EnableMMAP off in httpd.conf file

You edit those using pico in terminal

I also created a directory for images specifically so that when you type in the browser address bar domainname.com/images, you will get a list of photos which can be downloaded and need to be downloaded successfully to indicate image files that are working properly

<Directory /usr/local/apache2/htdocs/images>
AddType images/png .png
</Directory>

And those are the solutions I have tried, now I have functioning images... yay!!!

Onto the next problem(s)

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

Use tab to indent in textarea

The simplest way I found to do that in modern browsers with vanilla JavaScript is:

_x000D_
_x000D_
  <textarea name="codebox"></textarea>_x000D_
  _x000D_
  <script>_x000D_
  const codebox = document.querySelector("[name=codebox]")_x000D_
_x000D_
  codebox.addEventListener("keydown", (e) => {_x000D_
    let { keyCode } = e;_x000D_
    let { value, selectionStart, selectionEnd } = codebox;_x000D_
_x000D_
    if (keyCode === 9) {  // TAB = 9_x000D_
      e.preventDefault();_x000D_
_x000D_
      codebox.value = value.slice(0, selectionStart) + "\t" + value.slice(selectionEnd);_x000D_
_x000D_
      codebox.setSelectionRange(selectionStart+2, selectionStart+2)_x000D_
    }_x000D_
  });_x000D_
  </script>
_x000D_
_x000D_
_x000D_

Note that I used many ES6 features in this snippet for the sake of simplicity, you'll probably want to transpile it (with Babel or TypeScript) before deploying it.

Best way to alphanumeric check in JavaScript

If you want a simplest one-liner solution, then go for the accepted answer that uses regex.

However, if you want a faster solution then here's a function you can have.

_x000D_
_x000D_
console.log(isAlphaNumeric('a')); // true
console.log(isAlphaNumericString('HelloWorld96')); // true
console.log(isAlphaNumericString('Hello World!')); // false

/**
 * Function to check if a character is alpha-numeric.
 *
 * @param {string} c
 * @return {boolean}
 */
function isAlphaNumeric(c) {
  const CHAR_CODE_A = 65;
  const CHAR_CODE_Z = 90;
  const CHAR_CODE_AS = 97;
  const CHAR_CODE_ZS = 122;
  const CHAR_CODE_0 = 48;
  const CHAR_CODE_9 = 57;

  let code = c.charCodeAt(0);

  if (
    (code >= CHAR_CODE_A && code <= CHAR_CODE_Z) ||
    (code >= CHAR_CODE_AS && code <= CHAR_CODE_ZS) ||
    (code >= CHAR_CODE_0 && code <= CHAR_CODE_9)
  ) {
    return true;
  }

  return false;
}

/**
 * Function to check if a string is fully alpha-numeric.
 *
 * @param {string} s
 * @returns {boolean}
 */
function isAlphaNumericString(s) {
  for (let i = 0; i < s.length; i++) {
    if (!isAlphaNumeric(s[i])) {
      return false;
    }
  }

  return true;
}
_x000D_
_x000D_
_x000D_

How to get name of calling function/method in PHP?

The simplest way is:

echo debug_backtrace()[1]['function'];

Which is faster: Stack allocation or Heap allocation

Never do premature assumption as other application code and usage can impact your function. So looking at function is isolation is of no use.

If you are serious with application then VTune it or use any similar profiling tool and look at hotspots.

Ketan

split string only on first instance of specified character

Non-regex solution

I ran some benchmarks, and this solution won hugely:1

str.slice(str.indexOf(delim) + delim.length)

// as function
function gobbleStart(str, delim) {
    return str.slice(str.indexOf(delim) + delim.length);
}

// as polyfill
String.prototype.gobbleStart = function(delim) {
    return this.slice(this.indexOf(delim) + delim.length);
};

Performance comparison with other solutions

The only close contender was the same line of code, except using substr instead of slice.

Other solutions I tried involving split or RegExps took a big performance hit and were about 2 orders of magnitude slower. Using join on the results of split, of course, adds an additional performance penalty.

Why are they slower? Any time a new object or array has to be created, JS has to request a chunk of memory from the OS. This process is very slow.

Here are some general guidelines, in case you are chasing benchmarks:

  • New dynamic memory allocations for objects {} or arrays [] (like the one that split creates) will cost a lot in performance.
  • RegExp searches are more complicated and therefore slower than string searches.
  • If you already have an array, destructuring arrays is about as fast as explicitly indexing them, and looks awesome.

Removing beyond the first instance

Here's a solution that will slice up to and including the nth instance. It's not quite as fast, but on the OP's question, gobble(element, '_', 1) is still >2x faster than a RegExp or split solution and can do more:

/*
`gobble`, given a positive, non-zero `limit`, deletes
characters from the beginning of `haystack` until `needle` has
been encountered and deleted `limit` times or no more instances
of `needle` exist; then it returns what remains. If `limit` is
zero or negative, delete from the beginning only until `-(limit)`
occurrences or less of `needle` remain.
*/
function gobble(haystack, needle, limit = 0) {
  let remain = limit;
  if (limit <= 0) { // set remain to count of delim - num to leave
    let i = 0;
    while (i < haystack.length) {
      const found = haystack.indexOf(needle, i);
      if (found === -1) {
        break;
      }
      remain++;
      i = found + needle.length;
    }
  }

  let i = 0;
  while (remain > 0) {
    const found = haystack.indexOf(needle, i);
    if (found === -1) {
      break;
    }
    remain--;
    i = found + needle.length;
  }
  return haystack.slice(i);
}

With the above definition, gobble('path/to/file.txt', '/') would give the name of the file, and gobble('prefix_category_item', '_', 1) would remove the prefix like the first solution in this answer.


  1. Tests were run in Chrome 70.0.3538.110 on macOSX 10.14.

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

If you want to change the permissions of an existing file, use chmod (change mode):

$itWorked = chmod ("/yourdir/yourfile", 0777);

If you want all new files to have certain permissions, you need to look into setting your umode. This is a process setting that applies a default modification to standard modes.

It is a subtractive one. By that, I mean a umode of 022 will give you a default permission of 755 (777 - 022 = 755).

But you should think very carefully about both these options. Files created with that mode will be totally unprotected from changes.

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

Adapted from Timmmm to PYQT5

from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel


class Label(QLabel):

    def __init__(self):
        super(Label, self).__init__()
        self.pixmap_width: int = 1
        self.pixmapHeight: int = 1

    def setPixmap(self, pm: QPixmap) -> None:
        self.pixmap_width = pm.width()
        self.pixmapHeight = pm.height()

        self.updateMargins()
        super(Label, self).setPixmap(pm)

    def resizeEvent(self, a0: QResizeEvent) -> None:
        self.updateMargins()
        super(Label, self).resizeEvent(a0)

    def updateMargins(self):
        if self.pixmap() is None:
            return
        pixmapWidth = self.pixmap().width()
        pixmapHeight = self.pixmap().height()
        if pixmapWidth <= 0 or pixmapHeight <= 0:
            return
        w, h = self.width(), self.height()
        if w <= 0 or h <= 0:
            return

        if w * pixmapHeight > h * pixmapWidth:
            m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
            self.setContentsMargins(m, 0, m, 0)
        else:
            m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
            self.setContentsMargins(0, m, 0, m)

How do you overcome the svn 'out of date' error?

Are you sure you've checked out the head and not a lower revision? Also, have you done an update to make sure you've got the latest version?

There's a discussion about this on http://svn.haxx.se/users/archive-2007-01/0170.shtml.

Using a Loop to add objects to a list(python)

Auto-incrementing the index in a loop:

myArr[(len(myArr)+1)]={"key":"val"}

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

removing html element styles via javascript

In jQuery, you can use

$(".className").attr("style","");

AngularJS - Animate ng-view transitions

Angularjs 1.1.4 has now introduced the ng-animate directive to help animating different elements, in particular ng-view.

You can also watch the video about this new featue

UPDATE as of angularjs 1.2, the way animations work has changed drastically, most of it is now controlled with CSS, without having to setup javascript callbacks, etc.. You can check the updated tutorial on Year Of Moo. @dfsq pointed out in the comments a nice set of examples.

Mockito - NullpointerException when stubbing Method

I had this issue and my problem was that I was calling my method with any() instead of anyInt(). So I had:

doAnswer(...).with(myMockObject).thisFuncTakesAnInt(any())

and I had to change it to:

doAnswer(...).with(myMockObject).thisFuncTakesAnInt(anyInt())

I have no idea why that produced a NullPointerException. Maybe this will help the next poor soul.

What does -z mean in Bash?

-z

string is null, that is, has zero length

String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

Use a JSON array with objects with javascript

_x000D_
_x000D_
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];_x000D_
document.writeln("<table border = '1' width = 100 >");_x000D_
document.writeln("<tr><td>No Id</td><td>Title</td></tr>"); _x000D_
for(var i=0;i<datas.length;i++){_x000D_
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");_x000D_
}_x000D_
document.writeln("</table>");
_x000D_
_x000D_
_x000D_

Create an empty object in JavaScript with {} or new Object()?

The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...

rand() returns the same number each time the program is run

srand() seeds the random number generator. Without a seed, the generator is unable to generate the numbers you are looking for. As long as one's need for random numbers is not security-critical (e.g. any sort of cryptography), common practice is to use the system time as a seed by using the time() function from the <ctime> library as such: srand(time(0)). This will seed the random number generator with the system time expressed as a Unix timestamp (i.e. the number of seconds since the date 1/1/1970). You can then use rand() to generate a pseudo-random number.

Here is a quote from a duplicate question:

The reason is that a random number generated from the rand() function isn't actually random. It simply is a transformation. Wikipedia gives a better explanation of the meaning of pseudorandom number generator: deterministic random bit generator. Every time you call rand() it takes the seed and/or the last random number(s) generated (the C standard doesn't specify the algorithm used, though C++11 has facilities for specifying some popular algorithms), runs a mathematical operation on those numbers, and returns the result. So if the seed state is the same each time (as it is if you don't call srand with a truly random number), then you will always get the same 'random' numbers out.

If you want to know more, you can read the following:

http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/

http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/

Can I get the name of the current controller in the view?

#to get controller name:
<%= controller.controller_name %>
#=> 'users'

#to get action name, it is the method:
<%= controller.action_name %>
#=> 'show'


#to get id information:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
#=> '23'

# or display nicely
<%= debug Rails.application.routes.recognize_path(request.url) %>

reference

How to get a index value from foreach loop in jstl

You can use the varStatus attribute like this:-

<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">

myIndex.index will give you the index. Here myIndex is a LoopTagStatus object.

Hence, you can send that to your javascript method like this:-

<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>

Regular expression to match a dot

A . in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so \.

android View not attached to window manager

Another option is not to start the async task until the dialog is attached to the window by overriding onAttachedToWindow() on the dialog, that way it is always dismissible.

Why are empty catch blocks a bad idea?

I wouldn't stretch things as far as to say that who uses empty catch blocks is a bad programmer and doesn't know what he is doing...

I use empty catch blocks if necessary. Sometimes programmer of library I'm consuming doesn't know what he is doing and throws exceptions even in situations when nobody needs it.

For example, consider some http server library, I couldn't care less if server throws exception because client has disconnected and index.html couldn't be sent.

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

I know its late but I think you can try like this

$("#multipledpdwn").on("select2:select select2:unselect", function (e) {

    //this returns all the selected item
    var items= $(this).val();       

    //Gets the last selected item
    var lastSelectedItem = e.params.data.id;

})

Hope it may help some one in future.

how to set textbox value in jquery

I would like to point out to you that .val() also works with selects to select the current selected value.

align text center with android

Set also android:gravity parameter in TextView to center.

For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.

git recover deleted file where no commit was made after the delete

Since you're doing a git checkout ., it looks like you are trying to restore your branch back to the last commit state.

You can achieve this with a git reset HEAD --hard

Warning

Doing this may remove all your latest modifications and unstage your modifications, e.g., you can lose work. It may be what you want, but check out the docs to make sure.

Which Python memory profiler is recommended?

I'm developing a memory profiler for Python called memprof:

http://jmdana.github.io/memprof/

It allows you to log and plot the memory usage of your variables during the execution of the decorated methods. You just have to import the library using:

from memprof import memprof

And decorate your method using:

@memprof

This is an example on how the plots look like:

enter image description here

The project is hosted in GitHub:

https://github.com/jmdana/memprof

How to get the unix timestamp in C#

When you subtract 1970 from the current time, be aware that the timespan will most often have a non zero milliseconds field. If for some reason you are interested in the milliseconds, keep this in mind.

Here's what I did to get around this issue.

 DateTime now = UtcNow();

 // milliseconds Not included.
 DateTime nowToTheSecond = new DateTime(now.Year,now.Month,now.Day,now.Hour,now.Minute,now.Second); 

 TimeSpan span = (date - new DateTime(1970, 1, 1, 0, 0, 0, 0));

 Assert.That(span.Milliseconds, Is.EqualTo(0)); // passes.

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

Flexbox: 4 items per row

Hope it helps. for more detail you can follow this Link

_x000D_
_x000D_
.parent{ 
  display: flex; 
  flex-wrap: wrap; 
}

.parent .child{ 
  flex: 1 1 25%;
  /*Start Run Code Snippet output CSS*/
  padding: 5px; 
  box-sizing: border-box;
  text-align: center;
  border: 1px solid #000;
  /*End Run Code Snippet output CSS*/
}
_x000D_
<div class="parent">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
  <div class="child">6</div>
  <div class="child">7</div>
  <div class="child">8</div>
</div>
_x000D_
_x000D_
_x000D_

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

If you are interested only in the last X lines, you can use the "tail" command like this.

$ tail -n XXXXX yourlogfile.log >> mycroppedfile.txt

This will save the last XXXXX lines of your log file to a new file called "mycroppedfile.txt"

Creating a jQuery object from a big HTML-string

As of jQuery 1.8 you can just use parseHtml to create your jQuery object:

var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));

I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/

It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.

How do Python's any and all functions work?

>>> any([False, False, False])
False
>>> any([False, True, False])
True
>>> all([False, True, True])
False
>>> all([True, True, True])
True

Remove empty elements from an array in Javascript

The clean way to do it.

var arr = [0,1,2,"Thomas","false",false,true,null,3,4,undefined,5,"end"];
arr = arr.filter(Boolean);
// [1, 2, "Thomas", "false", true, 3, 4, 5, "end"]

Remove Item from ArrayList

If you use "=", a replica is created for the original arraylist in the second one, but the reference is same so if you change in one list , the other one will also get modified. Use this instead of "="

        List_Of_Array1.addAll(List_Of_Array);

Xcode doesn't see my iOS device but iTunes does

After updating my iPhone to 10.3.3, Xcode 8.3.3 cannot find it in the Device window but iTunes can. Restarting Xcode fixed the problem.

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

How to call loading function with React useEffect only once

If you only want to run the function given to useEffect after the initial render, you can give it an empty array as second argument.

function MyComponent() {
  useEffect(() => {
    loadDataOnlyOnce();
  }, []);

  return <div> {/* ... */} </div>;
}

Which MySQL datatype to use for an IP address?

You have two possibilities (for an IPv4 address) :

  • a varchar(15), if your want to store the IP address as a string
    • 192.128.0.15 for instance
  • an integer (4 bytes), if you convert the IP address to an integer
    • 3229614095 for the IP I used before


The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).

About those manipulations, see the ip2long() and long2ip() functions, on the PHP-side, or inet_aton() and inet_ntoa() on the MySQL-side.

Python: Figure out local timezone

I want to compare UTC timestamps from a log file with local timestamps

If this is your intent, then I wouldn't worry about specifying specific tzinfo parameters or any additional external libraries. Since Python 3.5, the built in datetime module is all you need to create a UTC and a local timestamp automatically.

import datetime
f = "%a %b %d %H:%M:%S %Z %Y"         # Full format with timezone

# tzinfo=None
cdatetime = datetime.datetime(2010, 4, 27, 12, 0, 0, 0)  # 1. Your example from log
cdatetime = datetime.datetime.now()   # 2. Basic date creation (default: local time)
print(cdatetime.strftime(f))          # no timezone printed
# Tue Apr 27 12:00:00  2010

utctimestamp = cdatetime.astimezone(tz=datetime.timezone.utc)  # 1. convert to UTC
utctimestamp = datetime.datetime.now(tz=datetime.timezone.utc) # 2. create in UTC
print(utctimestamp.strftime(f))
# Tue Apr 27 17:00:00 UTC 2010

localtimestamp = cdatetime.astimezone()               # 1. convert to local [default]
localtimestamp = datetime.datetime.now().astimezone()  # 2. create with local timezone
print(localtimestamp.strftime(f))
# Tue Apr 27 12:00:00 CDT 2010

The '%Z' parameter of datetime.strftime() prints the timezone acronym into the timestamp for humans to read.

How to fix "unable to write 'random state' " in openssl

Or this in windows powershell

$env:RANDFILE=".rnd"

How to create a jQuery function (a new jQuery method or plugin)?

It sounds like you want to extend the jQuery object via it's prototype (aka write a jQuery plugin). This would mean that every new object created through calling the jQuery function ($(selector/DOM element)) would have this method.

Here is a very simple example:

$.fn.myFunction = function () {
    alert('it works');
};

Demo

What is the difference between res.end() and res.send()?

res is an HttpResponse object which extends from OutgoingMessage. res.send calls res.end which is implemented by OutgoingMessage to send HTTP response and close connection. We see code here

How can I use Html.Action?

Another case is http redirection. If your page redirects http requests to https, then may be your partial view tries to redirect by itself.

It causes same problem again. For this problem, you can reorganize your .net error pages or iis error pages configuration.

Just make sure you are redirecting requests to right error or not found page and make sure this error page contains non problematic partial. If your page supports only https, do not forward requests to error page without using https, if error page contains partial, this partials tries to redirect seperately from requested url, it causes problem.

Passing an integer by reference in Python

The correct answer, is to use a class and put the value inside the class, this lets you pass by reference exactly as you desire.

class Thing:
  def __init__(self,a):
    self.a = a
def dosomething(ref)
  ref.a += 1

t = Thing(3)
dosomething(t)
print("T is now",t.a)

Is __init__.py not required for packages in Python 3.3+

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.

Packages are only recognized if they include an __init__.py file

UPD: If you want to use implicit namespace packages without __init__.py you just have to use find_namespace_packages() instead

Docs

How can I get date and time formats based on Culture Info?

You could take a look at the DateTimeFormat property which contains the culture specific formats.

How to run a makefile in Windows?

If you install Cygwin. Make sure to select make in the installer. You can then run the following command provided you have a Makefile.

make -f Makefile

https://cygwin.com/install.html

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

data = json.load(urllib2.urlopen('http://someurl/path/to/json'))

Get the first element of an array

Also worth bearing in mind is the context in which you're doing this, as an exhaustive check can be expensive and not always necessary.

For example, this solution works fine for the situation in which I'm using it (but obviously it can't be relied on in all cases...)

 /**
 * A quick and dirty way to determine whether the passed in array is associative or not, assuming that either:<br/>
 * <br/>
 * 1) All the keys are strings - i.e. associative<br/>
 * or<br/>
 * 2) All the keys are numeric - i.e. not associative<br/>
 *
 * @param array $objects
 * @return boolean
 */
private function isAssociativeArray(array $objects)
{
    // This isn't true in the general case, but it's a close enough (and quick) approximation for the context in
    // which we're using it.

    reset($objects);
    return count($objects) > 0 && is_string(key($objects));
}

cURL POST command line on WINDOWS RESTful service

We can use below Curl command in Windows Command prompt to send the request. Use the Curl command below, replace single quote with double quotes, remove quotes where they are not there in below format and use the ^ symbol.

curl http://localhost:7101/module/url ^
  -d @D:/request.xml ^
  -H "Content-Type: text/xml" ^
  -H "SOAPAction: process" ^
  -H "Authorization: Basic xyz" ^
  -X POST

how to set width for PdfPCell in ItextSharp

Why not use a PdfPTable object for this? Create a fixed width table and use a float array to set the widths of the columns

PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);

addCell(table, "SER.\nNO.", 2);

addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);

addCell(table, "DESCRIPTION OF GOODS", 2);

addCell(table, "LINE DOC. RECL DATE", 1);

addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);

addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);

....

private static void addCell(PdfPTable table, string text, int rowspan)
{
    BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
    iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

    PdfPCell cell = new PdfPCell(new Phrase(text, times));
    cell.Rowspan = rowspan;
    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
    cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
    table.AddCell(cell);
}

have a look at this tutorial too...

Data truncated for column?

I had the same problem because of an table column which was defined as ENUM('x','y','z') and later on I was trying to save the value 'a' into this column, thus I got the mentioned error.

Solved by altering the table column definition and added value 'a' into the enum set.

If hasClass then addClass to parent

The reason that does not work is because this has no specific meaning inside of an if statement, you will have to go back to a level of scope where this is defined (a function).

For example:

$('#element1').click(function() {
    console.log($(this).attr('id')); // logs "element1"

    if ($('#element2').hasClass('class')) {
        console.log($(this).attr('id')); // still logs "element1"
    }
});

Java Calendar, getting current month value, clarification needed

import java.util.*;

class GetCurrentmonth
{
    public static void main(String args[])
    {
        int month;
        GregorianCalendar date = new GregorianCalendar();      
        month = date.get(Calendar.MONTH);
        month = month+1;
        System.out.println("Current month is  " + month);
    }
}

HTML email with Javascript

What you are trying to achieve should be done in the web browser because javascript simply doesn't work with html email design. The various email clients that are out there e.g. gmail, outlook, yahoo strip scripts put of the code for security reasons.

It is best to just use HTML and CSS to style your emails. Maybe you could have a call to action (cta) in your html email that sends the user to a web page with your expanding and collapsing content feature.

input[type='text'] CSS selector does not apply to default-type text inputs?

To be compliant with all browsers you should always declare the input type.

Some browsers will assume default type as 'text', but this isn't a good practice.

How to select rows that have current day's timestamp?

On Visual Studio 2017, using the built-in database for development I had problems with the current given solution, I had to change the code to make it work because it threw the error that DATE() was not a built in function.

Here is my solution:

where CAST(TimeCalled AS DATE) = CAST(GETDATE() AS DATE)

Any difference between await Promise.all() and multiple await?

In case of await Promise.all([task1(), task2()]); "task1()" and "task2()" will run parallel and will wait until both promises are completed (either resolved or rejected). Whereas in case of

const result1 = await t1;
const result2 = await t2;

t2 will only run after t1 has finished execution (has been resolved or rejected). Both t1 and t2 will not run parallel.

add new row in gridview after binding C#, ASP.net

If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:

adapter.Fill(ds);
ds.Tables(0).Rows.Add();

What REALLY happens when you don't free after malloc?

I think that your two examples are actually only one: the free() should occur only at the end of the process, which as you point out is useless since the process is terminating.

In you second example though, the only difference is that you allow an undefined number of malloc(), which could lead to running out of memory. The only way to handle the situation is to check the return code of malloc() and act accordingly.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Hope this will help someone... Here's a little PHP script I wrote in case you need to copy some columns but not others, and/or the columns are not in the same order on both tables. As long as the columns are named the same, this will work. So if table A has [userid, handle, something] and tableB has [userID, handle, timestamp], then you'd "SELECT userID, handle, NOW() as timestamp FROM tableA", then get the result of that, and pass the result as the first parameter to this function ($z). $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. This is relatively fast for small sets of data. Not suggested that you try to move more than a few thousand rows at a time this way in a production setting. I use this primarily to back up data collected during a session when a user logs out, and then immediately clear the data from the live db to keep it slim.

 function mysql_multirow_copy($z,$toTable,$link_identifier) {
            $fields = "";
            for ($i=0;$i<mysql_num_fields($z);$i++) {
                if ($i>0) {
                    $fields .= ",";
                }
                $fields .= mysql_field_name($z,$i);
            }
            $q = "INSERT INTO $toTable ($fields) VALUES";
            $c = 0;
            mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
            while ($a = mysql_fetch_assoc($z)) {
                foreach ($a as $key=>$as) {
                    $a[$key] = addslashes($as);
                    next ($a);
                }
                if ($c>0) {
                    $q .= ",";
                }
                $q .= "('".implode(array_values($a),"','")."')";
                $c++;
            }
            $q .= ";";
            $z = mysql_query($q,$link_identifier);
            return ($q);
        }