Programs & Examples On #Custom routes

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

"Multiple definition", "first defined here" errors

The problem here is that you are including commands.c in commands.h before the function prototype. Therefore, the C pre-processor inserts the content of commands.c into commands.h before the function prototype. commands.c contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.

The content of commands.h after the pre-processor phase looks like this:

#ifndef COMMANDS_H_
#define COMMANDS_H_

// function definition
void f123(){

}

// function declaration
void f123();

#endif /* COMMANDS_H_ */

This is an error because you can't declare a function after its definition in C. If you swapped #include "commands.c" and the function declaration the error shouldn't happen because, now, the function prototype comes before the function declaration.

However, including a .c file is a bad practice and should be avoided. A better solution for this problem would be to include commands.h in commands.c and link the compiled version of command to the main file. For example:

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123(); // function declaration

#endif

commands.c

#include "commands.h"

void f123(){} // function definition

Enable PHP Apache2

You have two ways to enable it.

First, you can set the absolute path of the php module file in your httpd.conf file like this:

LoadModule php5_module /path/to/mods-available/libphp5.so

Second, you can link the module file to the mods-enabled directory:

ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so

Why should I use core.autocrlf=true in Git?

For me.

Edit .gitattributes file.

add

*.dll binary

Then everything goes well.

How do you access the value of an SQL count () query in a Java program

I have done it this way (example):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"[email protected]"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

Change jsp on button click

You could make those submit buttons and inside the servlet your are submitting the form to you could test the name of the button which was pressed and render the corresponding jsp page.

<input type="submit" value="Creazione Nuovo Corso" name="CreateCourse" />
<input type="submit" value="Gestione Autorizzazioni" name="AuthorizationManager" />

Inside the TrainerMenu servlet if request.getParameter("CreateCourse") is not empty then the first button was clicked and you could render the corresponding jsp.

XAMPP: Couldn't start Apache (Windows 10)

This advice was great. I had the same problem, but my solution was different, because I was so stupid, that I have renamed directory where XAMPP was located and since I had installed a lot of another programs I couldn't rename it back.

In my case there was original directory C:\Programs\Xampp and renamed it to C:\PROGRAMS_\Xampp and that was the mistake.

The solution was to find all references on C:\Programs and rename them C:\PROGRAMS_ in the XAMPP directory, because for some reason during the installation it writes absolute paths, not relative. Of course, there are some references in the registry too.

Logging best practices

I don't often develop in asp.net, however when it comes to loggers I think a lot of best practices are universal. Here are some of my random thoughts on logging that I have learned over the years:

Frameworks

  • Use a logger abstraction framework - like slf4j (or roll your own), so that you decouple the logger implementation from your API. I have seen a number of logger frameworks come and go and you are better off being able to adopt a new one without much hassle.
  • Try to find a framework that supports a variety of output formats.
  • Try to find a framework that supports plugins / custom filters.
  • Use a framework that can be configured by external files, so that your customers / consumers can tweak the log output easily so that it can be read by commerical log management applications with ease.
  • Be sure not to go overboard on custom logging levels, otherwise you may not be able to move to different logging frameworks.

Logger Output

  • Try to avoid XML/RSS style logs for logging that could encounter catastrophic failures. This is important because if the power switch is shut off without your logger writing the closing </xxx> tag, your log is broken.
  • Log threads. Otherwise, it can be very difficult to track the flow of your program.
  • If you have to internationalize your logs, you may want to have a developer only log in English (or your language of choice).
  • Sometimes having the option to insert logging statements into SQL queries can be a lifesaver in debugging situations. Such as:
    -- Invoking Class: com.foocorp.foopackage.FooClass:9021
    SELECT * FROM foo;
  • You want class-level logging. You normally don't want static instances of loggers as well - it is not worth the micro-optimization.
  • Marking and categorizing logged exceptions is sometimes useful because not all exceptions are created equal. So knowing a subset of important exceptions a head of time is helpful, if you have a log monitor that needs to send notifications upon critical states.
  • Duplication filters will save your eyesight and hard disk. Do you really want to see the same logging statement repeated 10^10000000 times? Wouldn't it be better just to get a message like: This is my logging statement - Repeated 100 times

Also see this question of mine.

How to expire a cookie in 30 minutes using jQuery?

I had issues getting the above code to work within cookie.js. The following code managed to create the correct timestamp for the cookie expiration in my instance.

var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);

This was from the FAQs for Cookie.js

How to get numbers after decimal point?

Sometimes trailing zeros matter

In [4]: def split_float(x):
   ...:     '''split float into parts before and after the decimal'''
   ...:     before, after = str(x).split('.')
   ...:     return int(before), (int(after)*10 if len(after)==1 else int(after))
   ...: 
   ...: 

In [5]: split_float(105.10)
Out[5]: (105, 10)

In [6]: split_float(105.01)
Out[6]: (105, 1)

In [7]: split_float(105.12)
Out[7]: (105, 12)

How to toggle a boolean?

bool = !bool;

This holds true in most languages.

RegEx for valid international mobile phone number

Posting a note here for users looking into this into the future. Google's libphonenumber is what you most likely would want to use. There is wrappers for PHP, node.js, Java, etc. to use the data which Google has been collecting and reduces the requirements for maintaining large arrays of regex patterns to apply.

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

For me it was :

C:\Users\{your-user-name}\AppData\Local\Android\Sdk\tools\bin

Hope it helps!

Uploading/Displaying Images in MVC 4

        <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }

Enum "Inheritance"

I also wanted to overload Enums and created a mix of the answer of 'Seven' on this page and the answer of 'Merlyn Morgan-Graham' on a duplicate post of this, plus a couple of improvements.
Main advantages of my solution over the others:

  • automatic increment of the underlying int value
  • automatic naming

This is an out-of-the-box solution and may be directly inserted into your project. It is designed to my needs, so if you don't like some parts of it, just replace them with your own code.

First, there is the base class CEnum that all custom enums should inherit from. It has the basic functionality, similar to the .net Enum type:

public class CEnum
{
  protected static readonly int msc_iUpdateNames  = int.MinValue;
  protected static int          ms_iAutoValue     = -1;
  protected static List<int>    ms_listiValue     = new List<int>();

  public int Value
  {
    get;
    protected set;
  }

  public string Name
  {
    get;
    protected set;
  }

  protected CEnum ()
  {
    CommonConstructor (-1);
  }

  protected CEnum (int i_iValue)
  {
    CommonConstructor (i_iValue);
  }

  public static string[] GetNames (IList<CEnum> i_listoValue)
  {
    if (i_listoValue == null)
      return null;
    string[] asName = new string[i_listoValue.Count];
    for (int ixCnt = 0; ixCnt < asName.Length; ixCnt++)
      asName[ixCnt] = i_listoValue[ixCnt]?.Name;
    return asName;
  }

  public static CEnum[] GetValues ()
  {
    return new CEnum[0];
  }

  protected virtual void CommonConstructor (int i_iValue)
  {
    if (i_iValue == msc_iUpdateNames)
    {
      UpdateNames (this.GetType ());
      return;
    }
    else if (i_iValue > ms_iAutoValue)
      ms_iAutoValue = i_iValue;
    else
      i_iValue = ++ms_iAutoValue;

    if (ms_listiValue.Contains (i_iValue))
      throw new ArgumentException ("duplicate value " + i_iValue.ToString ());
    Value = i_iValue;
    ms_listiValue.Add (i_iValue);
  }

  private static void UpdateNames (Type i_oType)
  {
    if (i_oType == null)
      return;
    FieldInfo[] aoFieldInfo = i_oType.GetFields (BindingFlags.Public | BindingFlags.Static);

    foreach (FieldInfo oFieldInfo in aoFieldInfo)
    {
      CEnum oEnumResult = oFieldInfo.GetValue (null) as CEnum;
      if (oEnumResult == null)
        continue;
      oEnumResult.Name = oFieldInfo.Name;
    }
  }
}

Secondly, here are 2 derived Enum classes. All derived classes need some basic methods in order to work as expected. It's always the same boilerplate code; I haven't found a way yet to outsource it to the base class. The code of the first level of inheritance differs slightly from all subsequent levels.

public class CEnumResult : CEnum
{
  private   static List<CEnumResult>  ms_listoValue = new List<CEnumResult>();

  public    static readonly CEnumResult Nothing         = new CEnumResult (  0);
  public    static readonly CEnumResult SUCCESS         = new CEnumResult (  1);
  public    static readonly CEnumResult UserAbort       = new CEnumResult ( 11);
  public    static readonly CEnumResult InProgress      = new CEnumResult (101);
  public    static readonly CEnumResult Pausing         = new CEnumResult (201);
  private   static readonly CEnumResult Dummy           = new CEnumResult (msc_iUpdateNames);

  protected CEnumResult () : base ()
  {
  }

  protected CEnumResult (int i_iValue) : base (i_iValue)
  {
  }

  protected override void CommonConstructor (int i_iValue)
  {
    base.CommonConstructor (i_iValue);

    if (i_iValue == msc_iUpdateNames)
      return;
    if (this.GetType () == System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType)
      ms_listoValue.Add (this);
  }

  public static new CEnumResult[] GetValues ()
  {
    List<CEnumResult> listoValue = new List<CEnumResult> ();
    listoValue.AddRange (ms_listoValue);
    return listoValue.ToArray ();
  }
}

public class CEnumResultClassCommon : CEnumResult
{
  private   static List<CEnumResultClassCommon> ms_listoValue = new List<CEnumResultClassCommon>();

  public    static readonly CEnumResult Error_InternalProgramming           = new CEnumResultClassCommon (1000);

  public    static readonly CEnumResult Error_Initialization                = new CEnumResultClassCommon ();
  public    static readonly CEnumResult Error_ObjectNotInitialized          = new CEnumResultClassCommon ();
  public    static readonly CEnumResult Error_DLLMissing                    = new CEnumResultClassCommon ();
  // ... many more
  private   static readonly CEnumResult Dummy                               = new CEnumResultClassCommon (msc_iUpdateNames);

  protected CEnumResultClassCommon () : base ()
  {
  }

