Programs & Examples On #Tstringlist

TStringList is a RTL class whose purpose is to store and manipulate a list of strings. It is defined in Classes.pas

What is difference between XML Schema and DTD?

Similarities:

DTDs and Schemas both perform the same basic functions:

  • First, they both declare a laundry list of elements and attributes.
  • Second, both describe how those elements are grouped, nested or used within the XML. In other words, they declare the rules by which you are allowing someone to create an XML file within your workflow, and
  • Third, both DTDs and schemas provide methods for restricting, or forcing, the type or format of an element. For example, within the DTD or Schema you can force a date field to be written as 01/05/06 or 1/5/2006.

Differences:

  • DTDs are better for text-intensive applications, while schemas have several advantages for data-intensive workflows.

  • Schemas are written in XML and thusly follow the same rules, while DTDs are written in a completely different language.

Examples:

DTD:

<?xml version="1.0" encoding="UTF-8"?>
    <!ELEMENT employees (Efirstname, Elastname, Etitle, Ephone, Eemail)>
         <!ELEMENT Efirstname (#PCDATA)>
         <!ELEMENT Elastname (#PCDATA)>
         <!ELEMENT Etitle (#PCDATA)>
         <!ELEMENT Ephone (#PCDATA)>
         <!ELEMENT Eemail (#PCDATA)>

XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:od="urn:schemas-microsoft-com:officedata">
<xsd:element name="dataroot">
     <xsd:complexType>
          <xsd:sequence>
               <xsd:element ref="employees" minOccurs="0" maxOccurs="unbounded"/>
          </xsd:sequence>
          <xsd:attribute name="generated" type="xsd:dateTime"/>
      </xsd:complexType>
</xsd:element>
<xsd:element name="employees">
      <xsd:annotation>
           <xsd:appinfo>
               <od:index index-name="PrimaryKey" index-key="Employeeid " primary="yes"
                unique="yes" clustered="no"/>
          <od:index index-name="Employeeid" index-key="Employeeid " primary="no" unique="no"
           clustered="no"/>
     </xsd:appinfo>
</xsd:annotation>
     <xsd:complexType>
          <xsd:sequence>
               <xsd:element name="Elastname" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Etitle" minOccurs="0" od:jetType="text" od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Ephone" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Eemail" minOccurs="0" od:jetType="text"
               od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Ephoto" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
          </xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

Convert Map to JSON using Jackson

You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON

Virtual Serial Port for Linux

Would you be able to use a USB->RS232 adapter? I have a few, and they just use the FTDI driver. Then, you should be able to rename /dev/ttyUSB0 (or whatever gets created) as /dev/ttyS2 .

IOS - How to segue programmatically using swift

What you want to do is really important for unit testing. Basically you need to create a small local function in the view controller. Name the function anything, just include the performSegueWithIndentifier.

func localFunc() {
    println("we asked you to do it")
    performSegueWithIdentifier("doIt", sender: self)
}

Next change your utility class FBManager to include an initializer that takes an argument of a function and a variable to hold the ViewController's function that performs the segue.

public class UtilClass {

    var yourFunction : () -> ()

    init (someFunction: () -> ()) {
        self.yourFunction = someFunction
        println("initialized UtilClass")
    }

    public convenience init() {
        func dummyLog () -> () {
            println("no action passed")
        }
        self.init(dummyLog)
    }

    public func doThatThing() -> () {
        // the facebook login function
        println("now execute passed function")
        self.yourFunction()
        println("did that thing")
    }
}

(The convenience init allows you to use this in unit testing without executing the segue.)

Finally, where you have //todo: segue to the next view???, put something along the lines of:

self.yourFunction()

In your unit tests, you can simply invoke it as:

let f = UtilClass()
f.doThatThing()

where doThatThing is your fbsessionstatechange and UtilClass is FBManager.

For your actual code, just pass localFunc (no parenthesis) to the FBManager class.

Do you need to dispose of objects and set them to null?

I agree with the common answer here that yes you should dispose and no you generally shouldn't set the variable to null... but I wanted to point out that dispose is NOT primarily about memory management. Yes, it can help (and sometimes does) with memory management, but it's primary purpose is to give you deterministic releasing of scarce resources.

For example, if you open a hardware port (serial for example), a TCP/IP socket, a file (in exclusive access mode) or even a database connection you have now prevented any other code from using those items until they are released. Dispose generally releases these items (along with GDI and other "os" handles etc. which there are 1000's of available, but are still limited overall). If you don't call dipose on the owner object and explicitly release these resources, then try to open the same resource again in the future (or another program does) that open attempt will fail because your undisposed, uncollected object still has the item open. Of course, when the GC collects the item (if the Dispose pattern has been implemented correctly) the resource will get released... but you don't know when that will be, so you don't know when it's safe to re-open that resource. This is the primary issue Dispose works around. Of course, releasing these handles often releases memory too, and never releasing them may never release that memory... hence all the talk about memory leaks, or delays in memory clean up.

I have seen real world examples of this causing problems. For instance, I have seen ASP.Net web applications that eventually fail to connect to the database (albeit for short periods of time, or until the web server process is restarted) because the sql server 'connection pool is full'... i.e, so many connections have been created and not explicitly released in so short a period of time that no new connections can be created and many of the connections in the pool, although not active, are still referenced by undiposed and uncollected objects and so can't be reused. Correctly disposing the database connections where necessary ensures this problem doesn't happen (at least not unless you have very high concurrent access).

Request Permission for Camera and Library in iOS 10 - Info.plist

Swift 5 The easiest way to add permissions without having to do it programatically, is to open your info.plist file and select the + next to Information Property list. Scroll through the drop down list to the Privacy options and select Privacy Camera Usage Description for accessing camera, or Privacy Photo Library Usage Description for accessing the Photo Library. Fill in the String value on the right after you've made your selection, to include the text you would like displayed to your user when the alert pop up asks for permissions. Camera/Photo Library permission

What is a simple command line program or script to backup SQL server databases?

You could use a VB Script I wrote exactly for this purpose: https://github.com/ezrarieben/mssql-backup-vbs/

Schedule a task in the "Task Scheduler" to execute the script as you like and it'll backup the entire DB to a BAK file and save it wherever you specify.

How do I PHP-unserialize a jQuery-serialized form?

Simply do this

$get = explode('&', $_POST['seri']); // explode with and

foreach ($get as $key => $value) {
    $need[substr($value, 0 , strpos($value, '='))] =  substr(
        $value, 
        strpos( $value, '=' ) + 1 
    );
}

// access your query param name=ddd&email=aaaaa&username=wwwww&password=wwww&password=eeee
var_dump($need['name']);

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

A simple one liner:

$("#text").val( $("#text").val().replace(".", ":") );

Creating a new dictionary in Python

>>> dict.fromkeys(['a','b','c'],[1,2,3])


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I have decompiled Google Play services revision 14 library. I think there is a bug in com.google.android.gms.common.GooglePlayServicesUtil.class. The aforementioned string appears only in one place:

public static int isGooglePlayServicesAvailable(Context context) {
    PackageManager localPackageManager = context.getPackageManager();
    try {
        Resources localResources = context.getResources();
        localResources.getString(R.string.common_google_play_services_unknown_issue);
    } catch (Throwable localThrowable1) {
        Log.e("GooglePlayServicesUtil", "The Google Play services resources were not found. "
                + "Check your project configuration to ensure that the resources are included.");
    }
....

There is no R.class in com.google.android.gms.common package.

There is an import com.google.android.gms.R.string;, but no usage of string.something, so I guess this is the error - there should be import com.google.android.gms.R;.

Nevertheless the isGooglePlayServicesAvailable method works as intended (except of logging that warning), but there are other methods in that class, which uses unimported R.class, so there may be some other errors. Although banners in my application works fine...

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

How to print to console using swift playground?

In Xcode 6.3 and later (including Xcode 7 and 8), console output appears in the Debug area at the bottom of the playground window (similar to where it appears in a project). To show it:

  • Menu: View > Debug Area > Show Debug Area (??Y)

  • Click the middle button of the workspace-layout widget in the toolbar

    workspace layout widget

  • Click the triangle next to the timeline at the bottom of the window

    triangle for console

Anything that writes to the console, including Swift's print statement (renamed from println in Swift 2 beta) shows up there.


In earlier Xcode 6 versions (which by now you probably should be upgrading from anyway), show the Assistant editor (e.g. by clicking the little circle next to a bit in the output area). Console output appears there.

When to use %r instead of %s in Python?

This is a version of Ben James's answer, above:

>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>> 
>>> 
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>> 
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>

When I ran this, it helped me see the usefulness of %r.

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

I found an issue with Diagram and Schema in SQL-Server 2016 that could be useful to the subject. I was editing diagram (related to, and with lot of tables of, the "sales" schema) and added a new table, BUT forgot to declare it schema, so it was with the default "dbo". Then when I returned to, and opened up, the schema "sales" and tried to add an existent table... Bluf! THAT Triggered exactly the same error described in that thread. I even tried the workaround (drag the table) but it didn't work. Suddenly I noticed that the schema was incorrect, I updated it, tried again, and Eureka! the problem was immediately away... Regards.

How to get back to most recent version in Git?

With Git 2.23+ (August 2019), the best practice would be to use git switch instead of the confusing git checkout command.

To create a new branch based on an older version:

git switch -c temp_branch HEAD~2

To go back to the current master branch:

git switch master

What is the difference between UTF-8 and Unicode?

Unicode only define code points, that is, a number which represents a character. How you store these code points in memory depends of the encoding that you are using. UTF-8 is one way of encoding Unicode characters, among many others.

Is this a good way to clone an object in ES6?

You can do it like this as well,

let copiedData = JSON.parse(JSON.stringify(data));

How to reset form body in bootstrap modal box?

If you using ajax to load modal's body such way and want to be able to reload it's content

<a data-toggle="modal" data-target="#myModal" href="./add">Add</a>
<a data-toggle="modal" data-target="#myModal" href="./edit/id">Modify</a>

<div id="myModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Content will be loaded here -->
        </div>
    </div>
</div>

use

<script>
    $(function() {
        $('.modal').on('hidden.bs.modal', function(){
            $(this).removeData('bs.modal');
        });
    });
</script>

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How to format numbers as currency string?

Short and fast solution (works everywhere!)

(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');  // 12,345.67

The idea behind this solution is replacing matched sections with first match and comma, i.e. '$&,'. The matching is done using lookahead approach. You may read the expression as "match a number if it is followed by a sequence of three number sets (one or more) and a dot".

TESTS:

1        --> "1.00"
12       --> "12.00"
123      --> "123.00"
1234     --> "1,234.00"
12345    --> "12,345.00"
123456   --> "123,456.00"
1234567  --> "1,234,567.00"
12345.67 --> "12,345.67"

DEMO: http://jsfiddle.net/hAfMM/9571/


Extended short solution

You can also extend the prototype of Number object to add additional support of any number of decimals [0 .. n] and the size of number groups [0 .. x]:

/**
 * Number.prototype.format(n, x)
 * 
 * @param integer n: length of decimal
 * @param integer x: length of sections
 */
Number.prototype.format = function(n, x) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};

1234..format();           // "1,234"
12345..format(2);         // "12,345.00"
123456.7.format(3, 2);    // "12,34,56.700"
123456.789.format(2, 4);  // "12,3456.79"

DEMO / TESTS: http://jsfiddle.net/hAfMM/435/


Super extended short solution

In this super extended version you may set different delimiter types:

/**
 * Number.prototype.format(n, x, s, c)
 * 
 * @param integer n: length of decimal
 * @param integer x: length of whole part
 * @param mixed   s: sections delimiter
 * @param mixed   c: decimal delimiter
 */
Number.prototype.format = function(n, x, s, c) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
        num = this.toFixed(Math.max(0, ~~n));

    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};

12345678.9.format(2, 3, '.', ',');  // "12.345.678,90"
123456.789.format(4, 4, ' ', ':');  // "12 3456:7890"
12345678.9.format(0, 3, '-');       // "12-345-679"

DEMO / TESTS: http://jsfiddle.net/hAfMM/612/

Is it possible to use JS to open an HTML select to show its option list?

This is very late, but I thought it could be useful to someone should they reference this question. I beleive the below JS will do what is asked.

<script>     
         $(document).ready(function()
           {
          document.getElementById('select').size=3;
           });
    </script> 

Bulk Record Update with SQL

Your approach is OK

Maybe slightly clearer (to me anyway!)

UPDATE
  T1
SET
  [Description] = t2.[Description]
FROM
   Table1 T1
   JOIN
   [Table2] t2 ON t2.[ID] = t1.DescriptionID

Both this and your query should run the same performance wise because it is the same query, just laid out differently.

Python: importing a sub-package or sub-module

If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?

In version 2, instead of

from module import attribute1

you can do

attribute1 = module.attribute1

Ignoring directories in Git repositories on Windows

You can create the ".gitignore" file with the contents:

*
!.gitignore

It works for me.

Javascript/Jquery Convert string to array

Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:

var traingIds = ${triningIdArray};

not

var traingIds = "${triningIdArray}";

How to cd into a directory with space in the name?

try

DOCS="/cygdrive/c/Users/my\ dir/Documents";

cd "$DOCS"

How to measure elapsed time

There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime() and TimeUnit.NANOSECONDS as the time unit. Why should I do this? Well, it is because System.nanoTime() method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

For the same reason, it is recommended to avoid the use of the System.currentTimeMillis() method for measuring elapsed time. This method returns the wall-clock time, which may change based on many factors. This will be negative for your measurements.

Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

So here you have one solution based on the System.nanoTime() method, another one using Guava, and the final one Apache Commons Lang

public class TimeBenchUtil
{
    public static void main(String[] args) throws InterruptedException
    {
        stopWatch();
        stopWatchGuava();
        stopWatchApacheCommons();
    }

    public static void stopWatch() throws InterruptedException
    {
        long endTime, timeElapsed, startTime = System.nanoTime();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        endTime = System.nanoTime();

        // get difference of two nanoTime values
        timeElapsed = endTime - startTime;

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchGuava() throws InterruptedException
    {
        // Creates and starts a new stopwatch
        Stopwatch stopwatch = Stopwatch.createStarted();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);
        /* ... the code being measured ends ... */

        stopwatch.stop(); // optional

        // get elapsed time, expressed in milliseconds
        long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchApacheCommons() throws InterruptedException
    {
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        stopwatch.stop();    // Optional

        long timeElapsed = stopwatch.getNanoTime();

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }
}

How can I URL encode a string in Excel VBA?

Since office 2013 use this inbuilt function here.

If before office 2013

Function encodeURL(str As String)
Dim ScriptEngine As ScriptControl
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"

ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"
Dim encoded As String


encoded = ScriptEngine.Run("encode", str)
encodeURL = encoded
End Function

Add Microsoft Script Control as reference and you are done.

Same as last post just complete function ..works!

How to delete columns in pyspark dataframe

You can delete column like this:

df.drop("column Name).columns

In your case :

df.drop("id").columns

If you want to drop more than one column you can do:

dfWithLongColName.drop("ORIGIN_COUNTRY_NAME", "DEST_COUNTRY_NAME")

Python "extend" for a dictionary

Have you tried using dictionary comprehension with dictionary mapping:

a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}

c = {**a, **b}
# c = {"a": 1, "b": 2, "c": 3, "d": 4}

Another way of doing is by Using dict(iterable, **kwarg)

c = dict(a, **b)
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

In Python 3.9 you can add two dict using union | operator

# use the merging operator |
c = a | b
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

How to create my json string by using C#?

The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....

About the libraries you could use are.

And there could be many more, but that are what I've used

About the json I don't now maybe something like this

public class GetQuestions
{
    public List<Student> Questions { get; set; }
}

public class Student
{
    public string Code { get; set; }
    public string Questions { get; set; }
}

void Main()
{
    var gq = new GetQuestions
    {
        Questions = new List<Student>
        {
            new Student {Code = "s1", Questions = "Q1,Q2"},
            new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
            new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
            new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
        }
    };

    //Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
    JsonConvert.SerializeObject(gq).Dump();
}

Linqpad

and the result is this

{
     "Questions":[
        {"Code":"s1","Questions":"Q1,Q2"},
        {"Code":"s2","Questions":"Q1,Q2,Q3"},
        {"Code":"s3","Questions":"Q1,Q2,Q4"},
        {"Code":"s4","Questions":"Q1,Q2,Q5"}
      ]
 }

Yes I know the json is different, but the json that you want with dictionary.

void Main()
{
    var f = new Foo
    {
        GetQuestions = new Dictionary<string, string>
                {
                    {"s1", "Q1,Q2"},
                    {"s2", "Q1,Q2,Q3"},
                    {"s3", "Q1,Q2,Q4"},
                    {"s4", "Q1,Q2,Q4,Q6"},
                }
    };

    JsonConvert.SerializeObject(f).Dump();
}

class Foo
{
    public Dictionary<string, string> GetQuestions { get; set; }
}

And with Dictionary is as you want it.....

{
      "GetQuestions":
       {
              "s1":"Q1,Q2",
              "s2":"Q1,Q2,Q3",
              "s3":"Q1,Q2,Q4",
              "s4":"Q1,Q2,Q4,Q6"
       }
 }

CSS - display: none; not working

In the HTML source provided, the element #tfl has an inline style "display:block". Inline style will always override stylesheets styles…

Then, you have some options (while as you said you can't modify the html code nor using javascript):

  • force display:none with !important rule (not recommended)
  • put the div offscreen with theses rules :

    #tfl {
        position: absolute;
        left: -9999px;
    }
    

What is a predicate in c#?

The following code can help you to understand some real world use of predicates (Combined with named iterators).

namespace Predicate
{
    class Person
    {
        public int Age { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            foreach (Person person in OlderThan(18))
            {
                Console.WriteLine(person.Age);
            }
        }

        static IEnumerable<Person> OlderThan(int age)
        {
            Predicate<Person> isOld = x => x.Age > age;
            Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };

            foreach (Person person in persons)
                if (isOld(person)) yield return person;
        }
    }
}

Add a column to existing table and uniquely number them on MS SQL Server

for oracle you could do something like below

alter table mytable add (myfield integer);

update mytable set myfield = rownum;

Accessing the logged-in user in a template

{{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

Insert null/empty value in sql datetime column by default

you can use like this:

string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");

Printing out all the objects in array list

You have to define public String toString() method in your Student class. For example:

public String toString() {
  return "Student: " + studentName + ", " + studentNo;
}

Determining whether an object is a member of a collection in VBA

i used this code to convert array to collection and back to array to remove duplicates, assembled from various posts here (sorry for not giving properly credit).

Function ArrayRemoveDups(MyArray As Variant) As Variant
Dim nFirst As Long, nLast As Long, i As Long
Dim item As Variant, outputArray() As Variant
Dim Coll As New Collection

'Get First and Last Array Positions
nFirst = LBound(MyArray)
nLast = UBound(MyArray)
ReDim arrTemp(nFirst To nLast)
i = nFirst
'convert to collection
For Each item In MyArray
    skipitem = False
    For Each key In Coll
        If key = item Then skipitem = True
    Next
    If skipitem = False Then Coll.Add (item)
Next item
'convert back to array
ReDim outputArray(0 To Coll.Count - 1)
For i = 1 To Coll.Count
    outputArray(i - 1) = Coll.item(i)
Next
ArrayRemoveDups = outputArray
End Function

What does the ">" (greater-than sign) CSS selector mean?

The greater sign ( > ) selector in CSS means that the selector on the right is a direct descendant / child of whatever is on the left.

An example:

article > p { }

Means only style a paragraph that comes after an article.

Function pointer as a member of a C struct

My guess is that part of your problem is the parameter lists not matching.

int (* length)();

and

int length(PString * self)

are not the same. It should be int (* length)(PString *);.

...woah, it's Jon!

Edit: and, as mentioned below, your struct pointer is never set to point to anything. The way you're doing it would only work if you were declaring a plain struct, not a pointer.

str = (PString *)malloc(sizeof(PString));

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

This will also work

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

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

Refer to the following blog "how to kill tomcat without have to restart your computer"

http://stanicblog.blogspot.fr/2012/01/how-to-kill-apache-tomcat-without.html

Hope this will help someone in the future.

In PANDAS, how to get the index of a known value?

I think this may help you , both index and columns of the values.

value you are looking for is not duplicated:

poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
value=poz.iloc[0,0]
index=poz.index.item()
column=poz.columns.item()

you can get its index and column

duplicated:

matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]: 
   f    h
q  1  1.0
g  1  NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]

you will get a list

Difference between app.use and app.get in express.js

Difference between app.use & app.get:

app.use ? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.

app.get ? It is only for handling GET HTTP requests.

Now, there is a confusion between app.use & app.all. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests. But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.

  1. app.use() ? It takes only one callback.
    app.all() ? It can take multiple callbacks.

  2. app.use() will only see whether url starts with specified path.
    But, app.all() will match the complete path.

For example,

app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject

app.all( "/book" , handler);
// will match /book
// won't match /book/author   
// won't match /book/subject    

app.all( "/book/*" , handler);
// won't match /book        
// will match /book/author
// will match /book/subject
  1. next() call inside the app.use() will call either the next middleware or any route handler, but next() call inside app.all() will invoke the next route handler (app.all(), app.get/post/put... etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.

How can I go back/route-back on vue-router?

You can use Programmatic Navigation.In order to go back, you use this:

router.go(n) 

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

Notepad++ - How can I replace blank lines

By the way, in Notepad++ there's built-in plugin that can handle this: TextFX -> TextFX Edit -> Delete Blank Lines (first press CTRL+A to select all).

Make outer div be automatically the same height as its floating content

You may want to try self-closing floats, as detailed on http://www.sitepoint.com/simple-clearing-of-floats/

So perhaps try either overflow: auto (usually works), or overflow: hidden, as alex said.

How could I create a list in c++?

You should really use the standard List class. Unless, of course, this is a homework question, or you want to know how lists are implemented by STL.

You'll find plenty of simple tutorials via google, like this one. If you want to know how linked lists work "under the hood", try searching for C list examples/tutorials rather than C++.

Multiple HttpPost method in Web API controller

It is Possible to add Multiple Get and Post methods in the same Web API Controller. Here default Route is Causing the Issue. Web API checks for Matching Route from Top to Bottom and Hence Your Default Route Matches for all Requests. As per default route only one Get and Post Method is possible in one controller. Either place the following code on top or Comment Out/Delete Default Route

    config.Routes.MapHttpRoute("API Default", 
                               "api/{controller}/{action}/{id}",
                               new { id = RouteParameter.Optional });

Android Emulator sdcard push error: Read-only file system

sometimes this can cause of a very simple reason, go to your list in eclipse and check whether you have set SDCard size

Is there any way to debug chrome in any IOS device

If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.

https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html

Chrome for iOS Console

MD5 is 128 bits but why is it 32 characters?

I wanted summerize some of the answers into one post.

First, don't think of the MD5 hash as a character string but as a hex number. Therefore, each digit is a hex digit (0-15 or 0-F) and represents four bits, not eight.

Taking that further, one byte or eight bits are represented by two hex digits, e.g. b'1111 1111' = 0xFF = 255.

MD5 hashes are 128 bits in length and generally represented by 32 hex digits.

SHA-1 hashes are 160 bits in length and generally represented by 40 hex digits.

For the SHA-2 family, I think the hash length can be one of a pre-determined set. So SHA-512 can be represented by 128 hex digits.

Again, this post is just based on previous answers.

Quotation marks inside a string

You need to escape the quotation marks:

String name = "\"john\"";

How to pass a form input value into a JavaScript function

It might be cleaner to take out your inline click handler and do it like this:

$(document).ready(function() {
    $('#button-id').click(function() {
      foo($('#formValueId').val());
    });
});

How can I debug git/git-shell related problems?

For older git versions (1.8 and before)

I could find no suitable way to enable SSH debugging in an older git and ssh versions. I looked for environment variables using ltrace -e getenv ... and couldn't find any combination of GIT_TRACE or SSH_DEBUG variables that would work.

Instead here's a recipe to temporarily inject 'ssh -v' into the git->ssh sequence:

$ echo '/usr/bin/ssh -v ${@}' >/tmp/ssh
$ chmod +x /tmp/ssh
$ PATH=/tmp:${PATH} git clone ...
$ rm -f /tmp/ssh

Here's output from git version 1.8.3 with ssh version OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013 cloning a github repo:

$ (echo '/usr/bin/ssh -v ${@}' >/tmp/ssh; chmod +x /tmp/ssh; PATH=/tmp:${PATH} \
   GIT_TRACE=1 git clone https://github.com/qneill/cliff.git; \
   rm -f /tmp/ssh) 2>&1 | tee log
trace: built-in: git 'clone' 'https://github.com/qneill/cliff.git'
trace: run_command: 'git-remote-https' 'origin' 'https://github.com/qneill/cliff.git'
Cloning into 'cliff'...
OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /home/q.neill/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to github.com ...
...
Transferred: sent 4120, received 724232 bytes, in 0.2 seconds
Bytes per second: sent 21590.6, received 3795287.2
debug1: Exit status 0
trace: run_command: 'rev-list' '--objects' '--stdin' '--not' '--all'
trace: exec: 'git' 'rev-list' '--objects' '--stdin' '--not' '--all'
trace: built-in: git 'rev-list' '--objects' '--stdin' '--not' '--all'

Multiple argument IF statement - T-SQL

Not sure what the problem is, this seems to work just fine?

DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        Select 'This works just fine' as Msg
    END
Else
    BEGIN
    Select 'No Lol' as Msg
    END

How to give a user only select permission on a database

create LOGIN guest WITH PASSWORD='guest@123', CHECK_POLICY = OFF;

Be sure when you want to exceute the following

DENY VIEW ANY DATABASE TO guest;

ALTER AUTHORIZATION ON DATABASE::BiddingSystemDB TO guest

Selected Database should be Master

Global Angular CLI version greater than local version

I'm not fluent in English

but if I understand the problem, is it that locally in the project you have an older version of CLI than globally?

And would you like to use this global newer instead of the local older one?

If so, a very simple method is enough to run in the project directory npm link @angular/cli

more in the subject on the page: https://docs.npmjs.com/cli/link

Link vs compile vs controller

A directive allows you to extend the HTML vocabulary in a declarative fashion for building web components. The ng-app attribute is a directive, so is ng-controller and all of the ng- prefixed attributes. Directives can be attributes, tags or even class names, comments.

How directives are born (compilation and instantiation)

Compile: We’ll use the compile function to both manipulate the DOM before it’s rendered and return a link function (that will handle the linking for us). This also is the place to put any methods that need to be shared around with all of the instances of this directive.

link: We’ll use the link function to register all listeners on a specific DOM element (that’s cloned from the template) and set up our bindings to the page.

If set in the compile() function they would only have been set once (which is often what you want). If set in the link() function they would be set every time the HTML element is bound to data in the object.

<div ng-repeat="i in [0,1,2]">
    <simple>
        <div>Inner content</div>
    </simple>
</div>

app.directive("simple", function(){
   return {
     restrict: "EA",
     transclude:true,
     template:"<div>{{label}}<div ng-transclude></div></div>",        
     compile: function(element, attributes){  
     return {
             pre: function(scope, element, attributes, controller, transcludeFn){

             },
             post: function(scope, element, attributes, controller, transcludeFn){

             }
         }
     },
     controller: function($scope){

     }
   };
});

Compile function returns the pre and post link function. In the pre link function we have the instance template and also the scope from the controller, but yet the template is not bound to scope and still don't have transcluded content.

Post link function is where post link is the last function to execute. Now the transclusion is complete, the template is linked to a scope, and the view will update with data bound values after the next digest cycle. The link option is just a shortcut to setting up a post-link function.

controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.

You have to specify the name of the directive to be required – It should be bound to same element or its parent. The name can be prefixed with:

? – Will not raise any error if a mentioned directive does not exist.
^ – Will look for the directive on parent elements, if not available on the same element.

Use square bracket [‘directive1', ‘directive2', ‘directive3'] to require multiple directives controller.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope, $element) {
});

app.directive('parentDirective', function() {
  return {
    restrict: 'E',
    template: '<child-directive></child-directive>',
    controller: function($scope, $element){
      this.variable = "Hi Vinothbabu"
    }
  }
});

app.directive('childDirective', function() {
  return {
    restrict:  'E',
    template: '<h1>I am child</h1>',
    replace: true,
    require: '^parentDirective',
    link: function($scope, $element, attr, parentDirectCtrl){
      //you now have access to parentDirectCtrl.variable
    }
  }
});

Unable to add window -- token null is not valid; is your activity running?

I was getting this error while trying to show DatePicker from Fragment.

I changed

val datePickerDialog = DatePickerDialog(activity!!.applicationContext, ...)

to

val datePickerDialog = DatePickerDialog(requireContext(), ...)

and it worked just fine.

How do I call a SQL Server stored procedure from PowerShell?

I include invoke-sqlcmd2.ps1 and write-datatable.ps1 from http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/01/use-powershell-to-collect-server-data-and-write-to-sql.aspx. Calls to run SQL commands take the form:
Invoke-sqlcmd2 -ServerInstance "<sql-server>" -Database <DB> -Query "truncate table <table>"
An example of writing the contents of DataTable variables to a SQL table looks like:
$logs = (get-item SQLSERVER:\sql\<server_path>).ReadErrorLog() Write-DataTable -ServerInstance "<sql-server>" -Database "<DB>" -TableName "<table>" -Data $logs
I find these useful when doing SQL Server database-related PowerShell scripts as the resulting scripts are clean and readable.

Is there a way of setting culture for a whole application? All current threads and new threads?

For .NET 4.5 and higher, you should use:

var culture = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;

PostgreSQL function for last inserted ID

( tl;dr : goto option 3: INSERT with RETURNING )

Recall that in postgresql there is no "id" concept for tables, just sequences (which are typically but not necessarily used as default values for surrogate primary keys, with the SERIAL pseudo-type).

If you are interested in getting the id of a newly inserted row, there are several ways:


Option 1: CURRVAL(<sequence name>);.

For example:

  INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
  SELECT currval('persons_id_seq');

The name of the sequence must be known, it's really arbitrary; in this example we assume that the table persons has an id column created with the SERIAL pseudo-type. To avoid relying on this and to feel more clean, you can use instead pg_get_serial_sequence:

  INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
  SELECT currval(pg_get_serial_sequence('persons','id'));

Caveat: currval() only works after an INSERT (which has executed nextval() ), in the same session.


Option 2: LASTVAL();

This is similar to the previous, only that you don't need to specify the sequence name: it looks for the most recent modified sequence (always inside your session, same caveat as above).


Both CURRVAL and LASTVAL are totally concurrent safe. The behaviour of sequence in PG is designed so that different session will not interfere, so there is no risk of race conditions (if another session inserts another row between my INSERT and my SELECT, I still get my correct value).

However they do have a subtle potential problem. If the database has some TRIGGER (or RULE) that, on insertion into persons table, makes some extra insertions in other tables... then LASTVAL will probably give us the wrong value. The problem can even happen with CURRVAL, if the extra insertions are done intto the same persons table (this is much less usual, but the risk still exists).


Option 3: INSERT with RETURNING

INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John') RETURNING id;

This is the most clean, efficient and safe way to get the id. It doesn't have any of the risks of the previous.

Drawbacks? Almost none: you might need to modify the way you call your INSERT statement (in the worst case, perhaps your API or DB layer does not expect an INSERT to return a value); it's not standard SQL (who cares); it's available since Postgresql 8.2 (Dec 2006...)


Conclusion: If you can, go for option 3. Elsewhere, prefer 1.

Note: all these methods are useless if you intend to get the last inserted id globally (not necessarily by your session). For this, you must resort to SELECT max(id) FROM table (of course, this will not read uncommitted inserts from other transactions).

Conversely, you should never use SELECT max(id) FROM table instead one of the 3 options above, to get the id just generated by your INSERT statement, because (apart from performance) this is not concurrent safe: between your INSERT and your SELECT another session might have inserted another record.

Auto start node.js server on boot

This isn't something to configure in node.js at all, this is purely OS responsibility (Windows in your case). The most reliable way to achieve this is through a Windows Service.

There's this super easy module that installs a node script as a windows service, it's called node-windows (npm, github, documentation). I've used before and worked like a charm.

var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

p.s.

I found the thing so useful that I built an even easier to use wrapper around it (npm, github).

Installing it:

npm install -g qckwinsvc

Installing your service:

> qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed

Uninstalling your service:

> qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled

shorthand If Statements: C#

Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:

var redirectUrl =
      status == LoginStatusEnum.Success ? "/SecretPage"
    : status == LoginStatusEnum.Failure ? "/LoginFailed"
    : status == LoginStatusEnum.Sms ? "/2-StepSms"
    : status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
    : "/404-Error";

instead of

string redirectUrl;
switch (status)
{
    case LoginStatusEnum.Success:
        redirectUrl = "/SecretPage";
        break;
    case LoginStatusEnum.Failure:
        redirectUrl = "/LoginFailed";
        break;
    case LoginStatusEnum.Sms:
        redirectUrl = "/2-StepSms";
        break;
    case LoginStatusEnum.EmailNotConfirmed:
        redirectUrl = "/EmailNotConfirmed";
        break;
    default:
        redirectUrl = "/404-Error";
        break;
}

Using Cygwin to Compile a C program; Execution error

If you are not comfortable with bash, you can continue to work in a standard windows command (i.e. DOS) shell.

For this to work you must add C:\cygwin\bin (or your local alternative) to the Windows PATH variable.

With this done, you may: 1) Open a command (DOS) shell 2) Change the directory to the location of your code (c:, then cd path\to\file) 3) gcc myProgram.c -o myProgram

As mentioned in nik's response, the "Using Cygwin" documentation is a great place to learn more.

HTML 'td' width and height

The width attribute of <td> is deprecated in HTML 5.

Use CSS. e.g.

 <td style="width:100px">

in detail, like this:

<table >
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td style="width:70%">January</td>
    <td style="width:30%">$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

new Date() is working in Chrome but not Firefox

I have used following date format and it's working in all browser.

var target_date = new Date("Jul 17, 2015 16:55:22").getTime();

var days, hours, minutes, seconds;

var countdown = document.getElementById("countdown");

remaining = setInterval(function () {

    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;
    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;
    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);
    countdown.innerHTML = "<b>"+days + " day, " + hours + " hour, "
        + minutes + " minute, " + seconds + " second.</b>";  
}, 1000);

laravel 5.5 The page has expired due to inactivity. Please refresh and try again

If you have already included the CSRF token in your form. Then you are getting the error page possibly because of cache data in your form.

Open your terminal/command prompt and run these commands in your project root.

  1. php artisan cache:clear
  2. php artisan config:clear
  3. php artisan route:clear
  4. php artisan view:clear,

Also try to clear the browser cache along with running these commands.

Submit form after calling e.preventDefault()

came across the same prob and found no straight solution to it on the forums etc. Finally the following solution worked perfectly for me: simply implement the following logic inside your event handler function for the form 'submit' Event:

document.getElementById('myForm').addEventListener('submit', handlerToTheSubmitEvent);

function handlerToTheSubmitEvent(e){
    //DO NOT use e.preventDefault();
   
    /*
    your form validation logic goes here
    */

    if(allInputsValidatedSuccessfully()){
         return true;
     }
     else{
         return false; 
     }
}

SIMPLE AS THAT; NOTE: when a 'false' is returned from the handler of the form 'submit' event, the form is not submitted to the URI specified in the action attribute of your html markup; until and unless a 'true' is returned by the handler; and as soon as all your input fields are validated a 'true' will be returned by the Event handler, and your form is gonna be submitted;

ALSO NOTE THAT: the function call inside the if() condition is basically your own implementation of ensuring that all the fields are validated and consequently a 'true' must be returned from there otherwise 'false'

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.

How to set session timeout in web.config

If it's not working from web.config, you need to set it from IIS.

How to disable the resize grabber of <textarea>?

Just use resize: none

textarea {
   resize: none;
}

You can also decide to resize your textareas only horizontal or vertical, this way:

textarea { resize: vertical; }

textarea { resize: horizontal; }

Finally, resize: both enables the resize grabber.

Unable to find velocity template resources

I put my .vm under the src/main/resources/templates, then the code is :

Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init( p );       
VelocityContext context = new VelocityContext();           
Template template = Velocity.getTemplate("templates/my.vm");

this works in web project.

In eclipse Velocity.getTemplate("my.vm") works since velocity will look for the .vm file in src/main/resources/ or src/main/resources/templates, but in web project, we have to use Velocity.getTemplate("templates/my.vm");

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Using the latest 7.x Tomcat (currently 7.0.69) solved the problem for me.

We did also try a workaround in a old eclipse bug, maybe that did it's part to solve the problem, too?

https://bugs.eclipse.org/bugs/show_bug.cgi?id=67414

Workaround:

  • Window->Preferences->Java->Installed JREs
  • Uncheck selected JRE
  • Click OK (this step may be optional?)
  • Check JRE again

How to manually reload Google Map with JavaScript

Yes, you can 'refresh' a Google Map like this:

google.maps.event.trigger(map, 'resize');

This basically sends a signal to your map to redraw it.

Hope that helps!

How do you convert a jQuery object into a string?

No need to clone and add to the DOM to use .html(), you can do:

$('#item-of-interest').wrap('<div></div>').html()

How to temporarily exit Vim and go back

If you are on a Unix system, Ctrl + Z will suspend Vim and give you a shell.

Type fg to go back. Note that Vim creates a swap file while editing, and suspending Vim wouldn't delete that file (you aren't exiting Vim after all). On dumb terminals, this method was pretty standard for edit-compile-edit cycles using vi. I just found out that for me, gVim minimizes on typing Z.

Html.DropdownListFor selected value not being set

You should forget the class

SelectList

Use this in your Controller:

var customerTypes = new[] 
{ 
    new SelectListItem(){Value = "all", Text= "All"},
    new SelectListItem(){Value = "business", Text= "Business"},
    new SelectListItem(){Value = "private", Text= "Private"},
};

Select the value:

var selectedCustomerType = customerTypes.FirstOrDefault(d => d.Value == "private");
if (selectedCustomerType != null)
    selectedCustomerType.Selected = true;

Add the list to the ViewData:

ViewBag.CustomerTypes = customerTypes;

Use this in your View:

@Html.DropDownList("SectionType", (SelectListItem[])ViewBag.CustomerTypes)

-

More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

git command to move a folder inside another

I had a similar problem with git mv where I wanted to move the contents of one folder into an existing folder, and ended up with this "simple" script:

pushd common; for f in $(git ls-files); do newdir="../include/$(dirname $f)"; mkdir -p $newdir; git mv $f $newdir/$(basename "$f"); done; popd

Explanation

  • git ls-files: Find all files (in the common folder) checked into git
  • newdir="../include/$(dirname $f)"; mkdir -p $newdir;: Make a new folder inside the include folder, with the same directory structure as common
  • git mv $f $newdir/$(basename "$f"): Move the file into the newly created folder

The reason for doing this is that git seems to have problems moving files into existing folders, and it will also fail if you try to move a file into a non-existing folder (hence mkdir -p).

The nice thing about this approach is that it only touches files that are already checked in to git. By simply using git mv to move an entire folder, and the folder contains unstaged changes, git will not know what to do.

After moving the files you might want to clean the repository to remove any remaining unstaged changes - just remember to dry-run first!

git clean -fd -n

VBA for clear value in specific range of cell and protected cell from being wash away formula

Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:

  1. Ctrl-G
  2. A1:X50 Enter
  3. Delete

Unless you have to do this very often, entering and then triggering the VBAcode is more effort.

And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S to select Goto Special and here select Formulas or Values.

Serialize an object to string

[VB]

Public Function XmlSerializeObject(ByVal obj As Object) As String

    Dim xmlStr As String = String.Empty

    Dim settings As New XmlWriterSettings()
    settings.Indent = False
    settings.OmitXmlDeclaration = True
    settings.NewLineChars = String.Empty
    settings.NewLineHandling = NewLineHandling.None

    Using stringWriter As New StringWriter()
        Using xmlWriter__1 As XmlWriter = XmlWriter.Create(stringWriter, settings)

            Dim serializer As New XmlSerializer(obj.[GetType]())
            serializer.Serialize(xmlWriter__1, obj)

            xmlStr = stringWriter.ToString()
            xmlWriter__1.Close()
        End Using

        stringWriter.Close()
    End Using

    Return xmlStr.ToString
End Function

Public Function XmlDeserializeObject(ByVal data As [String], ByVal objType As Type) As Object

    Dim xmlSer As New System.Xml.Serialization.XmlSerializer(objType)
    Dim reader As TextReader = New StringReader(data)

    Dim obj As New Object
    obj = DirectCast(xmlSer.Deserialize(reader), Object)
    Return obj
End Function

[C#]

public string XmlSerializeObject(object obj)
{
    string xmlStr = String.Empty;
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = false;
    settings.OmitXmlDeclaration = true;
    settings.NewLineChars = String.Empty;
    settings.NewLineHandling = NewLineHandling.None;

    using (StringWriter stringWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
        {
            XmlSerializer serializer = new XmlSerializer( obj.GetType());
            serializer.Serialize(xmlWriter, obj);
            xmlStr = stringWriter.ToString();
            xmlWriter.Close();
        }
    }
    return xmlStr.ToString(); 
}

public object XmlDeserializeObject(string data, Type objType)
{
    XmlSerializer xmlSer = new XmlSerializer(objType);
    StringReader reader = new StringReader(data);

    object obj = new object();
    obj = (object)(xmlSer.Deserialize(reader));
    return obj;
}

How to write a unit test for a Spring Boot Controller endpoint

Adding @WebAppConfiguration (org.springframework.test.context.web.WebAppConfiguration) annotation to your DemoApplicationTests class will work.

Checking to see if a DateTime variable has had a value assigned

I generally prefer, where possible, to use the default value of value types to determine whether they've been set. This obviously isn't possible all the time, especially with ints - but for DateTimes, I think reserving the MinValue to signify that it hasn't been changed is fair enough. The benefit of this over nullables is that there's one less place where you'll get a null reference exception (and probably lots of places where you don't have to check for null before accessing it!)

Create a new database with MySQL Workbench

This answer is for Ubuntu users looking for a solution without writing SQL queries.

The following is the initial screen you'll get after opening it

Initial screen

In the top right, where it says Administration, click in the arrow to the right

From Administration to Schemas

This will show Schema (instead of Administration) and it's possible to see a sys database.

Schema menu with databases

Right click in the grey area after functions and click Create Schema...

Create Schema

This will open the following where I'm creating a table named StackOverflow_db

Create new Schema

Clicking in the bottom right button that says "Apply",

Create a new Schema in Workbench

And in this new view click in "Apply" too. In the end you'll get a database called StackOverflow_db

Database created

How can I get the current user directory?

Try:

System.Environment.GetEnvironmentVariable("USERPROFILE");

Edit:

If the version of .NET you are using is 4 or above, you can use the Environment.SpecialFolder enumeration:

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

Why is Visual Studio 2013 very slow?

There is a good workaround for this solution if you are experiencing slowness in rendering the .cs files and .cshtml files.

Just close all the files opened so that the cache gets cleared and open the required files again.

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

\n or \n in php echo not print

Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:

echo '<p>' . $unit1 . "</p>\n";

PS: One clarification, single quotes strings do accept two escape sequences:

  • \' when you want to use single quote inside single quoted strings
  • \\ when you want to use backslash literally

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

scale Image in an UIButton to AspectFit?

The easiest way to programmatically set a UIButton imageView in aspect fit mode :

Swift

button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageView?.contentMode = .scaleAspectFit

Objective-C

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.imageView.contentMode = UIViewContentModeScaleAspectFit;

Note: You can change .scaleAspectFit (UIViewContentModeScaleAspectFit) to .scaleAspectFill (UIViewContentModeScaleAspectFill) to set an aspect fill mode

How do I use regular expressions in bash scripts?

You need spaces around the operator =~

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi

HTML-parser on Node.js

Try https://github.com/tmpvar/jsdom - you give it some HTML and it gives you a DOM.

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Another way is to use TRANSLATE:

TRANSLATE (col_name, 'x'||CHR(10)||CHR(13), 'x')

The 'x' is any character that you don't want translated to null, because TRANSLATE doesn't work right if the 3rd parameter is null.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?

It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/

I've created the boot entry that disables HyperV and it's working

What does "all" stand for in a makefile?

Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

int main(int argc, char *argv[]){

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

How to declare a global variable in C++

Not sure if this is correct in any sense but this seems to work for me.

someHeader.h
inline int someVar;

I don't have linking/multiple definition issues and it "just works"... ;- )

It's quite handy for "quick" tests... Try to avoid global vars tho, because every says so... ;- )

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

/* I have done it this way, and also tested it */

Step 1 = Register custom cell class (in case of prototype cell in table) or nib (in case of custom nib for custom cell) for table like this in viewDidLoad method:

[self.yourTableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCell"];

OR

[self.yourTableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];

Step 2 = Use UITableView's "dequeueReusableCellWithIdentifier: forIndexPath:" method like this (for this, you must register class or nib) :

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];

            cell.imageViewCustom.image = nil; // [UIImage imageNamed:@"default.png"];
            cell.textLabelCustom.text = @"Hello";

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                // retrive image on global queue
                UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:     [NSURL URLWithString:kImgLink]]];

                dispatch_async(dispatch_get_main_queue(), ^{

                    CustomTableViewCell * cell = (CustomTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
                  // assign cell image on main thread
                    cell.imageViewCustom.image = img;
                });
            });

            return cell;
        }

