Programs & Examples On #Processstartinfo

ProcessStartInfo hanging on "WaitForExit"? Why?

I was having the same issue, but the reason was different. It would however happen under Windows 8, but not under Windows 7. The following line seems to have caused the problem.

pProcess.StartInfo.UseShellExecute = False

The solution was to NOT disable UseShellExecute. I now received a Shell popup window, which is unwanted, but much better than the program waiting for nothing particular to happen. So I added the following work-around for that:

pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

Now the only thing bothering me is to why this is happening under Windows 8 in the first place.

Executing Batch File in C#

Here is sample c# code that are sending 2 parameters to a bat/cmd file for answer this question.

Comment: how can I pass parameters and read a result of command execution?

/by @Janatbek Sharsheyev

Option 1 : Without hiding the console window, passing arguments and without getting the outputs

using System;
using System.Diagnostics;


namespace ConsoleApplication
{
    class Program
    { 
        static void Main(string[] args)
        {
         System.Diagnostics.Process.Start(@"c:\batchfilename.bat", "\"1st\" \"2nd\"");
        }
    }
}

Option 2 : Hiding the console window, passing arguments and taking outputs


using System;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    { 
        static void Main(string[] args)
        {
         var process = new Process();
         var startinfo = new ProcessStartInfo(@"c:\batchfilename.bat", "\"1st_arg\" \"2nd_arg\" \"3rd_arg\"");
         startinfo.RedirectStandardOutput = true;
         startinfo.UseShellExecute = false;
         process.StartInfo = startinfo;
         process.OutputDataReceived += (sender, argsx) => Console.WriteLine(argsx.Data); // do whatever processing you need to do in this handler
         process.Start();
         process.BeginOutputReadLine();
         process.WaitForExit();
        }
    }
}

nginx: [emerg] "server" directive is not allowed here

That is not an nginx configuration file. It is part of an nginx configuration file.

The nginx configuration file (usually called nginx.conf) will look like:

events {
    ...
}
http {
    ...
    server {
        ...
    }
}

The server block is enclosed within an http block.

Often the configuration is distributed across multiple files, by using the include directives to pull in additional fragments (for example from the sites-enabled directory).

Use sudo nginx -t to test the complete configuration file, which starts at nginx.conf and pulls in additional fragments using the include directive. See this document for more.

"A referral was returned from the server" exception when accessing AD from C#

This is the answer for the question.Reason for the cause is my LDAP string was wrong.

    try
    {
        string adServer = ConfigurationManager.AppSettings["Server"];
        string adDomain = ConfigurationManager.AppSettings["Domain"];
        string adUsername = ConfigurationManager.AppSettings["AdiminUsername"];
        string password = ConfigurationManager.AppSettings["Password"];
        string[] dc = adDomain.Split('.');
        string dcAdDomain = string.Empty;

        foreach (string item in dc)
        {
            if (dc[dc.Length - 1].Equals(item))
                dcAdDomain = dcAdDomain + "DC=" + item;
            else
                dcAdDomain = dcAdDomain + "DC=" + item + ",";
        }

        DirectoryEntry de = new DirectoryEntry("LDAP://" + adServer + "/CN=Users," + dcAdDomain, adUsername, password);

        DirectorySearcher ds = new DirectorySearcher(de);

        ds.SearchScope = SearchScope.Subtree;

        ds.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))";

        if (ds.FindOne() != null)
            return true;
    }
    catch (Exception ex)
    {
        ExLog(ex);
    }
    return false;

How do I watch a file for changes?

Well after a bit of hacking of Tim Golden's script, I have the following which seems to work quite well:

import os

import win32file
import win32con

path_to_watch = "." # look at the current directory
file_to_watch = "test.txt" # look for changes to a file called test.txt

def ProcessNewData( newData ):
    print "Text added: %s"%newData

# Set up the bits we'll need for output
ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
hDir = win32file.CreateFile (
  path_to_watch,
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS,
  None
)

# Open the file we're interested in
a = open(file_to_watch, "r")

# Throw away any exising log data
a.read()

# Wait for new data and call ProcessNewData for each new chunk that's written
while 1:
  # Wait for a change to occur
  results = win32file.ReadDirectoryChangesW (
    hDir,
    1024,
    False,
    win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
    None,
    None
  )

  # For each change, check to see if it's updating the file we're interested in
  for action, file in results:
    full_filename = os.path.join (path_to_watch, file)
    #print file, ACTIONS.get (action, "Unknown")
    if file == file_to_watch:
        newText = a.read()
        if newText != "":
            ProcessNewData( newText )

It could probably do with a load more error checking, but for simply watching a log file and doing some processing on it before spitting it out to the screen, this works well.

Thanks everyone for your input - great stuff!

What is the difference between SQL, PL-SQL and T-SQL?

  • SQL a language for talking to the database. It lets you select data, mutate and create database objects (like tables, views, etc.), change database settings.
  • PL-SQL a procedural programming language (with embedded SQL)
  • T-SQL (procedural) extensions for SQL used by SQL Server

Checking whether a variable is an integer or not

You can use this function:

def is_int(x):    
    if type(x) == int:
       return True
    return False

Test:

print is_int('7.0') # False
print is_int(7.0) # False
print is_int(7.5) # False
print is_int(-1) # True

jQuery SVG, why can't I addClass?

Or just use old-school DOM methods when JQ has a monkey in the middle somewhere.

var myElement = $('#my_element')[0];
var myElClass = myElement.getAttribute('class').split(/\s+/g);
//splits class into an array based on 1+ white space characters

myElClass.push('new_class');

myElement.setAttribute('class', myElClass.join(' '));

//$(myElement) to return to JQ wrapper-land

Learn the DOM people. Even in 2016's framework-palooza it helps quite regularly. Also, if you ever hear someone compare the DOM to assembly, kick them for me.

XML Schema minOccurs / maxOccurs default values

example:

XML

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<country xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="country.xsd">
    <countryName>Australia</countryName>
    <capital>Canberra</capital>
    <nationalLanguage>English</nationalLanguage>
    <population>21000000</population>
    <currency>Australian Dollar</currency>
    <nationalIdentities>
        <nationalAnthem>Advance Australia Fair</nationalAnthem>
        <nationalDay>Australia Day (26 January)</nationalDay>
        <nationalColour>Green and Gold</nationalColour>
        <nationalGemstone>Opal</nationalGemstone>
        <nationalFlower>Wattle (Acacia pycnantha)</nationalFlower>
    </nationalIdentities>
    <publicHolidays>
        <newYearDay>1 January</newYearDay>
        <australiaDay>26 January</australiaDay>
        <anzacDay>25 April</anzacDay>
        <christmasDay>25 December</christmasDay>
        <boxingDay>26 December</boxingDay>
        <laborDay>Variable Date</laborDay>
        <easter>Variable Date</easter>
        <queenBirthDay>21 April (Variable Date)</queenBirthDay>
    </publicHolidays>
    <states>
        <stateName><Name>NSW -  New South Wales</Name></stateName>
        <stateName><Name>VIC -  Victoria</Name></stateName>
        <stateName><Name>QLD -  Queensland</Name></stateName>
        <stateName><Name>SA -  South Australia</Name></stateName>
        <stateName><Name>WA -  Western Australia</Name></stateName>
        <stateName><Name>TAS -  Tasmania</Name></stateName>
    </states>
    <territories>
        <territoryName>ACT -  Australian Capital Territory</territoryName>
        <territoryName>NT -  Northern Territory</territoryName>
    </territories>
</country>

XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="country">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="countryName" type="xs:string"/>
                <xs:element name="capital" type="xs:string"/>
                <xs:element name="nationalLanguage" type="xs:string"/>
                <xs:element name="population" type="xs:double"/>
                <xs:element name="currency" type="xs:string"/>
                <xs:element name="nationalIdentities">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="nationalAnthem" type="xs:string"/>
                        <xs:element name="nationalDay" type="xs:string"/>
                        <xs:element name="nationalColour" type="xs:string"/>
                        <xs:element name="nationalGemstone" type="xs:string"/>
                        <xs:element name="nationalFlower" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
                </xs:element>
                <xs:element name="publicHolidays">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="newYearDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="australiaDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="anzacDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="christmasDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="boxingDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="laborDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="easter" maxOccurs="1" type="xs:string"/>
                            <xs:element name="queenBirthDay" maxOccurs="1" type="xs:string"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="states">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="stateName" minOccurs="1" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Name" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="territories">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="territoryName" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSL:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" version="4.0"/>
    <xsl:template match="/">
        <html>
            <body>          
                <xsl:for-each select="country">         
                    <xsl:value-of select="countryName"/><br/>
                    <xsl:value-of select="capital"/><br/>
                    <xsl:value-of select="nationalLanguage"/><br/>
                    <xsl:value-of select="population"/><br/>
                    <xsl:value-of select="currency"/><br/>              
                    <xsl:for-each select="nationalIdentities">
                        <xsl:value-of select="nationalAnthem"/><br/>
                        <xsl:value-of select="nationalDay"/><br/>
                        <xsl:value-of select="nationalColour"/><br/>
                        <xsl:value-of select="nationalGemstone"/><br/>
                        <xsl:value-of select="nationalFlower"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="publicHolidays">
                        <xsl:value-of select="newYearDay"/><br/>
                        <xsl:value-of select="australiaDay"/><br/>
                        <xsl:value-of select="anzacDay"/><br/>
                        <xsl:value-of select="christmasDay"/><br/>
                        <xsl:value-of select="boxingDay"/><br/>
                        <xsl:value-of select="laborDay"/><br/>
                        <xsl:value-of select="easter"/><br/>
                        <xsl:value-of select="queenBirthDay"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="states/stateName">
                        <xsl:value-of select="Name"/><br/>
                    </xsl:for-each>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Result:

Australia
Canberra
English
21000000
Australian Dollar
Advance Australia Fair
Australia Day (26 January)
Green and Gold
Opal
Wattle (Acacia pycnantha)
1 January
26 January
25 April
25 December
26 December
Variable Date
Variable Date
21 April (Variable Date)
NSW - New South Wales
VIC - Victoria
QLD - Queensland
SA - South Australia
WA - Western Australia
TAS - Tasmania

How to display Woocommerce product price by ID number on a custom page?

If you have the product's ID you can use that to create a product object:

$_product = wc_get_product( $product_id );

Then from the object you can run any of WooCommerce's product methods.

$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();

Update
Please review the Codex article on how to write your own shortcode.

Integrating the WooCommerce product data might look something like this:

function so_30165014_price_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
         $_product = wc_get_product( $atts['id'] );
         $html = "price = " . $_product->get_price();
    }
    return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );

Your shortcode would then look like [woocommerce_price id="99"]

How to search a string in multiple files and return the names of files in Powershell?

I modified one of the answers above to give me a bit more information. This spared me a second query later on. It was something like this:

Get-ChildItem `
        -Path "C:\data\path" -Filter "Example*.dat" -recurse | `
    Select-String -pattern "dummy" | `
    Select-Object -Property Path,LineNumber,Line | `
    Export-CSV "C:\ResultFile.csv"