  protected CEnumResultClassCommon (int i_iValue) : base (i_iValue)
  {
  }

  protected override void CommonConstructor (int i_iValue)
  {
    base.CommonConstructor (i_iValue);

    if (i_iValue == msc_iUpdateNames)
      return;
    if (this.GetType () == System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType)
      ms_listoValue.Add (this);
  }

  public static new CEnumResult[] GetValues ()
  {
    List<CEnumResult> listoValue = new List<CEnumResult> (CEnumResult.GetValues ());
    listoValue.AddRange (ms_listoValue);
    return listoValue.ToArray ();
  }
}

The classes have been successfully tested with follwing code:

private static void Main (string[] args)
{
  CEnumResult oEnumResult = CEnumResultClassCommon.Error_Initialization;
  string sName = oEnumResult.Name;   // sName = "Error_Initialization"

  CEnum[] aoEnumResult = CEnumResultClassCommon.GetValues ();   // aoEnumResult = {testCEnumResult.Program.CEnumResult[9]}
  string[] asEnumNames = CEnum.GetNames (aoEnumResult);
  int ixValue = Array.IndexOf (aoEnumResult, oEnumResult);    // ixValue = 6
}

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

Merge two dataframes by index

Use merge, which is inner join by default:

pd.merge(df1, df2, left_index=True, right_index=True)

Or join, which is left join by default:

df1.join(df2)

Or concat, which is outer join by default:

pd.concat([df1, df2], axis=1)

Samples:

df1 = pd.DataFrame({'a':range(6),
                    'b':[5,3,6,9,2,4]}, index=list('abcdef'))

print (df1)
   a  b
a  0  5
b  1  3
c  2  6
d  3  9
e  4  2
f  5  4

df2 = pd.DataFrame({'c':range(4),
                    'd':[10,20,30, 40]}, index=list('abhi'))

print (df2)
   c   d
a  0  10
b  1  20
h  2  30
i  3  40

#default inner join
df3 = pd.merge(df1, df2, left_index=True, right_index=True)
print (df3)
   a  b  c   d
a  0  5  0  10
b  1  3  1  20

#default left join
df4 = df1.join(df2)
print (df4)
   a  b    c     d
a  0  5  0.0  10.0
b  1  3  1.0  20.0
c  2  6  NaN   NaN
d  3  9  NaN   NaN
e  4  2  NaN   NaN
f  5  4  NaN   NaN

#default outer join
df5 = pd.concat([df1, df2], axis=1)
print (df5)
     a    b    c     d
a  0.0  5.0  0.0  10.0
b  1.0  3.0  1.0  20.0
c  2.0  6.0  NaN   NaN
d  3.0  9.0  NaN   NaN
e  4.0  2.0  NaN   NaN
f  5.0  4.0  NaN   NaN
h  NaN  NaN  2.0  30.0
i  NaN  NaN  3.0  40.0

How to add SHA-1 to android application

SHA-1 generation in android studio:

change firebase project setting

Press add fingerprint button


  1. Select Gradle in android studio from right panel

  2. Select Your App

  3. In Tasks -> android-> signingReport

Double click signingReport.

How to get sha1 fingerprint


You will find the SHA-1 fingerprint in the "Gradle Console"

Add this SHA-1 fingerprint in firebase console

Add SHA1 fingerprint

how to open a jar file in Eclipse

there is an Eclipse app called Import Jar As Project. I think it is quite simple and useful. https://marketplace.eclipse.org/content/import-jar-project?mpc=true&mpc_state=

Connecting to Oracle Database through C#?

The next approach work to me with Visual Studio 2013 Update 4 1- From Solution Explorer right click on References then select add references 2- Assemblies > Framework > System.Data.OracleClient > OK and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE

OracleConnection oraConnection = new OracleConnection(@"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}

and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method

public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;

if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}

How to remove .html from URL?

To remove the .html extension from your URLs, you can use the following code in root/htaccess :

#mode_rerwrite start here

RewriteEngine On

# does not apply to existing directores, meaning that if the folder exists on server then don't change anything and don't run the rule.

RewriteCond %{REQUEST_FILENAME} !-d

#Check for file in directory with .html extension 

RewriteCond %{REQUEST_FILENAME}\.html !-f

#Here we actually show the page that has .html extension

RewriteRule ^(.*)$ $1.html [NC,L]

Thanks

What is the difference between Amazon SNS and Amazon SQS?

From the AWS documentation:

Amazon SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminating the need to periodically check or “poll” for updates.

Amazon SQS is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components—without requiring each component to be concurrently available.

Fanout to Amazon SQS queues

The 'Access-Control-Allow-Origin' header contains multiple values

if you are in IIS you need to activate CORS in web.config, then you don't need to enable in App_Start/WebApiConfig.cs Register method

My solution was, commented the lines here:

// Enable CORS
//EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
//config.EnableCors(cors);

and write in the web.config:

<system.webServer>
  <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

How to change the background color on a Java panel?

You could call:


getContentPane().setBackground(Color.black);

Or add a JPanel to the JFrame your using. Then add your components to the JPanel. This will allow you to call


setBackground(Color.black);

on the JPanel to set the background color.

Redirecting a request using servlets and the "setHeader" method not working

As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302

How to call any method asynchronously in c#

If you use action.BeginInvoke(), you have to call EndInvoke somewhere - else the framework has to hold the result of the async call on the heap, resulting in a memory leak.

If you don't want to jump to C# 5 with the async/await keywords, you can just use the Task Parallels library in .Net 4. It's much, much nicer than using BeginInvoke/EndInvoke, and gives a clean way to fire-and-forget for async jobs:

using System.Threading.Tasks;
...
void Foo(){}
...
new Task(Foo).Start();

If you have methods to call that take parameters, you can use a lambda to simplify the call without having to create delegates:

void Foo2(int x, string y)
{
    return;
}
...
new Task(() => { Foo2(42, "life, the universe, and everything");}).Start();

I'm pretty sure (but admittedly not positive) that the C# 5 async/await syntax is just syntactic sugar around the Task library.

In Objective-C, how do I test the object type?

You would probably use

- (BOOL)isKindOfClass:(Class)aClass

This is a method of NSObject.

For more info check the NSObject documentation.

This is how you use this.

BOOL test = [self isKindOfClass:[SomeClass class]];

You might also try doing somthing like this

for(id element in myArray)
{
    NSLog(@"=======================================");
    NSLog(@"Is of type: %@", [element className]);
    NSLog(@"Is of type NSString?: %@", ([[element className] isMemberOfClass:[NSString class]])? @"Yes" : @"No");
    NSLog(@"Is a kind of NSString: %@", ([[element classForCoder] isSubclassOfClass:[NSString class]])? @"Yes" : @"No");    
}

How to get anchor text/href on click using jQuery?

Note: Apply the class info_link to any link you want to get the info from.

<a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
    ~/Resumes/Resumes1271354404687.docx
</a>

For href:

$(function(){
  $('.info_link').click(function(){
    alert($(this).attr('href'));
    // or alert($(this).hash();
  });
});

For Text:

$(function(){
  $('.info_link').click(function(){
    alert($(this).text());
  });
});

.

Update Based On Question Edit

You can get them like this now:

For href:

$(function(){
  $('div.res a').click(function(){
    alert($(this).attr('href'));
    // or alert($(this).hash();
  });
});

For Text:

$(function(){
  $('div.res a').click(function(){
    alert($(this).text());
  });
});

Confirm postback OnClientClick button ASP.NET

Try this:

<asp:Button runat="server" ID="btnDelete" Text="Delete"
   onClientClick="javascript:return confirm('Are you sure you want to delete this user?');" OnClick="BtnDelete_Click" />

Java ArrayList of Doubles

Try this:

List<Double> list = Arrays.asList(1.38, 2.56, 4.3);

which returns a fixed size list.

If you need an expandable list, pass this result to the ArrayList constructor:

List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));

How to get a value from the last inserted row?

With PostgreSQL you can do it via the RETURNING keyword:

PostgresSQL - RETURNING

INSERT INTO mytable( field_1, field_2,... )
VALUES ( value_1, value_2 ) RETURNING anyfield

It will return the value of "anyfield". "anyfield" may be a sequence or not.

To use it with JDBC, do:

ResultSet rs = statement.executeQuery("INSERT ... RETURNING ID");
rs.next();
rs.getInt(1);

DataTable: Hide the Show Entries dropdown but keep the Search box

This is key answer to this post "bLengthChange": false, will hide the Entries Dropdown

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

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

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

Laravel Eloquent limit and offset

Please try like this,

return Article::where('id',$article)->with(['products'=>function($products, $offset, $limit) {
    return $products->offset($offset*$limit)->limit($limit);
}])

How to start jenkins on different port rather than 8080 using command prompt in Windows?

For the benefit of Linux users who find themselves here: I found /etc/sysconfig/jenkins has a JENKINS_PORT="8080", which you should probably change too.

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

Changing text of UIButton programmatically swift

swift 4.2 and above

using button's IBOutlet

btnOutlet.setTitle("New Title", for: .normal)

using button's IBAction

@IBAction func btnAction(_ sender: UIButton) {
  sender.setTitle("New Title", for: .normal)
}

Git: How to return from 'detached HEAD' state

Use git reflog to find the hashes of previously checked out commits.

A shortcut command to get to your last checked out branch (not sure if this work correctly with detached HEAD and intermediate commits though) is git checkout -

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Converting Stream to String and back...what are we missing?

I have just tested this and works fine.

string test = "Testing 1-2-3";

// convert string to stream
byte[] byteArray = Encoding.ASCII.GetBytes(test);
MemoryStream stream = new MemoryStream(byteArray);

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

If stream has already been written to, you might want to seek to the beginning before first before reading out the text: stream.Seek(0, SeekOrigin.Begin);

How to make a vertical line in HTML

You can draw a vertical line by simply using height / width with any html element.

_x000D_
_x000D_
#verticle-line {_x000D_
  width: 1px;_x000D_
  min-height: 400px;_x000D_
  background: red;_x000D_
}
_x000D_
<div id="verticle-line"></div>
_x000D_
_x000D_
_x000D_