What are these attributes: `aria-labelledby` and `aria-hidden`

ARIA does not change functionality, it only changes the presented roles/properties to screen reader users. WebAIM’s WAVE toolbar identifies ARIA roles on the page.

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

Single vs double quotes in JSON

import ast 
answer = subprocess.check_output(PYTHON_ + command, shell=True).strip()
    print(ast.literal_eval(answer.decode(UTF_)))

Works for me

Jump to function definition in vim

After generating ctags, you can also use the following in vim:

:tag <f_name>

Above will take you to function definition.

Converting a datetime string to timestamp in Javascript

Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.

var dateString = '17-09-2013 10:08',
    dateTimeParts = dateString.split(' '),
    timeParts = dateTimeParts[1].split(':'),
    dateParts = dateTimeParts[0].split('-'),
    date;

date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400

You could also use a regular expression with capturing groups to parse the date string in one line.

var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);

console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]

running php script (php function) in linux bash

php -f test.php

See the manual for full details of running PHP from the command line

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

If you don't know which option to enter the params. Just want to keep the default value like on_delete=None before migration:

on_delete=models.CASCADE

This is a code snippet in the old version:

if on_delete is None:
    warnings.warn(
        "on_delete will be a required arg for %s in Django 2.0. Set "
        "it to models.CASCADE on models and in existing migrations "
        "if you want to maintain the current default behavior. "
        "See https://docs.djangoproject.com/en/%s/ref/models/fields/"
        "#django.db.models.ForeignKey.on_delete" % (
            self.__class__.__name__,
            get_docs_version(),
        ),
        RemovedInDjango20Warning, 2)
    on_delete = CASCADE