I can specify the path and file wildcards with this structures, and it saves the filename, line number and relevant line to an output file.

What is the difference between DBMS and RDBMS?

DBMS stands for "Database Management Systems" it includes all Databases. RDBMS are a special Type of DMBS . R in RDBMS implies that the database uses the Relational model. a collection of related tables in the relational model makes up a database.DBMS is used for simple and small application while RDBMS is used for applications with a huge database.DBMS are for smaller organizations where security is not concerned(i.e. DBMS does not impose any constraints) while RDBMS is quitely opposite( RDBMS define the integrity constraint for the purpose of holding ACID PROPERTY).

MongoDB vs. Cassandra

I haven't used Cassandra, but I have used MongoDB and think it's awesome.

If you're after simple setup, this is it: You simply untar MongoDB and run the mongod daemon and that's it ... it's running.

Obviously that's only a starter, but to get you started it's easy.

rejected master -> master (non-fast-forward)

Try this, in my case it works

git rebase --abort

C++ cout hex values?

I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf. I almost always prefer using it over std::cout (even with no previous C background).

printf("%.2X", a);

'2' defines the precision, 'X' or 'x' defines case.

The type WebMvcConfigurerAdapter is deprecated

Since Spring 5 you just need to implement the interface WebMvcConfigurer:

public class MvcConfig implements WebMvcConfigurer {

This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter class

See here:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html

OnClick Send To Ajax

Tried and working. you are using,

<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

I am using javascript , (don't know about php), use id ="status" in textarea like

<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag

<srcipt>
function UpdateStatus(){

//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({

        type:"GET",//or POST
        url:'http://localhost:7080/ajaxforjson/Testajax',
                           //  (or whatever your url is)
        data:{data1:var1},
        //can send multipledata like {data1:var1,data2:var2,data3:var3
        //can use dataType:'text/html' or 'json' if response type expected 
        success:function(responsedata){
               // process on data
               alert("got response as "+"'"+responsedata+"'");

        }
     })

}
</script>

and jsp is like

the servlet will look like:   //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")

public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
    super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String data1=request.getParameter("data1");
    //do processing on datas pass in other java class to add to DB
    // i am adding or concatenate
    String data="i Got : "+"'"+data1+"' ";
    System.out.println(" data1 : "+data1+"\n data "+data);
    response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example). You may use prefetch_related for anything that you can use select_related for.

The tradeoffs are that prefetch_related has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.

Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related has the extra benefit that a single object is used to represent each object in the database. With select_related duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.

Why are there two ways to unstage a file in Git?

git rm --cached <filePath> does not unstage a file, it actually stages the removal of the file(s) from the repo (assuming it was already committed before) but leaves the file in your working tree (leaving you with an untracked file).

git reset -- <filePath> will unstage any staged changes for the given file(s).

That said, if you used git rm --cached on a new file that is staged, it would basically look like you had just unstaged it since it had never been committed before.

Update git 2.24
In this newer version of git you can use git restore --staged instead of git reset. See git docs.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Bad: (jsHint will throw a error)

for (var name in item) {
    console.log(item[name]);
}

Good:

for (var name in item) {
  if (item.hasOwnProperty(name)) {
    console.log(item[name]);
  }
}

Django Rest Framework File Upload

I'm using the same stack and was also looking for an example of file upload, but my case is simpler since I use the ModelViewSet instead of APIView. The key turned out to be the pre_save hook. I ended up using it together with the angular-file-upload module like so:

# Django
class ExperimentViewSet(ModelViewSet):
    queryset = Experiment.objects.all()
    serializer_class = ExperimentSerializer

    def pre_save(self, obj):
        obj.samplesheet = self.request.FILES.get('file')

class Experiment(Model):
    notes = TextField(blank=True)
    samplesheet = FileField(blank=True, default='')
    user = ForeignKey(User, related_name='experiments')

class ExperimentSerializer(ModelSerializer):
    class Meta:
        model = Experiment
        fields = ('id', 'notes', 'samplesheet', 'user')

// AngularJS
controller('UploadExperimentCtrl', function($scope, $upload) {
    $scope.submit = function(files, exp) {
        $upload.upload({
            url: '/api/experiments/' + exp.id + '/',
            method: 'PUT',
            data: {user: exp.user.id},
            file: files[0]
        });
    };
});

Force "git push" to overwrite remote files

Another option (to avoid any forced push which can be problematic for other contributors) is to:

  • put your new commits in a dedicated branch
  • reset your master on origin/master
  • merge your dedicated branch to master, always keeping commits from the dedicated branch (meaning creating new revisions on top of master which will mirror your dedicated branch).
    See "git command for making one branch like another" for strategies to simulate a git merge --strategy=theirs.

That way, you can push master to remote without having to force anything.

Convert ASCII TO UTF-8 Encoding

ASCII is a subset of UTF-8, so if a document is ASCII then it is already UTF-8.

What is the best method of handling currency/money?

Using Virtual Attributes (Link to revised(paid) Railscast) you can store your price_in_cents in an integer column and add a virtual attribute price_in_dollars in your product model as a getter and setter.

# Add a price_in_cents integer column
$ rails g migration add_price_in_cents_to_products price_in_cents:integer

# Use virtual attributes in your Product model
# app/models/product.rb

def price_in_dollars
  price_in_cents.to_d/100 if price_in_cents
end

def price_in_dollars=(dollars)
  self.price_in_cents = dollars.to_d*100 if dollars.present?
end

Source: RailsCasts #016: Virtual Attributes: Virtual attributes are a clean way to add form fields that do not map directly to the database. Here I show how to handle validations, associations, and more.

How to set textColor of UILabel in Swift

The easiest workaround is create dummy labels in IB, give them the text the color you like and set to hidden. You can then reference this color in your code to set your label to the desired color.

yourLabel.textColor = hiddenLabel.textColor

The only way I could change the text color programmatically was by using the standard colors, UIColor.white, UIColor.green...

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

What is the idiomatic Go equivalent of C's ternary operator?

The map ternary is easy to read without parentheses:

c := map[bool]int{true: 1, false: 0} [5 > 4]

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

Convert CString to const char*

If your CString is Unicode, you'll need to do a conversion to multi-byte characters. Fortunately there is a version of CString which will do this automatically.

CString unicodestr = _T("Testing");
CStringA charstr(unicodestr);
DoMyStuff((const char *) charstr);

With CSS, use "..." for overflowed block of multi-lines

There are many answers here but I needed one that was:

  • CSS Only
  • Future-proof (gets more compatible with time)
  • Not going to break words apart (only breaks on spaces)

The caveat is that it doesn't provide an ellipsis for the browsers that don't support the -webkit-line-clamp rule (currently IE, Edge, Firefox) but it does use a gradient to fade their text out.

_x000D_
_x000D_
.clampMe {_x000D_
  position: relative;_x000D_
  height: 2.4em; _x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.clampMe:after {_x000D_
  content: "";_x000D_
  text-align: right;_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
  width: 50%;_x000D_
  height: 1.2em; /* Just use multiples of the line-height */_x000D_
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 80%);_x000D_
}_x000D_
_x000D_
/* Now add in code for the browsers that support -webkit-line-clamp and overwrite the non-supportive stuff */_x000D_
@supports (-webkit-line-clamp: 2) {_x000D_
  .clampMe {_x000D_
      overflow: hidden;_x000D_
      text-overflow: ellipsis;_x000D_
      display: -webkit-box;_x000D_
      -webkit-line-clamp: 2;_x000D_
      -webkit-box-orient: vertical;_x000D_
  }_x000D_
  _x000D_
  .clampMe:after {_x000D_
    display: none;_x000D_
  }_x000D_
}
_x000D_
<p class="clampMe">There's a lot more text in here than what you'll ever see. Pellentesque habitant testalotish morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
_x000D_
_x000D_
_x000D_

You can see it in action in this CodePen and you can also see a Javascript version here (no jQuery).

How to check if JavaScript object is JSON

An JSON object is an object. To check whether a type is an object type, evaluate the constructor property.

function isObject(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Object;
}

The same applies to all other types:

function isArray(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Array;
}

function isBoolean(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Boolean;
}

function isFunction(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Function;
}

function isNumber(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Number;
}

function isString(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == String;
}

function isInstanced(obj)
{
    if(obj === undefined || obj === null) { return false; }

    if(isArray(obj)) { return false; }
    if(isBoolean(obj)) { return false; }
    if(isFunction(obj)) { return false; }
    if(isNumber(obj)) { return false; }
    if(isObject(obj)) { return false; }
    if(isString(obj)) { return false; }

    return true;
}

Difference between private, public, and protected inheritance

If you inherit publicly from another class, everybody knows you are inheriting and you can be used polymorphically by anyone through a base class pointer.

If you inherit protectedly only your children classes will be able to use you polymorphically.

If you inherit privately only yourself will be able to execute parent class methods.

Which basically symbolizes the knowledge the rest of the classes have about your relationship with your parent class

Objective-C : BOOL vs bool

At the time of writing this is the most recent version of objc.h:

/// Type to represent a boolean value.
#if (TARGET_OS_IPHONE && __LP64__)  ||  TARGET_OS_WATCH
#define OBJC_BOOL_IS_BOOL 1
typedef bool BOOL;
#else
#define OBJC_BOOL_IS_CHAR 1
typedef signed char BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#endif

It means that on 64-bit iOS devices and on WatchOS BOOL is exactly the same thing as bool while on all other devices (OS X, 32-bit iOS) it is signed char and cannot even be overridden by compiler flag -funsigned-char

It also means that this example code will run differently on different platforms (tested it myself):

int myValue = 256;
BOOL myBool = myValue;
if (myBool) {
    printf("i'm 64-bit iOS");
} else {
    printf("i'm 32-bit iOS");
}

BTW never assign things like array.count to BOOL variable because about 0.4% of possible values will be negative.

PHP foreach change original array values

Use &:

foreach($arr as &$value) {
    $value = $newVal;
}

& passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.

PHP documentation for Passing by Reference

Edit 2018