difference between System.out.println() and System.err.println()

It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:

public class PrintQueue {
    public static void main(String[] args) {
        for(int i = 0; i < 100; i++) {
            System.out.println("out");
            System.err.println("err");
        }
    }
}

If you compile and run the program, you will see that the order of outputs in console is mixed up.

An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.

Even in this code snippet you can see that the order is mixed up sometimes:

public class PrintQueue {
    public static void main(String[] args) {
        System.out.println("out");
        System.err.println("err");
    }
}

How to check if $? is not equal to zero in unix shell scripting?

Put it in a variable first and then try to test it, as shown below

ret=$?
if [ $ret -ne 0 ]; then
        echo "In If"
else
        echo "In Else"
fi

This should help.


Edit: If the above is not working as expected then, there is a possibility that you are not using $? at right place. It must be the very next line after the command of which you need to catch the return status. Even if there is any other single command in between the target and you catching it's return status, you'll be retrieving the returns_status of this intermediate command and not the one you are expecting.

click() event is calling twice in jquery

please try this

$('#ddlSupervisor').live('change', function (e) {
    if (e.handled !== true) { //this makes event to fire only once
    getEmployeesbySupervisor();
    e.handled = true;
   }
});

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

As I can't add a comment, just thought I'd post this for completion. tufy's answer is correct, it's to do with parenthesis (brackets) in the path to the application being run.

There is an existing networking bug where the networking layer is unable to parse program locations that contain parenthesis in the path to the executable which is attempting to connect to Oracle.

Filed with Oracle, Bug 3807408 refers.

Source

Rails create or update magic?

Add this to your model:

def self.update_or_create_by(args, attributes)
  obj = self.find_or_create_by(args)
  obj.update(attributes)
  return obj
end

With that, you can:

User.update_or_create_by({name: 'Joe'}, attributes)

How to size an Android view based on its parent's dimensions

You could solve this by creating a custom View and override the onMeasure() method. If you always use "fill_parent" for the layout_width in your xml then the widthMeasureSpec parameter that is passed into the onMeasusre() method should contain the width of the parent.

public class MyCustomView extends TextView {

    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
        this.setMeasuredDimension(parentWidth / 2, parentHeight);
    }
}   

Your XML would look something like this:

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <view
        class="com.company.MyCustomView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

CSS Inset Borders

I know this is three years old, but thought it might be helpful to someone.

The concept is to use the :after (or :before) selector to position a border within the parent element.

    .container{
        position:relative; /*Position must be set to something*/
    }

    .container:after{
        position:relative;
        top: 0;
        content:"";
        left:0;
        height: 100%; /*Set pixel height and width if not defined in parent element*/
        width: 100%; 

        -webkit-box-sizing:border-box;
        -moz-box-sizing:border-box;
        -ms-box-sizing:border-box;
        box-sizing:border-box;

        border:1px solid #000; /*set your border style*/

    }

Is there a sleep function in JavaScript?

You can use the setTimeout or setInterval functions.

Compiling C++11 with g++

You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.

Regarding your question you can compile using

  1. g++ -std=c++11 for C++11
  2. g++ -std=c++14 for C++14
  3. g++ -std=c++17 for C++17
  4. g++ -std=c++2a for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.

Best way to retrieve variable values from a text file?

Use ConfigParser.

Your config:

[myvars]
var_a: 'home'
var_b: 'car'
var_c: 15.5

Your python code:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read("config.ini")
var_a = config.get("myvars", "var_a")
var_b = config.get("myvars", "var_b")
var_c = config.get("myvars", "var_c")

Is there possibility of sum of ArrayList without looping

Given that a list can hold any type of object, there is no built in method which allows you to sum all the elements. You could do something like this:

int sum = 0;

for( Integer i : ( ArrayList<Integer> )tt ) {
  sum += i;
}

Alternatively you could create your own container type which inherits from ArrayList but also implements a method called sum() which implements the code above.

What are Transient and Volatile Modifiers?

The volatile and transient modifiers can be applied to fields of classes1 irrespective of field type. Apart from that, they are unrelated.

The transient modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null for a reference type, and zero or false for a primitive type. Note that the JLS (see 8.3.1.3) does not say what transient means, but defers to the Java Object Serialization Specification. Other serialization mechanisms may pay attention to a field's transient-ness. Or they may ignore it.

(Note that the JLS permits a static field to be declared as transient. This combination doesn't make sense for Java Object Serialization, since it doesn't serialize statics anyway. However, it could make sense in other contexts, so there is some justification for not forbidding it outright.)

The volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. Similarly, reads and writes to volatile fields are atomic. (This does not apply to >>non-volatile<< long or double fields, which may be subject to "word tearing" on some JVMs.) The relevant parts of the JLS are 8.3.1.4, 17.4 and 17.7.


1 - But not to local variables or parameters.

How to specify more spaces for the delimiter using cut?

Actually awk is exactly the tool you should be looking into:

ps axu | grep '[j]boss' | awk '{print $5}'

or you can ditch the grep altogether since awk knows about regular expressions:

ps axu | awk '/[j]boss/ {print $5}'

But if, for some bizarre reason, you really can't use awk, there are other simpler things you can do, like collapse all whitespace to a single space first:

ps axu | grep '[j]boss' | sed 's/\s\s*/ /g' | cut -d' ' -f5

That grep trick, by the way, is a neat way to only get the jboss processes and not the grep jboss one (ditto for the awk variant as well).

The grep process will have a literal grep [j]boss in its process command so will not be caught by the grep itself, which is looking for the character class [j] followed by boss.

This is a nifty way to avoid the | grep xyz | grep -v grep paradigm that some people use.

Read whole ASCII file into C++ std::string

I figured out another way that works with most istreams, including std::cin!

std::string readFile()
{
    stringstream str;
    ifstream stream("Hello_World.txt");
    if(stream.is_open())
    {
        while(stream.peek() != EOF)
        {
            str << (char) stream.get();
        }
        stream.close();
        return str.str();
    }
}

How to change angular port from 4200 to any other

No one has updated answer for latest Angular CLI.With latest Angular CLI

With latest version of angular-cli in which angular-cli.json renamed to angular.json , you can change the port by editing angular.json file you now specify a port per "project"

projects": {
    "my-cool-project": {
        ... rest of project config omitted
        "architect": {
            "serve": {
                "options": {
                    "port": 4500
                }
            }
        }
    }
}

Read more about it here

How to parse a JSON string to an array using Jackson

The other answer is correct, but for completeness, here are other ways:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

Converting string to title case

You can directly change text or string to proper using this simple method, after checking for null or empty string values in order to eliminate errors:

public string textToProper(string text)
{
    string ProperText = string.Empty;
    if (!string.IsNullOrEmpty(text))
    {
        ProperText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
    }
    else
    {
        ProperText = string.Empty;
    }
    return ProperText;
}

Targeting .NET Framework 4.5 via Visual Studio 2010

FYI, if you want to create an Installer package in VS2010, unfortunately it only targets .NET 4. To work around this, you have to add NET 4.5 as a launch condition.

Add the following in to the Launch Conditions of the installer (Right click, View, Launch Conditions).

In "Search Target Machine", right click and select "Add Registry Search".

Property: REGISTRYVALUE1
RegKey: Software\Microsoft\NET Framework Setup\NDP\v4\Full
Root: vsdrrHKLM
Value: Release

Add new "Launch Condition":

Condition: REGISTRYVALUE1>="#378389"
InstallUrl: http://www.microsoft.com/en-gb/download/details.aspx?id=30653
Message: Setup requires .NET Framework 4.5 to be installed.

Where:

378389 = .NET Framework 4.5

378675 = .NET Framework 4.5.1 installed with Windows 8.1

378758 = .NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2

379893 = .NET Framework 4.5.2

Launch condition reference: http://msdn.microsoft.com/en-us/library/vstudio/xxyh2e6a(v=vs.100).aspx

How to create an object property from a variable value in JavaScript?

The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.

Example #1:

(function(o,a,b){return o[a]=b,o})({},'key','val');

Example: #2:

var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');

As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).

Result #1: { key: 'val' }

Result #2: { foo: 'bar', key: 'val' }

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

Adding new column to existing DataFrame in Python pandas

Doing this directly via NumPy will be the most efficient:

df1['e'] = np.random.randn(sLength)

Note my original (very old) suggestion was to use map (which is much slower):

df1['e'] = df1['a'].map(lambda x: np.random.random())

How is Docker different from a virtual machine?

In relation to:-

"Why is deploying software to a docker image easier than simply deploying to a consistent production environment ?"

Most software is deployed to many environments, typically a minimum of three of the following:

  1. Individual developer PC(s)
  2. Shared developer environment
  3. Individual tester PC(s)
  4. Shared test environment
  5. QA environment
  6. UAT environment
  7. Load / performance testing
  8. Live staging
  9. Production
  10. Archive

There are also the following factors to consider:

  • Developers, and indeed testers, will all have either subtlely or vastly different PC configurations, by the very nature of the job
  • Developers can often develop on PCs beyond the control of corporate or business standardisation rules (e.g. freelancers who develop on their own machines (often remotely) or contributors to open source projects who are not 'employed' or 'contracted' to configure their PCs a certain way)
  • Some environments will consist of a fixed number of multiple machines in a load balanced configuration
  • Many production environments will have cloud-based servers dynamically (or 'elastically') created and destroyed depending on traffic levels

As you can see the extrapolated total number of servers for an organisation is rarely in single figures, is very often in triple figures and can easily be significantly higher still.

This all means that creating consistent environments in the first place is hard enough just because of sheer volume (even in a green field scenario), but keeping them consistent is all but impossible given the high number of servers, addition of new servers (dynamically or manually), automatic updates from o/s vendors, anti-virus vendors, browser vendors and the like, manual software installs or configuration changes performed by developers or server technicians, etc. Let me repeat that - it's virtually (no pun intended) impossible to keep environments consistent (okay, for the purist, it can be done, but it involves a huge amount of time, effort and discipline, which is precisely why VMs and containers (e.g. Docker) were devised in the first place).