Background thread with QThread in PyQt

According to the Qt developers, subclassing QThread is incorrect (see http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/). But that article is really hard to understand (plus the title is a bit condescending). I found a better blog post that gives a more detailed explanation about why you should use one style of threading over another: http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

In my opinion, you should probably never subclass thread with the intent to overload the run method. While that does work, you're basically circumventing how Qt wants you to work. Plus you'll miss out on things like events and proper thread safe signals and slots. Plus as you'll likely see in the above blog post, the "correct" way of threading forces you to write more testable code.

Here's a couple of examples of how to take advantage of QThreads in PyQt (I posted a separate answer below that properly uses QRunnable and incorporates signals/slots, that answer is better if you have a lot of async tasks that you need to load balance).

import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt

# very testable class (hint: you can use mock.Mock for the signals)
class Worker(QtCore.QObject):
    finished = QtCore.pyqtSignal()
    dataReady = QtCore.pyqtSignal(list, dict)

    @QtCore.pyqtSlot()
    def processA(self):
        print "Worker.processA()"
        self.finished.emit()

    @QtCore.pyqtSlot(str, list, list)
    def processB(self, foo, bar=None, baz=None):
        print "Worker.processB()"
        for thing in bar:
            # lots of processing...
            self.dataReady.emit(['dummy', 'data'], {'dummy': ['data']})
        self.finished.emit()