This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach (or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.

  1. Loops in PHP don't have their own scope. - @Mark Amery

    This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.

  2. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.

    Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.

  3. Foreach performance.
    In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.

  4. Code readability.
    Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about & operator take a look at this guide: Reference — What does this symbol mean in PHP?
    For those who want to learn more about this part of PHP language: PHP References Explained

A very nice technical explanation by @NikiC of the internal logic of PHP foreach loops:
How does PHP 'foreach' actually work?

PHP Echo text Color

How about writing out some escape sequences?

echo "\033[01;31m Request has been sent. Please wait for my reply! \033[0m";

Won't work through browser though, only from console ;))

Get the content of a sharepoint folder with Excel VBA

I spent some time on this very problem - I was trying to verify a file existed before opening it.

Eventually, I came up with a solution using XML and SOAP - use the EnumerateFolder method and pull in an XML response with the folder's contents.

I blogged about it here.

How to use document.getElementByName and getElementByTag?

I assume you are talking about getElementById() returning a reference to an element whilst the others return a node list. Just subscript the nodelist for the others, e.g. document.getElementBytag('table')[4].

Also, elements is only a property of a form (HTMLFormElement), not a table such as in your example.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST.

That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.

Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a CORS request, your browser:

  • Will first send an OPTION request to the target URL
  • And then only if the server response to that OPTION contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.

How to install PyQt4 on Windows using pip?

With current latest python 3.6.5

pip3 install PyQt5

works fine

How to change the timeout on a .NET WebClient object

I had to fight with this issue yesterday and I've also ended up to write my custom extension class.

As you can see by looking at the code below and comparing it with the accepted answer, I tried to tweak the suggestion a little bit more in order to have a more versatile class: this way you can set a precise timeout either upon instancing the object or right before using a method that uses the internal WebRequest handler.

using System;
using System.Net;

namespace Ryadel.Components.Web
{
    /// <summary>
    /// An extension of the standard System.Net.WebClient
    /// featuring a customizable constructor and [Timeout] property.
    /// </summary>
    public class RyadelWebClient : WebClient
    {
        /// <summary>
        /// Default constructor (30000 ms timeout)
        /// NOTE: timeout can be changed later on using the [Timeout] property.
        /// </summary>
        public RyadelWebClient() : this(30000) { }

        /// <summary>
        /// Constructor with customizable timeout
        /// </summary>
        /// <param name="timeout">
        /// Web request timeout (in milliseconds)
        /// </param>
        public RyadelWebClient(int timeout)
        {
            Timeout = timeout;
        }

        #region Methods
        protected override WebRequest GetWebRequest(Uri uri)
        {
            WebRequest w = base.GetWebRequest(uri);
            w.Timeout = Timeout;
            ((HttpWebRequest)w).ReadWriteTimeout = Timeout;
            return w;
        }
        #endregion

        /// <summary>
        /// Web request timeout (in milliseconds)
        /// </summary>
        public int Timeout { get; set; }
    }
}

While I was there, I also took the chance to lower the default Timeout value to 30 seconds, as 100 seemed way too much for me.

In case you need additional info regarding this class or how to use it, check out this post I wrote on my blog.

C compiler for Windows?

Cygwin offers full GCC support on Windows; also, the free Microsoft Visual C++ Express Edition supports 'legacy' C projects just fine.

'mvn' is not recognized as an internal or external command, operable program or batch file

Go to the shell (cmd for windows) and set the path variable manually from there. It works often from there. Read more at http://www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/

Mailto links do nothing in Chrome but work in Firefox?

You can use like this also,

<a href="javascript:void(0);" onclick="javascript:window.location.href='mailto:[email protected]'; return false;">[email protected]</a>

I think this is best way to resolved for chrome issues.

Thanks..

Check if a value is in an array or not with Excel VBA

This Question was asked here: VBA Arrays - Check strict (not approximative) match

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

remove borders around html input

Try this

#generic_search_button
{
    float: left;
    width: 24px; /*new width*/
    height: 24px; /*new width*/
    border: none !important; /* no border and override any inline styles*/
    margin-top: 7px;
    cursor: pointer;
    background-color: White;
    background-image: url(/Images/search.png);
    background-repeat: no-repeat;
    background-position: center center;
}

I think the image size might be wrong

How to use an environment variable inside a quoted string in Bash

If unsure, you might use the 'cols' request on the terminal, and forget COLUMNS:

COLS=$(tput cols)

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Try to add

GRANT USAGE ON SCHEMA public to readonly;

You probably were not aware that one needs to have the requisite permissions to a schema, in order to use objects in the schema.

How do you get the string length in a batch file?

I like the two line approach of jmh_gr.

It won't work with single digit numbers unless you put () around the portion of the command before the redirect. since 1> is a special command "Echo is On" will be redirected to the file.

This example should take care of single digit numbers but not the other special characters such as < that may be in the string.

(ECHO %strvar%)> tempfile.txt

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

Adding a tooltip to an input box

Apart from HTML 5 data-tip You can use css also for making a totally customizable tooltip to be used anywhere throughout your markup.

_x000D_
_x000D_
/* ToolTip classses */ _x000D_
.tooltip {_x000D_
    display: inline-block;    _x000D_
}_x000D_
.tooltip .tooltiptext {_x000D_
    margin-left:9px;_x000D_
    width : 320px;_x000D_
    visibility: hidden;_x000D_
    background-color: #FFF;_x000D_
    border-radius:4px;_x000D_
    border: 1px solid #aeaeae;_x000D_
    position: absolute;_x000D_
    z-index: 1;_x000D_
    padding: 5px;_x000D_
    margin-top : -15px; _x000D_
    opacity: 0;_x000D_
    transition: opacity 0.5s;_x000D_
}_x000D_
.tooltip .tooltiptext::after {_x000D_
    content: " ";_x000D_
    position: absolute;_x000D_
    top: 5%;_x000D_
    right: 100%;  _x000D_
    margin-top: -5px;_x000D_
    border-width: 5px;_x000D_
    border-style: solid;_x000D_
    border-color: transparent #aeaeae transparent transparent;_x000D_
}_x000D_
_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
  <input type="text" />_x000D_
  <span class="tooltiptext">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Mobile website "WhatsApp" button to send message to a specific number

This answer is useful to them who want click to chat whatsapp in website to redirect web.whatsapp.com with default content or message and in mobile device to open in whatsapp in mobile app with default content to text bar in app.

also add jquery link.

<a  target="_blank" title="Contact Us On WhatsApp" href="https://web.whatsapp.com/send?phone=+91xxxxxxxxx&amp;text=Hi, I would like to get more information.." class="whatsapplink hidemobile" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
    Contact Us On WhatsApp        </span>
</a>
<a  target="_blank" title="Contact Us On WhatsApp" href="https://api.whatsapp.com/send?phone=+91xxxxxxxxx&text=Hi,%20I%20would%20like%20to%20get%20more%20information.." class="whatsapplink hideweb" style="background-color:#2DC100">
<i class="fa fa-fw fa-whatsapp" style="color:#fff"></i>
<span style="color:#fff">
    Contact Us On WhatsApp        </span>
</a>

<script type="text/javascript"> 
var mobile = (/iphone|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
if (mobile) { 

$('.hidemobile').css('display', 'none'); // OR you can use $('.hidemobile').hide();
} 
else 
{ 
$('.hideweb').css('display', 'none'); // OR you can use $('.hideweb').hide();
}
</script>

"column not allowed here" error in INSERT statement

While inserting the data, we have to used character string delimiter (' '). And, you missed it (' ') while inserting values which is the reason of your error message. The correction of code is given below:

INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');

jQuery get value of select onChange

Arrow function has a different scope than function, this.value will give undefined for an arrow function. To fix use

$('select').on('change',(event) => {
     alert( event.target.value );
 });

How to set default value for form field in Symfony2?

There is a very simple way, you can set defaults as here :

$defaults = array('sortby' => $sortby,'category' => $category,'page' => 1);

$form = $this->formfactory->createBuilder('form', $defaults)
->add('sortby','choice')
->add('category','choice')
->add('page','hidden')
->getForm();

Styling multi-line conditions in 'if' statements?

This doesn't improve so much but...

allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
                 cond3 == 'val3' and cond4 == 'val4')

if allCondsAreOK:
   do_something

Iterating through a list to render multiple widgets in Flutter?

For googler, I wrote a simple Stateless Widget containing 3 method mentioned in this SO. Hope this make it easier to understand.

import 'package:flutter/material.dart';

class ListAndFP extends StatelessWidget {
  final List<String> items = ['apple', 'banana', 'orange', 'lemon'];

  //  for in (require dart 2.2.2 SDK or later)
  Widget method1() {
    return Column(
      children: <Widget>[
        Text('You can put other Widgets here'),
        for (var item in items) Text(item),
      ],
    );
  }

  // map() + toList() + Spread Property
  Widget method2() {
    return Column(
      children: <Widget>[
        Text('You can put other Widgets here'),
        ...items.map((item) => Text(item)).toList(),
      ],
    );
  }

  // map() + toList()
  Widget method3() {
    return Column(
      // Text('You CANNOT put other Widgets here'),
      children: items.map((item) => Text(item)).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: method1(),
    );
  }
}

Custom toast on Android: a simple example

//A custom toast class where you can show custom or default toast as desired)

public class ToastMessage {
    private Context context;
    private static ToastMessage instance;

    /**
     * @param context
     */
    private ToastMessage(Context context) {
        this.context = context;
    }

    /**
     * @param context
     * @return
     */
    public synchronized static ToastMessage getInstance(Context context) {
        if (instance == null) {
            instance = new ToastMessage(context);
        }
        return instance;
    }

    /**
     * @param message
     */
    public void showLongMessage(String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * @param message
     */
    public void showSmallMessage(String message) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }

    /**
     * The Toast displayed via this method will display it for short period of time
     *
     * @param message
     */
    public void showLongCustomToast(String message) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
        TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
        msgTv.setText(message);
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();


    }

    /**
     * The toast displayed by this class will display it for long period of time
     *
     * @param message
     */
    public void showSmallCustomToast(String message) {

        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
        TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
        msgTv.setText(message);
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();
    }

}

How does System.out.print() work?

I think you are confused with the printf(String format, Object... args) method. The first argument is the format string, which is mandatory, rest you can pass an arbitrary number of Objects.

There is no such overload for both the print() and println() methods.

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

How to automate drag & drop functionality using Selenium WebDriver Java

I used below piece of code. Here dragAndDrop(x,y) is a method of Action class. Which takes two parameters (x,y), source location, and target location respectively

try {
                System.out.println("Drag and Drom started :");
                Thread.sleep(12000);
                Actions actions = new Actions(webdriver);
                WebElement srcElement = webdriver.findElement(By.xpath("source Xpath"));
                WebElement targetElement = webdriver.findElement(By.xpath("Target Xpath"));
                actions.dragAndDrop(srcElement, targetElement); 
                actions.build().perform();
                System.out.println("Drag and Drom complated :");
            } catch (Exception e) {
                System.out.println(e.getMessage());
                resultDetails.setFlag(true);
            }

How to make links in a TextView clickable?

Autolink phone does not worked for me. The following worked like a charm,

TextView tv = (TextView) findViewById(R.id.emergencynos);
String html2="<br><br>Fire - <b><a href=tel:997>997</a> </b></br></br>";        
tv.append(Html.fromHtml(html2));
tv.setMovementMethod(LinkMovementMethod.getInstance());

Removing duplicate elements from an array in Swift

if you want to keep the order as well then use this

let fruits = ["apple", "pear", "pear", "banana", "apple"] 
let orderedNoDuplicates = Array(NSOrderedSet(array: fruits).map({ $0 as! String }))

How to reset AUTO_INCREMENT in MySQL?

SET @num := 0;
UPDATE your_table SET id = @num := (@num+1);
ALTER TABLE your_table AUTO_INCREMENT =1;

Set NA to 0 in R