So think of your question more like this "Given the extreme difficulty of keeping all environments consistent, is it easier to deploying software to a docker image, even when taking the learning curve into account ?". I think you'll find the answer will invariably be "yes" - but there's only one way to find out, post this new question on Stack Overflow.

How to get data out of a Node.js http get request

from learnyounode:

var http = require('http')  

http.get(options, function (response) {  
  response.setEncoding('utf8')  
  response.on('data', console.log)  
  response.on('error', console.error)  
})

'options' is the host/path variable

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

How do I start my app on startup?

screenshot

I would like to add one point in this question which I was facing for couple of days. I tried all the answers but those were not working for me. If you are using android version 5.1 please change these settings.

If you are using android version 5.1 then you have to dis-select (Restrict to launch) from app settings.

settings> app > your app > Restrict to launch (dis-select)

How to set a default entity property value with Hibernate

One solution is to have your getter check to see if whatever value you are working with is null (or whatever its non-initialized state would be) and if it's equal to that, just return your default value:

public String getStringValue(){
     return (this.stringValue == null) ? "Default" : stringValue;
}

Pandas Merge - How to avoid duplicating columns

You can work out the columns that are only in one DataFrame and use this to select a subset of columns in the merge.

cols_to_use = df2.columns.difference(df.columns)

Then perform the merge (note this is an index object but it has a handy tolist() method).

dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')

This will avoid any columns clashing in the merge.

How can I check if a View exists in a Database?

To expand on Kevin's answer.

    private bool CustomViewExists(string viewName)
    {
        using (SalesPad.Data.DataConnection dc = yourconnection)
        {
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format(@"IF EXISTS(select * FROM sys.views where name = '{0}')
                Select 1
            else
                Select 0", viewName));
            cmd.CommandType = CommandType.Text;
            return Convert.ToBoolean(dc.ExecuteScalar(cmd));
        }
    }

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

How does Google calculate my location on a desktop?

I've finally worked it out. The biggest issue is how they managed to work out what Wireless networks were around me and how do they know where these networks are.

It "seems" to be something similar to this:

  1. skyhookwireless.com [or similar] Company has mapped the location of many wireless access points, i assume by similar means that google streetview went around and picked up all the photos.
  2. Using Google gears and my browser, we can report which wireless networks i see and have around me
  3. Compare these wireless points to their geolocation and triangulate my position.

Reference: Slashdot

Import existing source code to GitHub

Yes. Create a new repository, doing a git init in the directory where the source currently exists.

More here: http://help.github.com/creating-a-repo/

phpmyadmin "Not Found" after install on Apache, Ubuntu

You will need to configure your apache2.conf to make phpMyAdmin works.

sudo nano /etc/apache2/apache2.conf

Then add the following line to the end of the file.

Include /etc/phpmyadmin/apache.conf

Then restart apache

sudo service apache2 restart

Command to get time in milliseconds

When you use GNU AWK since version 4.1, you can load the time library and do:

$ awk '@load "time"; BEGIN{printf "%.6f", gettimeofday()}'

This will print the current time in seconds since 1970-01-01T00:00:00 in sub second accuracy.

the_time = gettimeofday() Return the time in seconds that has elapsed since 1970-01-01 UTC as a floating-point value. If the time is unavailable on this platform, return -1 and set ERRNO. The returned time should have sub-second precision, but the actual precision may vary based on the platform. If the standard C gettimeofday() system call is available on this platform, then it simply returns the value. Otherwise, if on MS-Windows, it tries to use GetSystemTimeAsFileTime().

source: GNU awk manual

On Linux systems, the standard C function getimeofday() returns the time in microsecond accuracy.

How to preventDefault on anchor tags?

if you never want to go to href... you should change your markup and use a button not an anchor tag because semantically it's not an anchor or a link. Inversely if you have a button that does some checks and then redirects it should be a link / anchor tag and not a button... for SEO purposes as well testing [insert test suite here].

for links that you only want to redirect conditionally like prompting to save changes, or acknowledge dirty state... you should use ng-click="someFunction($event)" and in someFunction on your validationError preventDefault and or stopPropagation.

also just because you can doesn't mean you should. javascript:void(0) worked well back in the day... but because of the nefarious hackers/crackers browsers flag apps/sites that use javascript within an href... see no reason to ducktype above..

it's 2016 since 2010 should be no reason anywhere to use links that act like buttons... if you still have to support IE8 and below you need to re-evaluate your place of business.

Google Maps: How to create a custom InfoWindow?

I'm not sure how FWIX.com is doing it specifically, but I'd wager they are using Custom Overlays.

Error ITMS-90717: "Invalid App Store Icon"

Whatever way you try above you need to test it by upload it to app connect like me to make sure it works and save your valuable time

enter image description here

enter image description here

Why do people say that Ruby is slow?

Ruby is slower than C++ at a number of easily measurable tasks (e.g., doing code that is heavily dependent on floating point). This is not very surprising, but enough justification for some people to say that “Ruby is Slow” without qualification. They don't count the fact that it is far easier and safer to write Ruby code than C++.

The best fix is to use targeted modules written in another language (e.g., C, C++, Fortran) in your Ruby code. Those can do the heavy lifting and your scripts can focus on higher level coordination issues.

MySQL - How to select rows where value is in array?

Use the FIND_IN_SET function:

SELECT t.*
  FROM YOUR_TABLE t
 WHERE FIND_IN_SET(3, t.ids) > 0

How to get value of Radio Buttons?

An alterntive is to use an enum and a component class that extends the standard RadioButton.

public enum Genders
{
    Male,
    Female
}

[ToolboxBitmap(typeof(RadioButton))]
public partial class GenderRadioButton : RadioButton
{
    public GenderRadioButton()
    {
        InitializeComponent();
    }

    public GenderRadioButton (IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }

    public Genders gender{ get; set; }
}

Use a common event handler for the GenderRadioButtons

private void Gender_CheckedChanged(Object sender, EventArgs e)
{
    if (((RadioButton)sender).Checked)
    {
        //get selected value
        Genders myGender = ((GenderRadioButton)sender).Gender;
        //get the name of the enum value
        string GenderName = Enum.GetName(typeof(Genders ), myGender);
        //do any work required when you change gender
        switch (myGender)
        {
            case Genders.Male:
                break;
            case Genders.Female:
                break;
            default:
                break;
        }
    }
}

JPA getSingleResult() or null

Try this in Java 8:

Optional first = query.getResultList().stream().findFirst();

ReactNative: how to center text?

Wherever you have Text component in your page just you need to set style of the Text component.

 <Text style={{ textAlign: 'center' }}> Text here </Text>

you don't need to add any other styling property, this is spectacular magic it will set you text in center of the your UI.

SyntaxError: missing ; before statement

Looks like you have an extra parenthesis.

The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.

foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
   return '[' + (+$1 + 1) + ']';
})

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

Could not install packages due to an EnvironmentError: [Errno 13]

This also happens to me when I try to install the opencv-python package:

installation attempt

I can fix it with command line

python3 -m pip install {name of package} --user

When I try to install the said package, the command becomes:

python3 -m pip install opencv-python --user

Resulting in this:

result

ngOnInit not being called when Injectable class is Instantiated

Adding to answer by @Sasxa,

In Injectables you can use class normally that is putting initial code in constructor instead of using ngOnInit(), it works fine.

Fastest way to list all primes below N

If you have control over N, the very fastest way to list all primes is to precompute them. Seriously. Precomputing is a way overlooked optimization.

Using Chrome's Element Inspector in Print Preview Mode?

Note: This answer covers several versions of Chrome, scroll to see v52, v48, v46, v43 and v42 each with their updated changes.

Chrome v52+:

  • Open the Developer Tools (Windows: F12 or Ctrl+Shift+I, Mac: Cmd+Opt+I)
  • Click the Customize and control DevTools hamburger menu button and choose More tools > Rendering settings (or Rendering in newer versions).
  • Check the Emulate print media checkbox at the Rendering tab and select the Print media type.

Chrome v52+

Chrome v48+ (Thanks Alex for noticing):

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (CTRLSHIFTM).
  • Make sure the console is shown by clicking Show console in menu at (1) (ESC key toggles the console if Developer Toolbar has focus).
  • Check Emulate print media at the rendering tab which can be opened by selecting Rendering in menu at (2).

Chrome v48+

Chrome v46+:

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (1).
  • Make sure the console is shown by clicking the menu button (2) > Show console (3) or pressing the ESC key to toggle the console (only works when Developer Toolbar has the focus).
  • Open the Emulation (4) > Media (5) tabs, check CSS media and select print (3).

Chrome v46+ support

Chrome v43+:

  • The drawer icon at step 2 has changed.

Emulate print media query on Chrome v43

Chrome v42:

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (1).
  • Make sure the drawer is shown by clicking the Show drawer button (2) or pressing the ESC key to toggle the drawer.
  • Under Emulation > Media check CSS media and select print (3).

Emulate print media query on Chrome v42

How to style UITextview to like Rounded Rect text field?

How about just:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, 280, 32)];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self addSubview:textField];

Node update a specific package

Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).

npm update browser-sync
-------
yarn upgrade browser-sync
  • Use npm|yarn outdated to see which modules have newer versions
  • Use npm update|yarn upgrade (without a package name) to update all modules
  • Include --save-dev|--dev if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary for devDependencies).

Major version upgrades:

In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x by doing:

npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev

...or the latest 2.1.x by doing:

npm install [email protected] --save-dev
-------
yarn add [email protected] --dev

...or the latest and greatest by doing:

npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev

Note: the last one is no different than doing this:

npm uninstall browser-sync --save-dev
npm install browser-sync --save-dev
-------
yarn remove browser-sync --dev
yarn add browser-sync --dev

The --save-dev part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.

Python - abs vs fabs

abs() : Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float. Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() : It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

How do I activate a Spring Boot profile when running from IntelliJ?

Replace your profile name with BE

You can try the above way to activate a profile

Convert String to java.util.Date

It sounds like you may want to use something like SimpleDateFormat. http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

You declare your date format and then call the parse method with your string.

