Programs & Examples On #File manager

What does set -e mean in a bash script?

From help set :

  -e  Exit immediately if a command exits with a non-zero status.

But it's considered bad practice by some (bash FAQ and irc freenode #bash FAQ authors). It's recommended to use:

trap 'do_something' ERR

to run do_something function when errors occur.

See http://mywiki.wooledge.org/BashFAQ/105

How to return JSON data from spring Controller using @ResponseBody

When I was facing this issue, I simply put just getter setter methods and my issues were resolved.

I am using Spring boot version 2.0.

Failed to load resource: net::ERR_INSECURE_RESPONSE

If you're developing, and you're developing with a Windows machine, simply add localhost as a Trusted Site.

And yes, per DarrylGriffiths' comment, although it may look like you're adding an Internet Explorer setting...

I believe those are Windows rather than IE settings. Although MS tend to assume that they're only IE (hence the alert next to "Enable Protected Mode" that it requries restarted IE)...

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName

Why does Boolean.ToString output "True" and not "true"

How is it not compatible with C#? Boolean.Parse and Boolean.TryParse is case insensitive and the parsing is done by comparing the value to Boolean.TrueString or Boolean.FalseString which are "True" and "False".

EDIT: When looking at the Boolean.ToString method in reflector it turns out that the strings are hard coded so the ToString method is as follows:

public override string ToString()
{
    if (!this)
    {
        return "False";
    }
    return "True";
}

PHP code to convert a MySQL query to CSV

An update to @jrgns (with some slight syntax differences) solution.

$result = mysql_query('SELECT * FROM `some_table`'); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{     
       $headers[] = mysql_field_name($result , $i); 
} 
$fp = fopen('php://output', 'w'); 
if ($fp && $result) 
{     
       header('Content-Type: text/csv');
       header('Content-Disposition: attachment; filename="export.csv"');
       header('Pragma: no-cache');    
       header('Expires: 0');
       fputcsv($fp, $headers); 
       while ($row = mysql_fetch_row($result)) 
       {
          fputcsv($fp, array_values($row)); 
       }
die; 
} 

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.

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Rather than having nested cursor loops a more efficient approach would be to use one cursor loop with an outer join between the tables.

BEGIN
    FOR rec IN (SELECT a.needed_field,b.other_field
                  FROM table1 a
                  LEFT OUTER JOIN table2 b
                    ON a.needed_field = b.condition_field
                 WHERE a.column = ???)
    LOOP
       IF rec.other_field IS NOT NULL THEN
         -- whatever processing needs to be done to other_field
       END IF;
    END LOOP;
END;

Pretty printing XML in Python

If for some reason you can't get your hands on any of the Python modules that other users mentioned, I suggest the following solution for Python 2.7:

import subprocess

def makePretty(filepath):
  cmd = "xmllint --format " + filepath
  prettyXML = subprocess.check_output(cmd, shell = True)
  with open(filepath, "w") as outfile:
    outfile.write(prettyXML)

As far as I know, this solution will work on Unix-based systems that have the xmllint package installed.

How do I compare a value to a backslash?

Escape the backslash:

if message.value[0] == "/" or message.value[0] == "\\":

From the documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):

SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X

Perform a Shapiro-Wilk Normality Test

You are applying shapiro.test() to a data.frame instead of the column. Try the following:

shapiro.test(heisenberg$HWWIchg)

How to get the size of a varchar[n] field in one SQL statement?

For SQL Server (2008 and above):

SELECT COLUMNPROPERTY(OBJECT_ID('mytable'), 'Remarks', 'PRECISION');

COLUMNPROPERTY returns information for a column or parameter (id, column/parameter, property). The PRECISION property returns the length of the data type of the column or parameter.

COLUMNPROPERTY documentation

Convert hex string (char []) to int?

Or if you want to have your own implementation, I wrote this quick function as an example:

/**
 * hex2int
 * take a hex string and convert it to a 32bit number (max 8 hex digits)
 */
uint32_t hex2int(char *hex) {
    uint32_t val = 0;
    while (*hex) {
        // get current character then increment
        uint8_t byte = *hex++; 
        // transform hex character to the 4bit equivalent number, using the ascii table indexes
        if (byte >= '0' && byte <= '9') byte = byte - '0';
        else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
        else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
        // shift 4 to make space for new digit, and add the 4 bits of the new digit 
        val = (val << 4) | (byte & 0xF);
    }
    return val;
}

JSON Array iteration in Android/Java

I have done it two different ways,

1.) make a Map

        HashMap<String, String> applicationSettings = new HashMap<String,String>();
        for(int i=0; i<settings.length(); i++){
            String value = settings.getJSONObject(i).getString("value");
            String name = settings.getJSONObject(i).getString("name");
            applicationSettings.put(name, value);
        }

2.) make a JSONArray of names

    JSONArray names = json.names();
    JSONArray values = json.toJSONArray(names);
    for(int i=0; i<values.length(); i++){
        if (names.getString(i).equals("description")){
            setDescription(values.getString(i));
        }
        else if (names.getString(i).equals("expiryDate")){
            String dateString = values.getString(i);
            setExpiryDate(stringToDateHelper(dateString)); 
        }
        else if (names.getString(i).equals("id")){
            setId(values.getLong(i));
        }
        else if (names.getString(i).equals("offerCode")){
            setOfferCode(values.getString(i));
        }
        else if (names.getString(i).equals("startDate")){
            String dateString = values.getString(i);
            setStartDate(stringToDateHelper(dateString));
        }
        else if (names.getString(i).equals("title")){
            setTitle(values.getString(i));
        }
    }

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

How do I check if the mouse is over an element in jQuery?

WARNING: is(':hover') is deprecated in jquery 1.8+. See this post for a solution.

You can also use this answer : https://stackoverflow.com/a/6035278/8843 to test if the mouse is hover an element :

$('#test').click(function() {
    if ($('#hello').is(':hover')) {
        alert('hello');
    }
});

How to dynamically add elements to String array?

when using String array, you have to give size of array while initializing

eg

String[] str = new String[10];

you can use index 0-9 to store values

str[0] = "value1"
str[1] = "value2"
str[2] = "value3"
str[3] = "value4"
str[4] = "value5"
str[5] = "value6"
str[6] = "value7"
str[7] = "value8"
str[8] = "value9"
str[9] = "value10"

if you are using ArrayList instread of string array, you can use it without initializing size of array ArrayList str = new ArrayList();

you can add value by using add method of Arraylist

str.add("Value1");

get retrieve a value from arraylist, you can use get method

String s = str.get(0);

find total number of items by size method

int nCount = str.size();

read more from here

How to add a Java Properties file to my Java Project in Eclipse

steps:

  1. Right click on any package where you want to create your .properties file or create a new package as required
  2. now select new then select file (if you dont find file then go to location of your package and create it there)
  3. now named it as yourfilename.properties

Can I use tcpdump to get HTTP requests, response header and response body?

Here is another choice: Chaosreader

So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...

The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/

It worked like a treat, I did the following:

tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile

How to change the session timeout in PHP?

Session timeout is a notion that has to be implemented in code if you want strict guarantees; that's the only way you can be absolutely certain that no session ever will survive after X minutes of inactivity.

If relaxing this requirement a little is acceptable and you are fine with placing a lower bound instead of a strict limit to the duration, you can do so easily and without writing custom logic.

Convenience in relaxed environments: how and why

If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an upper bound on the session duration by tweaking certain parameters. If you are using PHP's default session handling with cookies, setting session.gc_maxlifetime along with session_set_cookie_params should work for you like this:

// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);

session_start(); // ready to go!

This works by configuring the server to keep session data around for at least one hour of inactivity and instructing your clients that they should "forget" their session id after the same time span. Both of these steps are required to achieve the expected result.

  • If you don't tell the clients to forget their session id after an hour (or if the clients are malicious and choose to ignore your instructions) they will keep using the same session id and its effective duration will be non-deterministic. That is because sessions whose lifetime has expired on the server side are not garbage-collected immediately but only whenever the session GC kicks in.

    GC is a potentially expensive process, so typically the probability is rather small or even zero (a website getting huge numbers of hits will probably forgo probabilistic GC entirely and schedule it to happen in the background every X minutes). In both cases (assuming non-cooperating clients) the lower bound for effective session lifetimes will be session.gc_maxlifetime, but the upper bound will be unpredictable.

  • If you don't set session.gc_maxlifetime to the same time span then the server might discard idle session data earlier than that; in this case, a client that still remembers their session id will present it but the server will find no data associated with that session, effectively behaving as if the session had just started.

Certainty in critical environments

You can make things completely controllable by using custom logic to also place an upper bound on session inactivity; together with the lower bound from above this results in a strict setting.

Do this by saving the upper bound together with the rest of the session data:

session_start(); // ready to go!

$now = time();
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
    // this session has worn out its welcome; kill it and start a brand new one
    session_unset();
    session_destroy();
    session_start();
}

// either new or old, it should live at most for another hour
$_SESSION['discard_after'] = $now + 3600;

Session id persistence

So far we have not been concerned at all with the exact values of each session id, only with the requirement that the data should exist as long as we need them to. Be aware that in the (unlikely) case that session ids matter to you, care must be taken to regenerate them with session_regenerate_id when required.

Stored procedure or function expects parameter which is not supplied

Your stored procedure expects 5 parameters as input

@userID int, 
@userName varchar(50), 
@password nvarchar(50), 
@emailAddress nvarchar(50), 
@preferenceName varchar(20) 

So you should add all 5 parameters to this SP call:

    cmd.CommandText = "SHOWuser";
    cmd.Parameters.AddWithValue("@userID",userID);
    cmd.Parameters.AddWithValue("@userName", userName);
    cmd.Parameters.AddWithValue("@password", password);
    cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
    cmd.Parameters.AddWithValue("@preferenceName", preferences);
    dbcon.Open();