class Thread(QtCore.QThread):
    """Need for PyQt4 <= 4.6 only"""
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)

     # this class is solely needed for these two methods, there
     # appears to be a bug in PyQt 4.6 that requires you to
     # explicitly call run and start from the subclass in order
     # to get the thread to actually start an event loop

    def start(self):
        QtCore.QThread.start(self)

    def run(self):
        QtCore.QThread.run(self)


app = QtGui.QApplication(sys.argv)

thread = Thread() # no parent!
obj = Worker() # no parent!
obj.moveToThread(thread)

# if you want the thread to stop after the worker is done
# you can always call thread.start() again later
obj.finished.connect(thread.quit)

# one way to do it is to start processing as soon as the thread starts
# this is okay in some cases... but makes it harder to send data to
# the worker object from the main gui thread.  As you can see I'm calling
# processA() which takes no arguments
thread.started.connect(obj.processA)
thread.start()

# another way to do it, which is a bit fancier, allows you to talk back and
# forth with the object in a thread safe way by communicating through signals
# and slots (now that the thread is running I can start calling methods on
# the worker object)
QtCore.QMetaObject.invokeMethod(obj, 'processB', Qt.QueuedConnection,
                                QtCore.Q_ARG(str, "Hello World!"),
                                QtCore.Q_ARG(list, ["args", 0, 1]),
                                QtCore.Q_ARG(list, []))