private static final DateFormat DF = new SimpleDateFormat(...);
Date myDate = DF.parse("1234");

And as Guillaume says, set the timezone!

Flask ImportError: No Module Named Flask

The flask script is nice to start a local development server, but you would have to restart it manually after each change to your code. That is not very nice and Flask can do better. If you enable debug support the server will reload itself on code changes, and it will also provide you with a helpful debugger if things go wrong. To enable debug mode you can export the FLASK_DEBUG environment variable before running the server: forexample your file is hello.py

$ export FLASK_APP=hello.py
$ export FLASK_DEBUG=1
$ flask run

How to set the first option on a select box using jQuery?

You can try this:

$( 'select' ).each( function () {
    if ( $( this ).children().length > 0 ) {
        $( $( this ).children()[0] ).attr( 'selected', 'selected' );
        $( this ).change();
    }
} );

How to get IntPtr from byte[] in C#

Not sure about getting an IntPtr to an array, but you can copy the data for use with unmanaged code by using Mashal.Copy:

IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
// Call unmanaged code
Marshal.FreeHGlobal(unmanagedPointer);

Alternatively you could declare a struct with one property and then use Marshal.PtrToStructure, but that would still require allocating unmanaged memory.

Edit: Also, as Tyalis pointed out, you can also use fixed if unsafe code is an option for you

Creating a simple XML file using python

For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates

For a Jinja example, see my answer to a similar question.

Here is an example of generating your xml with string templates.

import string
from xml.sax.saxutils import escape

inner_template = string.Template('    <field${id} name="${name}">${value}</field${id}>')

outer_template = string.Template("""<root>
 <doc>
${document_list}
 </doc>
</root>
 """)

data = [
    (1, 'foo', 'The value for the foo document'),
    (2, 'bar', 'The <value> for the <bar> document'),
]

inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result

Output:

<root>
 <doc>
    <field1 name="foo">The value for the foo document</field1>
    <field2 name="bar">The &lt;value&gt; for the &lt;bar&gt; document</field2>
 </doc>
</root>

The downer of the template approach is that you won't get escaping of < and > for free. I danced around that problem by pulling in a util from xml.sax

Target class controller does not exist - Laravel 8

In laravel 8 you just add your controller namespace in routes\web.php

use App\Http\Controllers\InvoiceController; // InvoiceController is controller name Route::get('invoice',[InvoiceController::class, 'index']);

Or

go `app\Providers\RouteServiceProvider.php` path and remove comments

protected $namespace = 'App\\Http\\Controllers';

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.

If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.

Display number with leading zeros

You can do this with f strings.

import numpy as np

print(f'{np.random.choice([1, 124, 13566]):0>8}')

This will print constant length of 8, and pad the rest with leading 0.

00000001
00000124
00013566

Insert data into hive table

Although there is an accepted answer I would want to add that as of Hive 0.14, record level operations are allowed. The correct syntax and query would be:

INSERT INTO TABLE tweet_table VALUES ('data');

Convert Java object to XML string

Here is a util class for marshaling and unmarshaling objects. In my case it was a nested class, so I made it static JAXBUtils.

import javax.xml.bind.JAXB;
import java.io.StringReader;
import java.io.StringWriter;

public class JAXBUtils
{
    /**
     * Unmarshal an XML string
     * @param xml     The XML string
     * @param type    The JAXB class type.
     * @return The unmarshalled object.
     */
    public <T> T unmarshal(String xml, Class<T> type)
    {
        StringReader reader = new StringReader(xml);
        return javax.xml.bind.JAXB.unmarshal(reader, type);
    }

    /**
     * Marshal an Object to XML.
     * @param object    The object to marshal.
     * @return The XML string representation of the object.
     */
    public String marshal(Object object)
    {
        StringWriter stringWriter = new StringWriter();
        JAXB.marshal(object, stringWriter);
        return stringWriter.toString();
    }
}

Django. Override save for model

You may supply extra argument for confirming a new image is posted.
Something like:

def save(self, new_image=False, *args, **kwargs):
    if new_image:
        small=rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)
    super(Model, self).save(*args, **kwargs)

or pass request variable

def save(self, request=False, *args, **kwargs):
    if request and request.FILES.get('image',False):
        small=rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)
    super(Model, self).save(*args, **kwargs)

I think these wont break your save when called simply.

You may put this in your admin.py so that this work with admin site too (for second of above solutions):

class ModelAdmin(admin.ModelAdmin):

    ....
    def save_model(self, request, obj, form, change): 
        instance = form.save(commit=False)
        instance.save(request=request)
        return instance

Adding/removing items from a JavaScript object with jQuery

First off, your quoted code is not JSON. Your code is JavaScript object literal notation. JSON is a subset of that designed for easier parsing.

Your code defines an object (data) containing an array (items) of objects (each with an id, name, and type).

You don't need or want jQuery for this, just JavaScript.

Adding an item:

data.items.push(
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

That adds to the end. See below for adding in the middle.

Removing an item:

There are several ways. The splice method is the most versatile:

data.items.splice(1, 3); // Removes three items starting with the 2nd,
                         // ("Witches of Eastwick", "X-Men", "Ordinary People")

splice modifies the original array, and returns an array of the items you removed.

Adding in the middle:

splice actually does both adding and removing. The signature of the splice method is:

removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
  • index - the index at which to start making changes
  • num_to_remove - starting with that index, remove this many entries
  • addN - ...and then insert these elements

So I can add an item in the 3rd position like this:

data.items.splice(2, 0,
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

What that says is: Starting at index 2, remove zero items, and then insert this following item. The result looks like this:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "7", name: "Douglas Adams", type: "comedy"},     // <== The new item
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

You can remove some and add some at once:

data.items.splice(1, 3,
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"}
);

...which means: Starting at index 1, remove three entries, then add these two entries. Which results in:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

How can I extract a predetermined range of lines from a text file on Unix?

Using ed:

ed -s infile <<<'16224,16482p'

-s suppresses diagnostic output; the actual commands are in a here-string. Specifically, 16224,16482p runs the p (print) command on the desired line address range.

VBA check if file exists

For checking existence one can also use (works for both, files and folders):

Not Dir(DirFile, vbDirectory) = vbNullString

The result is True if a file or a directory exists.

Example:

If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then
    MsgBox "exists"
Else
    MsgBox "does not exist"
End If

React Native fixed footer

You get the Dimension first and then manipulate it through flex style

var Dimensions = require('Dimensions')
var {width, height} = Dimensions.get('window')

In render

<View style={{flex: 1}}>
    <View style={{width: width, height: height - 200}}>main</View>
    <View style={{width: width, height: 200}}>footer</View>
</View>

The other method is to use flex

<View style={{flex: 1}}>
    <View style={{flex: .8}}>main</View>
    <View style={{flex: .2}}>footer</View>
</View>

Is there 'byte' data type in C++?

No there is no byte data type in C++. However you could always include the bitset header from the standard library and create a typedef for byte:

typedef bitset<8> BYTE;

NB: Given that WinDef.h defines BYTE for windows code, you may want to use something other than BYTE if your intending to target Windows.

Edit: In response to the suggestion that the answer is wrong. The answer is not wrong. The question was "Is there a 'byte' data type in C++?". The answer was and is: "No there is no byte data type in C++" as answered.

With regards to the suggested possible alternative for which it was asked why is the suggested alternative better?

According to my copy of the C++ standard, at the time:

"Objects declared as characters (char) shall be large enough to store any member of the implementations basic character set": 3.9.1.1

I read that to suggest that if a compiler implementation requires 16 bits to store a member of the basic character set then the size of a char would be 16 bits. That today's compilers tend to use 8 bits for a char is one thing, but as far as I can tell there is certainly no guarantee that it will be 8 bits.

On the other hand, "the class template bitset<N> describes an object that can store a sequence consisting of a fixed number of bits, N." : 20.5.1. In otherwords by specifying 8 as the template parameter I end up with an object that can store a sequence consisting of 8 bits.

Whether or not the alternative is better to char, in the context of the program being written, therefore depends, as far as I understand, although I may be wrong, upon your compiler and your requirements at the time. It was therefore upto the individual writing the code, as far as I'm concerned, to do determine whether the suggested alternative was appropriate for their requirements/wants/needs.

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

Log to the base 2 in python

http://en.wikipedia.org/wiki/Binary_logarithm

def lg(x, tol=1e-13):
  res = 0.0

  # Integer part
  while x<1:
    res -= 1
    x *= 2
  while x>=2:
    res += 1
    x /= 2

  # Fractional part
  fp = 1.0
  while fp>=tol:
    fp /= 2
    x *= x
    if x >= 2:
        x /= 2
        res += fp

  return res

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

Alternative to deprecated getCellType

You can use:

cell.getCellTypeEnum()

Further to compare the cell type, you have to use CellType as follows:-

if(cell.getCellTypeEnum() == CellType.STRING){
      .
      .
      .
}

You can Refer to the documentation. Its pretty helpful:-

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html

Difference between clustered and nonclustered index

You should be using indexes to help SQL server performance. Usually that implies that columns that are used to find rows in a table are indexed.

Clustered indexes makes SQL server order the rows on disk according to the index order. This implies that if you access data in the order of a clustered index, then the data will be present on disk in the correct order. However if the column(s) that have a clustered index is frequently changed, then the row(s) will move around on disk, causing overhead - which generally is not a good idea.

Having many indexes is not good either. They cost to maintain. So start out with the obvious ones, and then profile to see which ones you miss and would benefit from. You do not need them from start, they can be added later on.

Most column datatypes can be used when indexing, but it is better to have small columns indexed than large. Also it is common to create indexes on groups of columns (e.g. country + city + street).

Also you will not notice performance issues until you have quite a bit of data in your tables. And another thing to think about is that SQL server needs statistics to do its query optimizations the right way, so make sure that you do generate that.

What is the difference between an Instance and an Object?

Once you instantiate a class (using new), that instantiated thing becomes an object. An object is something that can adhere to encapsulation, polymorphism, abstraction principles of object oriented programming and the real thing a program interacts with to consume the instance members defined in class. Object contains instance members (non-static members).

Thus instance of a class is an object. The word ‘instance’ is used when you are referring to the origin from where it born, it's more clearer if you say ‘instance of a class’ compared to ‘object of a class’ (although the latter can be used to).

Can also read the 'Inner classes' section of this java document on nested classes - https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Javascript: How to check if a string is empty?

if (value == "") {
  // it is empty
}

How can I clear or empty a StringBuilder?

delete is not overly complicated :

myStringBuilder.delete(0, myStringBuilder.length());

You can also do :

myStringBuilder.setLength(0);

Python NoneType object is not callable (beginner)

You should not pass the call function hi() to the loop() function, This will give the result.

def hi():     
  print('hi')

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)            # Do not use hi() function inside loop() function