PS: It's not clear what these parameter are for. You don't use these parameters in your SP body so your SP should looks like:

ALTER PROCEDURE [dbo].[SHOWuser] AS BEGIN ..... END

Passing base64 encoded strings in URL

Yes and no.

The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()).

Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

Convert varchar to uniqueidentifier in SQL Server

your varchar col C:

SELECT CONVERT(uniqueidentifier,LEFT(C, 8)
                                + '-' +RIGHT(LEFT(C, 12), 4)
                                + '-' +RIGHT(LEFT(C, 16), 4)
                                + '-' +RIGHT(LEFT(C, 20), 4)
                                + '-' +RIGHT(C, 12))

How to run stored procedures in Entity Framework Core?

Nothing have to do... when you are creating dbcontext for code first approach initialize namespace below the fluent API area make list of sp and use it another place where you want.

public partial class JobScheduleSmsEntities : DbContext
{
    public JobScheduleSmsEntities()
        : base("name=JobScheduleSmsEntities")
    {
        Database.SetInitializer<JobScheduleSmsEntities>(new CreateDatabaseIfNotExists<JobScheduleSmsEntities>());
    }

    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<ReachargeDetail> ReachargeDetails { get; set; }
    public virtual DbSet<RoleMaster> RoleMasters { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //modelBuilder.Types().Configure(t => t.MapToStoredProcedures());

        //modelBuilder.Entity<RoleMaster>()
        //     .HasMany(e => e.Customers)
        //     .WithRequired(e => e.RoleMaster)
        //     .HasForeignKey(e => e.RoleID)
        //     .WillCascadeOnDelete(false);
    }
    public virtual List<Sp_CustomerDetails02> Sp_CustomerDetails()
    {
        //return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Sp_CustomerDetails02>("Sp_CustomerDetails");
        //  this.Database.SqlQuery<Sp_CustomerDetails02>("Sp_CustomerDetails");
        using (JobScheduleSmsEntities db = new JobScheduleSmsEntities())
        {
           return db.Database.SqlQuery<Sp_CustomerDetails02>("Sp_CustomerDetails").ToList();

        }

    }

}

}

public partial class Sp_CustomerDetails02
{
    public long? ID { get; set; }
    public string Name { get; set; }
    public string CustomerID { get; set; }
    public long? CustID { get; set; }
    public long? Customer_ID { get; set; }
    public decimal? Amount { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public int? CountDay { get; set; }
    public int? EndDateCountDay { get; set; }
    public DateTime? RenewDate { get; set; }
    public bool? IsSMS { get; set; }
    public bool? IsActive { get; set; }
    public string Contact { get; set; }
}

https with WCF error: "Could not find base address that matches scheme https"

It turned out that my problem was that I was using a load balancer to handle the SSL, which then sent it over http to the actual server, which then complained.

Description of a fix is here: http://blog.hackedbrain.com/2006/09/26/how-to-ssl-passthrough-with-wcf-or-transportwithmessagecredential-over-plain-http/

Edit: I fixed my problem, which was slightly different, after talking to microsoft support.

My silverlight app had its endpoint address in code going over https to the load balancer. The load balancer then changed the endpoint address to http and to point to the actual server that it was going to. So on each server's web config I added a listenUri for the endpoint that was http instead of https

<endpoint address="" listenUri="http://[LOAD_BALANCER_ADDRESS]" ... />

Can we overload the main method in Java?

Yes. 'main( )' method can be overloaded. I have tried to put in some piece of code to answer your question.

public class Test{
static public void main( String [] args )
        {
                System.out.println( "In the JVMs static main" );
                main( 5, 6, 7 );    //Calling overloaded static main method
                Test t = new Test( );
                String [] message  = { "Subhash", "Loves", "Programming" };
                t.main(5);
                t.main( 6, message );
        }

        public static void main( int ... args )
        {
                System.out.println( "In the static main called by JVM's main" );
                for( int val : args )
                {
                        System.out.println( val );
                }
        }

        public void main( int x )
        {
                System.out.println( "1: In the overloaded  non-static main with int with value " + x );
        }

        public void main( int x, String [] args )
        {
                System.out.println( "2: In the overloaded  non-static main with int with value " + x );
                for ( String val : args )
                {
                        System.out.println( val );
                }
        }
}

Output:

$ java Test
In the JVMs static main
In the static main called by JVM's main
5
6
7
1: In the overloaded  non-static main with int with value 5
2: In the overloaded  non-static main with int with value 6
Subhash
Loves
Programming
$

In the above code, both static-method as well as a non-static version of main methods are overloaded for demonstration purpose. Note that, by writing JVMs main, I mean to say, it is the main method that JVM uses first to execute a program.

Storing Images in DB - Yea or Nay?

I'd almost never store them in the DB. The best approach is usually to store your images in a path controlled by a central configuration variable and name the images according to the DB table and primary key (if possible). This gives you the following advantages:

  • Move your images to another partition or server just by updating the global config.
  • Find the record matching the image by searching on its primary key.
  • Your images are accessable to processing tools like imagemagick.
  • In web-apps your images can be handled by your webserver directly (saving processing).
  • CMS tools and web languages like Coldfusion can handle uploading natively.

Remove the last character from a string

First, I try without a space, rtrim($arraynama, ","); and get an error result.

Then I add a space and get a good result:

$newarraynama = rtrim($arraynama, ", ");

How to utilize date add function in Google spreadsheet?

In a fresh spreadsheet (US locale) with 12/19/11 in A1 and DT 30 in B1 then:

=A1+right(B1,2)

in say C1 returns 1/18/12.

As a string function RIGHT returns Text but that can be coerced into a number when adding. In adding a number to dates unity is treated as one day. Within (very wide) limits, months and even years are adjusted automatically.

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

Rule 1: You can not add a new table without specifying the primary key constraint[not a good practice if you create it somehow]. So the code:

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id));

Rule 2: You are not allowed to use the keywords(words with predefined meaning) as a field name. Here type is something like that is used(commonly used with Join Types). So the code:

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
transaction_type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id));

Now you please try with this code. First check it in your database user interface(I am running HeidiSQL, or you can try it in your xampp/wamp server also)and make sure this code works. Now delete the table from your db and execute the code in your program. Thank You.

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

Javascript - get array of dates between 2 dates

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function getDates(startDate, stopDate) {
    var dateArray = new Array();
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        dateArray.push(new Date (currentDate));
        currentDate = currentDate.addDays(1);
    }
    return dateArray;
}

Here is a functional demo http://jsfiddle.net/jfhartsock/cM3ZU/

PHP : send mail in localhost

It is possible to send Emails without using any heavy libraries I have included my example here.

lightweight SMTP Email sender for PHP

https://github.com/jerryurenaa/EZMAIL

Tested in both environments production and development.

and most importantly emails will not go to spam unless your IP is blacklisted by the server.

cheers.

How to find Max Date in List<Object>?