# that looks a bit scary, but its a totally ok thing to do in Qt,
# we're simply using the system that Signals and Slots are built on top of,
# the QMetaObject, to make it act like we safely emitted a signal for 
# the worker thread to pick up when its event loop resumes (so if its doing
# a bunch of work you can call this method 10 times and it will just queue
# up the calls.  Note: PyQt > 4.6 will not allow you to pass in a None
# instead of an empty list, it has stricter type checking

app.exec_()

# Without this you may get weird QThread messages in the shell on exit
app.deleteLater()        

Django: Model Form "object has no attribute 'cleaned_data'"

For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.

Just get rid of the second form = SearchForm(request.POST) and all should be well.

AppSettings get value from .config file

Give this a go:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

How do I raise the same Exception with a custom message in Python?

None of the above solutions did exactly what I wanted, which was to add some information to the first part of the error message i.e. I wanted my users to see my custom message first.

This worked for me:

exception_raised = False
try:
    do_something_that_might_raise_an_exception()
except ValueError as e:
    message = str(e)
    exception_raised = True

if exception_raised:
    message_to_prepend = "Custom text"
    raise ValueError(message_to_prepend + message)

Visual Studio: How to show Overloads in IntelliSense?

The default key binding for this is Ctrl+Shift+Space. The underlying Visual Studio command is Edit.ParameterInfo.

If the standard keybinding doesn't work for you (possible in some profiles) then you can change it via the keyboard options page

  • Tools -> Options
  • Keyboard
  • Type in Edit.ParameterInfo
  • Change the shortcut key
  • Hit Assign

Scroll Automatically to the Bottom of the Page

jQuery isn't necessary. Most of the top results I got from a Google search gave me this answer:

window.scrollTo(0,document.body.scrollHeight);

Where you have nested elements, the document might not scroll. In this case, you need to target the element that scrolls and use it's scroll height instead.

window.scrollTo(0,document.querySelector(".scrollingContainer").scrollHeight);

You can tie that to the onclick event of your question (i.e. <div onclick="ScrollToBottom()" ...).

Some additional sources you can take a look at:

Use images instead of radio buttons

Example:

Heads up! This solution is CSS-only.

Credit-card selector, the MasterCard on the modded demo is hovered.

I recommend you take advantage of CSS3 to do that, by hidding the by-default input radio button with CSS3 rules:

.options input{
    margin:0;padding:0;
    -webkit-appearance:none;
       -moz-appearance:none;
            appearance:none;
}

I just make an example a few days ago.

Difference Between Cohesion and Coupling

Cohesion is an indication of how related and focused the responsibilities of an software element are.

Coupling refers to how strongly a software element is connected to other elements.

The software element could be class, package, component, subsystem or a system. And while designing the systems it is recommended to have software elements that have High cohesion and support Low coupling.

Low cohesion results in monolithic classes that are difficult to maintain, understand and reduces re-usablity. Similarly High Coupling results in classes that are tightly coupled and changes tend not be non-local, difficult to change and reduces the reuse.

We can take a hypothetical scenario where we are designing an typical monitor-able ConnectionPool with the following requirements. Note that, it might look too much for a simple class like ConnectionPool but the basic intent is just to demonstrate low coupling and high cohesion with some simple example and I think should help.

  1. support getting a connection
  2. release a connection
  3. get stats about connection vs usage count
  4. get stats about connection vs time
  5. Store the connection retrieval and release information to a database for reporting later.

With low cohesion we could design a ConnectionPool class by forcefully stuffing all this functionality/responsibilities into a single class as below. We can see that this single class is responsible for connection management, interacting with database as well maintaining connection stats.

Low Cohesion Connection Pool

With high cohesion we can assign these responsibility across the classes and make it more maintainable and reusable.

High Cohesion Connection Pool

To demonstrate Low coupling we will continue with the high cohesion ConnectionPool diagram above. If we look at the above diagram although it supports high cohesion, the ConnectionPool is tightly coupled with ConnectionStatistics class and PersistentStore it interacts with them directly. Instead to reduce the coupling we could introduce a ConnectionListener interface and let these two classes implement the interface and let them register with ConnectionPool class. And the ConnectionPool will iterate through these listeners and notify them of connection get and release events and allows less coupling.

Low Coupling ConnectionPool

Note/Word or Caution: For this simple scenario it may look like an overkill but if we imagine a real-time scenario where our application needs to interact with multiple third party services to complete a transaction: Directly coupling our code with the third party services would mean that any changes in the third party service could result in changes to our code at multiple places, instead we could have Facade that interacts with these multiple services internally and any changes to the services become local to the Facade and enforce low coupling with the third party services.

Calling a particular PHP function on form submit

you don't need this code

<?php
function display()
{
echo "hello".$_POST["studentname"];
}
?>

Instead, you can check whether the form is submitted by checking the post variables using isset.

here goes the code

if(isset($_POST)){
echo "hello ".$_POST['studentname'];
}

click here for the php manual for isset

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

How to modify a global variable within a function in bash?

A solution to this problem, without having to introduce complex functions and heavily modify the original one, is to store the value in a temporary file and read / write it when needed.

This approach helped me greatly when I had to mock a bash function called multiple times in a bats test case.

For example, you could have:

# Usage read_value path_to_tmp_file
function read_value {
  cat "${1}"
}

# Usage: set_value path_to_tmp_file the_value
function set_value {
  echo "${2}" > "${1}"
}
#----

# Original code:

function test1() {
  e=4
  set_value "${tmp_file}" "${e}"
  echo "hello"
}


# Create the temp file
# Note that tmp_file is available in test1 as well
tmp_file=$(mktemp)

# Your logic
e=2
# Store the value
set_value "${tmp_file}" "${e}"

# Run test1
test1

# Read the value modified by test1
e=$(read_value "${tmp_file}")
echo "$e"

The drawback is that you might need multiple temp files for different variables. And also you might need to issue a sync command to persist the contents on the disk between one write and read operations.

Populate a Drop down box from a mySQL table in PHP

After a while of research and disappointments....I was able to make this up

     <?php $conn = new mysqli('hostname', 'username', 'password','dbname') or die ('Cannot connect to db') $result = $conn->query("select * from table");?>