How to get the current location latitude and longitude in android

Here is Android Location library you can find your current location without using Google account or subscription.

Find this link and download repository

https://github.com/mrmans0n/smart-location-lib

Take care and Enjoy...

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Johnny's answer is the right one to upvote. I'm just adding this below in objective-c to make it clearer to beginners (and those of us who refuse to learn Swift syntax :)

Make sure you declare the uitableviewdelegate and have the following methods:

 -(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
 UITableViewRowAction *button = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Button 1" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
    {
        NSLog(@"Action to perform with Button 1");
    }];
    button.backgroundColor = [UIColor greenColor]; //arbitrary color
    UITableViewRowAction *button2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Button 2" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
                                    {
                                        NSLog(@"Action to perform with Button2!");
                                    }];
    button2.backgroundColor = [UIColor blueColor]; //arbitrary color

    return @[button, button2]; //array with all the buttons you want. 1,2,3, etc...
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
// you need to implement this method too or nothing will work:

}
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return YES; //tableview must be editable or nothing will work...
    }

What is an ORM, how does it work, and how should I use one?

Introduction

Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM".

An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using.

For example, here is a completely imaginary case with a pseudo language:

You have a book class, you want to retrieve all the books of which the author is "Linus". Manually, you would do something like that:

book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // I over simplify ...
while (row = data.next())
{
     book = new Book();
     book.setAuthor(row.get('author');
     book_list.add(book);
}

With an ORM library, it would look like this:

book_list = BookTable.query(author="Linus");

The mechanical part is taken care of automatically via the ORM library.

Pros and Cons

Using ORM saves a lot of time because:

  • DRY: You write your data model in only one place, and it's easier to update, maintain, and reuse the code.
  • A lot of stuff is done automatically, from database handling to I18N.
  • It forces you to write MVC code, which, in the end, makes your code a little cleaner.
  • You don't have to write poorly-formed SQL (most Web programmers really suck at it, because SQL is treated like a "sub" language, when in reality it's a very powerful and complex one).
  • Sanitizing; using prepared statements or transactions are as easy as calling a method.

Using an ORM library is more flexible because:

  • It fits in your natural way of coding (it's your language!).
  • It abstracts the DB system, so you can change it whenever you want.
  • The model is weakly bound to the rest of the application, so you can change it or use it anywhere else.
  • It lets you use OOP goodness like data inheritance without a headache.

But ORM can be a pain:

  • You have to learn it, and ORM libraries are not lightweight tools;
  • You have to set it up. Same problem.
  • Performance is OK for usual queries, but a SQL master will always do better with his own SQL for big projects.
  • It abstracts the DB. While it's OK if you know what's happening behind the scene, it's a trap for new programmers that can write very greedy statements, like a heavy hit in a for loop.

How to learn about ORM?

Well, use one. Whichever ORM library you choose, they all use the same principles. There are a lot of ORM libraries around here:

If you want to try an ORM library in Web programming, you'd be better off using an entire framework stack like:

  • Symfony (PHP, using Propel or Doctrine).
  • Django (Python, using a internal ORM).

Do not try to write your own ORM, unless you are trying to learn something. This is a gigantic piece of work, and the old ones took a lot of time and work before they became reliable.

Trust Anchor not found for Android SSL Connection

You can trust particular certificate at runtime.
Just download it from server, put in assets and load like this using ssl-utils-android:

OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());

In the example above I used OkHttpClient but SSLContext can be used with any client in Java.

If you have any questions feel free to ask. I'm the author of this small library.

How can I parse a string with a comma thousand separator to a number?

If you want a l10n answer do it this way. Example uses currency, but you don't need that. Intl library will need to be polyfilled if you have to support older browsers.

var value = "2,299.00";
var currencyId = "USD";
var nf = new Intl.NumberFormat(undefined, {style:'currency', currency: currencyId, minimumFractionDigits: 2});

value = nf.format(value.replace(/,/g, ""));

C# Base64 String to JPEG Image

public Image Base64ToImage(string base64String)
{
   // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

    // Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);

    return image;
}

What characters do I need to escape in XML documents?

Escaping characters is different for tags and attributes.

For tags:

 < &lt;
 > &gt; (only for compatibility, read below)
 & &amp;

For attributes:

" &quot;
' &apos;

From Character Data and Markup:

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " &amp; " and " &lt; " respectively. The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility, be escaped using either " &gt; " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as " &apos; ", and the double-quote character (") as " &quot; ".

What is the difference between "long", "long long", "long int", and "long long int" in C++?

While in Java a long is always 64 bits, in C++ this depends on computer architecture and operating system. For example, a long is 64 bits on Linux and 32 bits on Windows (this was done to keep backwards-compatability, allowing 32-bit programs to compile on 64-bit Windows without any changes).

It is considered good C++ style to avoid short int long ... and instead use:

std::int8_t   # exactly  8 bits
std::int16_t  # exactly 16 bits
std::int32_t  # exactly 32 bits
std::int64_t  # exactly 64 bits

std::size_t   # can hold all possible object sizes, used for indexing

These (int*_t) can be used after including the <cstdint> header. size_t is in <stdlib.h>.

How to rotate a 3D object on axis three.js?

Just in case...in r52 the method is called setEulerFromRotationMatrix instead of getRotationFromMatrix

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

Simple way to get element by id within a div tag?

You don't want to do this. It is invalid HTML to have more than one element with the same id. Browsers won't treat that well, and you will have undefined behavior, meaning you have no idea what the browser will give you when you select an element by that id, it could be unpredictable.

You should be using a class, or just iterating through the inputs and keeping track of an index.

Try something like this:

var div2 = document.getElementById('div2');
for(i = j = 0; i < div2.childNodes.length; i++)
    if(div2.childNodes[i].nodeName == 'INPUT'){
        j++;
        var input = div2.childNodes[i];
        alert('This is edit'+j+': '+input);
    }

JSFiddle

What does Include() do in LINQ?

Let's say for instance you want to get a list of all your customers:

var customers = context.Customers.ToList();

And let's assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product.

As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include() allows you to indicate which related entities should be read from the database as part of the same query.

Using the same example, this might bring in all of the related order headers, but none of the other records:

var customersWithOrderDetail = context.Customers.Include("Orders").ToList();

As a final point since you asked for SQL, the first statement without Include() could generate a simple statement:

SELECT * FROM Customers;

The final statement which calls Include("Orders") may look like this:

SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;

How to add Android Support Repository to Android Studio?

Android Studio 3

Make sure you have the latest version of Android Studio. The support library is included by default when you create new projects. If you are adding the Support Library to a project that doesn't have it, then you just need to add a single line to your app module's build.gradle file, and then sync gradle.

build.gradle

dependencies {
    ...
    implementation 'com.android.support:appcompat-v7:27.1.1'
} 

It should just be that easy, though there may be some things to note:

  • Android Studio should give you a warning nowadays if the support library needs to be updated. Just update the 27.1.1 numbers that I have here to whatever it tells you to. You can also manually check what the latest revision is if you want to.
  • The implementation keyword replaces compile that was used in Android Studio 2.x. (What's the difference?)
  • There are other support library packages that you may need to include depending on what your app uses (like constraint-layout or recyclerview).
  • Make sure that you have the latest updates for everything in the SDK Manager. Go to Tools > SDK Manager.

Documentation

Convert double/float to string

sprintf can do this:

#include <stdio.h>
int main() {
  float w = 234.567;
  char x[__SIZEOF_FLOAT__];
  sprintf(x, "%g", w);
  puts(x);
}

Android EditText Hint

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            et.setHint(temp +" Characters");
        }
    });

Print second last column/field in awk

If you have many columns and want to print all but not the three cloumns in the last, then this might help

awk '{ $NF="";$(NF-1)="";$(NF-2)="" ; print $0 }'

Best way to add Gradle support to IntelliJ Project

To add to other answers. For me it was helpful to delete .mvn directory and then add build.gradle. New versions of IntelliJ will then automatically notice that you use Gradle.

Operator overloading in Java

Or, you can make Java Groovy and just overload these functions to achieve what you want

//plus() => for the + operator
//multiply() => for the * operator
//leftShift() = for the << operator
// ... and so on ...

class Fish {
    def leftShift(Fish fish) {
        print "You just << (left shifted) some fish "
    }
}


def fish = new Fish()
def fish2 = new Fish()

fish << fish2

Who doesnt want to be/use groovy? :D

No you cannot use the compiled groovy JARs in Java the same way. It still is a compiler error for Java.

A regex for version number parsing

Thanks for all the responses! This is ace :)

Based on OneByOne's answer (which looked the simplest to me), I added some non-capturing groups (the '(?:' parts - thanks to VonC for introducing me to non-capturing groups!), so the groups that do capture only contain the digits or * character.

^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$

Many thanks everyone!

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

IIS 6.0 and previous versions :

ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.

This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.

Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.

The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests

What's a SCRIPT MAP ?

Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed

A good example can be seen here

IIS 7 and above

IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.

IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )

What this means is that IIS 7 processes requests that arrive for any content type, with both NON ASP.NET Modules / native IIS modules and ASP.NET modules providing request processing in all stages This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.

  • You can build new managed modules (IHttpModule) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.
  • Add new managed Handlers ( IHttpHandler)

setContentView(R.layout.main); error