LocalDate maxDate = dates.stream()
                            .max( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

LocalDate minDate = dates.stream()
                            .min( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

Why does the 'int' object is not callable error occur when using the sum() function?

In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> sum(l)
6
>>> sum = 0 # oops! shadowed a builtin!
>>> sum(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> import sys
>>> sum = sys.modules['__builtin__'].sum # -- fixing sum
>>> sum(l)
6

This also comes in handy if you happened to assign a value to any other builtin, like dict or list

jQuery - hashchange event

Here is updated version of @johnny.rodgers

Hope helps someone.

// ie9 ve ie7 return true but never fire, lets remove ie less then 10
if(("onhashchange" in window) && navigator.userAgent.toLowerCase().indexOf('msie') == -1){ // event supported?
    window.onhashchange = function(){
        var url = window.location.hash.substring(1);
        alert(url);
    }
}
else{ // event not supported:
    var storedhash = window.location.hash;
    window.setInterval(function(){
        if(window.location.hash != storedhash){
            storedhash = window.location.hash;
            alert(url);
        }
    }, 100);
}

Installing mcrypt extension for PHP on OSX Mountain Lion

sudo apt-get install php5-mcrypt

ln -s /etc/php5/mods-available/mcrypt.ini /etc/php5/fpm/conf.d/mcrypt.ini

service php5-fpm restart

service nginx restart

PKIX path building failed: unable to find valid certification path to requested target

I've run into this a few times and it was due to a certificate chain being incomplete. If you are using the standard java trust store, it may not have a certificate that is needed to complete the certificate chain which is required to validate the certificate of the SSL site you are connecting to.

I ran into this problem with some DigiCert certificates and had to manually add the intermediary cert myself.

String is immutable. What exactly is the meaning?

Java String is immutable, String will Store the value in the form of object. so if u assign the value String a="a"; it will create an object and the value is stored in that and again if you are assigning value a="ty" means it will create an another object store the value in that, if you want to understand clearly, check the has code for the String.

Converting Epoch time into the datetime

You can also use datetime:

>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%c')
  '2012-09-13 02:22:50'

How to give color to each class in scatter plot in R?

Here is how I do it in 2018. Who knows, maybe an R newbie will see it one day and fall in love with ggplot2.

library(ggplot2)

ggplot(data = iris, aes(Petal.Length, Petal.Width, color = Species)) +
  geom_point() +
  scale_color_manual(values = c("setosa" = "red", "versicolor" = "blue", "virginica" = "yellow"))

How to make Unicode charset in cmd.exe by default?

Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like :

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20 :

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like :

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

How to write a Python module/package?

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py

create hello.py then write the following function as its content:

def helloworld():
   print "hello"

Then you can import hello:

>>> import hello
>>> hello.helloworld()
'hello'
>>>

To group many .py files put them in a folder. Any folder with an __init__.py is considered a module by python and you can call them a package

|-HelloModule
  |_ __init__.py
  |_ hellomodule.py

You can go about with the import statement on your module the usual way.

For more information, see 6.4. Packages.

How to open a new HTML page using jQuery?

Use window.open("file2.html");

Syntax

var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);

Return value and parameters

windowObjectReference 

A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements.

strUrl 

The URL to be loaded in the newly opened window. strUrl can be an HTML document on the web, image file or any resource supported by the browser.

strWindowName 

A string name for the new window. The name can be used as the target of links and forms using the target attribute of an <a> or <form> element. The name should not contain any blank space. Note that strWindowName does not specify the title of the new window.

strWindowFeatures 

Optional parameter listing the features (size, position, scrollbars, etc.) of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma.

Responding with a JSON object in Node.js (converting object/array to JSON string)

var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

If you alert(JSON.stringify(objToJson)) you will get {"response":"value"}

No templates in Visual Studio 2017

I found the path and wrote it in the options enter image description here

How to add a string to a string[] array? There's no .Add function

Use List<T> from System.Collections.Generic

List<string> myCollection = new List<string>();

…

myCollection.Add(aString);

Or, shorthand (using collection initialiser):

List<string> myCollection = new List<string> {aString, bString}

If you really want an array at the end, use

myCollection.ToArray();

You might be better off abstracting to an interface, such as IEnumerable, then just returning the collection.

Edit: If you must use an array, you can preallocate it to the right size (i.e. the number of FileInfo you have). Then, in the foreach loop, maintain a counter for the array index you need to update next.

private string[] ColeccionDeCortes(string Path)
{
    DirectoryInfo X = new DirectoryInfo(Path);
    FileInfo[] listaDeArchivos = X.GetFiles();
    string[] Coleccion = new string[listaDeArchivos.Length];
    int i = 0;

    foreach (FileInfo FI in listaDeArchivos)
    {
        Coleccion[i++] = FI.Name;
        //Add the FI.Name to the Coleccion[] array, 
    }

    return Coleccion;
}

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

For those interested, this is code for creating SHA-256 hash using sjcl:

import sjcl from 'sjcl'

const myString = 'Hello'
const myBitArray = sjcl.hash.sha256.hash(myString)
const myHash = sjcl.codec.hex.fromBits(myBitArray)

Checking for an empty file in C++

Perhaps something akin to:

bool is_empty(std::ifstream& pFile)
{
    return pFile.peek() == std::ifstream::traits_type::eof();
}

Short and sweet.


With concerns to your error, the other answers use C-style file access, where you get a FILE* with specific functions.

Contrarily, you and I are working with C++ streams, and as such cannot use those functions. The above code works in a simple manner: peek() will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof(). Ergo, we just peek() at the stream and see if it's eof(), since an empty file has nothing to peek at.

Note, this also returns true if the file never opened in the first place, which should work in your case. If you don't want that:

std::ifstream file("filename");

if (!file)
{
    // file is not open
}

if (is_empty(file))
{
    // file is empty
}

// file is open and not empty

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

To add a bit to accepted answer ...

If you get an UnfinishedStubbingException, be sure to set the method to be stubbed after the when closure, which is different than when you write Mockito.when

Mockito.doNothing().when(mock).method()    //method is declared after 'when' closes

Mockito.when(mock.method()).thenReturn(something)   //method is declared inside 'when'

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I my case \xe2 was a which should be replaced by '.

In general I recommend to convert UTF-8 to ASCII using e.g. https://onlineasciitools.com/convert-utf8-to-ascii

However if you want to keep UTF-8 you can use

#-*- mode: python -*-
# -*- coding: utf-8 -*-

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

For completeness sake, also a solution with Joda-Time version 2.5 and its DateTime class:

new Timestamp(new DateTime(2007, 9, 23, 0, 0, DateTimeZone.forID( "America/Montreal" )).getMillis())

Best practice to validate null and empty collection in Java

If you use the Apache Commons Collections library in your project, you may use the CollectionUtils.isEmpty and MapUtils.isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").

The code behind these methods is more or less what user @icza has written in his answer.

Regardless of what you do, remember that the less code you write, the less code you need to test as the complexity of your code decreases.

What is key=lambda

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())

Actually, above codes can be:

>>> sorted(['Some','words','sort','differently'],key=str.lower)

According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

Transition of background-color

Another way of accomplishing this is using animation which provides more control.

#content #nav a {
    background-color: #FF0;
    
    /* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
    animation-duration: 1s; /* same as transition duration */
    animation-timing-function: linear; /* kind of same as transition timing */
    animation-delay: 0ms; /* same as transition delay */
    animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
    animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
    animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
    animation-play-state: running; /* can be set dynamically to pause mid animation*/
    
    /* declaring the states of the animation to transition through */
    /* optionally add other properties that will change here, or new states (50% etc) */
    @keyframes onHoverAnimation {
    0% {
      background-color: #FF0;  
    }
    100% {
      background-color: #AD310B;
    }
  }
}

#content #nav a:hover {
    /* animation wont run unless the element is given the name of the animation. This is set on hover */
    animation-name: onHoverAnimation;
}

Angular Material: mat-select not selecting default

Binding or setting of default value works only if the value attribute on MatSelect is comparable to value attribute binded to MatOption. If you bind caption of your item to value attribute of mat-option element you must set the default element on mat-select to caption of your item too. If you bind Id of your item to mat-option, you must bind id to mat-select too, not a whole item, caption or any other, only the same field.

But you need to do it with binding []

How can I redirect a php page to another php page?

Send a Location header to redirect. Keep in mind this only works before any other output is sent.

header('Location: index.php'); // redirect to index.php

Why are my CSS3 media queries not working on mobile devices?

For everyone having the same issue, make sure you actually wrote "120px" instead of only "120". This was my mistake and it drove me crazy.

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

PHP: How to check if image file exists?

You can use the file_get_contents function to access remote files. See http://php.net/manual/en/function.file-get-contents.php for details.

Getting checkbox values on submit

Perhaps a better way is using the php function in_array() like this:

$style='V';//can be 'V'ertical or 'H'orizontal
$lineBreak=($style=='V')?'<br>':'';
$name='colors';//the name of your options
$Legent="Select your $name";//dress it up in a nice fieldset with a ledgent
$options=array('red','green','blue','orange','yellow','white','black');
$boxes='';//innitiate the list of tickboxes to be generated
if(isset($_REQUEST["$name"])){ 
//we shall use $_REQUEST but $_POST would be better
   $Checked=$_REQUEST["$name"];
}else{
   $Checked=array();
}
foreach($options as $option){
$checkmark=(in_array($option,$Checked))?'checked':'';
$nameAsArray=$name.'[]';//we would like the returned data to be in an array so we end with []
$boxes.=($style=='V')?"<span class='label2' align='right'><b>$option : </b></span>":"<b>$option </b>";
$boxes.="<input style='width:2em;' type='checkbox' name='$nameAsArray' id='$option' value='$option' $checkmark >$lineBreak";
}

echo<<<EOF
<html>
<head></head>
<body>
<form name="Update" method="GET" action="{$_SERVER['PHP_SELF']}">\n
<fieldset id="tickboxes" style="width:25em;">
<legend>{$Legent}</legend>
{$boxes}
</fieldset>
<button type="submit" >Submit Form</button>
</form>
<body>
</html>
EOF
;

To start with we have created a variable $style to set if we want the options in a horizontal or vertical way. This will infrequence how we display our checkboxes. Next we set the $name for our options, this is needed as a name of the array where we want to keep our options. I have created a loop here to construct each option as given in the array $options, then we check each item if it should be checked in our returned form. I believe this should simplify the way we can reproduce a form with checkboxes.

SQL : BETWEEN vs <= and >=

As mentioned by @marc_s, @Cloud, et al. they're basically the same for a closed range.

But any fractional time values may cause issues with a closed range (greater-or-equal and less-or-equal) as opposed to a half-open range (greater-or-equal and less-than) with an end value after the last possible instant.

So to avoid that the query should be rewritten as:

SELECT EventId, EventName
  FROM EventMaster
 WHERE (EventDate >= '2009-10-15' AND
        EventDate <  '2009-10-19')    /* <<<== 19th, not 18th */

Since BETWEEN doesn't work for half-open intervals I always take a hard look at any date/time query that uses it, since its probably an error.

How should a model be structured in MVC?

Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.

You can have the data access in the model itself, the MVC pattern doesn't restrict you from doing that. You can sugar coat it with services, mappers and what not, but the actual definition of a model is a layer that handles business logic, nothing more, nothing less. It can be a class, a function, or a complete module with a gazillion objects if that's what you want.

It's always easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):

class Database {
   protected $_conn;

   public function __construct($connection) {
       $this->_conn = $connection;
   }

   public function ExecuteObject($sql, $data) {
       // stuff
   }
}

abstract class Model {
   protected $_db;

   public function __construct(Database $db) {
       $this->_db = $db;
   }
}

class User extends Model {
   public function CheckUsername($username) {
       // ...
       $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
       return $this->_db->ExecuteObject($sql, $data);
   }
}

$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');

Also, in PHP, you rarely need to catch/rethrow exceptions because the backtrace is preserved, especially in a case like your example. Just let the exception be thrown and catch it in the controller instead.

How do I open phone settings when a button is clicked?

word of warning: the prefs:root or App-Prefs:root URL schemes are considered private API. Apple may reject you app if you use those, here is what you may get when submitting your app:

Your app uses the "prefs:root=" non-public URL scheme, which is a private entity. The use of non-public APIs is not permitted on the App Store because it can lead to a poor user experience should these APIs change. Continuing to use or conceal non-public APIs in future submissions of this app may result in the termination of your Apple Developer account, as well as removal of all associated apps from the App Store.