//insert the below code in the body


    <table id="myTable"> <tr class="header"> <th style="width:20%;">Name</th>
    <th style="width:20%;">Email</th>
       <th style="width:10%;">City/ Region</th>
        <th style="width:30%;">Details</th>
  </tr>
  <?php
   while ($row = mysqli_fetch_array($result)) {

               echo "<tr>";
               echo "<td>".$row['username']."</td>";
               echo "<td>".$row['city']."</td>";
                echo "<td>".$row['details']."</td>";
               echo "</tr>";
           }

     ?>
</table>

Trust me it works :)

Protect image download

Another way to remove the "save image" context menu is to use some CSS. This also leaves the rest of the context-menu intact.

img {
    pointer-events: none;
}

It makes all img elements non-reactive to any mouse events such as dragging, hovering, clicking etc.

See spec for more info.

Reset textbox value in javascript

this is might be a possible solution

void 0 != document.getElementById("ad") &&       (document.getElementById("ad").onclick =function(){
 var a = $("#client_id").val();
 var b = $("#contact").val();
 var c = $("#message").val();
 var Qdata = { client_id: a, contact:b, message:c }
 var respo='';
     $("#message").html('');

return $.ajax({

    url: applicationPath ,
    type: "POST",
    data: Qdata,
    success: function(e) {
         $("#mcg").html("msg send successfully");

    }

})

});

Run CRON job everyday at specific time

you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM

1 10 * * * php -f /var/www/package/index.php controller function

30 14 * * * php -f /var/www/package/index.php controller function

but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30 .

30 10,14 * * * php -f /var/www/package/index.php controller function

Update style of a component onScroll in React.js

To expand on @Austin's answer, you should add this.handleScroll = this.handleScroll.bind(this) to your constructor:

constructor(props){
    this.handleScroll = this.handleScroll.bind(this)
}
componentDidMount: function() {
    window.addEventListener('scroll', this.handleScroll);
},

componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
},

handleScroll: function(event) {
    let scrollTop = event.srcElement.body.scrollTop,
        itemTranslate = Math.min(0, scrollTop/3 - 60);

    this.setState({
      transform: itemTranslate
    });
},
...

This gives handleScroll() access to the proper scope when called from the event listener.

Also be aware you cannot do the .bind(this) in the addEventListener or removeEventListener methods because they will each return references to different functions and the event will not be removed when the component unmounts.

Playing a video in VideoView in Android

Well ! if you are using a android Compatibility Video then the only cause of this alert is you must be using a video sized more then the 300MB. Android doesn't support large Video (>300MB). We can get it by using NDK optimization.

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

MVC 5 Access Claims Identity User Data

According to the ControllerBase class, you can get the claims for the user executing the action.

enter image description here

here's how you can do it in 1 line.

var claims = User.Claims.ToList();

ESLint not working in VS Code?

I had a similar problem with eslint saying it was '..not validating any files yet', but nothing was reported in the VS Code problems console. However after upgrading VS Code to the latest version (1.32.1) and restarting, eslint started working.

Installation failed with message Invalid File

Try cleaning the project and rebuild, if doesn't work try disabling the Instant Run from Settings>Build>Instant Run in case you are running someone else's code.

How to run a shell script on a Unix console or Mac terminal?

Little addition, to run an interpreter from the same folder, still using #!hashbang in scripts.

As example a php7.2 executable copied from /usr/bin is in a folder along a hello script.

#!./php7.2
<?php

echo "Hello!"; 

To run it:

./hello

Which behave just as equal as:

./php7.2 hello

The proper solutions with good documentation can be the tools linuxdeploy and/or appimage, this is using this method under the hood.

Indent multiple lines quickly in vi

This answer summarises the other answers and comments of this question, and it adds extra information based on the Vim documentation and the Vim wiki. For conciseness, this answer doesn't distinguish between Vi and Vim-specific commands.

In the commands below, "re-indent" means "indent lines according to your indentation settings." shiftwidth is the primary variable that controls indentation.

General Commands

>>   Indent line by shiftwidth spaces
<<   De-indent line by shiftwidth spaces
5>>  Indent 5 lines
5==  Re-indent 5 lines

>%   Increase indent of a braced or bracketed block (place cursor on brace first)
=%   Reindent a braced or bracketed block (cursor on brace)
<%   Decrease indent of a braced or bracketed block (cursor on brace)
]p   Paste text, aligning indentation with surroundings