Simply:

  1. Right click on your project.

  2. Go to properties.

  3. Select android (second option in the Left panel).

  4. Click "add..." (in library), select your project.

  5. Click ok.

  6. And finally, clean your project.

If this doesn't work, make sure that "android-support-v7-appcompat" is in your Project Explorer.

If it isn't there, you can add it by importing a simple project from: C:/android-sdks\extras\android\support\v7\appcompat

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

Capture Signature using HTML5 and iPad

Perhaps the best two browser techs for this are Canvas, with Flash as a back up.

We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.

With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.

MySQL SELECT statement for the "length" of the field is greater than 1

select * from [tbl] where [link] is not null and len([link]) > 1

For MySQL user:

LENGTH([link]) > 1

Error when trying to access XAMPP from a network

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>

and add

"Allow from all"

after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

In later versions of Xampp

...you can simply remove this part

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

from the same file and it should work over the local network.

How to get Exception Error Code in C#

Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.

 try
 {
     object result = processClass.InvokeMethod("Create", methodArgs);
 }
 catch (Exception e)
 {
     // Here I was hoping to get an error code.
     if (ExceptionContainsErrorCode(e, 10004))
     {
         // Execute desired actions
     }
 }

...

private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
    Win32Exception winEx = e as Win32Exception;
    if (winEx != null && ErrorCode == winEx.ErrorCode) 
        return true;

    if (e.InnerException != null) 
        return ExceptionContainsErrorCode(e.InnerException, ErrorCode);

    return false;
}

This code has been unit tested.

I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.

Map and filter an array at the same time

One line reduce with ES6 fancy spread syntax is here!

_x000D_
_x000D_
var options = [_x000D_
  { name: 'One', assigned: true }, _x000D_
  { name: 'Two', assigned: false }, _x000D_
  { name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
const filtered = options_x000D_
  .reduce((result, {name, assigned}) => [...result, ...assigned ? [name] : []], []);_x000D_
_x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

Submitting the value of a disabled input field

I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.

Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.

You can use the readonly property in your input field

<input type="text" readonly="readonly" />

dotnet ef not found in .NET Core 3

For everyone using .NET Core CLI on MinGW MSYS. After installing using

dotnet tool install --global dotnet-ef

add this line to to bashrc file c:\msys64\home\username\ .bashrc (location depend on your setup)

export PATH=$PATH:/c/Users/username/.dotnet/tools

Get value from SimpleXMLElement Object

$codeZero = null;
foreach ($xml->code->children() as $child) {
   $codeZero = $child;
}

$lat = null;
foreach ($codeZero->children() as $child) {
   if (isset($child->lat)) {
      $lat = $child->lat;
   }
}

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

Using GregorianCalendar with SimpleDateFormat

SimpleDateFormat.format() method takes a Date as a parameter. You can get a Date from a Calendar by calling its getTime() method:

public static String format(GregorianCalendar calendar) {
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    fmt.setCalendar(calendar);
    String dateFormatted = fmt.format(calendar.getTime());

    return dateFormatted;
}

Also note that the months start at 0, so you probably meant:

int month = Integer.parseInt(splitDate[1]) - 1;

Auto-redirect to another HTML page

Its a late answer, but as I can see most of the people mentioned about "refresh" method to redirect a webpage. As per W3C, we should not use "refresh" to redirect. Because it could break the "back" button. Imagine that the user presses the "back" button, the refresh would work again, and the user would bounce forward. The user will most likely get very annoyed, and close the window, which is probably not what you, as the author of this page, want.

Use HTTP redirects instead. One can refer the complete documentation here: W3C document

Django set field value after a form is initialized

Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:

form = FormType(request.POST)
if request.method == "POST":
    formcopy = form(request.POST.copy())
    formcopy.data['Email'] = GetEmailString()

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Because switching to HTTPS can be painful or impossible depending on your architecture, I found a workaround solution: you can use the Google Maps Geolocation API. Although it has usage limits, it does the job. You will need an browser API key, so don't forget to limit it's usage to your page hostname.

I use it as a fallback method to the getCurrentPosition() method if it fails. It allows me to make it work until I switch to HTTPS.

Here's the JSFiddles:

  • HTTP: getCurrentPosition() will fail and fall back to the API
  • HTTPS: getCurrentPosition() will succeed

How to get selected option using Selenium WebDriver with Java

You should be able to get the text using getText() (for the option element you got using getFirstSelectedOption()):

Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );

Materialize CSS - Select Doesn't Seem to Render

The solution that worked for me is by calling the 'material_select' function after the options data has been loaded. If you print out the value of OptionsList.find().count() to the console it's first 0 then a few milliseconds later the list gets populated with data.

Template.[name].rendered = function() {
    this.autorun(function() {
        var optionsCursor = OptionsList.find().count();
        if(optionsCursor > 0)
        {
            $('select').material_select();
        }
    });
};

What is the difference between "::" "." and "->" in c++

In C++ you can access fields or methods, using different operators, depending on it's type:

  • ClassName::FieldName : class public static field and methods
  • ClassInstance.FieldName : accessing a public field (or method) through class reference
  • ClassPointer->FieldName : accessing a public field (or method) dereferencing a class pointer

Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.

class AClass{
public:
static int static_field;
int instance_field;

static void static_method();
void method();
};

then you access this way:

AClass instance;
AClass *pointer = new AClass();

instance.instance_field; //access instance_field through a reference to AClass
instance.method();

pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();

AClass::static_field;  
AClass::static_method();

adding directory to sys.path /PYTHONPATH

This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.

Get the name of a pandas DataFrame

Sometimes df.name doesn't work.

you might get an error message:

'DataFrame' object has no attribute 'name'

try the below function:

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

Java JRE 64-bit download for Windows?

I believe the link below will always give you the latest version of the 64-bit JRE http://javadl.sun.com/webapps/download/AutoDL?BundleId=43883

Setting up Eclipse with JRE Path

You are most probably missing PATH entries in your windows. Follow this instruction : How do I set or change the PATH system variable?

Insertion Sort vs. Selection Sort

In layman terms, (and probably the easiest way to attain a high level understanding of the problem)

Bubble sort is similar to standing in a line and trying to sort yourselves by height. You keep switching with the person next to you until you are at the right place. This takes place all the way from the left (or right depending on the implementation) and you keep switching until everybody is sorted.

In selection sort, however, what you are doing is similar to arranging a hand of cards. You look at the cards, take the smallest one, place it all the way to the left, and so on.

How to calculate age (in years) based on Date of Birth and getDate()

Here is how i calculate age given a birth date and current date.

select case 
            when cast(getdate() as date) = cast(dateadd(year, (datediff(year, '1996-09-09', getdate())), '1996-09-09') as date)
                then dateDiff(yyyy,'1996-09-09',dateadd(year, 0, getdate()))
            else dateDiff(yyyy,'1996-09-09',dateadd(year, -1, getdate()))
        end as MemberAge
go

Using pointer to char array, values in that array can be accessed?

Your should create ptr as follows:

char *ptr;

You have created ptr as an array of pointers to chars. The above creates a single pointer to a char.

Edit: complete code should be:

char *ptr;
char arr[5] = {'a','b','c','d','e'};
ptr = arr;
printf("\nvalue:%c", *(ptr+0));

How to limit google autocomplete results to City and Country only

You can try the country restriction

function initialize() {

 var options = {
  types: ['(cities)'],
  componentRestrictions: {country: "us"}
 };

 var input = document.getElementById('searchTextField');
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}

More info:

ISO 3166-1 alpha-2 can be used to restrict results to specific groups. Currently, you can use componentRestrictions to filter by country.

The country must be passed as as a two character, ISO 3166-1 Alpha-2 compatible country code.


Officially assigned country codes

Get the current displaying UIViewController on the screen in AppDelegate.m

This worked for me. I have many targets that have different controllers so previous answers didn't seemed to work.

first you want this inside your AppDelegate class:

var window: UIWindow?

then, in your function

let navigationController = window?.rootViewController as? UINavigationController
if let activeController = navigationController!.visibleViewController {
    if activeController.isKindOfClass( MyViewController )  {
        println("I have found my controller!")    
   }
}

FirebaseInstanceIdService is deprecated

And here the solution for C#/Xamarin.Android:

var token = await FirebaseInstallations.Instance.GetToken(forceRefresh: false).AsAsync<InstallationTokenResult>();

How do I exit from the text window in Git?

There is a default text editor that will be used when Git needs you to type in a message. By default, Git uses your system’s default editor, which is generally Vi or Vim. In your case, it is Vim that Git has chosen. See How do I make Git use the editor of my choice for commits? for details of how to choose another editor. Meanwhile...

You'll want to enter a message before you leave Vim:

O

...will start a new line for you to type in.

To exit (g)Vim type:

EscZZ or Esc:wqReturn.

It's worth getting to know Vim, as you can use it for editing text on almost any platform. I recommend the Vim Tutor, I used it many years ago and have never looked back (barely a day goes by when I don't use Vim).

What is an unhandled promise rejection?

I had faced a similar issue with NodeJS, where the culprit was a forEach loop. Note that forEach is a synchronous function (NOT Asynchronous). Therefore it just ignores the promise returned. The solution was to use a for-of loop instead: Code where I got the error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

is as follows:

permissionOrders.forEach( async(order) => {
        const requestPermissionOrder = new RequestPermissionOrderSchema({
            item: order.item,
            item_desc: order.item_desc,
            quantity: order.quantity,
            unit_price: order.unit_price,
            total_cost: order.total_cost,
            status: order.status,
            priority: order.priority,
            directOrder: order.directOrder
        });

        try {
            const dat_order = await requestPermissionOrder.save();
            res.json(dat_order);
        } catch(err){
            res.json({ message : err});
        }
    });

Solution for the above issue is as follows:

for (let order of permissionOrders){
        const requestPermissionOrder = new RequestPermissionOrderSchema({
            item: order.item,
            item_desc: order.item_desc,
            quantity: order.quantity,
            unit_price: order.unit_price,
            total_cost: order.total_cost,
            status: order.status,
            priority: order.priority,
            directOrder: order.directOrder
        });

        try {
            const dat_order = await requestPermissionOrder.save();
            res.json(dat_order);
        } catch(err){
            res.json({ message : err});
        }
    };