Next Steps

To resolve this issue, please revise your app to provide the associated functionality using public APIs or remove the functionality using the "prefs:root" or "App-Prefs:root" URL scheme.

If there are no alternatives for providing the functionality your app requires, you can file an enhancement request.

Difference between Constructor and ngOnInit

constructor() is the default method in the Component life cycle and is used for dependency injection. Constructor is a Typescript Feature.

ngOnInit() is called after the constructor and ngOnInit is called after the first ngOnChanges.

i.e.:

Constructor() --> ngOnChanges() --> ngOnInit()

as mentioned above ngOnChanges() is called when an input or output binding value changes.

Where does the @Transactional annotation belong?

It's better to keep @Transactional in a separate middle layer between DAO and Service Layer. Since, rollback is very important, you can place all your DB manipulation in the middle layer and write business logic in Service Layer. Middle layer will interact with your DAO layers.

This will help you in many situations like ObjectOptimisticLockingFailureException - This exception occurs only after your Transaction is over. So, you cannot catch it in middle layer but you can catch in your service layer now. This would not be possible if you have @Transactional in Service layer. Although you can catch in Controller but Controller should be as clean as possible.

If you are sending mail or sms in seperate thread after completing all the save,delete and update options, you can do this in service after Transaction is completed in your middle layer. Again, if you mention @Transactional in service layer, you mail will go even if your transaction fails.

So having a middle @Transaction layer will help to make your code better and easy to handle. Otherwise, If you use in DAO layer, you may not be able to Rollback all operations. If you use in Service layer, you may have to use AOP(Aspect Oriented Programming) in certain cases.

Refresh a page using PHP

Adding this meta tag in PHP might help:

echo '<META HTTP-EQUIV="Refresh" Content="0; URL=' . $location . '">';

Decoding a Base64 string in Java

Modify the package you're using:

import org.apache.commons.codec.binary.Base64;

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I just used -static-libstdc++ while building. w/ that, I can run the a.out

g++ test.cpp -static-libstdc++

Mythical man month 10 lines per developer day - how close on large projects?

There is no such thing as a silver bullet.

A single metric like that is useless by itself.

For instance, I have my own class library. Currently, the following statistics are true:

Total lines: 252.682
Code lines: 127.323
Comments: 99.538
Empty lines: 25.821

Let's assume I don't write any comments at all, that is, 127.323 lines of code. With your ratio, that code library would take me around 10610 days to write. That's 29 years.

I certainly didn't spend 29 years writing that code, since it's all C#, and C# hasn't been around that long.

Now, you can argue that the code isn't all that good, since obviously I must've surpassed your 12 lines a day metric, and yes, I'll agree to that, but if I'm to bring the timeline down to when 1.0 was released (and I didn't start actually making it until 2.0 was released), which is 2002-02-13, about 2600 days, the average is 48 lines of code a day.

All of those lines of code are good? Heck no. But down to 12 lines of code a day?

Heck no.

Everything depends.

You can have a top notch programmer churning out code in the order of thousands of lines a day, and a medium programmer churning out code in the order of hundreds of lines a day, and the quality is the same.

And yes, there will be bugs.

The total you want is the balance. Amount of code changed, versus the number of bugs found, versus the complexity of the code, versus the hardship of fixing those bugs.

VirtualBox error "Failed to open a session for the virtual machine"

For windows users ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯

I had the same issue, and this trick works for me

  1. Goto control panel
  2. Open Uninstall program
  3. Click on turn windows features on or off
  4. Scroll down and find the hyper-V folder.
  5. Uncheck the Hyper-V.
  6. Apply changes and restart your system.
  7. Now here you go... Open your virtual box and start the os you want.

Hope this helps..

Can't find SDK folder inside Android studio path, and SDK manager not opening

Tools > Android > SDK Manager > there you'll see the path to SDK

How do I set the selected item in a comboBox to match my string using C#?

this works for me.....

comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];

How do I use tools:overrideLibrary in a build.gradle file?

use this code in manifest.xml

<uses-sdk
android:minSdkVersion="16"
android:maxSdkVersion="17"
tools:overrideLibrary="x"/>

What is the difference between a .cpp file and a .h file?

The .cpp file is the compilation unit : it's the real source code file that will be compiled (in C++).

The .h (header) files are files that will be virtually copy/pasted in the .cpp files where the #include precompiler instruction appears. Once the headers code is inserted in the .cpp code, the compilation of the .cpp can start.

Share link on Google+

Yep! Use the link:

https://m.google.com/app/plus/x/?v=compose&content=YOUR_TEXT

It's SHARE url (not used for plus one) button.

If this will not work (not for me) try this url:

https://plusone.google.com/_/+1/confirm?hl=ru&url=_URL_&title=_TITLE_

Or see this solution:

Adding a Google Plus (one or share) link to an email newsletter

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

How to add shortcut keys for java code in eclipse

Type "Sysout" and then Ctrl+Space. It expands to

System.out.println();

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

A key issue here is that this loop iterates over the rows (1st dimension) of B:

In [258]: B
Out[258]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
In [259]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b += 1
     ...:     print(b)
     ...:     
[0 1 2] =>[1 2 3]
[3 4 5] =>[4 5 6]
[6 7 8] =>[7 8 9]
[ 9 10 11] =>[10 11 12]

Thus the += is acting on a mutable object, an array.

This is implied in the other answers, but easily missed if your focus is on the a = a+1 reassignment.

I could also make an in-place change to b with [:] indexing, or even something fancier, b[1:]=0:

In [260]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b[:] = b * 2

[1 2 3] =>[2 4 6]
[4 5 6] =>[ 8 10 12]
[7 8 9] =>[14 16 18]
[10 11 12] =>[20 22 24]

Of course with a 2d array like B we usually don't need to iterate on the rows. Many operations that work on a single of B also work on the whole thing. B += 1, B[1:] = 0, etc.

Get environment variable value in Dockerfile

add -e key for passing environment variables to container. example:

$ MYSQLHOSTIP=$(sudo docker inspect -format="{{ .NetworkSettings.IPAddress }}" $MYSQL_CONRAINER_ID)
$ sudo docker run -e DBIP=$MYSQLHOSTIP -i -t myimage /bin/bash

root@87f235949a13:/# echo $DBIP
172.17.0.2

How to get UTF-8 working in Java webapps?

Faced the same issue on Spring MVC 5 + Tomcat 9 + JSP.
After the long research, came to an elegant solution (no need filters and no need changes in the Tomcat server.xml (starting from 8.0.0-RC3 version))

  1. In the WebMvcConfigurer implementation set default encoding for messageSource (for reading data from messages source files in the UTF-8 encoding.

    @Configuration
    @EnableWebMvc
    @ComponentScan("{package.with.components}")
    public class WebApplicationContextConfig implements WebMvcConfigurer {
    
        @Bean
        public MessageSource messageSource() {
            final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    
            messageSource.setBasenames("messages");
            messageSource.setDefaultEncoding("UTF-8");
    
            return messageSource;
        }
    
        /* other beans and methods */
    
    }
    
  2. In the DispatcherServletInitializer implementation @Override the onStartup method and set request and resource character encoding in it.

    public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        public void onStartup(final ServletContext servletContext) throws ServletException {
    
            // https://wiki.apache.org/tomcat/FAQ/CharacterEncoding
            servletContext.setRequestCharacterEncoding("UTF-8");
            servletContext.setResponseCharacterEncoding("UTF-8");
    
            super.onStartup(servletContext);
        }
    
        /* servlet mappings, root and web application configs, other methods */
    
    }
    
  3. Save all message source and view files in UTF-8 encoding.

  4. Add <%@ page contentType="text/html;charset=UTF-8" %> or <%@ page pageEncoding="UTF-8" %> in each *.jsp file or add jsp-config descriptor to web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     id="WebApp_ID" version="3.0">
        <display-name>AppName</display-name>
    
        <jsp-config>
            <jsp-property-group>
                <url-pattern>*.jsp</url-pattern>
                <page-encoding>UTF-8</page-encoding>
            </jsp-property-group>
        </jsp-config>
    </web-app>
    

How to set a maximum execution time for a mysql query?

pt_kill has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel for a hint of how to come close with cron.

HTML img align="middle" doesn't align an image

How about this? I frequently use the CSS Flexible Box Layout to center something.

_x000D_
_x000D_
<div style="display: flex; justify-content: center;">_x000D_
  <img src="http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png" style="width: 40px; height: 40px;" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Defining private module functions in python

Python allows for private class members with the double underscore prefix. This technique doesn't work at a module level so I am thinking this is a mistake in Dive Into Python.

Here is an example of private class functions:

class foo():
    def bar(self): pass
    def __bar(self): pass

f = foo()
f.bar()   # this call succeeds
f.__bar() # this call fails

Hive: Filtering Data between Specified Dates when Date is a String

No need to extract the month and year.Just need to use the unix_timestamp(date String,format String) function.

For Example:

select yourdate_column
from your_table
where unix_timestamp(yourdate_column, 'yyyy-MM-dd') >= unix_timestamp('2014-06-02', 'yyyy-MM-dd')
and unix_timestamp(yourdate_column, 'yyyy-MM-dd') <= unix_timestamp('2014-07-02','yyyy-MM-dd')
order by yourdate_column limit 10; 

Inner Joining three tables

dbo.tableA AS A INNER JOIN dbo.TableB AS B
ON A.common = B.common INNER JOIN TableC C
ON B.common = C.common

How to prevent the "Confirm Form Resubmission" dialog?

You could try using AJAX calls with jQuery. Like how youtube adds your comment without refreshing. This would remove the problem with refreshing overal.