=i{  Re-indent the 'inner block', i.e. the contents of the block
=a{  Re-indent 'a block', i.e. block and containing braces
=2a{ Re-indent '2 blocks', i.e. this block and containing block

>i{  Increase inner block indent
<i{  Decrease inner block indent

You can replace { with } or B, e.g. =iB is a valid block indent command. Take a look at "Indent a Code Block" for a nice example to try these commands out on.

Also, remember that

.    Repeat last command

, so indentation commands can be easily and conveniently repeated.

Re-indenting complete files

Another common situation is requiring indentation to be fixed throughout a source file:

gg=G  Re-indent entire buffer

You can extend this idea to multiple files:

" Re-indent all your C source code:
:args *.c
:argdo normal gg=G
:wall

Or multiple buffers:

" Re-indent all open buffers:
:bufdo normal gg=G:wall

In Visual Mode

Vjj> Visually mark and then indent three lines

In insert mode

These commands apply to the current line:

CTRL-t   insert indent at start of line
CTRL-d   remove indent at start of line
0 CTRL-d remove all indentation from line

Ex commands

These are useful when you want to indent a specific range of lines, without moving your cursor.

:< and :> Given a range, apply indentation e.g.
:4,8>   indent lines 4 to 8, inclusive

Indenting using markers

Another approach is via markers:

ma     Mark top of block to indent as marker 'a'

...move cursor to end location

>'a    Indent from marker 'a' to current location

Variables that govern indentation

You can set these in your .vimrc file.

set expandtab       "Use softtabstop spaces instead of tab characters for indentation
set shiftwidth=4    "Indent by 4 spaces when using >>, <<, == etc.
set softtabstop=4   "Indent by 4 spaces when pressing <TAB>

set autoindent      "Keep indentation from previous line
set smartindent     "Automatically inserts indentation in some cases
set cindent         "Like smartindent, but stricter and more customisable

Vim has intelligent indentation based on filetype. Try adding this to your .vimrc:

if has ("autocmd")
    " File type detection. Indent based on filetype. Recommended.
    filetype plugin indent on
endif

References

How to edit default dark theme for Visual Studio Code?

tldr

You can get the colors for any theme (including the builtin ones) by switching to the theme then choosing Developer > Generate Color Theme From Current Settings from the command palette.

Details

  1. Switch to the builtin theme you wish to modify by selecting Preferences: Color Theme from the command palette then choosing the theme.

  2. Get the colors for that theme by choosing Developer > Generate Color Theme From Current Settings from the command palette. Save the file with the suffix -color-theme.jsonc.
    The color-theme part will enable color picker widgets when editing the file and jsonc sets the filetype to JSON with comments.

  3. From the command palette choose Preferences: Open Settings (JSON) to open your settings.json file. Then add your desired changes to either the workbench.colorCustomizations or tokenColorCustomizations section.

    • To restrict the settings to just this theme, use an associative arrays where the key is the theme name in brackets ([]) and the value is an associative array of settings.
    • The theme name can be found in settings.json at workbench.colorTheme.

For example, the following customizes the theme listed as Dark+ (default dark) from the Color Theme list. It sets the editor background to near black and the syntax highlighting for comments to a dim gray.

// settings.json
"workbench.colorCustomizations": {
    "[Default Dark+]": {
        "editor.background": "#19191f"
    }
},
"editor.tokenColorCustomizations": {
    "[Default Dark+]": {
        "comments": "#5F6167"
    }
},

Android SDK location

Do you have a screen of the content of your folder? This is my setup:

Xamarin

Folder

I hope these screenshots can help you out.

Conda environments not showing up in Jupyter Notebook

Just run conda install ipykernel in your new environment, only then you will get a kernel with this env. This works even if you have different versions installed in each envs and it doesn't install jupyter notebook again. You can start youe notebook from any env you will be able to see newly added kernels.

Sending emails through SMTP with PHPMailer

SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:

that's typical of trying to connect to a SSL service with a client that's not using SSL

SMTP Error: Could not authenticate.

no suprise there having failed to start an SMTP conversation authentigation is not an option,.

phpmailer doesn't do implicit SSL (aka TLS on connect, SMTPS) Short of rewriting smtp.class.php to include support for it there it no way to do what you ask.

Use port 587 with explicit SSL (aka TLS, STARTTLS) instead.

Setting PHP tmp dir - PHP upload not working

In my case, it was the open_basedir which was defined. I commented it out (default) and my issue was resolved. I can now set the upload directory anywhere.

MySql server startup error 'The server quit without updating PID file '

its a problem in 5.5 version

Here's an example for the [mysqld] section of your my.cnf:

 skip-character-set-client-handshake
 collation_server=utf8_unicode_ci
 character_set_server=utf8

refers :http://dev.mysql.com/doc/refman/5.6/en/charset-server.html

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

The problem is also identified in your status bar at the bottom:

overwrite label in status bar

You are in overwrite mode instead of insert mode.

The “Insert” key toggles between insert and overwrite modes.

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

If you are using liquibase to update your SQL Server, you are likely trying to insert a record key into an autoIncrement field. By removing the column from the insert, your script should run.

<changeSet id="CREATE_GROUP_TABLE" >
    <createTable tableName="GROUP_D">
        <column name="GROUP_ID" type="INTEGER" autoIncrement="true">
            <constraints primaryKey="true"/>
        </column>
    </createTable>
</changeSet>

<changeSet id="INSERT_UNKNOWN_GROUP" >
    <insert tableName="GROUP_D">    

        <column name="GROUP_ID" valueNumeric="-1"/>
 ...
    </insert>
</changeSet>

Disable Chrome strict MIME type checking

Another solution when a file pretends another extension

I use php inside of var.js file with this .htaccess.

<Files var.js>
    AddType application/x-httpd-php .js
</Files>

Then I write php code in the .js file

<?php
// This is a `.js` file but works with php
echo "var js_variable = '$php_variable';";

When I got the MIME type warning on Chrome, I fixed it by adding a Content-Type header line in the .js(but php) file.

<?php
header('Content-Type: application/javascript');        // <- Add this line
// This is a `.js` file but works with php
...

A browser won't execute .js file because apache sends the Content-Type header of the file as application/x-httpd-php that is defined in .htaccess. That's a security reason. But apache won't execute php as far as htaccess commands the impersonation, it's necessary. So we need to overwrite apache's Content-Type header with the php function header(). I guess that apache stops sending its own header when php sends it instead of apache before.

Ambiguous overload call to abs(double)

Its boils down to this: math.h is from C and was created over 10 years ago. In math.h, due to its primitive nature, the abs() function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs(). When C++ was created it took math.h and made it cmath. cmath is essentially math.h but improved for C++. It improved things like having to distinguish between fabs() and abs, and just made abs() for both doubles and integer types. In summary either: Use math.h and use abs() for integers, fabs() for doubles or use cmath and just have abs for everything (easier and recommended)

Hope this helps anyone who is having the same problem!

Jquery Hide table rows

This should do the trick.

$(textInput).closest("tr").hide();

How to leave space in HTML

“Insensitive to space” is an oversimplification. A more accurate description is that consecutive whitespace characters (spaces, tabs, newlines) are equivalent to a single space, in normal content.

You make empty spaces between words using space characters: “hello world”. I you want more space, you should consider what you are doing, since in normal text content, that does not make sense. For spacing elements, use CSS margin properties.

To get useful example codes, you need to describe a specific problem, like markup and a description of desired rendering.

Test if characters are in a string

Just in case you would also like check if a string (or a set of strings) contain(s) multiple sub-strings, you can also use the '|' between two substrings.

>substring="as|at"
>string_vector=c("ass","ear","eye","heat") 
>grepl(substring,string_vector)

You will get

[1]  TRUE FALSE FALSE  TRUE

since the 1st word has substring "as", and the last word contains substring "at"

"Could not find or load main class" Error while running java program using cmd prompt

I was getting the exact same error for forgetting to remove the .class extension when running the JAVA class. So instead of this:

java myClass.class

One should do this:

java myClass

Trying to add adb to PATH variable OSX

In your terminal, navigate to home directory

cd
create file .bash_profile

touch .bash_profile
open file with TextEdit

open -e .bash_profile
insert line into TextEdit

export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/
save file and reload file

source ~/.bash_profile is very important check if adb was set into path

adb version

It should be fine now.

WPF Datagrid Get Selected Cell Value

If SelectionUnit="Cell" try this:

    string cellValue = GetSelectedCellValue();

Where:

    public string GetSelectedCellValue()
    {
        DataGridCellInfo cellInfo = MyDataGrid.SelectedCells[0];
        if (cellInfo == null) return null;

        DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn;
        if (column == null) return null;

        FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item };
        BindingOperations.SetBinding(element, TagProperty, column.Binding);

        return element.Tag.ToString();
    }

Seems like it shouldn't be that complicated, I know...

Edit: This doesn't seem to work on DataGridTemplateColumn type columns. You could also try this if your rows are made up of a custom class and you've assigned a sort member path:

    public string GetSelectedCellValue()
    {
        DataGridCellInfo cells = MyDataGrid.SelectedCells[0];

        YourRowClass item = cells.Item as YourRowClass;
        string columnName = cells.Column.SortMemberPath;

        if (item == null || columnName == null) return null;

        object result = item.GetType().GetProperty(columnName).GetValue(item, null);

        if (result == null) return null;

        return result.ToString();
    }

How to access the ith column of a NumPy multidimensional array?

To get several and indepent columns, just:

> test[:,[0,2]]

you will get colums 0 and 2

How can I manually generate a .pyc file from a .py file

I would use compileall. It works nicely both from scripts and from the command line. It's a bit higher level module/tool than the already mentioned py_compile that it also uses internally.

Why is my element value not getting changed? Am I using the wrong function?

Sounds like we need to assume that your textbox name and ID are both set to "Tue." If that's the case, try using a lower-case V on .value.

Max tcp/ip connections on Windows Server 2008

There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:

It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.

How can I find a file/directory that could be anywhere on linux command line?

If need to find nested in some dirs:

find / -type f -wholename "*dirname/filename"

Or connected dirs:

find / -type d -wholename "*foo/bar"

What is "android.R.layout.simple_list_item_1"?

Per Arvand:
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select Open declaration in layout/simple_list_item_1.xml. It'll direct you to the contents of the XML.

From there, if you then hover over the resulting simple_list_item_1.xml tab in the Editor, you'll see the file is located at C:\Data\applications\Android\android-sdk\platforms\android-19\data\res\layout\simple_list_item_1.xml (or equivalent location for your installation).

How do I output coloured text to a Linux terminal?

As others have stated, you can use escape characters. You can use my header in order to make it easier:

#ifndef _COLORS_
#define _COLORS_

/* FOREGROUND */
#define RST  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST

#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST

#endif  /* _COLORS_ */

An example using the macros of the header could be:

#include <iostream>
#include "colors.h"
using namespace std;

int main()
{
    cout << FBLU("I'm blue.") << endl;
    cout << BOLD(FBLU("I'm blue-bold.")) << endl;
    return 0;
}

enter image description here

Difference between dates in JavaScript

You can also use it

export function diffDateAndToString(small: Date, big: Date) {


    // To calculate the time difference of two dates 
    const Difference_In_Time = big.getTime() - small.getTime()

    // To calculate the no. of days between two dates 
    const Days = Difference_In_Time / (1000 * 3600 * 24)
    const Mins = Difference_In_Time / (60 * 1000)
    const Hours = Mins / 60

    const diffDate = new Date(Difference_In_Time)

    console.log({ date: small, now: big, diffDate, Difference_In_Days: Days, Difference_In_Mins: Mins, Difference_In_Hours: Hours })

    var result = ''

    if (Mins < 60) {
        result = Mins + 'm'
    } else if (Hours < 24) result = diffDate.getMinutes() + 'h'
    else result = Days + 'd'
    return { result, Days, Mins, Hours }
}

results in { result: '30d', Days: 30, Mins: 43200, Hours: 720 }

Logcat not displaying my log calls

After upgrade to Android 3.6.1, I have experienced this issue multiple times. The only thing that works in my case is RESTARTING THE DEVICE.

Py_Initialize fails - unable to load the file system codec

Ran into the same thing trying to install brew's python3 under Mac OS! The issue here is that in Mac OS, homebrew puts the "real" python a whole layer deeper than you think. You would think from the homebrew output that

$ echo $PYTHONHOME
/usr/local/Cellar/python3/3.6.2/
$ echo $PYTHONPATH
/usr/local/Cellar/python3/3.6.2/bin

would be correct, but invoking $PYTHONPATH/python3 immediately crashes with the abort 6 "can't find encodings." This is because although that $PYTHONHOME looks like a complete installation, having a bin, lib etc, it is NOT the actual Python, which is in a Mac OS "Framework". Do this:

PYTHONHOME=/usr/local/Cellar/python3/3.x.y/Frameworks/Python.framework/Versions/3.x
PYTHONPATH=$PYTHONHOME/bin

(substituting version numbers as appropriate) and it will work fine.

SQL/mysql - Select distinct/UNIQUE but return all columns?

That's a really good question. I have read some useful answers here already, but probably I can add a more precise explanation.

Reducing the number of query results with a GROUP BY statement is easy as long as you don't query additional information. Let's assume you got the following table 'locations'.

--country-- --city--
 France      Lyon
 Poland      Krakow
 France      Paris
 France      Marseille
 Italy       Milano

Now the query

SELECT country FROM locations
GROUP BY country

will result in:

--country--
 France
 Poland
 Italy

However, the following query

SELECT country, city FROM locations
GROUP BY country

...throws an error in MS SQL, because how could your computer know which of the three French cities "Lyon", "Paris" or "Marseille" you want to read in the field to the right of "France"?

In order to correct the second query, you must add this information. One way to do this is to use the functions MAX() or MIN(), selecting the biggest or smallest value among all candidates. MAX() and MIN() are not only applicable to numeric values, but also compare the alphabetical order of string values.

SELECT country, MAX(city) FROM locations
GROUP BY country

will result in:

--country-- --city--
 France      Paris
 Poland      Krakow
 Italy       Milano

or:

SELECT country, MIN(city) FROM locations
GROUP BY country

will result in:

--country-- --city--
 France      Lyon
 Poland      Krakow
 Italy       Milano

These functions are a good solution as long as you are fine with selecting your value from the either ends of the alphabetical (or numeric) order. But what if this is not the case? Let us assume that you need a value with a certain characteristic, e.g. starting with the letter 'M'. Now things get complicated.

The only solution I could find so far is to put your whole query into a subquery, and to construct the additional column outside of it by hands:

SELECT
     countrylist.*,
     (SELECT TOP 1 city
     FROM locations
     WHERE
          country = countrylist.country
          AND city like 'M%'
     )
FROM
(SELECT country FROM locations
GROUP BY country) countrylist

will result in:

--country-- --city--
 France      Marseille
 Poland      NULL
 Italy       Milano

Custom HTTP Authorization Header

No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string ) (see section 1.2), and your example doesn't use "=" that way.

How to play a local video with Swift?

Swift 3

if let filePath = Bundle.main.path(forResource: "small", ofType: ".mp4") {
    let filePathURL = NSURL.fileURL(withPath: filePath)

    let player = AVPlayer(url: filePathURL)
    let playerController = AVPlayerViewController()
    playerController.player = player
    self.present(playerController, animated: true) {
        player.play()
    }
}

How to handle the modal closing event in Twitter Bootstrap?

Updated for Bootstrap 3 and 4

Bootstrap 3 and Bootstrap 4 docs refer two events you can use.

hide.bs.modal: This event is fired immediately when the hide instance method has been called.
hidden.bs.modal: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).

And provide an example on how to use them:

$('#myModal').on('hidden.bs.modal', function () {
  // do something…
})

Legacy Bootstrap 2.3.2 answer

Bootstrap's documentation refers two events you can use.

hide: This event is fired immediately when the hide instance method has been called.
hidden: This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).

And provides an example on how to use them:

$('#myModal').on('hidden', function () {
    // do something…
})

How to sort an array based on the length of each element?

If you want to preserve the order of the element with the same length as the original array, use bubble sort.

Input = ["ab","cdc","abcd","de"];

Output  = ["ab","cd","cdc","abcd"]

Function:

function bubbleSort(strArray){
  const arrayLength = Object.keys(strArray).length;
    var swapp;
    var newLen = arrayLength-1;
    var sortedStrArrByLenght=strArray;
    do {
        swapp = false;
        for (var i=0; i < newLen; i++)
        {
            if (sortedStrArrByLenght[i].length > sortedStrArrByLenght[i+1].length)
            {
               var temp = sortedStrArrByLenght[i];
               sortedStrArrByLenght[i] = sortedStrArrByLenght[i+1];
               sortedStrArrByLenght[i+1] = temp;
               swapp = true;
            }
        }
        newLen--;
    } while (swap);
  return sortedStrArrByLenght;
}

How to drop a table if it exists?

I wrote a little UDF that returns 1 if its argument is the name of an extant table, 0 otherwise:

CREATE FUNCTION [dbo].[Table_exists]
(
    @TableName VARCHAR(200)
)
    RETURNS BIT
AS
BEGIN
    If Exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = @TableName)
        RETURN 1;

    RETURN 0;
END

GO

To delete table User if it exists, call it like so:

IF [dbo].[Table_exists]('User') = 1 Drop table [User]

Find a class somewhere inside dozens of JAR files?

A bit late to the party, but nevertheless...

I've been using JarBrowser to find in which jar a particular class is present. It's got an easy to use GUI which allows you to browse through the contents of all the jars in the selected path.

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to disable registration new users in Laravel

add

use \Redirect;

at the top of the file

Using sed and grep/egrep to search and replace

Use this command:

egrep -lRZ "\.jpg|\.png|\.gif" . \
    | xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
  • egrep: find matching lines using extended regular expressions

    • -l: only list matching filenames

    • -R: search recursively through all given directories

    • -Z: use \0 as record separator

    • "\.jpg|\.png|\.gif": match one of the strings ".jpg", ".gif" or ".png"

    • .: start the search in the current directory

  • xargs: execute a command with the stdin as argument

    • -0: use \0 as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.

    • -l: use one line per command as parameter

  • sed: the stream editor

    • -i: replace the input file with the output without making a backup

    • -e: use the following argument as expression

    • 's/\.jpg\|\.gif\|\.png/.bmp/g': replace all occurrences of the strings ".jpg", ".gif" or ".png" with ".bmp"