Left Join With Where Clause

When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON or WHERE clauses -- the result will be the same.

  SELECT  s.*, 
          cs.`value`
     FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
                               AND cs.character_id = 1

How do I handle newlines in JSON?

You could just escape your string on the server when writing the value of the JSON field and unescape it when retrieving the value in the client browser, for instance.

The JavaScript implementation of all major browsers have the unescape command.

Example:

On the server:

response.write "{""field1"":""" & escape(RS_Temp("textField")) & """}"

In the browser:

document.getElementById("text1").value = unescape(jsonObject.field1)

How to flush route table in windows?

From command prompt as admin run:

netsh interface ip delete destinationcache

Works on Win7.

Plot multiple columns on the same graph in R

To select columns to plot, I added 2 lines to Vincent Zoonekynd's answer:

#convert to tall/long format(from wide format)
col_plot = c("A","B")
dlong <- melt(d[,c("Xax", col_plot)], id.vars="Xax")  

#"value" and "variable" are default output column names of melt()
ggplot(dlong, aes(Xax,value, col=variable)) +
  geom_point() + 
  geom_smooth()

Google "tidy data" to know more about tall(or long)/wide format.

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

You can close every Java Process and start again your app:

taskkill /F /IM java.exe

start your app again...

MySQL count occurrences greater than 2

To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:

SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1

To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:

SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    GROUP BY word
    HAVING COUNT(*) > 1
) T1

Determine whether an array contains a value

function setFound(){   
 var l = arr.length, textBox1 = document.getElementById("text1");
    for(var i=0; i<l;i++)
    {
     if(arr[i]==searchele){
      textBox1 .value = "Found";
      return;
     }
    }
    textBox1 .value = "Not Found";
return;
}

This program checks whether the given element is found or not. Id text1 represents id of textbox and searchele represents element to be searched (got fron user); if you want index, use i value

How to change UIPickerView height

In iOS 4.2 & 4.3 the following works:

UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.frame = CGRectMake(0, 0, 320, 180);
[self addSubview:datePicker];

The following does not work:

UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
[self addSubview:datePicker];

I have an app that is in the app store with a 3 line date picker. I thought the height change may have been prevented because you see the text under the date picker's border, but this happens to the normal 216 height date picker too.

Which is the bug? Your guess is as good as mine.

Also there are 3 valid heights for UIDatePicker (and UIPickerView) 162.0, 180.0, and 216.0. If you set a UIPickerView height to anything else you will see the following in the console when debugging on an iOS device.

2011-09-14 10:06:56.180 DebugHarness[1717:707] -[UIPickerView setFrame:]: invalid height value 300.0 pinned to 216.0

Strings in C, how to get subString

You'll need to allocate memory for the new string otherString. In general for a substring of length n, something like this may work for you (don't forget to do bounds checking...)

char *subString(char *someString, int n) 
{
   char *new = malloc(sizeof(char)*n+1);
   strncpy(new, someString, n);
   new[n] = '\0';
   return new;
}

This will return a substring of the first n characters of someString. Make sure you free the memory when you are done with it using free().

Can I invoke an instance method on a Ruby module without including it?

After almost 9 years here's a generic solution:

module CreateModuleFunctions
  def self.included(base)
    base.instance_methods.each do |method|
      base.module_eval do
        module_function(method)
        public(method)
      end
    end
  end
end

RSpec.describe CreateModuleFunctions do
  context "when included into a Module" do
    it "makes the Module's methods invokable via the Module" do
      module ModuleIncluded
        def instance_method_1;end
        def instance_method_2;end

        include CreateModuleFunctions
      end

      expect { ModuleIncluded.instance_method_1 }.to_not raise_error
    end
  end
end

The unfortunate trick you need to apply is to include the module after the methods have been defined. Alternatively you may also include it after the context is defined as ModuleIncluded.send(:include, CreateModuleFunctions).

Or you can use it via the reflection_utils gem.

spec.add_dependency "reflection_utils", ">= 0.3.0"

require 'reflection_utils'
include ReflectionUtils::CreateModuleFunctions

This could be due to the service endpoint binding not using the HTTP protocol

This error can be because of contract mismatch. Consider the three layered application below...

UI Layer
|
Process Layer
|
Data Access Layer
-> Contract Between Process and UI layer has the same enum with missing (Onhold = 3). Enum: Start = 1, Stop = 2. -> Contract Between Data Access And Process layer has enum Enum: Start = 1,Stop = 2,Onhold = 3.

In this case we will get the same error in process layer response.

The same error comes in other contract mismatch in multilayered application.

com.jcraft.jsch.JSchException: UnknownHostKey

While the question has been answered in general, I've found myself that there's a case when even existing known_hosts entry doesn't help. This happens when an SSH server sends ECDSA fingerprint and as a result, you'll have an entry like this:

|1|+HASH=|HASH= ecdsa-sha2-nistp256 FINGERPRINT=

The problem is that JSch prefers SHA_RSA and while connecting it will try to compare SHA-RSA fingerprint, which will result with error about "unknown host".

To fix this simply run:

$ ssh-keyscan -H -t rsa example.org >> known_hosts

or complain to Jcraft about prefering SHA_RSA instead of using the local HostKeyAlgorithms setting, although they don't seem to be too eager to fix their bugs.

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

Can Powershell Run Commands in Parallel?

http://gallery.technet.microsoft.com/scriptcenter/Invoke-Async-Allows-you-to-83b0c9f0

i created an invoke-async which allows you do run multiple script blocks/cmdlets/functions at the same time. this is great for small jobs (subnet scan or wmi query against 100's of machines) because the overhead for creating a runspace vs the startup time of start-job is pretty drastic. It can be used like so.

with scriptblock,

$sb = [scriptblock] {param($system) gwmi win32_operatingsystem -ComputerName $system | select csname,caption} 

$servers = Get-Content servers.txt 

$rtn = Invoke-Async -Set $server -SetParam system  -ScriptBlock $sb

just cmdlet/function

$servers = Get-Content servers.txt 

$rtn = Invoke-Async -Set $servers -SetParam computername -Params @{count=1} -Cmdlet Test-Connection -ThreadCount 50

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

How to delete a line from a text file in C#?

Read the file, remove the line in memory and put the contents back to the file (overwriting). If the file is large you might want to read it line for line, and creating a temp file, later replacing the original one.

How to convert timestamps to dates in Bash?

I have written a script that does this myself:

#!/bin/bash
LANG=C
if [ -z "$1" ]; then
    if [  "$(tty)" = "not a tty" ]; then
            p=`cat`;
    else
            echo "No timestamp given."
            exit
    fi
else
    p=$1
fi
echo $p | gawk '{ print strftime("%c", $0); }'

SyntaxError: expected expression, got '<'

May be this helps someone. The error I was getting was

SyntaxError: expected expression, got '<'

What I did clicked on view source in chrome and there I found this error

Notice: Undefined variable: string in D:\Projects\demo\ge.php on line 66

The issue was this snippet of code,

$string= ''; <---- this should be declared outside the loop

while($row = mysql_fetch_assoc($result))
    {
        $string .= '{ id:'.$row['menu_id'].', pId:'.$row['parent_id'].', name:"'.$row['menu_name'].'"},';
    }

which fixed the problem.

What is a loop invariant?

Definition by How to Think About Algorithms, by Jeff Edmonds

A loop invariant is an assertion that is placed at the top of a loop and that must hold true every time the computation returns to the top of the loop.

How to edit hosts file via CMD?

Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.

Examples of using

hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost

...and many others...

Help

Usage:
    hosts - run hosts command interpreter
    hosts <command> <params> - execute hosts command

Commands:
    add  <host> <aliases> <addr> # <comment>   - add new host
    set  <host|mask> <addr> # <comment>        - set ip and comment for host
    rem  <host|mask>   - remove host
    on   <host|mask>   - enable host
    off  <host|mask>   - disable host
    view [all] <mask>  - display enabled and visible, or all hosts
    hide <host|mask>   - hide host from 'hosts view'
    show <host|mask>   - show host in 'hosts view'
    print      - display raw hosts file
    format     - format host rows
    clean      - format and remove all comments
    rollback   - rollback last operation
    backup     - backup hosts file
    restore    - restore hosts file from backup
    recreate   - empty hosts file
    open       - open hosts file in notepad

Download

https://code.google.com/p/hostscmd/downloads/list

How to print all information from an HTTP request to the screen, in PHP

A simple way would be:

<?php
print_r($_SERVER);
print_r($_POST);
print_r($_GET);
print_r($_FILES);
?>

A bit of massaging would be required to get everything in the order you want, and to exclude the variables you are not interested in, but should give you a start.

How to crop an image using PIL?

(left, upper, right, lower) means two points,

  1. (left, upper)
  2. (right, lower)

with an 800x600 pixel image, the image's left upper point is (0, 0), the right lower point is (800, 600).

So, for cutting the image half:

from PIL import Image
img = Image.open("ImageName.jpg")

img_left_area = (0, 0, 400, 600)
img_right_area = (400, 0, 800, 600)

img_left = img.crop(img_left_area)
img_right = img.crop(img_right_area)

img_left.show()
img_right.show()

enter image description here

Coordinate System

The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Note that the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5).

Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper left corner given first. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

I know, this is an old question, but couldn't find the solution here. After some tries, I found out, that some added "<asp:UpdatePanel" had been the reason.

After (re)moving them, all works fine like before.

SQL JOIN, GROUP BY on three tables to get totals

Thank you very much for the replies!

Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:

1   39.00   9.00

You'll end up with:

1   78.00   48.00

Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.

After much struggling, I think that the following query returns what I need it to:

SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
  SELECT invoiceid, SUM(p.amount) amount
  FROM invoicepayments ip 
  LEFT JOIN payments p ON ip.paymentid = p.paymentid
  GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'

Would you guys concur?

How to resolve TypeError: Cannot convert undefined or null to object

Replace

if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged

with

if (obj === undefined) { return undefined;} // return undefined for undefined 
if (obj === null) { return null;} // null unchanged