You'd need to send the info necessary trough the ajax call.
I'll use the youtube comment as example.

$.ajax({
    type: 'POST',
    url: 'ajax/comment-on-video.php',
    data: {
        comment: $('#idOfInputField').val();
     },
    success: function(obj) {
        if(obj === 'true') {
            //Some code that recreates the inserted comment on the page.
        }
    }
});

You can now create the file comment-on-video.php and create something like this:

<?php
    session_start();

    if(isset($_POST['comment'])) {
        $comment = mysqli_real_escape_string($db, $_POST['comment']);
        //Given you are logged in and store the user id in the session.
        $user = $_SESSION['user_id'];

        $query = "INSERT INTO `comments` (`comment_text`, `user_id`) VALUES ($comment, $user);";
        $result = mysqli_query($db, $query);

        if($result) {
            echo true;
            exit();
        }
    }
    echo false;
    exit();
?>

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

C++: Rounding up to the nearest multiple of a number

well for one thing, since i dont really understand what you want to do, the lines

int roundUp = roundDown + multiple;
int roundCalc = roundUp;
return (roundCalc); 

could definitely be shortened to

int roundUp = roundDown + multiple;
return roundUp;

How to get multiple select box values using jQuery?

You can also use js map function:

$("#multipleSelect :selected").map(function(i, el) {
    return $(el).val();
}).get();

And then you can get any property of the option element:

return $(el).text();
return $(el).data("mydata");
return $(el).prop("disabled");
etc...

How to create multiple class objects with a loop in python?

I hope this is what you are looking for.

class Try:
    def do_somthing(self):
        print 'Hello'

if __name__ == '__main__':
    obj_list = []
    for obj in range(10):
        obj = Try()
        obj_list.append(obj)

    obj_list[0].do_somthing()

Output:

Hello

Javascript: Easier way to format numbers?

No, there is no built-in support for number formatting, but googling will turn up loads of code snippets that will do this for you.

EDIT: I missed the last sentence of your post. Try http://code.google.com/p/jquery-utils/wiki/StringFormat for a jQuery solution.

Programmatically navigate to another view controller/scene

I'm not sure try below steps,i think may be error occurs below reasons.

  • you rename some files outside XCode. To solve it remove the files from your project and re-import the files in your project.
  • check and add missing Nib file in Build phases->Copy bundle resources.finally check the nib name spelling, it's correct, case sensitive.
  • check the properties of the .xib/storyboard files in the file inspector ,the property "Target Membership" pitch on the select box,then your xib/storyboard file was linked with your target.
  • such as incorrect type of NIB.Right click on the file and click "Get Info" to verify that the type is what you would expect.

jQuery: Scroll down page a set increment (in pixels) on click?

Pure js solution for newcomers or anyone else.

var scrollAmount = 150;
var element = document.getElementById("elem");

element.addEventListener("click", scrollPage);

function scrollPage() {
    var currentPositionOfPage = window.scrollY;
    window.scrollTo(0, currentPositionOfPage + scrollAmount);
}

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

intellij idea - Error: java: invalid source release 1.9

Alternatively via Project Settings:

  • Project Settings
  • Project
  • Project language Level (set to fit your needs)

Depending on how your build is set up, this may be the way to go.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

For me issue is resolved by changing envs like this:

 env.put("LDAP_BASEDN", base)
 env.put(Context.SECURITY_PRINCIPAL,"user@domain")

How to check programmatically if an application is installed or not in Android?

A simpler implementation using Kotlin

fun PackageManager.isAppInstalled(packageName: String): Boolean =
        getInstalledApplications(PackageManager.GET_META_DATA)
                .firstOrNull { it.packageName == packageName } != null

And call it like this (seeking for Spotify app):

packageManager.isAppInstalled("com.spotify.music")

How to discard all changes made to a branch?

In the source root: git reset ./ HEAD <--un-stage any staged changes git checkout ./ <--discard any unstaged changes

Trim last character from a string

An example Extension class to simplify this: -

internal static class String
{
    public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
    public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
    public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;

    private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}

Usage

"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)

"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something'  (End Characters removed)

"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!'  (Only End instances removed)

C# getting the path of %AppData%

Just wanted to share another way of accessing 'App_Data' folder in my mvc application in case that someone needs this.

 Path.Combine(HttpRuntime.AppDomainAppPath,"App_Data")

How to fix "containing working copy admin area is missing" in SVN?

I had this problem when I was trying to add a directory to svn. I solved it by going into repo browser. Right clicking in the left window, choosing add folder and adding the directory directly in the repo browser.

I then deleted the directory locally (after backup of course) did a clean up and svn update and everything was working again.

List files in local git repo?

Try this command:

git ls-files 

This lists all of the files in the repository, including those that are only staged but not yet committed.

http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

I had this same problem. For me the fix was to remove the custom content type from the jQuery AJAX call. Custom content types trigger the pre-flight request. I found this:

The browser can skip the preflight request if the following conditions are true:

The request method is GET, HEAD, or POST, and

The application does not set any request headers other than Accept, Accept-Language, Content-Language, Content-Type, or Last-Event-ID, and

The Content-Type header (if set) is one of the following:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

From this page: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api (under "Preflight Requests")

App.Config file in console application C#

You can add a reference to System.Configuration in your project and then:

using System.Configuration;

then

string sValue = ConfigurationManager.AppSettings["BatchFile"];

with an app.config file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="BatchFile" value="blah.bat" />
   </appSettings>
</configuration>

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

How to erase the file contents of text file in Python?

You have to overwrite the file. In C++:

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();

String "true" and "false" to boolean

Security Notice

Note that this answer in its bare form is only appropriate for the other use case listed below rather than the one in the question. While mostly fixed, there have been numerous YAML related security vulnerabilities which were caused by loading user input as YAML.


A trick I use for converting strings to bools is YAML.load, e.g.:

YAML.load(var) # -> true/false if it's one of the below

YAML bool accepts quite a lot of truthy/falsy strings:

y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF

Another use case

Assume that you have a piece of config code like this:

config.etc.something = ENV['ETC_SOMETHING']

And in command line:

$ export ETC_SOMETHING=false

Now since ENV vars are strings once inside code, config.etc.something's value would be the string "false" and it would incorrectly evaluate to true. But if you do like this:

config.etc.something = YAML.load(ENV['ETC_SOMETHING'])

it would be all okay. This is compatible with loading configs from .yml files as well.

How to get label of select option with jQuery?

<SELECT id="sel" onmouseover="alert(this.options[1].text);"
<option value=1>my love</option>
<option value=2>for u</option>
</SELECT>

$apply already in progress error

Just use $evalAsync instead of $apply.

Why declare unicode by string in python?

That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello" is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello" everywhere. The header is just a hint of what format to use when reading the .py file.

Reactjs: Unexpected token '<' Error

The issue Unexpected token '<' is because of missing the babel preset.

Solution : You have to configure your webpack configuration as follows

{
  test   : /\.jsx?$/,
  exclude: /(node_modules|bower_components)/,
  loader : 'babel',
  query  : {
    presets:[ 'react', 'es2015' ]
  }
}

here .jsx checks both .js and .jsx formats.

you can simply install the babel dependency using node as follows

npm install babel-preset-react

Thank you

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Based on a comment in another answer, here's my shell function.

# mvp = move + create parents
function mvp () {
    source="$1"
    target="$2"
    target_dir="$(dirname "$target")"
    mkdir --parents $target_dir; mv $source $target
}

Include this in .bashrc or similar so you can use it everywhere.

How to kill/stop a long SQL query immediately?

sp_who2 'active'

Check values under CPUTime and DiskIO. Note the SPID of process having large value comparatively.

kill {SPID value}

Moment.js - How to convert date string into date?

if you have a string of date, then you should try this.

const FORMAT = "YYYY ddd MMM DD HH:mm";

const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300

const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019

or try this :

const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);

Redirect to external URL with return in laravel

Define the url you want to redirect in $url

Then just use

return Redirect::away($url);

If you want to redirect inside your views use

return Redirect::to($url);

Read more about Redirect here

Update 1 :

Here is the simple example

return Redirect::to('http://www.google.com');

Update 2 :

As the Questioner wants to return in the same page

$triggersms = file_get_contents('http://www.cloud.smsindiahub.in/vendorsms/pushsms.aspx?user=efg&password=abcd&msisdn=9197xxx2&sid=MYID&msg=Hello');
return $triggersms;

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

Describe table structure

For SQL Server use exec sp_help

USE db_name;
exec sp_help 'dbo.table_name'

For MySQL, use describe

DESCRIBE table_name;

TypeError: 'builtin_function_or_method' object is not subscriptable

This error arises when you don't use brackets with pop operation. Write the code in this manner.

listb.pop(0)

This is a valid python expression.

Background color on input type=button :hover state sticks in IE

You need to make sure images come first and put in a comma after the background image call. then it actually does work:

    background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */

What's the difference between ASCII and Unicode?

ASCII defines 128 characters, which map to the numbers 0–127. Unicode defines (less than) 221 characters, which, similarly, map to numbers 0–221 (though not all numbers are currently assigned, and some are reserved).

Unicode is a superset of ASCII, and the numbers 0–127 have the same meaning in ASCII as they have in Unicode. For example, the number 65 means "Latin capital 'A'".

Because Unicode characters don't generally fit into one 8-bit byte, there are numerous ways of storing Unicode characters in byte sequences, such as UTF-32 and UTF-8.

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

FTP protocol may be blocked by your ISP firewall, try connecting via SFTP (i.e. use 22 for port num instead of 21 which is simply FTP).

For more information try this link.

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

You need to take the encoding into account, because 1 character could be represented by 1 or more bytes (up to about 6), and different encodings will treat these bytes differently.

Joel has a posting on this:

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to copy a file to a remote server in Python using SCP or SSH?