A solution using mutate_all from dplyr in case you want to add that to your dplyr pipeline:

library(dplyr)
df %>%
  mutate_all(funs(ifelse(is.na(.), 0, .)))

Result:

   A B C
1  0 0 0
2  1 0 0
3  2 0 2
4  3 0 5
5  0 0 2
6  0 0 1
7  1 0 1
8  2 0 5
9  3 0 2
10 0 0 4
11 0 0 3
12 1 0 5
13 2 0 5
14 3 0 0
15 0 0 1

If in any case you only want to replace the NA's in numeric columns, which I assume it might be the case in modeling, you can use mutate_if:

library(dplyr)
df %>%
  mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))

or in base R:

replace(is.na(df), 0)

Result:

   A    B C
1  0    0 0
2  1 <NA> 0
3  2    0 2
4  3 <NA> 5
5  0    0 2
6  0 <NA> 1
7  1    0 1
8  2 <NA> 5
9  3    0 2
10 0 <NA> 4
11 0    0 3
12 1 <NA> 5
13 2    0 5
14 3 <NA> 0
15 0    0 1

Update

with dplyr 1.0.0, across is introduced:

library(dplyr)
# Replace `NA` for all columns
df %>%
  mutate(across(everything(), ~ ifelse(is.na(.), 0, .)))

# Replace `NA` for numeric columns
df %>%
  mutate(across(where(is.numeric), ~ ifelse(is.na(.), 0, .)))

Data:

set.seed(123)
df <- data.frame(A=rep(c(0:3, NA), 3), 
                 B=rep(c("0", NA), length.out = 15), 
                 C=sample(c(0:5, NA), 15, replace = TRUE))

sort dict by value python

You could created sorted list from Values and rebuild the dictionary:

myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}

newDictionary={}

sortedList=sorted(myDictionary.values())

for sortedKey in sortedList:
    for key, value in myDictionary.items():
        if value==sortedKey:
            newDictionary[key]=value

Output: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}

ImportError: No module named pythoncom

If you're on windows you probably want the pywin32 library, which includes pythoncom and a whole lot of other stuff that is pretty standard.

How to add a custom HTTP header to every WCF call?

You add it to the call using:

using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
{
    MessageHeader<string> header = new MessageHeader<string>("secret message");
    var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
    OperationContext.Current.OutgoingMessageHeaders.Add(untyped);

    // now make the WCF call within this using block
}

And then, server-side you grab it using:

MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string identity = headers.GetHeader<string>("Identity", "http://www.my-website.com");

Java generating non-repeating random numbers

If you need generate numbers with intervals, it can be just like that:

Integer[] arr = new Integer[((int) (Math.random() * (16 - 30) + 30))];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));`

The result:

[1, 10, 2, 4, 9, 8, 7, 13, 18, 17, 5, 21, 12, 16, 23, 20, 6, 0, 22, 14, 24, 15, 3, 11, 19]

Note:

If you need that the zero does not leave you could put an "if"

How can I hide a TD tag using inline JavaScript or CSS?

What do you expect to happen in it's place? The table can't reflow to fill the space left - this seems like a recipe for buggy browser responses.

Think about hiding the contents of the td, not the td itself.

How to resolve 'unrecognized selector sent to instance'?

Mine was something simple/stupid. Newbie mistake, for anyone that has converted their NSManagedObject to a normal NSObject.

I had:

@dynamic order_id;

when i should have had:

@synthesize order_id;

How to solve javax.net.ssl.SSLHandshakeException Error?

Now I solved this issue in this way,

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream;
// Create a trust manager that does not validate certificate chains like the 
default TrustManager[] trustAllCerts = new TrustManager[] {
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            //No need to implement. 
        }
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            //No need to implement. 
        }
    }
};
// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
    System.out.println(e);
}

How to stop INFO messages displaying on spark console?

Edit your conf/log4j.properties file and change the following line:

log4j.rootCategory=INFO, console

to

log4j.rootCategory=ERROR, console

Another approach would be to :

Start spark-shell and type in the following:

import org.apache.log4j.Logger
import org.apache.log4j.Level

Logger.getLogger("org").setLevel(Level.OFF)
Logger.getLogger("akka").setLevel(Level.OFF)

You won't see any logs after that.

Other options for Level include: all, debug, error, fatal, info, off, trace, trace_int, warn

Details about each can be found in the documentation.

Integer value comparison

Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.

Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:

if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.

If you're having trouble understanding this, check out the link above, or imagine it's doing this:

if (count.intValue() > 0) { }

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

Check if a String contains a special character

This worked for me:

String s = "string";
if (Pattern.matches("[a-zA-Z]+", s)) {
 System.out.println("clear");
} else {
 System.out.println("buzz");
}

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

You need to do two additional things after following the link that you have mentioned in your post:

One have to map the changed login cridentials in phpmyadmin's config.inc.php

and second, you need to restart your web and mysql servers..

php version is not the issue here..you need to go to phpmyadmin installation directory and find file config.inc.php and in that file put your current mysql password at line

$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here

Java Multiple Inheritance

Java does not have a Multiple inheritance problem, since it does not have multiple inheritance. This is by design, in order to solve the real multiple inheritance problem (The diamond problem).

There are different strategies for mitigating the problem. The most immediately achievable one being the Composite object that Pavel suggests (essentially how C++ handles it). I don't know if multiple inheritence via C3 linearization (or similar) is on the cards for Java's future, but I doubt it.

If your question is academic, then the correct solution is that Bird and Horse are more concrete, and it is false to assume that a Pegasus is simply a Bird and a Horse combined. It would be more correct to say that a Pegasus has certain intrinsic properties in common with Birds and Horses (that is they have maybe common ancestors). This can be sufficiently modeled as Moritz' answer points out.

Append date to filename in linux

cp somefile somefile_`date +%d%b%Y`

Intercept a form submit in JavaScript and prevent normal submission

Use @Kristian Antonsen's answer, or you can use:

$('button').click(function() {
    preventDefault();
    captureForm();
});

How to lock specific cells but allow filtering and sorting

Lorie's answer is good, but if a user selects a range that contains locked and unlocked cells, the data in the locked/protected cells can be deleted.

Isaac's answer is great, but doesn't work if the user highlights a range that has both locked and unlocked cells.

I modified Isaac's code a bit to undo changes if ANY of the cells in the target range are locked. It also displays a message explaining why the action was undone. Combined with Lorie's answer, I was able to achieve the desired result of being able to sort/filter a protected sheet, while still allowing a user to make changes to an unprotected cell.

Follow the instructions in Lorie's answer, then put the following code in the worksheet module:

Private Sub Worksheet_Change(ByVal Target As Range)
    For Each i In Target
       If i.Locked = True Then
            Application.EnableEvents = False
            Application.Undo
            Application.EnableEvents = True
            MsgBox "Your action was undone because it made changes to a locked cell.", , "Action Undone"
        Exit For
        End If
    Next i
End Sub

How to get a path to the desktop for current user in C#?

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))
 {
      Directory.CreateDirectory(filePath);
 }

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

Flattening a shallow list in Python

Performance Results. Revised.

import itertools
def itertools_flatten( aList ):
    return list( itertools.chain(*aList) )

from operator import add
def reduce_flatten1( aList ):
    return reduce(add, map(lambda x: list(x), [mi for mi in aList]))

def reduce_flatten2( aList ):
    return reduce(list.__add__, map(list, aList))

def comprehension_flatten( aList ):
    return list(y for x in aList for y in x)

I flattened a 2-level list of 30 items 1000 times

itertools_flatten     0.00554
comprehension_flatten 0.00815
reduce_flatten2       0.01103
reduce_flatten1       0.01404

Reduce is always a poor choice.

Html attributes for EditorFor() in ASP.NET MVC

As of MVC 5.1, you can now do the following:

@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })

http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features

What are the differences among grep, awk & sed?

Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.

Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.

Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.

iTunes Connect: How to choose a good SKU?

Spending some time coming up with an SKU naming strategy can help you. You’ll be able to make it easy for team members to read and understand what each SKU represents. Use a value that is meaningful to your organization.

Ultimately, your SKU is a way to record important product information, so the more straightforward it is, the better for everyone.

Sticking to alphanumeric SKUs and substituting “-” or “_” for space is always the safest and best bet.

E.g. Your app name: Social Point, Submit year: 2020 = Your SKU is: Social_Point_2020

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

How to export JSON from MongoDB using Robomongo

An extension to Florian Winter answer for people looking to generate ready to execute query.

drop and insertMany query using cursor:

{
    // collection name
    var collection_name = 'foo';

    // query
    var cursor = db.getCollection(collection_name).find({});

    // drop collection and insert script
    print('db.' + collection_name + '.drop();');
    print('db.' + collection_name + '.insertMany([');

    // print documents
    while(cursor.hasNext()) {
        print(tojson(cursor.next()));

        if (cursor.hasNext()) // add trailing "," if not last item
            print(',');
    }

    // end script
    print(']);');
}

Its output will be like:

db.foo.drop();
db.foo.insertMany([
{
    "_id" : ObjectId("abc"),
    "name" : "foo"
}
,
{
    "_id" : ObjectId("xyz"),
    "name" : "bar"
}
]);

Hibernate JPA Sequence (non-Id)

If you have a column with UNIQUEIDENTIFIER type and default generation needed on insert but column is not PK

@Generated(GenerationTime.INSERT)
@Column(nullable = false , columnDefinition="UNIQUEIDENTIFIER")
private String uuidValue;

In db you will have

CREATE TABLE operation.Table1
(
    Id         INT IDENTITY (1,1)               NOT NULL,
    UuidValue  UNIQUEIDENTIFIER DEFAULT NEWID() NOT NULL)

In this case you will not define generator for a value which you need (It will be automatically thanks to columnDefinition="UNIQUEIDENTIFIER"). The same you can try for other column types

Flutter command not found

flutter document tell us

cd ~/development
unzip ~/Downloads/flutter_macos_1.17.5-stable.zip

directory like this

/development/flutter_macos_1.17.5-stable/bin/

Then he told us to do this

export PATH="$PATH:`pwd`/flutter/bin"

Then the problem is coming, the file path name does not correspond

wtf?

you need change file name like this

/development/flutter/bin/

or change export path

export PATH="$PATH:`pwd`/flutter_macos_1.17.5-stable/bin"

How to delete the first row of a dataframe in R?

dat <- dat[-1, ] worked but it killed my dataframe, changing it into another type. Had to instead use dat <- data.frame(dat[-1, ]) but this is possibly a special case as this dataframe initially had only one column.

How do you clear the focus in javascript?

With jQuery its just: $(this).blur();

Button inside of anchor link works in Firefox but not in Internet Explorer?

You can't have a <button> inside an <a> element. As W3's content model description for the <a> element states:

"there must be no interactive content descendant."

(a <button> is considered interactive content)

To get the effect you're looking for, you can ditch the <a> tags and add a simple event handler to each button which navigates the browser to the desired location, e.g.

<input type="button" value="stackoverflow.com" onClick="javascript:location.href = 'http://stackoverflow.com';" />

Please consider not doing this, however; there's a reason regular links work as they do:

  • Users can instantly recognize links and understand that they navigate to other pages
  • Search engines can identify them as links and follow them
  • Screen readers can identify them as links and advise their users appropriately

You also add a completely unnecessary requirement to have JavaScript enabled just to perform a basic navigation; this is such a fundamental aspect of the web that I would consider such a dependency as unacceptable.

You can style your links, if desired, using a background image or background color, border and other techniques, so that they look like buttons, but under the covers, they should be ordinary links.

Converting binary to decimal integer output

If you want/need to do it without int:

sum(int(c) * (2 ** i) for i, c in enumerate(s[::-1]))

This reverses the string (s[::-1]), gets each character c and its index i (for i, c in enumerate(), multiplies the integer of the character (int(c)) by two to the power of the index (2 ** i) then adds them all together (sum()).

Is it possible to dynamically compile and execute C# code fragments?

The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)

Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

The class of primary importance here is the CSharpCodeProvider which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.

Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection namespace.

How Do I Upload Eclipse Projects to GitHub?

While the EGit plugin for Eclipse is a good option, an even better one would be to learn to use git bash -- i.e., git from the command line. It isn't terribly difficult to learn the very basics of git, and it is often very beneficial to understand some basic operations before relying on a GUI to do it for you. But to answer your question:

First things first, download git from http://git-scm.com/. Then go to http://github.com/ and create an account and repository.

On your machine, first you will need to navigate to the project folder using git bash. When you get there you do:

git init

which initiates a new git repository in that directory.

When you've done that, you need to register that new repo with a remote (where you'll upload -- push -- your files to), which in this case will be github. This assumes you have already created a github repository. You'll get the correct URL from your repo in GitHub.

git remote add origin https://github.com/[username]/[reponame].git

You need to add you existing files to your local commit:

git add .   # this adds all the files

Then you need to make an initial commit, so you do:

git commit -a -m "Initial commit" # this stages your files locally for commit. 
                                  # they haven't actually been pushed yet

Now you've created a commit in your local repo, but not in the remote one. To put it on the remote, you do the second line you posted:

git push -u origin --all

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

[Updated 2017]

Step 1: On Top Right side of Android Studio Click On Gradle option.

Android Studio Click On Gradle option

Step 2:

-- Click on Refresh (Click on Refresh from Gradle Bar, you will see List Gradle scripts of your Project)

-- Click on Your Project (Your Project Name form List (root))

-- Click on Tasks

-- Click on Android

-- Double Click on signingReport (You will get SHA1 and MD5 in Gradle Console/Run Bar)

enter image description here

Step 3: Click on the Gradle Console option present bottom of Android Studio to see your SHA1 Key.

enter image description here

Step 4: Now you got the SHA key but you can't run your project.That is why Change your configuration to app mode. See image below.

enter image description here

Like this.

enter image description here

Step 5: Happy Coding!!

Retrieving the last record in each group - MySQL

Try this:

SELECT jos_categories.title AS name,
       joined .catid,
       joined .title,
       joined .introtext
FROM   jos_categories
       INNER JOIN (SELECT *
                   FROM   (SELECT `title`,
                                  catid,
                                  `created`,
                                  introtext
                           FROM   `jos_content`
                           WHERE  `sectionid` = 6
                           ORDER  BY `id` DESC) AS yes
                   GROUP  BY `yes`.`catid` DESC
                   ORDER  BY `yes`.`created` DESC) AS joined
         ON( joined.catid = jos_categories.id )  

Can I make a function available in every controller in angular?

I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. globalFunctions.foo = myFunc();. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions; and I instantly have access to any function I added to the globalFunctions object in the global script.

This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

I encountered a similar problem. I am using WinNMP. When I started it, MariaDB was also not running and prompts "Can't connect to MySQL server on '127.0.0.1' (10061) (2003)" whenever I try to connect to a database.

Just want to help. For WinNMP users like me, this worked for me:

  1. Run msyqld installer located at "C:\WinNMP\bin\MariaDB\bin".
  2. Restart your WinNMP.
  3. MariaDB should be running now.

Hope this helps someone! :D

Echoing the last command run in Bash?

After reading the answer from Gilles, I decided to see if the $BASH_COMMAND var was also available (and the desired value) in an EXIT trap - and it is!

So, the following bash script works as expected:

#!/bin/bash

exit_trap () {
  local lc="$BASH_COMMAND" rc=$?
  echo "Command [$lc] exited with code [$rc]"
}

trap exit_trap EXIT
set -e

echo "foo"
false 12345
echo "bar"

The output is

foo
Command [false 12345] exited with code [1]

bar is never printed because set -e causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345 passed to false is just there to show that the arguments to the failed command are captured as well (the false command ignores any arguments passed to it)

Get all child elements

Yes, you can use find_elements_by_ to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html

Example HTML:

<ul class="bar">
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

You can use the find_elements_by_ like so:

parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")

If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.

how to get program files x86 env variable?

Another relevant environment variable is:

%ProgramW6432%

So, on a 64-bit machine running in 32-bit (WOW64) mode:

  • echo %programfiles% ==> C:\Program Files (x86)
  • echo %programfiles(x86)% ==> C:\Program Files (x86)
  • echo %ProgramW6432% ==> C:\Program Files

From Wikipedia:

The %ProgramFiles% variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and %ProgramW6432%, which defaults to "C:\Program Files". The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).

Reference: http://en.wikipedia.org/wiki/Environment_variable

Java generics - ArrayList initialization

You can't assign a List<Number> to a reference of type List<Integer> because List<Number> allows types of numbers other than Integer. If you were allowed to do that, the following would be allowed:

List<Number> numbers = new ArrayList<Number>();
numbers.add(1.1); // add a double
List<Integer> ints = numbers;
Integer fail = ints.get(0); // ClassCastException!

The type List<Integer> is making a guarantee that anything it contains will be an Integer. That's why you're allowed to get an Integer out of it without casting. As you can see, if the compiler allowed a List of another type such as Number to be assigned to a List<Integer> that guarantee would be broken.

Assigning a List<Integer> to a reference of a type such as List<?> or List<? extends Number> is legal because the ? means "some unknown subtype of the given type" (where the type is Object in the case of just ? and Number in the case of ? extends Number).

Since ? indicates that you do not know what specific type of object the List will accept, it isn't legal to add anything but null to it. You are, however, allowed to retrieve any object from it, which is the purpose of using a ? extends X bounded wildcard type. Note that the opposite is true for a ? super X bounded wildcard type... a List<? super Integer> is "a list of some unknown type that is at least a supertype of Integer". While you don't know exactly what type of List it is (could be List<Integer>, List<Number>, List<Object>) you do know for sure that whatever it is, an Integer can be added to it.

Finally, new ArrayList<?>() isn't legal because when you're creating an instance of a paramterized class like ArrayList, you have to give a specific type parameter. You could really use whatever in your example (Object, Foo, it doesn't matter) since you'll never be able to add anything but null to it since you're assigning it directly to an ArrayList<?> reference.

Why is there an unexplainable gap between these inline-block div elements?

The easiest fix is to just float the container. (eg. float: left;) On another note, each id should be unique, meaning you can't use the same id twice in the same HTML document. You should use classes instead, where you can use the same class for multiple elements.

.container {
    position: relative;
    background: rgb(255, 100, 0);
    margin: 0;
    width: 40%;
    height: 100px;
    float: left;
}

Select columns from result set of stored procedure

For anyone who has SQL 2012 or later, I was able to accomplish this with stored procedures that aren't dynamic and have the same columns output each time.

The general idea is I build the dynamic query to create, insert into, select from, and drop the temp table, and execute this after it's all generated. I dynamically generate the temp table by first retrieving column names and types from the stored procedure.

Note: there are much better, more universal solutions that will work with fewer lines of code if you're willing/able to update the SP or change configuration and use OPENROWSET. Use the below if you have no other way.

DECLARE @spName VARCHAR(MAX) = 'MyStoredProc'
DECLARE @tempTableName VARCHAR(MAX) = '#tempTable'

-- might need to update this if your param value is a string and you need to escape quotes
DECLARE @insertCommand VARCHAR(MAX) = 'INSERT INTO ' + @tempTableName + ' EXEC MyStoredProc @param=value'

DECLARE @createTableCommand VARCHAR(MAX)

-- update this to select the columns you want
DECLARE @selectCommand VARCHAR(MAX) = 'SELECT col1, col2 FROM ' + @tempTableName

DECLARE @dropCommand VARCHAR(MAX) = 'DROP TABLE ' + @tempTableName

-- Generate command to create temp table
SELECT @createTableCommand = 'CREATE TABLE ' + @tempTableName + ' (' +
    STUFF
    (
        (
            SELECT ', ' + CONCAT('[', name, ']', ' ', system_type_name)
            FROM sys.dm_exec_describe_first_result_set_for_object
            (
              OBJECT_ID(@spName), 
              NULL
            )
            FOR XML PATH('')
        )
        ,1
        ,1
        ,''
    ) + ')'

EXEC( @createTableCommand + ' '+ @insertCommand + ' ' + @selectCommand + ' ' + @dropCommand)

Can you break from a Groovy "each" closure?

Nope, you can't abort an "each" without throwing an exception. You likely want a classic loop if you want the break to abort under a particular condition.

Alternatively, you could use a "find" closure instead of an each and return true when you would have done a break.

This example will abort before processing the whole list:

def a = [1, 2, 3, 4, 5, 6, 7]

a.find { 
    if (it > 5) return true // break
    println it  // do the stuff that you wanted to before break
    return false // keep looping
}

Prints

1
2
3
4
5

but doesn't print 6 or 7.

It's also really easy to write your own iterator methods with custom break behavior that accept closures:

List.metaClass.eachUntilGreaterThanFive = { closure ->
    for ( value in delegate ) {
        if ( value  > 5 ) break
        closure(value)
    }
}

def a = [1, 2, 3, 4, 5, 6, 7]

a.eachUntilGreaterThanFive {
    println it
}

Also prints:

1
2
3
4
5    

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

//first: Create a class as your view model

public class EventViewModel 
{
 public int Id{get;set}
 public string Property1{get;set;}
 public string Property2{get;set;}
}
//then from your method
[HttpGet]
public async Task<ActionResult> GetEvent()
{
 var events = await db.Event.Find(x => x.ID != 0);
 List<EventViewModel> model = events.Select(event => new EventViewModel(){
 Id = event.Id,
 Property1 = event.Property1,
 Property1 = event.Property2
}).ToList();
 return Json(new{ data = model }, JsonRequestBehavior.AllowGet);
}

How to check if a text field is empty or not in swift

another way to check in realtime textField source :

 @IBOutlet var textField1 : UITextField = UITextField()

 override func viewDidLoad() 
 {
    ....
    self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
 }

 func yourNameFunction(sender: UITextField) {

    if sender.text.isEmpty {
      // textfield is empty
    } else {
      // text field is not empty
    }
  }

Hot deploy on JBoss - how do I make JBoss "see" the change?

I am using JBoss AS 7.1.1.Final. Adding following code snippet in my web.xml helped me to change jsp files on the fly :

<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>development</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>

Hope this helps.!!

Tools: replace not replacing in Android manifest

Try reordering your dependencies in your gradle file. I had to move the offending library from the bottom of the list to the top, and then it worked.

Is it possible to listen to a "style change" event?

Interesting question. The problem is that height() does not accept a callback, so you wouldn't be able to fire up a callback. Use either animate() or css() to set the height and then trigger the custom event in the callback. Here is an example using animate() , tested and works (demo), as a proof of concept :

$('#test').bind('style', function() {
    alert($(this).css('height'));
});

$('#test').animate({height: 100},function(){
$(this).trigger('style');
}); 

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

You may also get :

Could not load file or assembly 'WebMatrix.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This has moved to this package

 Install-Package Microsoft.AspNet.WebPages.Data

You should probably do a clean build before attempting any of the answers to this question and after updating packages

How to copy selected lines to clipboard in vim

For GVIM, hit v to go into visual mode; select text and hit Ctrl+Insert to copy selection into global clipboard.

From the menu you can see that the shortcut key is "+y i.e. hold Shift key, then press ", then + and then release Shift and press y (cumbersome in comparison to Shift+Insert).

Loading and parsing a JSON file with multiple JSON objects

for those stumbling upon this question: the python jsonlines library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/

Concatenate chars to form String in java

Use str = ""+a+b+c;

Here the first + is String concat, so the result will be a String. Note where the "" lies is important.

Or (maybe) better, use a StringBuilder.

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

If, like me, you prefer to deal with strongly typed objects** go with:

MyObj obj =  JsonConvert.DeserializeObject<MyObj>(jsonString);

This way you get to use intellisense and compile time type error checking.

You can easily create the required objects by copying your JSON into memory and pasting it as JSON objects (Visual Studio -> Edit -> Paste Special -> Paste JSON as Classes).

See here if you don't have that option in Visual Studio.

You will also need to make sure your JSON is valid. Add your own object at the start if it is just an array of objects. i.e. {"obj":[{},{},{}]}

** I know that dynamic makes things easier sometimes but I'm a bit ol'skool with this.

Gson library in Android Studio

There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

As every incremental version has some bugs fixes or up-gradations as mentioned here

Multiple REPLACE function in Oracle

This is an old post, but I ended up using Peter Lang's thoughts, and did a similar, but yet different approach. Here is what I did:

CREATE OR REPLACE FUNCTION multi_replace(
                        pString IN VARCHAR2
                        ,pReplacePattern IN VARCHAR2
) RETURN VARCHAR2 IS
    iCount  INTEGER;
    vResult VARCHAR2(1000);
    vRule   VARCHAR2(100);
    vOldStr VARCHAR2(50);
    vNewStr VARCHAR2(50);
BEGIN
    iCount := 0;
    vResult := pString;
    LOOP
        iCount := iCount + 1;

        -- Step # 1: Pick out the replacement rules
        vRule := REGEXP_SUBSTR(pReplacePattern, '[^/]+', 1, iCount);

        -- Step # 2: Pick out the old and new string from the rule
        vOldStr := REGEXP_SUBSTR(vRule, '[^=]+', 1, 1);
        vNewStr := REGEXP_SUBSTR(vRule, '[^=]+', 1, 2);

        -- Step # 3: Do the replacement
        vResult := REPLACE(vResult, vOldStr, vNewStr);

        EXIT WHEN vRule IS NULL;
    END LOOP;

    RETURN vResult;
END multi_replace;

Then I can use it like this:

SELECT  multi_replace(
                        'This is a test string with a #, a $ character, and finally a & character'
                        ,'#=%23/$=%24/&=%25'
        )
FROM dual

This makes it so that I can can any character/string with any character/string.

I wrote a post about this on my blog.

Excel VBA If cell.Value =... then

You can use the Like operator with a wildcard to determine whether a given substring exists in a string, for example:

If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If

In this example the * character in "*Word1*" is a wildcard character which matches zero or more characters.

NOTE: The Like operator is case-sensitive, so "Word1" Like "word1" is false, more information can be found on this MSDN page.

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

How to check if String is null

To sure, you should use function to check is null and empty as below:

string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}

How to select <td> of the <table> with javascript?

try document.querySelectorAll("#table td");

BeanFactory vs ApplicationContext

  1. ApplicationContext is more preferred way than BeanFactory

  2. In new Spring versions BeanFactory is replaced with ApplicationContext. But still BeanFactory exists for backward compatability

  3. ApplicationContext extends BeanFactory and has the following benefits
    • it supports internationalization for text messages
    • it supports event publication to the registered listeners
    • access to the resources such as URLs and files

Template not provided using create-react-app

For Linux this worked for me

sudo npm uninstall -g create-react-app
npx create-react-app my-test-app

Using Java to find substring of a bigger string using Regular Expression

I'd define that I want a maximum number of non-] characters between [ and ]. These need to be escaped with backslashes (and in Java, these need to be escaped again), and the definition of non-] is a character class, thus inside [ and ] (i.e. [^\\]]). The result:

FOO\\[([^\\]]+)\\]

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

"Instantiating" a List in Java?

A List isn't a real thing in Java. It's an interface, a way of defining how an object is allowed to interact with other objects. As such, it can't ever be instantiated. An ArrayList is an implementation of the List interface, as is a linked list, and so on. Use those instead.

How to get the path of src/test/resources directory in JUnit?

If it's a spring project, we can use the below code to get files from src/test/resource folder.

File file = ResourceUtils.getFile(this.getClass().getResource("/some_file.txt"));

Best way to script remote SSH commands in Batch (Windows)

The -m switch of PuTTY takes a path to a script file as an argument, not a command.

Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

plink.exe -ssh user@host -pw password command > output.txt

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

C# Iterating through an enum? (Indexing a System.Array)

How about a dictionary list?

Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
    list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}

and of course you can change the dictionary value type to whatever your enum values are.

How to make tesseract to recognize only numbers, when they are mixed with letters?

Recognizing only numbers is actually answered on the tesseract FAQ page. See that page for more info, but if you have the version 3 package, the config files are already set up. You just specify on the commandline:

tesseract image.tif outputbase nobatch digits

As for the threshold value, I'm not sure which you mean. If your input is an unusual font, perhaps you might retrain with a sample of your input. An alternative is to change tesseract's pruning threshold. Both options are also mentioned in the FAQ.

How to combine two or more querysets in a Django view?

This can be achieved by two ways either.

1st way to do this

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator.

For an instance

pagelist1 = Page.objects.filter(
    Q(title__icontains=cleaned_search_term) | 
    Q(body__icontains=cleaned_search_term))
pagelist2 = Page.objects.filter(
    Q(title__icontains=cleaned_search_term) | 
    Q(body__icontains=cleaned_search_term))
combined_list = pagelist1 | pagelist2 # this would take union of two querysets

2nd way to do this

One other way to achieve combine operation between two queryset is to use itertools chain function.

from itertools import chain
combined_results = list(chain(pagelist1, pagelist2))

how to get a list of dates between two dates in java

With Lamma it looks like this in Java:

    for (Date d: Dates.from(2014, 6, 29).to(2014, 7, 1).build()) {
        System.out.println(d);
    }

and the output is:

    Date(2014,6,29)
    Date(2014,6,30)
    Date(2014,7,1)

Jquery to get the id of selected value from dropdown

Try the change event and selected selector

$('#jobSel').change(function(){
    var optId = $(this).find('option:selected').attr('id')
})

Using npm behind corporate proxy .pac

At work we use ZScaler as our proxy. The only way I was able to get npm to work was to use Cntlm.

See this answer:

NPM behind NTLM proxy

Excel formula to get ranking position

The way I've done this, which is a bit convoluted, is as follows:

  1. Sort rows by the points in descending order
  2. Create an additional column (D) starting at D2 with numbers 1,2,3,... total number of positions
  3. In the cell for the actual positions (D2) use the formula if(C2=C1), D2, C1). This checks if the points in this row are the same as the points in the previous row. If it is it gives you the position of the previous row, otherwise it uses the value from column D and thus handle people with equal positions.
  4. Copy this formula down the entire column
  5. Copy the positions column(C), then paste special >> values to overwrite the formula with positions
  6. Resort the rows to their original order

That's worked for me! If there's a better way I'd love to know it!

Force flushing of output to a file while bash script is still running

This isn't a function of bash, as all the shell does is open the file in question and then pass the file descriptor as the standard output of the script. What you need to do is make sure output is flushed from your script more frequently than you currently are.

In Perl for example, this could be accomplished by setting:

$| = 1;

See perlvar for more information on this.

The calling thread cannot access this object because a different thread owns it

This works for me.

new Thread(() =>
        {

        Thread.CurrentThread.IsBackground = false;
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate {

          //Your Code here.

        }, null);
        }).Start();

Postgresql: password authentication failed for user "postgres"

For those who are using it first time and have no information regarding what the password is they can follow the below steps(assuming you are on ubuntu):

  1. Open the file pg_hba.conf in /etc/postgresql/9.x/main

     sudo vi pg_hba.conf 
    

    2.edit the below line

     local   all             postgres                                peer
    

    to

     local   all             postgres                                trust
    
  2. Restart the server

      sudo service postgresql restart
    
  3. Finally you can login without need of a password as shown in the figureFinally you can login without need of a password as shown in the figure

Ref here for more info

Best way to create unique token in Rails?

I think token should be handled just like password. As such, they should be encrypted in DB.

I'n doing something like this to generate a unique new token for a model:

key = ActiveSupport::KeyGenerator
                .new(Devise.secret_key)
                .generate_key("put some random or the name of the key")

loop do
  raw = SecureRandom.urlsafe_base64(nil, false)
  enc = OpenSSL::HMAC.hexdigest('SHA256', key, raw)

  break [raw, enc] unless Model.exist?(token: enc)
end

Complete list of reasons why a css file might not be working

I stylesheet may not get loaded for several reasons. But the main approach to solve such a problem is as follows:

1. After loading the page, press F12 to open the Developers Console. Check the console for any logged errors.

2. Then you should check the Stylesheet tab and see the list of stylesheets the browser loaded.

3. The URL you're using inside your HTML link tag may be unaccessable, so manually try to visit the stylesheet with a browser and see if everything renders correctly.

4. Any typo inside your HTML or CSS stylesheet may cause the stylesheet from loading.

5. Check for any occurrences of fatal errors before your <link> tag. A fatal error may stop the running code and suspend the page, thus not including your stylesheet.

Hope that helps.

Windows equivalent of linux cksum command

To avoid annoying non-checksum lines : CertUtil -v -hashfile "your_file" SHA1 | FIND /V "CertUtil" This will display only line(s) NOT contaning CertUtil

How to call a function from a string stored in a variable?

Solution: Use PHP7

Note: For a summarized version, see TL;DR at the end of the answer.

Old Methods

Update: One of the old methods explained here has been removed. Refer to other answers for explanation on other methods, it is not covered here. By the way, if this answer doesn't help you, you should return upgrading your stuff. PHP 5.6 support has ended in January 2019 (now even PHP 7.1 and 7.2 are not being supported). See supported versions for more information.

As others mentioned, in PHP5 (and also in newer versions like PHP7) we could use variables as function names, use call_user_func() and call_user_func_array() (which, personally, I hate those functions), etc.

New Methods

As of PHP7, there are new ways introduced:

Note: Everything inside <something> brackets means one or more expressions to form something, e.g. <function_name> means expressions forming a function name.

Dynamic Function Call: Function Name On-the-fly

We can use one or more expressions inside parentheses as the function name in just one go, in the form of:

(<function_name>)(arguments);

For example:

function something(): string
{
    return "something";
}

$bar = "some_thing";

(str_replace("_", "", $bar))(); // something

// Possible, too; but generally, not recommended, because makes your code more complicated
(str_replace("_", "", $bar))()(); 

Note: Although removing the parentheses around str_replace() is not an error, putting parentheses makes code more readable. However, you cannot do that sometimes, e.g. while using . operator. To be consistent, I recommend you to put the parentheses always.

Dynamic Method Call: Method Name On-the-fly

Just like dynamic function calls, we can do the same way with method calls, surrounded by curly braces instead of parentheses (for extra forms, navigate to TL;DR section):

$object->{<method_name>}(arguments);
$object::{<method_name>}(arguments);

See it in an example:

class Foo
{
    public function another(): string
    {
        return "something";
    }
}

$bar = "another thing";

(new Something())->{explode(" ", $bar)[0]}(); // something

Dynamic Method Call: The Array Syntax

A more elegant way added in PHP7 is the following:

[<object>, <method_name>](arguments);
[<class_name>, <method_name>](arguments); // Static calls only

As an example:

class Foo
{
    public function nonStaticCall()
    {
        echo "Non-static call";
    }
    public static function staticCall()
    {
        echo "Static call";
    }
}

$x = new X();

[$x, "non" . "StaticCall"](); // Non-static call
[$x, "static" . "Call"](); // Static call

Note: The benefit of using this method over the previous one is that, you don't care about the call type (i.e. whether it's static or not).

Note: If you care about performance (and micro-optimizations), don't use this method. As I tested, this method is really slower than other methods (more than 10 times).

Extra Example: Using Anonymous Classes

Making things a bit complicated, you could use a combination of anonymous classes and the features above:

$bar = "SomeThing";

echo (new class {
    public function something()
    {
        return 512;
    }
})->{strtolower($bar)}(); // 512

TL;DR (Conclusion)

Generally, in PHP7, using the following forms are all possible:

// Everything inside `<something>` brackets means one or more expressions
// to form something

// Dynamic function call
(<function_name>)(arguments)

// Dynamic method call on an object
$object->{<method_name>}(arguments)
$object::{<method_name>}(arguments)

// Dynamic method call on a dynamically-generated object
(<object>)->{<method_name>}(arguments)
(<object>)::{<method_name>}(arguments)

// Dynamic method call, statically
ClassName::{<method_name>}(arguments)
(<class_name>)::{<method_name>}(arguments)

// Dynamic method call, array-like (no different between static and non-static calls
[<object>, <method_name>](arguments)

// Dynamic method call, array-like, statically
[<class_name>, <method_name>](arguments)

Special thanks to this PHP talk.

Can I Set "android:layout_below" at Runtime Programmatically?

Alternatively you can use the views current layout parameters and modify them:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);

Socket transport "ssl" in PHP not enabled

I also ran into this issue just now while messing with laravel.

I am using wampserver for windows and had to copy the /bin/apache/apacheversion/bin/php.ini file to /bin/php/phpversion/php.ini

Please run `npm cache clean`

This error can be due to many many things.

The key here seems the hint about error reading. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.

You could also try with sudo, that might solve a permission problem if that's the case.

Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...

Android: upgrading DB version and adding new table

1. About onCreate() and onUpgrade()

onCreate(..) is called whenever the app is freshly installed. onUpgrade is called whenever the app is upgraded and launched and the database version is not the same.

2. Incrementing the db version

You need a constructor like:

MyOpenHelper(Context context) {
   super(context, "dbname", null, 2); // 2 is the database version
}

IMPORTANT: Incrementing the app version alone is not enough for onUpgrade to be called!

3. Don't forget your new users!

Don't forget to add

database.execSQL(DATABASE_CREATE_color);

to your onCreate() method as well or newly installed apps will lack the table.

4. How to deal with multiple database changes over time

When you have successive app upgrades, several of which have database upgrades, you want to be sure to check oldVersion:

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   switch(oldVersion) {
   case 1:
       db.execSQL(DATABASE_CREATE_color);
       // we want both updates, so no break statement here...
   case 2:
       db.execSQL(DATABASE_CREATE_someothertable); 
   }
}

This way when a user upgrades from version 1 to version 3, they get both updates. When a user upgrades from version 2 to 3, they just get the revision 3 update... After all, you can't count on 100% of your user base to upgrade each time you release an update. Sometimes they skip an update or 12 :)

5. Keeping your revision numbers under control while developing

And finally... calling

adb uninstall <yourpackagename>

totally uninstalls the app. When you install again, you are guaranteed to hit onCreate which keeps you from having to keep incrementing the database version into the stratosphere as you develop...

How do I add an active class to a Link from React Router?

You can actually replicate what is inside NavLink something like this

const NavLink = ( {
  to,
  exact,
  children
} ) => {

  const navLink = ({match}) => {

    return (
      <li class={{active: match}}>
        <Link to={to}>
          {children}
        </Link>
      </li>
    )

  }

  return (
    <Route
      path={typeof to === 'object' ? to.pathname : to}
      exact={exact}
      strict={false}
      children={navLink}
    />
  )
}

just look into NavLink source code and remove parts you don't need ;)

Shuffle DataFrame rows

Following could be one of ways:

dataframe = dataframe.sample(frac=1, random_state=42).reset_index(drop=True)

where

frac=1 means all rows of a dataframe

random_state=42 means keeping same order in each execution

reset_index(drop=True) means reinitialize index for randomized dataframe

How can I format a String number to have commas and round?

Here is the simplest way to get there:

String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result)); 

output: 10,987,655.88

Is it possible to force row level locking in SQL Server?

Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:

ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

Module AppRegistry is not registered callable module (calling runApplication)

1.Close Emülator

2.npm start -- --reset-cache

3.XCode -> Product -> Clean Build Folder

4.npx react-native run-ios

When is a CDATA section necessary within a script tag?

It's an X(HT)ML thing. When you use symbols like < and > within the JavaScript, e.g. for comparing two integers, this would have to be parsed like XML, thus they would mark as a beginning or end of a tag.

The CDATA means that the following lines (everything up unto the ]]> is not XML and thus should not be parsed that way.

How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Foobar'

VBScript How can I Format Date?

This snippet also solve this question with datePart function. I've also used the right() trick to perform a rpad(x,2,"0").

option explicit

Wscript.Echo "Today is " & myDate(now)

' date formatted as your request
Function myDate(dt)
    dim d,m,y, sep
    sep = "-"
    ' right(..) here works as rpad(x,2,"0")
    d = right("0" & datePart("d",dt),2)
    m = right("0" & datePart("m",dt),2)
    y = datePart("yyyy",dt)
    myDate= m & sep & d & sep & y
End Function

Convert XML String to Object

public string Serialize<T>(T settings)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    StringWriter outStream = new StringWriter();
    serializer.Serialize(outStream, settings);
    return outStream.ToString();
}

Linux / Bash, using ps -o to get process by specific name?

Sometimes you need to grep the process by name - in that case:

ps aux | grep simple-scan

Example output:

simple-scan  1090  0.0  0.1   4248  1432 ?        S    Jun11   0:00

How to justify a single flexbox item (override justify-content)

AFAIK there is no property for that in the specs, but here is a trick I’ve been using: set the container element ( the one with display:flex ) to justify-content:space-around Then add an extra element between the first and second item and set it to flex-grow:10 (or some other value that works with your setup)

Edit: if the items are tightly aligned it's a good idea to add flex-shrink: 10; to the extra element as well, so the layout will be properly responsive on smaller devices.

Read and write to binary files in C?

I'm quite happy with my "make a weak pin storage program" solution. Maybe it will help people who need a very simple binary file IO example to follow.

$ ls
WeakPin  my_pin_code.pin  weak_pin.c
$ ./WeakPin
Pin: 45 47 49 32
$ ./WeakPin 8 2
$ Need 4 ints to write a new pin!
$./WeakPin 8 2 99 49
Pin saved.
$ ./WeakPin
Pin: 8 2 99 49
$
$ cat weak_pin.c
// a program to save and read 4-digit pin codes in binary format

#include <stdio.h>
#include <stdlib.h>

#define PIN_FILE "my_pin_code.pin"

typedef struct { unsigned short a, b, c, d; } PinCode;


int main(int argc, const char** argv)
{
    if (argc > 1)  // create pin
    {
        if (argc != 5)
        {
            printf("Need 4 ints to write a new pin!\n");
            return -1;
        }
        unsigned short _a = atoi(argv[1]);
        unsigned short _b = atoi(argv[2]);
        unsigned short _c = atoi(argv[3]);
        unsigned short _d = atoi(argv[4]);
        PinCode pc;
        pc.a = _a; pc.b = _b; pc.c = _c; pc.d = _d;
        FILE *f = fopen(PIN_FILE, "wb");  // create and/or overwrite
        if (!f)
        {
            printf("Error in creating file. Aborting.\n");
            return -2;
        }

        // write one PinCode object pc to the file *f
        fwrite(&pc, sizeof(PinCode), 1, f);  

        fclose(f);
        printf("Pin saved.\n");
        return 0;
    }

    // else read existing pin
    FILE *f = fopen(PIN_FILE, "rb");
    if (!f)
    {
        printf("Error in reading file. Abort.\n");
        return -3;
    }
    PinCode pc;
    fread(&pc, sizeof(PinCode), 1, f);
    fclose(f);

    printf("Pin: ");
    printf("%hu ", pc.a);
    printf("%hu ", pc.b);
    printf("%hu ", pc.c);
    printf("%hu\n", pc.d);
    return 0;
}
$

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

Android change SDK version in Eclipse? Unable to resolve target android-x

Goto project -->properties --> (in the dialog box that opens goto Java build path), and in order and export select android 4.1 (your new version) and select dependencies.

What is Bit Masking?

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b
Value:  01010101b

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b
Value:  01010101b
Result: 00000101b

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {
  uint8_t mask = 0x0f;   // 00001111b
  uint8_t value = 0x55;  // 01010101b
  return mask & value;
}

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304
    uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so
                                              // no masking is necessary
    uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so
                                              // we must mask to get 0x02
    uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so
                                              // we must mask to get 0x03
    uint32_t byte4 = value & 0xff;            // here we only mask, no shifting
                                              // is necessary
    ...
}

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8;

Installing Tomcat 7 as Service on Windows Server 2008

I have spent a couple of hours looking for the magic configuration to get Tomcat 7 running as a service on Windows Server 2008... no luck.

I do have a solution though.

My install of Tomcat 7 works just fine if I just jump into a console window and run...

C:\apache-tomcat-7.0.26\bin\start.bat

At this point another console window pops up and tails the logs (tail meaning show the server logs as they happen).

SOLUTION

Run the start.bat file as a Scheduled Task.

  1. Start Menu > Accessories > System Tools > Task Scheduler

  2. In the Actions Window: Create Basic Task...

  3. Name the task something like "Start Tomcat 7" or something that makes sense a year from now.

  4. Click Next >

  5. Trigger should be set to "When the computer starts"

  6. Click Next >

  7. Action should be set to "Start a program"

  8. Click Next >

  9. Program/script: should be set to the location of the startup.bat file.

  10. Click Next >

  11. Click Finish

  12. IF YOUR SERVER IS NOT BEING USED: Reboot your server to test this functionality

C# How to determine if a number is a multiple of another?

Try

public bool IsDivisible(int x, int n)
{
   return (x % n) == 0;
}

The modulus operator % returns the remainder after dividing x by n which will always be 0 if x is divisible by n.

For more information, see the % operator on MSDN.

What's the difference between xsd:include and xsd:import?

Another difference is that <import> allows importing by referring to another namespace. <include> only allows importing by referring to a URI of intended include schema. That is definitely another difference than inter-intra namespace importing.

For example, the xml schema validator may already know the locations of all schemas by namespace already. Especially considering that referring to XML namespaces by URI may be problematic on different systems where classpath:// means nothing, or where http:// isn't allowed, or where some URI doesn't point to the same thing as it does on another system.

Code sample of valid and invalid imports and includes:

Valid:

<xsd:import namespace="some/name/space"/>
<xsd:import schemaLocation="classpath://mine.xsd"/>

<xsd:include schemaLocation="classpath://mine.xsd"/>

Invalid:

<xsd:include namespace="some/name/space"/>

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension.

So they should be exactly equivalent performance wise.

http://dev.mysql.com/doc/refman/5.6/en/insert.html says:

INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables.

Set Label Text with JQuery

I would just query for the for attribute instead of repetitively recursing the DOM tree.

$("input:checkbox").on("change", function() {
    $("label[for='"+this.id+"']").text("TESTTTT");
});

How to get .app file of a xcode application

Xcode 8.1

Product -> Archive Then export on the right hand side to somewhere on your drive.

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

Unresponsive KeyListener for JFrame

You could have custom JComponents set their parent JFrame focusable.

Just add a constructor and pass in the JFrame. Then make a call to setFocusable() in paintComponent.

This way the JFrame will always receive KeyEvents regardless of whether other components are pressed.

Issue with Task Scheduler launching a task

On properties,

Check whether radio button is selected for

Run only when user is logged on 

If you selected for the above option then that is the reason why it is failed.

so change the option to

Run whether user is logged on or not

OR

In other case, user might have changed his/her login credentials

Search All Fields In All Tables For A Specific Value (Oracle)

I was having following issues for @Lalit Kumars answer,

ORA-19202: Error occurred in XML processing
ORA-00904: "SUCCESS": invalid identifier
ORA-06512: at "SYS.DBMS_XMLGEN", line 288
ORA-06512: at line 1
19202. 00000 -  "Error occurred in XML processing%s"
*Cause:    An error occurred when processing the XML function
*Action:   Check the given error message and fix the appropriate problem

Solution is:

WITH  char_cols AS
  (SELECT /*+materialize */ table_name, column_name
   FROM   cols
   WHERE  data_type IN ('CHAR', 'VARCHAR2'))
SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
       SUBSTR (table_name, 1, 14) "Table",
       SUBSTR (column_name, 1, 14) "Column"
FROM   char_cols,
       TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select "'
       || column_name
       || '" from "'
       || table_name
       || '" where upper("'
       || column_name
       || '") like upper(''%'
       || :val
       || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
ORDER  BY "Table"
/ 

Changing iframe src with Javascript

Here's the jQuery way to do it:

$('#calendar').attr('src', loc);

How can INSERT INTO a table 300 times within a loop in SQL?

In ssms we can use GO to execute same statement

Edit This mean if you put

 some query

 GO n

Some query will be executed n times

How to outline text in HTML / CSS

from: Outline effect to text

.strokeme
{
    color: white;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;  
}

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);

How to solve npm error "npm ERR! code ELIFECYCLE"

The port is probably being used by another application, try listing and see if it's your application:

lsof -i:8080

You can kill the process of this port:

lsof -ti:8080 | xargs kill

Find closest previous element jQuery

see http://api.jquery.com/prev/

var link = $("#me").parent("div").prev("h3").find("b");
alert(link.text());

see http://jsfiddle.net/gBwLq/

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

How to implement if-else statement in XSLT?

The most straight-forward approach is to do a second if-test but with the condition inverted. This technique is shorter, easier on the eyes, and easier to get right than a choose-when-otherwise nested block:

<xsl:variable name="CreatedDate" select="@createDate"/>
     <xsl:variable name="IDAppendedDate" select="2012-01-01" />
     <b>date: <xsl:value-of select="$CreatedDate"/></b> 
     <xsl:if test="$CreatedDate &gt; $IDAppendedDate">
        <h2> mooooooooooooo </h2>
     </xsl:if>
     <xsl:if test="$CreatedDate &lt;= $IDAppendedDate">
        <h2> dooooooooooooo </h2>
     </xsl:if>

Here's a real-world example of the technique being used in the style-sheet for a government website: http://w1.weather.gov/xml/current_obs/latest_ob.xsl

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

Prepend line to beginning of a file

The clear way to do this is as follows if you do not mind writing the file again

with open("a.txt", 'r+') as fp:
    lines = fp.readlines()     # lines is list of line, each element '...\n'
    lines.insert(0, one_line)  # you can use any index if you know the line index
    fp.seek(0)                 # file pointer locates at the beginning to write the whole file again
    fp.writelines(lines)       # write whole lists again to the same file

Note that this is not in-place replacement. It's writing a file again.

In summary, you read a file and save it to a list and modify the list and write the list again to a new file with the same filename.

How to send an object from one Android Activity to another using Intents?

You can use android BUNDLE to do this.

Create a Bundle from your class like:

public Bundle toBundle() {
    Bundle b = new Bundle();
    b.putString("SomeKey", "SomeValue");

    return b;
}

Then pass this bundle with INTENT. Now you can recreate your class object by passing bundle like

public CustomClass(Context _context, Bundle b) {
    context = _context;
    classMember = b.getString("SomeKey");
}

Declare this in your Custom class and use.

How to split a file into equal parts, without breaking individual lines?

split was updated in coreutils release 8.8 (announced 22 Dec 2010) with the --number option to generate a specific number of files. The option --number=l/n generates n files without splitting lines.

http://www.gnu.org/software/coreutils/manual/html_node/split-invocation.html#split-invocation http://savannah.gnu.org/forum/forum.php?forum_id=6662

set column width of a gridview in asp.net

This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.

    <asp:TemplateField   HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
    <asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate> 
 <EditItemTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate> 
<FooterTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>

Linux command to list all available commands and aliases

Why don't you just type:

seachstr

In the terminal.

The shell will say somehing like

seacrhstr: command not found 

EDIT:

Ok, I take the downvote, because the answer is stupid, I just want to know: What's wrong with this answer!!! The asker said:

and see if a command is available.

Typing the command will tell you if it is available!.

Probably he/she meant "with out executing the command" or "to include it in a script" but I cannot read his mind ( is not that I can't regularly it is just that he's wearing a mind reading deflector )

HashMap - getting First Key value

Remember that the insertion order isn't respected in a map generally speaking. Try this :

    /**
     * Get the first element of a map. A map doesn't guarantee the insertion order
     * @param map
     * @param <E>
     * @param <K>
     * @return
     */
    public static <E,K> K getFirstKeyValue(Map<E,K> map){
        K value = null;
        if(map != null && map.size() > 0){
            Map.Entry<E,K> entry =  map.entrySet().iterator().next();
            if(entry != null)
                value = entry.getValue();
        }
        return  value;
    }

I use this only when I am sure that that map.size() == 1 .

How to convert char* to wchar_t*?

Use a std::wstring instead of a C99 variable length array. The current standard guarantees a contiguous buffer for std::basic_string. E.g.,

std::wstring wc( cSize, L'#' );
mbstowcs( &wc[0], c, cSize );

C++ does not support C99 variable length arrays, and so if you compiled your code as pure C++, it would not even compile.

With that change your function return type should also be std::wstring.

Remember to set relevant locale in main.

E.g., setlocale( LC_ALL, "" ).

Cheers & hth.,

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I tried to start my binary, compiled with Qt 5.7, on Ubuntu 16.04 LTS where Qt 5.5 is preinstalled. It didn't work.

At first, I inspected the binary itself with ldd as was suggested here, and "satisfied" all "not found" dependencies. Then this notorious This application failed to start because it could not find or load the Qt platform plugin "xcb" error was thrown.

How to resolve this in Linux

Firstly you should create platforms directory where your binary is, because it is the place where Qt looks for XCB library. Copy libqxcb.so there. I wonder why authors of other answers didn't mention this.

Then you may want to run your binary with QT_DEBUG_PLUGINS=1 environment variable set to check which dependencies of libqxcb.so are not "satisfied". (You may also use ldd for this as suggested in the accepted answer).

The command output may look like this:

me@xerus:/media/sf_Qt/Package$ LD_LIBRARY_PATH=. QT_DEBUG_PLUGINS=1 ./Binary
QFactoryLoader::QFactoryLoader() checking directory path "/media/sf_Qt/Package/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "/media/sf_Qt/Package/platforms/libqxcb.so"
Found metadata in lib /media/sf_Qt/Package/platforms/libqxcb.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "xcb"
        ]
    },
    "className": "QXcbIntegrationPlugin",
    "debug": false,
    "version": 329472
}


Got keys from plugin meta data ("xcb")
loaded library "/media/sf_Qt/Package/platforms/libqxcb.so"
QLibraryPrivate::loadPlugin failed on "/media/sf_Qt/Package/platforms/libqxcb.so" : "Cannot load library /media/sf_Qt/Package/platforms/libqxcb.so: (/usr/lib/x86_64-linux-gnu/libQt5DBus.so.5: version `Qt_5' not found (required by ./libQt5XcbQpa.so.5))"
This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".

Available platform plugins are: xcb.

Reinstalling the application may fix this problem.
Aborted (core dumped)

Note the failing libQt5DBus.so.5 library. Copy it to your libraries path, in my case it was the same directory where my binary is (hence LD_LIBRARY_PATH=.). Repeat this process until all dependencies are satisfied.

P.S. thanks to the author of this answer for QT_DEBUG_PLUGINS=1.