How do you clear the focus in javascript?

.focus() and then .blur() something else arbitrary on your page. Since only one element can have the focus, it is transferred to that element and then removed.

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

I'm using Fedora 25

sudo dnf search php | grep mysql

php-mysqlnd.x86_64 : A module for PHP applications that use MySQL databases
php-pear-MDB2-Driver-mysqli.noarch : MySQL Improved MDB2 driver mysqli

sudo dnf install php-mysqlnd.x86_64

How do I bind the enter key to a function in tkinter?

Another alternative is to use a lambda:

ent.bind("<Return>", (lambda event: name_of_function()))

Full code:

from tkinter import *
from tkinter.messagebox import showinfo

def reply(name):
    showinfo(title="Reply", message = "Hello %s!" % name)


top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")

Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)

top.mainloop()

As you can see, creating a lambda function with an unused variable "event" solves the problem.

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

Private pages for a private Github repo

You could host password in a repository and then just hide the page behind hidden address, that is derived from that password. This is not a very secure way, but it is simple.

Demonstration

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

Does C# have a String Tokenizer like Java's?

The split method of a string is what you need. In fact the tokenizer class in Java is deprecated in favor of Java's string split method.

How to output to the console in C++/Windows

I assume you're using some version of Visual Studio? In windows, std::cout << "something"; should write something to a console window IF your program is setup in the project settings as a console program.

Python: split a list based on a condition?

good, bad = [], []
for x in mylist:
    (bad, good)[x in goodvals].append(x)

How much memory can a 32 bit process access on a 64 bit operating system?

Nobody seems to touch upon the fact that if you have many different 32-bit applications, the wow64 subsystem can map them anywhere in memory above 4G, so on a 64-bit windows with sufficient memory, you can run many more 32-bit applications than on a native 32-bit system.

What does 'super' do in Python?

In the case of multiple inheritance, you normally want to call the initializers of both parents, not just the first. Instead of always using the base class, super() finds the class that is next in Method Resolution Order (MRO), and returns the current object as an instance of that class. For example:

class Base(object):
    def __init__(self):
        print("initializing Base")

class ChildA(Base):
    def __init__(self):
        print("initializing ChildA")
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        print("initializing ChildB")
        super().__init__()

class Grandchild(ChildA, ChildB):
    def __init__(self):
        print("initializing Grandchild")
        super().__init__()
        
Grandchild()

results in

initializing Grandchild
initializing ChildA
initializing Base

Replacing Base.__init__(self) with super().__init__() results in

initializing Grandchild
initializing ChildA
initializing ChildB
initializing Base

as desired.

ArrayList initialization equivalent to array initialization

The selected answer is: ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

However, its important to understand the selected answer internally copies the elements several times before creating the final array, and that there is a way to reduce some of that redundancy.

Lets start by understanding what is going on:

  1. First, the elements are copied into the Arrays.ArrayList<T> created by the static factory Arrays.asList(T...).

    This does not the produce the same class as java.lang.ArrayListdespite having the same simple class name. It does not implement methods like remove(int) despite having a List interface. If you call those methods it will throw an UnspportedMethodException. But if all you need is a fixed-sized list, you can stop here.

  2. Next the Arrays.ArrayList<T> constructed in #1 gets passed to the constructor ArrayList<>(Collection<T>) where the collection.toArray() method is called to clone it.

    public ArrayList(Collection<? extends E> collection) {
    ......
    Object[] a = collection.toArray();
    }
    
  3. Next the constructor decides whether to adopt the cloned array, or copy it again to remove the subclass type. Since Arrays.asList(T...) internally uses an array of type T, the very same one we passed as the parameter, the constructor always rejects using the clone unless T is a pure Object. (E.g. String, Integer, etc all get copied again, because they extend Object).

    if (a.getClass() != Object[].class) {      
        //Arrays.asList(T...) is always true here 
        //when T subclasses object
        Object[] newArray = new Object[a.length];
        System.arraycopy(a, 0, newArray, 0, a.length);
        a = newArray;
    }
    array = a;
    size = a.length;
    

Thus, our data was copied 3x just to explicitly initialize the ArrayList. We could get it down to 2x if we force Arrays.AsList(T...) to construct an Object[] array, so that ArrayList can later adopt it, which can be done as follows:

(List<Integer>)(List<?>) new ArrayList<>(Arrays.asList((Object) 1, 2 ,3, 4, 5));

Or maybe just adding the elements after creation might still be the most efficient.

403 - Forbidden: Access is denied. ASP.Net MVC

I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.

Connection Strings for Entity Framework

First try to understand how Entity Framework Connection string works then you will get idea of what is wrong.

  1. You have two different models, Entity and ModEntity
  2. This means you have two different contexts, each context has its own Storage Model, Conceptual Model and mapping between both.
  3. You have simply combined strings, but how does Entity's context will know that it has to pickup entity.csdl and ModEntity will pickup modentity.csdl? Well someone could write some intelligent code but I dont think that is primary role of EF development team.
  4. Also machine.config is bad idea.
  5. If web apps are moved to different machine, or to shared hosting environment or for maintenance purpose it can lead to problems.
  6. Everybody will be able to access it, you are making it insecure. If anyone can deploy a web app or any .NET app on server, they get full access to your connection string including your sensitive password information.

Another alternative is, you can create your own constructor for your context and pass your own connection string and you can write some if condition etc to load defaults from web.config

Better thing would be to do is, leave connection strings as it is, give your application pool an identity that will have access to your database server and do not include username and password inside connection string.

How to convert a GUID to a string in C#?

You need

String guid = System.Guid.NewGuid().ToString();

How to catch all exceptions in c# using try and catch?

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx


As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    

Note that in the last case the exception is rethrown using throw; and not throw ex;.

MySql sum elements of a column

select
  sum(a) as atotal,
  sum(b) as btotal,
  sum(c) as ctotal
from
  yourtable t
where
  t.id in (1, 2, 3)

Enforcing the type of the indexed members of a Typescript object?

Building on @shabunc's answer, this would allow enforcing either the key or the value — or both — to be anything you want to enforce.

type IdentifierKeys = 'my.valid.key.1' | 'my.valid.key.2';
type IdentifierValues = 'my.valid.value.1' | 'my.valid.value.2';

let stuff = new Map<IdentifierKeys, IdentifierValues>();

Should also work using enum instead of a type definition.

Swift: How to get substring from start to last index of character

edit/update:

In Swift 4 or later (Xcode 10.0+) you can use the new BidirectionalCollection method lastIndex(of:)

func lastIndex(of element: Element) -> Int?

let string = "www.stackoverflow.com"
if let lastIndex = string.lastIndex(of: ".") {
    let subString = string[..<lastIndex]  // "www.stackoverflow"
}

PHP date() with timezone?

U can just add, timezone difference to unix timestamp. Example for Moscow (UTC+3)

echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);

mysqli or PDO - what are the pros and cons?

Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.

Apart from that I find the PDO API a little more intuitive, and it feels more truly object oriented. mysqli feels like it is just a procedural API that has been objectified, if you know what I mean. In short, I find PDO easier to work with, but that is of course subjective.

How to blur background images in Android

You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/onboardingimg1">
    <View
        android:id="@+id/opacityFilter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black"
        android:layout_alignParentBottom="true"
        android:alpha="0.7">
    </View>


</RelativeLayout>

Why can't I shrink a transaction log file, even after backup?

This answer has been lifted from here and is posted here in case the other thread gets deleted:

The fact that you have non-distributed LSN in the log is the problem. I have seen this once before not sure why we dont unmark the transaction as replicated. We will investigate this internally. You can execute the following command to unmark the transaction as replicated

EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1

At this point you should be able to truncate the log.

How can I make my match non greedy in vim?

What's wrong with

%s/style="[^"]*"//g

SecurityError: The operation is insecure - window.history.pushState()

I had this problem on ReactJS history push, turned out i was trying to open //link (with double slashes)

Rebasing a Git merge commit

  • From your merge commit
  • Cherry-pick the new change which should be easy
  • copy your stuff
  • redo the merge and resolve the conflicts by just copying the files from your local copy ;)

Python syntax for "if a or b or c but not all of them"

If you work with an iterator of conditions, it could be slow to access. But you don't need to access each element more than once, and you don't always need to read all of it. Here's a solution that will work with infinite generators:

#!/usr/bin/env python3
from random import randint
from itertools import tee

def generate_random():
    while True:
        yield bool(randint(0,1))

def any_but_not_all2(s): # elegant
    t1, t2 = tee(s)
    return False in t1 and True in t2 # could also use "not all(...) and any(...)"

def any_but_not_all(s): # simple
    hadFalse = False
    hadTrue = False
    for i in s:
        if i:
            hadTrue = True
        else:
            hadFalse = True
        if hadTrue and hadFalse:
            return True
    return False


r1, r2 = tee(generate_random())
assert any_but_not_all(r1)
assert any_but_not_all2(r2)

assert not any_but_not_all([True, True])
assert not any_but_not_all2([True, True])

assert not any_but_not_all([])
assert not any_but_not_all2([])

assert any_but_not_all([True, False])
assert any_but_not_all2([True, False])

Object of class mysqli_result could not be converted to string in

The mysqli_query() method returns an object resource to your $result variable, not a string.

You need to loop it up and then access the records. You just can't directly use it as your $result variable.

while ($row = $result->fetch_assoc()) {
    echo $row['classtype']."<br>";
}

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

Well, this is basically the same as the first "reverse()" but it is 64 bit and only needs one immediate mask to be loaded from the instruction stream. GCC creates code without jumps, so this should be pretty fast.

#include <stdio.h>

static unsigned long long swap64(unsigned long long val)
{
#define ZZZZ(x,s,m) (((x) >>(s)) & (m)) | (((x) & (m))<<(s));
/* val = (((val) >>16) & 0xFFFF0000FFFF) | (((val) & 0xFFFF0000FFFF)<<16); */

val = ZZZZ(val,32,  0x00000000FFFFFFFFull );
val = ZZZZ(val,16,  0x0000FFFF0000FFFFull );
val = ZZZZ(val,8,   0x00FF00FF00FF00FFull );
val = ZZZZ(val,4,   0x0F0F0F0F0F0F0F0Full );
val = ZZZZ(val,2,   0x3333333333333333ull );
val = ZZZZ(val,1,   0x5555555555555555ull );

return val;
#undef ZZZZ
}

int main(void)
{
unsigned long long val, aaaa[16] =
 { 0xfedcba9876543210,0xedcba9876543210f,0xdcba9876543210fe,0xcba9876543210fed
 , 0xba9876543210fedc,0xa9876543210fedcb,0x9876543210fedcba,0x876543210fedcba9
 , 0x76543210fedcba98,0x6543210fedcba987,0x543210fedcba9876,0x43210fedcba98765
 , 0x3210fedcba987654,0x210fedcba9876543,0x10fedcba98765432,0x0fedcba987654321
 };
unsigned iii;

for (iii=0; iii < 16; iii++) {
    val = swap64 (aaaa[iii]);
    printf("A[]=%016llX Sw=%016llx\n", aaaa[iii], val);
    }
return 0;
}