A very simple approach is the following:

import os
os.system('sshpass -p "password" scp user@host:/path/to/file ./')

No python library are required (only os), and it works, however using this method relies on another ssh client to be installed. This could result in undesired behavior if ran on another system.

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

How to set headers in http get request?

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value")

How do you kill a Thread in Java?

There is of course the case where you are running some kind of not-completely-trusted code. (I personally have this by allowing uploaded scripts to execute in my Java environment. Yes, there are security alarm bell ringing everywhere, but it's part of the application.) In this unfortunate instance you first of all are merely being hopeful by asking script writers to respect some kind of boolean run/don't-run signal. Your only decent fail safe is to call the stop method on the thread if, say, it runs longer than some timeout.

But, this is just "decent", and not absolute, because the code could catch the ThreadDeath error (or whatever exception you explicitly throw), and not rethrow it like a gentlemanly thread is supposed to do. So, the bottom line is AFAIA there is no absolute fail safe.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

Check file uploaded is in csv format

the mime type might not be text/csv some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
  // do something
} else {
  die("Sorry, mime type not allowed");
}

if you wished you could add a further check if mime is returned as text/plain you could run a preg_match to make sure it has enough commas in it to be a csv.

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

C# testing to see if a string is an integer?

I think that I remember looking at a performance comparison between int.TryParse and int.Parse Regex and char.IsNumber and char.IsNumber was fastest. At any rate, whatever the performance, here's one more way to do it.

        bool isNumeric = true;
        foreach (char c in "12345")
        {
            if (!Char.IsNumber(c))
            {
                isNumeric = false;
                break;
            }
        }

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

Find a value in an array of objects in Javascript

You can do it with a simple loop:

var obj = null;    
for (var i = 0; i < array.length; i++) {
    if (array[i].name == "string 1") {
        obj = array[i];
        break;
    }
}

Unable to establish SSL connection, how do I fix my SSL cert?

I had this problem when setting up a new EC2 instance. I had not added HTTPS to my security group, and so port 443 was not open.

JavaScript: remove event listener

element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();


HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
    this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};


HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
    for (var i = 0; i < this.myListeners.length; i++) {
        this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
    };
   delete this.myListeners;
};
};

error, string or binary data would be truncated when trying to insert

You simply can't beat SQL Server on this.

You can insert into a new table like this:

select foo, bar
into tmp_new_table_to_dispose_later
from my_table

and compare the table definition with the real table you want to insert the data into.

Sometime it's helpful sometimes it's not.

If you try inserting in the final/real table from that temporary table it may just work (due to data conversion working differently than SSMS for example).

Another alternative is to insert the data in chunks, instead of inserting everything immediately you insert with top 1000 and you repeat the process, till you find a chunk with an error. At least you have better visibility on what's not fitting into the table.

jQuery selector for inputs with square brackets in the name attribute

If the selector is contained within a variable, the code below may be helpful:

selector_name = $this.attr('name');
//selector_name = users[0][first:name]

escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\\$1');
//escaped_selector_name = users\\[0\\]\\[first\\:name\\]

In this case we prefix all special characters with double backslash.

Is it possible to decompile an Android .apk file?

Decompilation of APK file is possible. But it might be difficult to understand the code if it is obfuscated.

ApkTool to view resources inside APK File

  • Extracts AndroidManifest.xml and everything in res folder(layout xml files, images, htmls used on webview etc..)
  • command : apktool.bat d sampleApp.apk
  • NOTE: You can achieve this by using zip utility like 7-zip. But, It also extracts the .smali file of all .class files.

Using dex2jar

  • Generates .jar file from .apk file, we need JD-GUI to view the source code from this .jar.
  • command : dex2jar sampleApp.apk

Decompiling .jar using JD-GUI

  • decompiles the .class files (obfuscated- in a case of the android app, but a readable original code is obtained in a case of other .jar file). i.e., we get .java back from the application.

Convert integer to hexadecimal and back again

NET FRAMEWORK

Very well explained and few programming lines GOOD JOB

// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

PASCAL >> C#

http://files.hddguru.com/download/Software/Seagate/St_mem.pas

Something from the old school very old procedure of pascal converted to C #

    /// <summary>
    /// Conver number from Decadic to Hexadecimal
    /// </summary>
    /// <param name="w"></param>
    /// <returns></returns>
    public string MakeHex(int w)
    {
        try
        {
           char[] b =  {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
           char[] S = new char[7];

              S[0] = b[(w >> 24) & 15];
              S[1] = b[(w >> 20) & 15];
              S[2] = b[(w >> 16) & 15];
              S[3] = b[(w >> 12) & 15];
              S[4] = b[(w >> 8) & 15];
              S[5] = b[(w >> 4) & 15];
              S[6] = b[w & 15];

              string _MakeHex = new string(S, 0, S.Count());

              return _MakeHex;
        }
        catch (Exception ex)
        {

            throw;
        }
    }

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

Depending on what you want to accomplish, you might replace INSERT with INSERT IGNORE in your file. This will avoid generating an error for the rows that you are trying to insert and already exist.

See http://dev.mysql.com/doc/refman/5.5/en/insert.html.

Google MAP API v3: Center & Zoom on displayed markers

Try this function....it works...

$(function() {
        var myOptions = {
            zoom: 10,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
        var latlng_pos=[];
        var j=0;
         $(".property_item").each(function(){
            latlng_pos[j]=new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val());
            j++;
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val()),
                // position: new google.maps.LatLng(-35.397, 150.640),
                map: map
            });
        }
        );
        // map: an instance of google.maps.Map object
        // latlng: an array of google.maps.LatLng objects
        var latlngbounds = new google.maps.LatLngBounds( );
        for ( var i = 0; i < latlng_pos.length; i++ ) {
            latlngbounds.extend( latlng_pos[ i ] );
        }
        map.fitBounds( latlngbounds );



    });

Can't compare naive and aware datetime.now() <= challenge.datetime_end

You are trying to set the timezone for date_time which already has a timezone. Use replace and astimezone functions.

local_tz = pytz.timezone('Asia/Kolkata')

current_time = datetime.now().replace(tzinfo=pytz.utc).astimezone(local_tz)

Generate pdf from HTML in div using Javascript

This example works great.

<button onclick="genPDF()">Generate PDF</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
    function genPDF() {
        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');
    
        doc.save('Test.pdf');
    }
</script>

Freely convert between List<T> and IEnumerable<T>

Aside: Note that the standard LINQ operators (as per the earlier example) don't change the existing list - list.OrderBy(...).ToList() will create a new list based on the re-ordered sequence. It is pretty easy, however, to create an extension method that allows you to use lambdas with List<T>.Sort:

static void Sort<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}

static void SortDescending<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(y), selector(x)));
}

Then you can use:

list.Sort(x=>x.SomeProp); // etc

This updates the existing list in the same way that List<T>.Sort usually does.

configure: error: C compiler cannot create executables

I furiously read all of this page, hoping to find a solution for:

"configure: error: C compiler cannot create executables"

In the end nothing worked, because my problem was a "typing" one, and was related to CFLAGS. In my .bash_profile file I had:

export ARM_ARCH="arm64”
export CFLAGS="-arch ${ARM_ARCH}"

As you can observe --- export ARM_ARCH="arm64” --- the last quote sign is not the same with the first quote sign. The first one ( " ) is legal while the second one ( ” ) is not.
This happended because I made the mistake to use TextEdit (I'm working under MacOS), and this is apparently a feature called SmartQuotes: the quote sign CHANGES BY ITSELF TO THE ILLEGAL STYLE whenever you edit something just next to it.
Lesson learned: use a proper text editor...

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

Mongoose query where value is not null

Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:

const profiles = await Profile.find({ user: {$exists: true,  $ne: null }})
                            .select("-gallery")
                            .sort( {_id: -1} )
                            .skip( skip )
                            .limit(10)
                            .select(exclude)
                            .populate({
                                path: 'user',
                                match: { role: {$eq: customer}},
                                select: '-password -verified -_id -__v'
                              })

                            .exec();

And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match).
{
    "code": 200,
    "profiles": [
        {
            "description": null,
            "province": "West Midlands",
            "country": "UK",
            "postal_code": "83000",
            "user": null
        },
        {
            "description": null,

            "province": "Madrid",
            "country": "Spain",
            "postal_code": "43000",
            "user": {
                "role": "customer",
                "name": "pedrita",
                "email": "[email protected]",
                "created_at": "2020-06-05T11:05:36.450Z"
            }
        }
    ],
    "page": 1
}

Thanks in advance.

Explanation of "ClassCastException" in Java

A very good example that I can give you for classcastException in Java is while using "Collection"

List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));

for(Object obj:list) {
    String str = (String)obj;
}

This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.

JQuery DatePicker ReadOnly

<sj:datepicker id="datepickerid" name="datepickername" displayFormat="%{formatDateJsp}" readonly="true"/>

Works for me.

How can I get a user's media from Instagram without authenticating as a user?

I really needed this function but for Wordpress. I fit and it worked perfectly

<script>
    jQuery(function($){
        var name = "caririceara.comcariri";
        $.get("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https://www.instagram.com/" + name + "/", function(html) {
            if (html) {
                var regex = /_sharedData = ({.*);<\/script>/m,
                  json = JSON.parse(regex.exec(html)[1]),
                  edges = json.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges;
              $.each(edges, function(n, edge) {
                   if (n <= 7){
                     var node = edge.node;
                    $('.img_ins').append('<a href="https://instagr.am/p/'+node.shortcode+'" target="_blank"><img src="'+node.thumbnail_src+'" width="150"></a>');
                   }
              });
            }
        });
    }); 
    </script>

Scale image to fit a bounding box

html:

    <div class="container">
      <img class="flowerImg" src="flower.jpg">
    </div>

css:

.container{
  width: 100px;
  height: 100px;
}


.flowerImg{
  width: 100px;
  height: 100px;
  object-fit: cover;
  /*object-fit: contain;
  object-fit: scale-down;
  object-position: -10% 0;
  object-fit: none;
  object-fit: fill;*/
}

How to change UINavigationBar background color from the AppDelegate

You can easily do this with Xcode 6.3.1. Select your NavigationBar in the Document outline. Select the Attributes Inspector. Uncheck Translucent. Set Bar Tint to your desired color. Done!

How to select the first, second, or third element with a given class name?

Yes, you can do this. For example, to style the td tags that make up the different columns of a table you could do something like this:

table.myClass tr > td:first-child /* First column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td /* Second column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td+td /* Third column */
{
  /* some style here */
}

sys.stdin.readline() reads without prompt, returning 'nothing in between'

stdin.read(1) reads one character from stdin. If there was more than one character to be read at that point (e.g. the newline that followed the one character that was read in) then that character or characters will still be in the buffer waiting for the next read() or readline().

As an example, given rd.py:

from sys import stdin

x = stdin.read(1)
userinput = stdin.readline()
betAmount = int(userinput)
print ("x=",x)
print ("userinput=",userinput)
print ("betAmount=",betAmount)

... if I run this script as follows (I've typed in the 234):

C:\>python rd.py
234
x= 2
userinput= 34

betAmount= 34

... so the 2 is being picked up first, leaving the 34 and the trailing newline character to be picked up by the readline().

I'd suggest fixing the problem by using readline() rather than read() under most circumstances.

var.replace is not a function

Replace wouldn't replace numbers. It replaces strings only.

This should work.

function trim(str) {
    return str.toString().replace(/^\s+|\s+$/g,'');
}

If you only want to trim the string. You can simply use "str.trim()"

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

A simple alternative to using a custom UserType is to construct a new java.util.Date in the setter for the date property in your persisted bean, eg:

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;

@Entity
public class Purchase {

    private Date date;

    @Column
    public Date getDate() {
        return this.date;
    }

    public void setDate(Date date) {
        // force java.sql.Timestamp to be set as a java.util.Date
        this.date = new Date(date.getTime());
    }

}

How can I make PHP display the error instead of giving me 500 Internal Server Error

Be careful to check if

display_errors

or

error_reporting

is active (not a comment) somewhere else in the ini file.

My development server refused to display errors after upgrade to Kubuntu 16.04 - I had checked php.ini numerous times ... turned out that there was a diplay_errors = off; about 100 lines below my

display_errors = on;

So remember the last one counts!

Maven Jacoco Configuration - Exclude classes/packages from report not working

https://github.com/jacoco/jacoco/issues/34

These are the different notations for classes we have:

  • VM Name: java/util/Map$Entry
  • Java Name: java.util.Map$Entry File
  • Name: java/util/Map$Entry.class

Agent Parameters, Ant tasks and Maven prepare-agent goal

  • includes: Java Name (VM Name also works)
  • excludes: Java Name (VM Name also works)
  • exclclassloader: Java Name

These specifications allow wildcards * and ?, where * wildcards any number of characters, even multiple nested folders.

Maven report goal

  • includes: File Name
  • excludes: File Name

These specs allow Ant Filespec like wildcards *, ** and ?, where * wildcards parts of a single path element only.

How to insert a column in a specific position in oracle without dropping and recreating the table?

Although this is somewhat old I would like to add a slightly improved version that really changes column order. Here are the steps (assuming we have a table TAB1 with columns COL1, COL2, COL3):

  1. Add new column to table TAB1:
alter table TAB1 add (NEW_COL number);
  1. "Copy" table to temp name while changing the column order AND rename the new column:
create table tempTAB1 as select NEW_COL as COL0, COL1, COL2, COL3 from TAB1;
  1. drop existing table:
drop table TAB1;
  1. rename temp tablename to just dropped tablename:
rename tempTAB1 to TAB1;

Is it possible to assign numeric value to an enum in Java?

public enum EXIT_CODE {
    A(104), B(203);

    private int numVal;

    EXIT_CODE(int numVal) {
        this.numVal = numVal;
    }

    public int getNumVal() {
        return numVal;
    }
}

How to break out of while loop in Python?

Don't use while True and break statements. It's bad programming.

Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.

The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.

Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.

jQuery AutoComplete Trigger Change Event

Well it works for me just binding a keypress event to the search input, like this:

... Instantiate your autofill here...

    $("#CompanyList").bind("keypress", function(){
    if (nowDoing==1) {
        nowDoing = 0;
        $('#form_459174').clearForm();
    }        
});

Android ADB device offline, can't issue commands

For me, it turned out that I had two different SDK installations. When I launched the Android SDK Manager and updated the tools from Eclipse, the SDK path pointed to one location, but the PATH environment variable used on the command line pointed to another location, that had an older version of the SDK, which always shows the 4.2.2 device as offline.

Android: How to handle right to left swipe gestures

Kotlin version of @Mirek Rusin is here:

OnSwipeTouchListener.kt :

open class OnSwipeTouchListener(ctx: Context) : OnTouchListener {

    private val gestureDetector: GestureDetector

    companion object {

        private val SWIPE_THRESHOLD = 100
        private val SWIPE_VELOCITY_THRESHOLD = 100
    }

    init {
        gestureDetector = GestureDetector(ctx, GestureListener())
    }

    override fun onTouch(v: View, event: MotionEvent): Boolean {
        return gestureDetector.onTouchEvent(event)
    }

    private inner class GestureListener : SimpleOnGestureListener() {


        override fun onDown(e: MotionEvent): Boolean {
            return true
        }

        override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
            var result = false
            try {
                val diffY = e2.y - e1.y
                val diffX = e2.x - e1.x
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight()
                        } else {
                            onSwipeLeft()
                        }
                        result = true
                    }
                } else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom()
                    } else {
                        onSwipeTop()
                    }
                    result = true
                }
            } catch (exception: Exception) {
                exception.printStackTrace()
            }

            return result
        }


    }

    open fun onSwipeRight() {}

    open fun onSwipeLeft() {}

    open fun onSwipeTop() {}

    open fun onSwipeBottom() {}
}

Usage:

view.setOnTouchListener(object : OnSwipeTouchListener(context) {

    override fun onSwipeTop() {
        super.onSwipeTop()
    }

    override fun onSwipeBottom() {
        super.onSwipeBottom()
    }

    override fun onSwipeLeft() {
        super.onSwipeLeft()
    }

    override fun onSwipeRight() {
        super.onSwipeRight()
    }
})

the open keyword was the point for me...

Functions that return a function

When you return b, it is just a reference to function b, but not being executed at this time.

When you return b(), you're executing the function and returning its value.

Try alerting typeof(s) in your examples. Snippet b will give you 'function'. What will snippet a give you?

How to extract the n-th elements from a list of tuples?

Using islice and chain.from_iterable:

>>> from itertools import chain, islice
>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> list(chain.from_iterable(islice(item, 1, 2) for item in elements))
[1, 3, 5]

This can be useful when you need more than one element:

>>> elements = [(0, 1, 2, 3, 4, 5), 
                (10, 11, 12, 13, 14, 15), 
                (20, 21, 22, 23, 24, 25)]
>>> list(chain.from_iterable(islice(tuple_, 2, 5) for tuple_ in elements))
[2, 3, 4, 12, 13, 14, 22, 23, 24]

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

I have created a JsonUtil which can be used to ignore fields at runtime while giving a response.

Example Usage : First argument should be any POJO class (Student) and ignoreFields is comma seperated fields you want to ignore in response.

 Student st = new Student();
 createJsonIgnoreFields(st,"firstname,age");

import java.util.logging.Logger;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;

public class JsonUtil {

  public static String createJsonIgnoreFields(Object object, String ignoreFields) {
     try {
         ObjectMapper mapper = new ObjectMapper();
         mapper.getSerializationConfig().addMixInAnnotations(Object.class, JsonPropertyFilterMixIn.class);
         String[] ignoreFieldsArray = ignoreFields.split(",");
         FilterProvider filters = new SimpleFilterProvider()
             .addFilter("filter properties by field names",
                 SimpleBeanPropertyFilter.serializeAllExcept(ignoreFieldsArray));
         ObjectWriter writer = mapper.writer().withFilters(filters);
         return writer.writeValueAsString(object);
     } catch (Exception e) {
         //handle exception here
     }
     return "";
   }

   public static String createJson(Object object) {
        try {
         ObjectMapper mapper = new ObjectMapper();
         ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
         return writer.writeValueAsString(object);
        }catch (Exception e) {
         //handle exception here
        }
        return "";
   }
 }    

Sending a notification from a service in Android

If none of these work, try getBaseContext(), instead of context or this.

How to set ObjectId as a data type in mongoose

The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: {
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }
})

Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.

How do I update a formula with Homebrew?

You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.

brew outdated | xargs brew upgrade

Select multiple value in DropDownList using ASP.NET and C#

Dropdown list wont allows multiple item select in dropdown.

If you need , you can use listbox control..

ASP.NET List Box

How to change the value of attribute in appSettings section with Web.config transformation

You want something like:

<appSettings>
  <add key="developmentModeUserId" xdt:Transform="Remove" xdt:Locator="Match(key)"/>
  <add key="developmentMode" value="false" xdt:Transform="SetAttributes"
          xdt:Locator="Match(key)"/>
</appSettings>

See Also: Web.config Transformation Syntax for Web Application Project Deployment

Homebrew refusing to link OpenSSL

Note: this no longer works due to https://github.com/Homebrew/brew/pull/612

I had the same problem today. I uninstalled (unbrewed??) openssl 1.0.2 and installed 1.0.1 also with homebrew. Dotnet new/restore/run then worked fine.

Install openssl 101:
brew install homebrew/versions/openssl101
Linking:
brew link --force homebrew/versions/openssl101

How to install latest version of Node using Brew

If you're willing to remove the brew dependency, I would recommend nvm - I can't really recommend it over any other versioning solution because I haven't needed to try anything else. Having the ability to switch instantly between versions depending on which project you're working on is pretty valuable.

More elegant way of declaring multiple variables at the same time

a, b, c, d, e, g, h, i, j = (True,)*9
f = False

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:

var regexp = /^[a-zA-Z0-9-_]+$/;

How do you dismiss the keyboard when editing a UITextField

Here's what I had to do to get it to work, and I think is necessary for anyone with a Number Pad for a keyboard (or any other ones without a done button:

  1. I changed the UIView in the ViewController to a UIControl.
  2. I created a function called

    -(IBAction)backgroundIsTapped:(id)sender
    

This was also defined in the .h file.

After this, I linked to to the 'touch down' bit for the ViewController in Interface Builder.

In the 'background is tapped' function, I put this:

    [answerField resignFirstResponder];

Just remember to change 'answerField' to the name of the UITextField you want to remove the keyboard from (obviously make sure your UITextField is defined like below:)

    IBOutlet UITextField * <nameoftextfieldhere>;

I know this topic probably died a long time ago... but I'm hoping this will help someone, somewhere!

Printing 1 to 1000 without loop or conditionals

Compile time recursion! :P

#include <iostream>
template<int N>
struct NumberGeneration{
  static void out(std::ostream& os)
  {
    NumberGeneration<N-1>::out(os);
    os << N << std::endl;
  }
};
template<>
struct NumberGeneration<1>{
  static void out(std::ostream& os)
  {
    os << 1 << std::endl;
  }
};
int main(){
   NumberGeneration<1000>::out(std::cout);
}

How to remove ASP.Net MVC Default HTTP Headers?

You can also remove them by adding code to your global.asax file:

 protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
 {
   HttpContext.Current.Response.Headers.Remove("X-Powered-By");
   HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
   HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
   HttpContext.Current.Response.Headers.Remove("Server");
 }

Why Maven uses JDK 1.6 but my java -version is 1.7

add the following to your ~/.mavenrc:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/{jdk-version}/Contents/Home

Second Solution:

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile

Is there shorthand for returning a default value if None in Python?

You've got the ternary syntax x if x else '' - is that what you're after?

Return value of x = os.system(..)

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

Refer my answer for more detail in What is the return value of os.system() in Python?

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

How to get exception message in Python properly

I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:

try:
    pass
    log.info('Success')
except:
    log.exception('Failed')

Efficiently updating database using SQLAlchemy ORM

Withough testing, I'd try:

for c in session.query(Stuff).all():
     c.foo = c.foo+1
session.commit()

(IIRC, commit() works without flush()).

I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.

[Please note comment below - this did not speed things up at all].

How to read a specific line using the specific line number from a file in Java?

You can also take a look at LineNumberReader, subclass of BufferedReader. Along with the readline method, it also has setter/getter methods to access line number. Very useful to keep track of the number of lines read, while reading data from file.

Select from where field not equal to Mysql Php

The key is the sql query, which you will set up as a string:

$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";

Note that there are a lot of ways to specify NOT. Another one that works just as well is:

$sqlquery = "SELECT field1, field2 FROM table WHERE columnA != 'x' AND columbB != 'y'";

Here is a full example of how to use it:

$link = mysql_connect($dbHost,$dbUser,$dbPass) or die("Unable to connect to database");
mysql_select_db("$dbName") or die("Unable to select database $dbName");
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
$result=mysql_query($sqlquery);

while ($row = mysql_fetch_assoc($result) {
//do stuff
}

You can do whatever you would like within the above while loop. Access each field of the table as an element of the $row array which means that $row['field1'] will give you the value for field1 on the current row, and $row['field2'] will give you the value for field2.

Note that if the column(s) could have NULL values, those will not be found using either of the above syntaxes. You will need to add clauses to include NULL values:

$sqlquery = "SELECT field1, field2 FROM table WHERE (NOT columnA = 'x' OR columnA IS NULL) AND (NOT columbB = 'y' OR columnB IS NULL)";

Check/Uncheck a checkbox on datagridview

This is how I did it.

private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
{

    if(Convert.ToBoolean(this.Grid.Rows[e.RowIndex].Cells["Selected"].Value) == false)
    {
        this.Grid.Rows[e.RowIndex].Cells["Selected"].Value = true;
    }
    else
    {
        this.productSpecGrid.Rows[e.RowIndex].Cells["Selected"].Value = false;
    }
}

What difference is there between WebClient and HTTPWebRequest classes in .NET?

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

How can I retrieve Id of inserted entity using Entity framework?

I had been using Ladislav Mrnka's answer to successfully retrieve Ids when using the Entity Framework however I am posting here because I had been miss-using it (i.e. using it where it wasn't required) and thought I would post my findings here in-case people are looking to "solve" the problem I had.

Consider an Order object that has foreign key relationship with Customer. When I added a new customer and a new order at the same time I was doing something like this;

var customer = new Customer(); //no Id yet;
var order = new Order(); //requires Customer.Id to link it to customer;
context.Customers.Add(customer);
context.SaveChanges();//this generates the Id for customer
order.CustomerId = customer.Id;//finally I can set the Id

However in my case this was not required because I had a foreign key relationship between customer.Id and order.CustomerId

All I had to do was this;

var customer = new Customer(); //no Id yet;
var order = new Order{Customer = customer}; 
context.Orders.Add(order);
context.SaveChanges();//adds customer.Id to customer and the correct CustomerId to order

Now when I save the changes the id that is generated for customer is also added to order. I've no need for the additional steps

I'm aware this doesn't answer the original question but thought it might help developers who are new to EF from over-using the top-voted answer for something that may not be required.

This also means that updates complete in a single transaction, potentially avoiding orphin data (either all updates complete, or none do).

Request is not available in this context

This worked for me - if you have to log in Application_Start, do it before you modify the context. You will get a log entry, just with no source, like:

2019-03-12 09:35:43,659 INFO (null) - Application Started

I generally log both the Application_Start and Session_Start, so I see more detail in the next message

2019-03-12 09:35:45,064 INFO ~/Leads/Leads.aspx - Session Started (Local)

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("Application Started");
            GlobalContext.Properties["page"] = new GetCurrentPage();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Globals._Environment = WebAppConfig.getEnvironment(Request.Url.AbsoluteUri, Properties.Settings.Default.LocalOverride);
            log.Info(string.Format("Session Started ({0})", Globals._Environment));
        }


No Persistence provider for EntityManager named

Hibernate 5.2.5
Jar Files Required in the class path. This is within a required folder of Hibernate 5.2.5 Final release. It can be downloaded from http://hibernate.org/orm/downloads/

  1. antlr-2.7.7
  2. cdi-api-1.1
  3. classmate-1.3.0
  4. dom4j-1.6.1
  5. el-api-2.2
  6. geronimo-jta_1.1_spec-1.1.1
  7. hibernate-commons-annotation-5.0.1.Final
  8. hibernate-core-5.2.5.Final
  9. hibernate-jpa-2.1-api-1.0.0.Final
  10. jandex-2.0.3.Final
  11. javassist-3.20.0-GA
  12. javax.inject-1
  13. jboss-interceptor-api_1.1_spec-1.0.0.Beta1
  14. jboss-logging-3.3.0.Final
  15. jsr250-api-1.0

Create an xml file "persistence.xml" in

YourProject/src/META-INF/persistence.xml

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
         http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
         version="2.1">

<persistence-unit name="sample">

    <class>org.pramod.data.object.UserDetail</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
        <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/hibernate_project"/>
        <property name="hibernate.connection.username" value="root"/>
        <property name="hibernate.connection.password" value="root"/>
        <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.format_sql" value="false"/>

        <property name="hibernate.cache.use_second_level_cache" value="false"/>

        <property name="hibernate.archive.autodetection" value="true"/>
    </properties>
</persistence-unit>

  1. please note down the information mentioned in the < persistance > tag and version should be 2.1.
  2. please note the name < persistance-unit > tag, name is mentioned as "sample". This name needs to be used exactly same while loading your

EntityManagerFactor = Persistance.createEntityManagerFactory("sample");. "sample" can be changed as per your naming convention.

Now create a Entity class. with name as per my example UserDetail, in the package org.pramod.data.object

UserDetail.java

package org.pramod.data.object;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user_detail")
public class UserDetail {
    @Id
    @Column(name="user_id")
    private int id;
    @Column(name="user_name")
    private String userName;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }   
    @Override
    public String toString() {
       return "UserDetail [id=" + id + ", userName=" + userName + "]";
    }
}

Now create a class with main method.

HibernateTest.java

package org.pramod.hibernate;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.pramod.data.object.UserDetail;

public class HibernateTest {
    private static EntityManagerFactory entityManagerFactory;

    public static void main(String[] args)  {
        UserDetail user = new UserDetail();
        user.setId(1);
        user.setUserName("Pramod Sharma");

        try {
            entityManagerFactory = Persistence.createEntityManagerFactory("sample");
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            entityManager.getTransaction().begin();
            entityManager.persist( user );
            entityManager.getTransaction().commit();
            System.out.println("successfull");
            entityManager.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Output will be

UserDetail [id=1, userName=Pramod Sharma]
Hibernate: drop table if exists user_details
Hibernate: create table user_details (user_id integer not null, user_name varchar(255), primary key (user_id))
Hibernate: insert into user_details (user_name, user_id) values (?, ?)
successfull

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.