Programs & Examples On #Fbml

Facebook Markup Language (FBML) enabled one to build Facebook applications that deeply integrate into a user's Facebook experience. Deprecated as of June 6, 2012. Not to be confused with xfbml.

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

Given URL is not permitted by the application configuration

An update to munsellj's update..

I got this working in development just by adding localhost:3000 to the 'Website URL' option and leaving the App Domains box blank. As munsellj mentioned, make sure you've added a website platform.

Facebook Open Graph Error - Inferred Property

In case it helps anyone I had the same error. It turns out my page had not been scrapped by Facebook in awhile and it was an old error. There was a scrape again button on the page that fixed it.

Facebook Javascript SDK Problem: "FB is not defined"

I had a very messy cody that loaded facebook's javascript via AJAX and i had to make sure that the js file has been completely loaded before calling FB.init this seem to work for me

    $jQuery.load( document.location.protocol + '//connect.facebook.net/en_US/all.js',
      function (obj) {
        FB.init({
           appId  : 'YOUR APP ID',
           status : true, // check login status
           cookie : true, // enable cookies to allow the server to access the session
           xfbml  : true  // parse XFBML
        });
        //ANy other FB.related javascript here
      });

This code uses jquery to load the javascript and do the function callback onLoad of the javascript. it's a lot less messier than having creating an onLoad eventlistener for the block which in the end didn't work very well on IE6, 7 and 8

How to detect when facebook's FB.init is complete

Here is a solution in case you use and Facebook Asynchronous Lazy Loading:

// listen to an Event
$(document).bind('fbInit',function(){
    console.log('fbInit complete; FB Object is Available');
});

// FB Async
window.fbAsyncInit = function() {
    FB.init({appId: 'app_id', 
         status: true, 
         cookie: true,
         oauth:true,
         xfbml: true});

    $(document).trigger('fbInit'); // trigger event
};

How can I display the users profile pic using the facebook graph api?

to get different sizes, you can use the type parameter:

You can specify the picture size you want with the type argument, which should be one of square (50x50), small (50 pixels wide, variable height), and large (about 200 pixels wide, variable height): http://graph.facebook.com/squall3d/picture?type=large.

Detect changed input text box

try keyup instead of change.

<script type="text/javascript">
   $(document).ready(function () {
       $('#inputDatabaseName').keyup(function () { alert('test'); });
   });
</script>

Here's the official jQuery documentation for .keyup().

Cross browser method to fit a child div to its parent's width

The solution is to simply not declare width: 100%.

The default is width: auto, which for block-level elements (such as div), will take the "full space" available anyway (different to how width: 100% does it).

See: http://jsfiddle.net/U7PhY/2/

Just in case it's not already clear from my answer: just don't set a width on the child div.

You might instead be interested in box-sizing: border-box.

How to send a html email with the bash command "sendmail"?

This page should help - http://www.zedwood.com/article/103/bash-send-mail-with-an-attachment

It includes a script to send e-mail with a MIME attachment, ie with a HTML page and images included.

Clicking a checkbox with ng-click does not update the model

Replacing ng-model with ng-checked works for me.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

jquery mobile background image

For jquery mobile and phonegap this is the correct code:

<style type="text/css">
body {
    background: url(imgage.gif);
    background-repeat:repeat-y;
    background-position:center center;
    background-attachment:scroll;
    background-size:100% 100%;
}
.ui-page {
    background: transparent;
}
.ui-content{
    background: transparent;
}
</style>

Position Absolute + Scrolling

position: fixed; will solve your issue. As an example, review my implementation of a fixed message area overlay (populated programmatically):

#mess {
    position: fixed;
    background-color: black;
    top: 20px;
    right: 50px;
    height: 10px;
    width: 600px;
    z-index: 1000;
}

And in the HTML

<body>
    <div id="mess"></div>
    <div id="data">
        Much content goes here.
    </div>
</body>

When #data becomes longer tha the sceen, #mess keeps its position on the screen, while #data scrolls under it.

How to fix "unable to open stdio.h in Turbo C" error?

First check whether the folder name is right or wrong since while you copying to one folder from other accidently it takes other folder address eg it take C instead of F So from OPTION>DIRECTORY change the folder name

Should I use Python 32bit or Python 64bit

In my experience, using the 32-bit version is more trouble-free. Unless you are working on applications that make heavy use of memory (mostly scientific computing, that uses more than 2GB memory), you're better off with 32-bit versions because:

  1. You generally use less memory.
  2. You have less problems using COM (since you are on Windows).
  3. If you have to load DLLs, they most probably are also 32-bit. Python 64-bit can't load 32-bit libraries without some heavy hacks running another Python, this time in 32-bit, and using IPC.
  4. If you have to load DLLs that you compile yourself, you'll have to compile them to 64-bit, which is usually harder to do (specially if using MinGW on Windows).
  5. If you ever use PyInstaller or py2exe, those tools will generate executables with the same bitness of your Python interpreter.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

Why doesn't catching Exception catch RuntimeException?

I faced similar scenario. It was happening because classA's initilization was dependent on classB's initialization. When classB's static block faced runtime exception, classB was not initialized. Because of this, classB did not throw any exception and classA's initialization failed too.

class A{//this class will never be initialized because class B won't intialize
  static{
    try{
      classB.someStaticMethod();
    }catch(Exception e){
      sysout("This comment will never be printed");
    }
 }
}

class B{//this class will never be initialized
 static{
    int i = 1/0;//throw run time exception 
 }

 public static void someStaticMethod(){}
}

And yes...catching Exception will catch run time exceptions as well.

Setting table column width

style="column-width:300px;white-space: normal;"

how to get file path from sd card in android

Environment.getExternalStorageDirectory() will NOT return path to micro SD card Storage.

how to get file path from sd card in android

By sd card, I am assuming that, you meant removable micro SD card.

In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type) in Context Class that allows apps to store data/files in micro SD cards.

Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.

Environment.getExternalStorageDirectory() was there from API level 1

getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).

But note that,

Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using getExternalStorageState(File).

There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

how to start stop tomcat server using CMD?

Create a .bat file and write two commands:

cd C:\ Path to your tomcat directory \ bin

startup.bat

Now on double-click, Tomcat server will start.

Select row with most recent date per user

Ok, this might be either a hack or error-prone, but somehow this is working as well-

SELECT id, MAX(user) as user, MAX(time) as time, MAX(io) as io FROM lms_attendance GROUP BY id;

Export a graph to .eps file with R

The easiest way I've found to create postscripts is the following, using the setEPS() command:

setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()

Creating a PDF from a RDLC Report in the Background

The below code work fine with me of sure thanks for the above comments. You can add report viewer and change the visible=false and use the below code on submit button:

protected void Button1_Click(object sender, EventArgs e)
{
    Warning[] warnings;
    string[] streamIds;
    string mimeType = string.Empty;
    string encoding = string.Empty;
    string extension = string.Empty;
    string HIJRA_TODAY = "01/10/1435";
    ReportParameter[] param = new ReportParameter[3];
    param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
    param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
    param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);

    byte[] bytes = ReportViewer1.LocalReport.Render(
        "PDF", 
        null, 
        out mimeType, 
        out encoding, 
        out extension, 
        out streamIds, 
        out warnings);

    Response.Buffer = true;
    Response.Clear();
    Response.ContentType = mimeType;
    Response.AddHeader(
        "content-disposition", 
        "attachment; filename= filename" + "." + extension);
    Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
    Response.Flush(); // send it to the client to download  
    Response.End();
}    

How to find the size of a table in SQL?

You may refer the answer by Marc_s in another thread, Very useful.

Get size of all tables in database

Case Statement Equivalent in R

i dont like any of these, they are not clear to the reader or the potential user. I just use an anonymous function, the syntax is not as slick as a case statement, but the evaluation is similar to a case statement and not that painful. this also assumes your evaluating it within where your variables are defined.

result <- ( function() { if (x==10 | y< 5) return('foo') 
                         if (x==11 & y== 5) return('bar')
                        })()

all of those () are necessary to enclose and evaluate the anonymous function.

How can I list ALL DNS records?

For Windows:

You may find the need to check the status of your domains DNS records, or check the Name Servers to see which records the servers are pulling.

  1. Launch Windows Command Prompt by navigating to Start > Command Prompt or via Run > CMD.

  2. Type NSLOOKUP and hit Enter. The default Server is set to your local DNS, the Address will be your local IP.

  3. Set the DNS Record type you wish to lookup by typing set type=## where ## is the record type, then hit Enter. You may use ANY, A, AAAA, A+AAAA, CNAME, MX, NS, PTR, SOA, or SRV as the record type.

  4. Now enter the domain name you wish to query then hit Enter.. In this example, we will use Managed.com.

  5. NSLOOKUP will now return the record entries for the domain you entered.

  6. You can also change the Name Servers which you are querying. This is useful if you are checking the records before DNS has fully propagated. To change the Name Server type server [name server]. Replace [name server] with the Name Servers you wish to use. In this example, we will set these as NSA.managed.com.

  7. Once changed, change the query type (Step 3) if needed then enter new a new domain (Step 4.)

For Linux:

1) Check DNS Records Using Dig Command Dig stands for domain information groper is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality than dig.

2) Check DNS Records Using NSlookup Command Nslookup is a program to query Internet domain name servers. Nslookup has two modes interactive and non-interactive.

Interactive mode allows the user to query name servers for information about various hosts and domains or to print a list of hosts in a domain.

Non-interactive mode is used to print just the name and requested information for a host or domain. It’s network administration tool which will help them to check and troubleshoot DNS related issues.

3) Check DNS Records Using Host Command host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host prints a short summary of its command line arguments and options.

How to validate an e-mail address in swift?

For anyone who is still looking for an answer to this, please have a look at the following framework;

ATGValidator

It is a rule based validation framework, which handles most of the validations out of box. And top it all, it has form validator which supports validation of multiple textfields at the same time.

For validating an email string, use the following;

"[email protected]".satisfyAll(rules: [StringRegexRule.email]).status

If you want to validate an email from textfield, try below code;

textfield.validationRules = [StringRegexRule.email]
textfield.validationHandler = { result in
    // This block will be executed with relevant result whenever validation is done.
    print(result.status, result.errors)
}
// Below line is to manually trigger validation.
textfield.validateTextField()

If you want to validate it while typing in textfield or when focus is changed to another field, add one of the following lines;

textfield.validateOnInputChange(true)
// or
textfield.validateOnFocusLoss(true)

Please check the readme file at the link for more use cases.

React-router urls don't work when refreshing or writing manually

If you are using Create React App:

There's a great walk though of this issue with solutions for many major hosting platforms that you can find HERE on the Create React App page. For example, I use React Router v4 and Netlify for my frontend code. All it took was adding 1 file to my public folder ("_redirects") and one line of code in that file:

/*  /index.html  200

Now my website properly renders paths like mysite.com/pricing when entered into the browser or when someone hits refresh.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Not able to run Appium {“message”:”A new session could not be created. (Original error: ‘java -version’ failed

I used Jdk 1.8 and JRE 1.8, Classpath is also set properly but I observed that Java command gives Error to initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Solution:
Uninstalled JRE and JDK completely 
Installed JRE 1.8 then
Installed JDK 1.8 
Set Classpath
check Java command works or not and its working 
also able to execute the Appium program thru Eclipse Kepler Service Release 2 with JDK1.8 support

What is the best way to uninstall gems from a rails3 project?

You must use 'gem uninstall gem_name' to uninstall a gem.

Note that if you installed the gem system-wide (ie. sudo bundle install) then you may need to specify the binary directory using the -n option, to ensure binaries belonging to the gem are removed. For example

sudo gem uninstall gem_name  -n /usr/lib/ruby/gems/1.9.1/bin

Difference between "and" and && in Ruby?

and has lower precedence, mostly we use it as a control-flow modifier such as if:

next if widget = widgets.pop

becomes

widget = widgets.pop and next

For or:

raise "Not ready!" unless ready_to_rock?

becomes

ready_to_rock? or raise "Not ready!"

I prefer to use if but not and, because if is more intelligible, so I just ignore and and or.

Refer to "Using “and” and “or” in Ruby" for more information.

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

Run "setup_xampp.bat/.sh" and then Delete "\" at the end, so your ServerRoot should be like "C:.....\apache" NO "C:.....\apache\"

How do I resolve git saying "Commit your changes or stash them before you can merge"?

For me this worked:

git reset --hard

and then

git pull origin <*current branch>

after that

git checkout <*branch>

Get total number of items on Json object?

Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length returns undefined rather than 5.

This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.

Remove blue border from css custom-styled button in Chrome

Until all modern browsers will start support css-selector :focus-visible,
the simplest and possibly best way to save accessibility is to remove this tricky focus only for mouse users and to save it for keyboard users:

1.Use this tiny polyfill (about 10kb): https://github.com/WICG/focus-visible
2.Add next code somewhere in your css:

.js-focus-visible :focus:not(.focus-visible) {
  outline: none;
}

Browser-support of css4-selector :focus-visible right now very weak:
https://caniuse.com/#search=focus-visible

Delaying a jquery script until everything else has loaded

This code block solve my problem,

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  $(window).bind("load", function () {_x000D_
    // Code here_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Does a finally block always get executed in Java?

Yes, finally will be called after the execution of the try or catch code blocks.

The only times finally won't be called are:

  1. If you invoke System.exit()
  2. If you invoke Runtime.getRuntime().halt(exitStatus)
  3. If the JVM crashes first
  4. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block
  5. If the OS forcibly terminates the JVM process; e.g., kill -9 <pid> on UNIX
  6. If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
  7. If the finally block is going to be executed by a daemon thread and all other non-daemon threads exit before finally is called

Setting CSS pseudo-class rules from JavaScript

You can't style a pseudo-class on a particular element alone, in the same way that you can't have a pseudo-class in an inline style="..." attribute (as there is no selector).

You can do it by altering the stylesheet, for example by adding the rule:

#elid:hover { background: red; }

assuming each element you want to affect has a unique ID to allow it to be selected.

In theory the document you want is http://www.w3.org/TR/DOM-Level-2-Style/Overview.html which means you can (given a pre-existing embedded or linked stylesheet) using syntax like:

document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';

IE, of course, requires its own syntax:

document.styleSheets[0].addRule('#elid:hover', 'background-color: red', 0);
document.styleSheets[0].rules[0].style.backgroundColor= 'red';

Older and minor browsers are likely not to support either syntax. Dynamic stylesheet-fiddling is rarely done because it's quite annoying to get right, rarely needed, and historically troublesome.

Name node is in safe mode. Not able to leave

The Command did not work for me but the following did

hdfs dfsadmin -safemode leave

I used the hdfs command instead of the hadoop command.

Check out http://ask.gopivotal.com/hc/en-us/articles/200933026-HDFS-goes-into-readonly-mode-and-errors-out-with-Name-node-is-in-safe-mode- link too

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

This error might occur when you return an object instead of a string in your __unicode__ method. For example:

class Author(models.Model):
    . . . 
    name = models.CharField(...)


class Book(models.Model):
    . . .
    author = models.ForeignKey(Author, ...)
    . . .
    def __unicode__(self):
        return self.author  # <<<<<<<< this causes problems

To avoid this error you can cast the author instance to unicode:

class Book(models.Model):
    . . . 
    def __unicode__(self):
        return unicode(self.author)  # <<<<<<<< this is OK

top align in html table?

Some CSS :

table td, table td * {
    vertical-align: top;
}

Speed up rsync with Simultaneous/Concurrent File Transfers?

There are a number of alternative tools and approaches for doing this listed arround the web. For example:

  • The NCSA Blog has a description of using xargs and find to parallelize rsync without having to install any new software for most *nix systems.

  • And parsync provides a feature rich Perl wrapper for parallel rsync.

Difference between "as $key => $value" and "as $value" in PHP foreach

A very important place where it is REQUIRED to use the key => value pair in foreach loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features array. You should do the following:

foreach($features as $key => $feature) {
    $features[$key]['new_key'] = 'new value';  
} 


Instead of this:

foreach($features as $feature) {
    $feature['new_key'] = 'new value';  
} 

The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.

While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature which is unset after each loop iteration.

Maximum length of HTTP GET request

You are asking two separate questions here:

What's the maximum length of an HTTP GET request?

As already mentioned, HTTP itself doesn't impose any hard-coded limit on request length; but browsers have limits ranging on the 2 KB - 8 KB (255 bytes if we count very old browsers).

Is there a response error defined that the server can/should return if it receives a GET request exceeds this length?

That's the one nobody has answered.

HTTP 1.1 defines status code 414 Request-URI Too Long for the cases where a server-defined limit is reached. You can see further details on RFC 2616.

For the case of client-defined limits, there isn't any sense on the server returning something, because the server won't receive the request at all.

How to get Real IP from Visitor?

This is my function.

benefits :

  • Work if $_SERVER was not available.
  • Filter private and/or reserved IPs;
  • Process all forwarded IPs in X_FORWARDED_FOR
  • Compatible with CloudFlare
  • Can set a default if no valid IP found!
  • Short & Simple !

/**
 * Get real user ip
 *
 * Usage sample:
 * GetRealUserIp();
 * GetRealUserIp('ERROR',FILTER_FLAG_NO_RES_RANGE);
 * 
 * @param string $default default return value if no valid ip found
 * @param int    $filter_options filter options. default is FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
 *
 * @return string real user ip
 */

function GetRealUserIp($default = NULL, $filter_options = 12582912) {
    $HTTP_X_FORWARDED_FOR = isset($_SERVER)? $_SERVER["HTTP_X_FORWARDED_FOR"]:getenv('HTTP_X_FORWARDED_FOR');
    $HTTP_CLIENT_IP = isset($_SERVER)?$_SERVER["HTTP_CLIENT_IP"]:getenv('HTTP_CLIENT_IP');
    $HTTP_CF_CONNECTING_IP = isset($_SERVER)?$_SERVER["HTTP_CF_CONNECTING_IP"]:getenv('HTTP_CF_CONNECTING_IP');
    $REMOTE_ADDR = isset($_SERVER)?$_SERVER["REMOTE_ADDR"]:getenv('REMOTE_ADDR');

    $all_ips = explode(",", "$HTTP_X_FORWARDED_FOR,$HTTP_CLIENT_IP,$HTTP_CF_CONNECTING_IP,$REMOTE_ADDR");
    foreach ($all_ips as $ip) {
        if ($ip = filter_var($ip, FILTER_VALIDATE_IP, $filter_options))
            break;
    }
    return $ip?$ip:$default;
}

How to set conditional breakpoints in Visual Studio?

Visual Studio provides lots of options for conditional breakpoints:

To set any of these you

  1. Set a breakpoint.
  2. Right-Click over the breakpoint, and in the popup menu you select an option that suites you.

These options are as follows:

  • You can set a condition, based on a code expression that you supply (select Condition from the popup menu). For instance, you can specify that foo == 8 or some other expression.
  • You can make breakpoints trigger after they have been hit a certain number of times. (select Hit Count from the popup menu). This is a fun option to play with as you actually aren't limited to breaking on a certain hit count, but you have options for a few other scenarios as well. I'll leave it to you to explore the possibilities.
  • You can Set filters on the Process ID, thread ID, and machine name (select Filter from the popup menu)

What permission do I need to access Internet from an Android application?

As per current versions, Android doesn't ask for permission to interact with the internet but you can add the below code which will help for users using older versions Just add these in AndroidManifest

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

How to convert a column of DataTable to a List

I make a sample for you , and I hope this is helpful...

    static void Main(string[] args)
    {
        var cols = new string[] { "col1", "col2", "col3", "col4", "col5" };

        DataTable table = new DataTable();
        foreach (var col in cols)
            table.Columns.Add(col);

        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });

        foreach (var col in cols)
        {
            var results = from p in table.AsEnumerable()
                          select p[col];

            Console.WriteLine("*************************");
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }
        }


        Console.ReadLine();
    }

What is the preferred syntax for defining enums in JavaScript?

You can use Object.prototype.hasOwnProperty()

_x000D_
_x000D_
var findInEnum,_x000D_
    colorEnum = {_x000D_
    red : 0,_x000D_
    green : 1,_x000D_
    blue : 2_x000D_
};_x000D_
_x000D_
// later on_x000D_
_x000D_
findInEnum = function (enumKey) {_x000D_
  if (colorEnum.hasOwnProperty(enumKey)) {_x000D_
    return enumKey+' Value: ' + colorEnum[enumKey]_x000D_
  }_x000D_
}_x000D_
_x000D_
alert(findInEnum("blue"))
_x000D_
_x000D_
_x000D_

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

How do I enable EF migrations for multiple contexts to separate databases?

I just bumped into the same problem and I used the following solution (all from Package Manager Console)

PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyProject.Models.ContextA
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextB" -ContextTypeName MyProject.Models.ContextB

This will create 2 separate folders in the Migrations folder. Each will contain the generated Configuration.cs file. Unfortunately you still have to rename those Configuration.cs files otherwise there will be complaints about having two of them. I renamed my files to ConfigA.cs and ConfigB.cs

EDIT: (courtesy Kevin McPheat) Remember when renaming the Configuration.cs files, also rename the class names and constructors /EDIT

With this structure you can simply do

PM> Add-Migration -ConfigurationTypeName ConfigA
PM> Add-Migration -ConfigurationTypeName ConfigB

Which will create the code files for the migration inside the folder next to the config files (this is nice to keep those files together)

PM> Update-Database -ConfigurationTypeName ConfigA
PM> Update-Database -ConfigurationTypeName ConfigB

And last but not least those two commands will apply the correct migrations to their corrseponding databases.

EDIT 08 Feb, 2016: I have done a little testing with EF7 version 7.0.0-rc1-16348

I could not get the -o|--outputDir option to work. It kept on giving Microsoft.Dnx.Runtime.Common.Commandline.CommandParsingException: Unrecognized command or argument

However it looks like the first time an migration is added it is added into the Migrations folder, and a subsequent migration for another context is automatically put into a subdolder of migrations.

The original names ContextA seems to violate some naming conventions so I now use ContextAContext and ContextBContext. Using these names you could use the following commands: (note that my dnx still works from the package manager console and I do not like to open a separate CMD window to do migrations)

PM> dnx ef migrations add Initial -c "ContextAContext"
PM> dnx ef migrations add Initial -c "ContextBContext"

This will create a model snapshot and a initial migration in the Migrations folder for ContextAContext. It will create a folder named ContextB containing these files for ContextBContext

I manually added a ContextA folder and moved the migration files from ContextAContext into that folder. Then I renamed the namespace inside those files (snapshot file, initial migration and note that there is a third file under the initial migration file ... designer.cs). I had to add .ContextA to the namespace, and from there the framework handles it automatically again.

Using the following commands would create a new migration for each context

PM>  dnx ef migrations add Update1 -c "ContextAContext"
PM>  dnx ef migrations add Update1 -c "ContextBContext"

and the generated files are put in the correct folders.

How to set upload_max_filesize in .htaccess?

Both commands are correct

php_value post_max_size 30M 
php_value upload_max_filesize 30M 

BUT to use the .htaccess you have to enable rewrite_module in Apache config file. In httpd.conf find this line:

# LoadModule rewrite_module modules/mod_rewrite.so

and remove the #.

right align an image using CSS HTML

Float the image right, which will at first cause your text to wrap around it.

Then whatever the very next element is, set it to { clear: right; } and everything will stop wrapping around the image.

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

How to make the 'cut' command treat same sequental delimiters as one?

This Perl one-liner shows how closely Perl is related to awk:

perl -lane 'print $F[3]' text.txt

However, the @F autosplit array starts at index $F[0] while awk fields start with $1

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

What is IllegalStateException?

Illegal State Exception is an Unchecked exception.

It indicate that method has been invoked at wrong time.

example:

Thread t = new Thread();
t.start();
//
//
t.start();

output:

Runtime Excpetion: IllegalThreadStateException

We cant start the Thread again, it will throw IllegalStateException.

Calculating average of an array list?

You can use standard looping constructs or iterator/listiterator for the same :

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
double sum = 0;
Iterator<Integer> iter1 = list.iterator();
while (iter1.hasNext()) {
    sum += iter1.next();
}
double average = sum / list.size();
System.out.println("Average = " + average);

If using Java 8, you could use Stream or IntSream operations for the same :

OptionalDouble avg = list.stream().mapToInt(Integer::intValue).average();
System.out.println("Average = " + avg.getAsDouble());

Reference : Calculating average of arraylist

How to create a simple http proxy in node.js?

Here's an implementation using node-http-proxy from nodejitsu.

var http = require('http');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});

http.createServer(function(req, res) {
    proxy.web(req, res, { target: 'http://www.google.com' });
}).listen(3000);

Session 'app' error while installing APK

i was also getting the same error repeatedly but could not solve it as i am complete new to android development. But then it came to my mind that the error is appearing because its not able to install the apk in the device as the error says. So i make sure that my Oneplus3 is in debugging mode and also allowing file transfer when connected via USB. And this solved the problem.

Also previously it was not doing the instant run but now it does.

So check whether your android device is allowed to transfer files while connected via USB. This might help.

pyplot scatter plot marker size

This can be a somewhat confusing way of defining the size but you are basically specifying the area of the marker. This means, to double the width (or height) of the marker you need to increase s by a factor of 4. [because A = WH => (2W)(2H)=4A]

There is a reason, however, that the size of markers is defined in this way. Because of the scaling of area as the square of width, doubling the width actually appears to increase the size by more than a factor 2 (in fact it increases it by a factor of 4). To see this consider the following two examples and the output they produce.

# doubling the width of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*4**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()

gives

enter image description here

Notice how the size increases very quickly. If instead we have

# doubling the area of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*2**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()

gives

enter image description here

Now the apparent size of the markers increases roughly linearly in an intuitive fashion.

As for the exact meaning of what a 'point' is, it is fairly arbitrary for plotting purposes, you can just scale all of your sizes by a constant until they look reasonable.

Hope this helps!

Edit: (In response to comment from @Emma)

It's probably confusing wording on my part. The question asked about doubling the width of a circle so in the first picture for each circle (as we move from left to right) it's width is double the previous one so for the area this is an exponential with base 4. Similarly the second example each circle has area double the last one which gives an exponential with base 2.

However it is the second example (where we are scaling area) that doubling area appears to make the circle twice as big to the eye. Thus if we want a circle to appear a factor of n bigger we would increase the area by a factor n not the radius so the apparent size scales linearly with the area.

Edit to visualize the comment by @TomaszGandor:

This is what it looks like for different functions of the marker size:

Exponential, Square, or Linear size

x = [0,2,4,6,8,10,12,14,16,18]
s_exp = [20*2**n for n in range(len(x))]
s_square = [20*n**2 for n in range(len(x))]
s_linear = [20*n for n in range(len(x))]
plt.scatter(x,[1]*len(x),s=s_exp, label='$s=2^n$', lw=1)
plt.scatter(x,[0]*len(x),s=s_square, label='$s=n^2$')
plt.scatter(x,[-1]*len(x),s=s_linear, label='$s=n$')
plt.ylim(-1.5,1.5)
plt.legend(loc='center left', bbox_to_anchor=(1.1, 0.5), labelspacing=3)
plt.show()

Convert columns to string in Pandas

If you need to convert ALL columns to strings, you can simply use:

df = df.astype(str)

This is useful if you need everything except a few columns to be strings/objects, then go back and convert the other ones to whatever you need (integer in this case):

 df[["D", "E"]] = df[["D", "E"]].astype(int) 

How do I install chkconfig on Ubuntu?

But how do I run this? I tried typing: sudo chkconfig.install which doesn't work.

I'm not sure where you got this package or what it contains; A url of download would be helpful. Without being able to look at the contents of chkconfig.install; I'm surprised to find a unix tool like chkconfig to be bundled in a zip archive, maybe it is still yet to be uncompressed, a tar.gz? but maybe it is a shell script?

I should suggest editing it and seeing what you are executing.

sh chkconfig.install or ./chkconfig.install ; which might work....but my suggestion would be to learn to use update-rc.d as the other answers have suggested but do not speak directly to the question...which is pretty hard to answer without being able to look at the data yourself.

File Upload ASP.NET MVC 3.0

file upload using formdata

.cshtml file

     var files = $("#file").get(0).files;
     if (files.length > 0) {
                data.append("filekey", files[0]);}


   $.ajax({
            url: '@Url.Action("ActionName", "ControllerName")', type: "POST", processData: false,
            data: data, dataType: 'json',
            contentType: false,
            success: function (data) {
                var response=data.JsonData;               
            },
            error: function (er) { }

        });

Server side code

if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    var pic = System.Web.HttpContext.Current.Request.Files["filekey"];
                    HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
                    var fileName = Path.GetFileName(filebase.FileName);


                    string fileExtension = System.IO.Path.GetExtension(fileName);

                    if (fileExtension == ".xls" || fileExtension == ".xlsx")
                    {
                        string FileName = Guid.NewGuid().GetHashCode().ToString("x");
                        string dirLocation = Server.MapPath("~/Content/PacketExcel/");
                        if (!Directory.Exists(dirLocation))
                        {
                            Directory.CreateDirectory(dirLocation);
                        }
                        string fileLocation = Server.MapPath("~/Content/PacketExcel/") + FileName + fileExtension;
                        filebase.SaveAs(fileLocation);
}
}

How to change the DataTable Column Name?

Try this:

dataTable.Columns["Marks"].ColumnName = "SubjectMarks";

Difference between an API and SDK

I'm not sure there's any official definition of these two terms. I understand an API to be a set of documented programmable libraries and supporting source such as headers or IDL files. SDKs usually contain APIs but often often add compilers, tools, and samples to the mix.

Logging POST data from $request_body

Try echo_read_request_body.

"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."

location /log {
  log_format postdata $request_body;
  access_log /mnt/logs/nginx/my_tracking.access.log postdata;
  echo_read_request_body;
}

How do I find which transaction is causing a "Waiting for table metadata lock" state?

SHOW ENGINE INNODB STATUS \G

Look for the Section -

TRANSACTIONS

We can use INFORMATION_SCHEMA Tables.

Useful Queries

To check about all the locks transactions are waiting for:

USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;

A list of blocking transactions:

SELECT * 
FROM INNODB_LOCKS 
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);

OR

SELECT INNODB_LOCKS.* 
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
  ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);

A List of locks on particular table:

SELECT * FROM INNODB_LOCKS 
WHERE LOCK_TABLE = db_name.table_name;

A list of transactions waiting for locks:

SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';

Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.

How to check if command line tools is installed

In macOS Catalina, and possibly some earlier versions, you can find out where the command line tools are installed using:

xcode-select -p a.k.a. xcode-select --print-path

Which will, if it is installed, respond with something like:

/Library/Developer/CommandLineTools

To find out which version you have installed there, you can use:

xcode-select -v a.k.a. xcode-select --version

Which will return something like:

xcode-select version 2370.

However, if you attempt to upgrade it to the latest version, assuming it is installed, using this:

xcode-select --install

You will receive in response:

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

Which rather erroneously gives the impression you need to use Spotlight find something called 'Software Update'. In actual fact, you need to continue in the Terminal, and use this:

softwareupdate -i -a a.k.a. softwareupdate --install --all

Which tries to update everything it can and may well respond with:

Software Update Tool

Finding available software
No new software available.

To find out which versions of the different Apple SDKs are installed on your machine, use this:

xcodebuild -showsdks

How can I clear the SQL Server query cache?

Note that neither DBCC DROPCLEANBUFFERS; nor DBCC FREEPROCCACHE; is supported in SQL Azure / SQL Data Warehouse.

However, if you need to reset the plan cache in SQL Azure, you can alter one of the tables in the query (for instance, just add then remove a column), this will have the side-effect of removing the plan from the cache.

I personally do this as a way of testing query performance without having to deal with cached plans.

More details about SQL Azure Procedure Cache here

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

For me, it was Maps Embed API that I had to enable.

In the Google Cloud Console

Go to API tab, look through the Additional APIs section and try to enable any map-related APIs.

enter image description here

How to wait for all threads to finish, using ExecutorService?

Clean way with ExecutorService

 List<Future<Void>> results = null;
 try {
     List<Callable<Void>> tasks = new ArrayList<>();
     ExecutorService executorService = Executors.newFixedThreadPool(4);
     results = executorService.invokeAll(tasks);
 } catch (InterruptedException ex) {
     ...
 } catch (Exception ex) {
     ...
 }

Disable Scrolling on Body

This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

PHP to search within txt file and echo the whole line

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

How to use mongoose findOne

In my case same error is there , I am using Asyanc / Await functions , for this needs to add AWAIT for findOne

Ex:const foundUser = User.findOne ({ "email" : req.body.email });

above , foundUser always contains Object value in both cases either user found or not because it's returning values before finishing findOne .

const foundUser = await User.findOne ({ "email" : req.body.email });

above , foundUser returns null if user is not there in collection with provided condition . If user found returns user document.

Node.js: How to send headers with form data using request module?

I found the solution of this problem and i should work i'm sure about this because i also face the same problem

here is my solution----->

var request = require('request');

//set url
var url = 'http://localhost:8088/example';

//set header
var headers = {
    'Authorization': 'Your authorization'
};

//set form data
var form = {first_name: first_name, last_name: last_name};

//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {

    var bodyValues = JSON.parse(body);
    res.send(bodyValues);
});

Resetting a setTimeout

i know this is an old thread but i came up with this today

var timer       = []; //creates a empty array called timer to store timer instances
var afterTimer = function(timerName, interval, callback){
    window.clearTimeout(timer[timerName]); //clear the named timer if exists
    timer[timerName] = window.setTimeout(function(){ //creates a new named timer 
        callback(); //executes your callback code after timer finished
    },interval); //sets the timer timer
}

and you invoke using

afterTimer('<timername>string', <interval in milliseconds>int, function(){
   your code here
});

This Handler class should be static or leaks might occur: IncomingHandler

This way worked well for me, keeps code clean by keeping where you handle the message in its own inner class.

The handler you wish to use

Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());

The inner class

class IncomingHandlerCallback implements Handler.Callback{

        @Override
        public boolean handleMessage(Message message) {

            // Handle message code

            return true;
        }
}

How do I round a double to two decimal places in Java?

Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:

DecimalFormat twoDForm = new DecimalFormat("#.00");

In Node.js, how do I turn a string to a json?

You need to use this function.

JSON.parse(yourJsonString);

And it will return the object / array that was contained within the string.

Mercurial — revert back to old version and continue from there

After using hg update -r REV it wasn't clear in the answer about how to commit that change so that you can then push.

If you just try to commit after the update, Mercurial doesn't think there are any changes.

I had to first make a change to any file (say in a README) so Mercurial recognized that I made a new change, then I could commit that.

This then created two heads as mentioned.

To get rid of the other head before pushing, I then followed the No-Op Merges step to remedy that situation.

I was then able to push.

Multiple types were found that match the controller named 'Home'

Some time in a single application this Issue also come In that case select these checkbox when you publish your application enter image description here

Finding height in Binary Search Tree

I know that I’m late to the party. After looking into wonderful answers provided here, I thought mine will add some value to this post. Although the posted answers are amazing and easy to understand however, all are calculating the height to the BST in linear time. I think this can be improved and Height can be retrieved in constant time, hence writing this answer – hope you will like it. Let’s start with the Node class:

public class Node
{
    public Node(string key)
    {
        Key = key;
        Height = 1;
    }    

    public int Height { get; set; } 
    public string Key { get; set; }
    public Node Left { get; set; }
    public Node Right { get; set; }

    public override string ToString()
    {
        return $"{Key}";
    }
}

BinarySearchTree class

So you might have guessed the trick here… Im keeping node instance variable Height to keep track of each node when added. Lets move to the BinarySearchTree class that allows us to add nodes into our BST:

public class BinarySearchTree
{
    public Node RootNode { get; private set; }

    public void Put(string key)
    {
        if (ContainsKey(key))
        {
            return;
        }

        RootNode = Put(RootNode, key);
    }

    private Node Put(Node node, string key)
    {
        if (node == null) return new Node(key);

        if (node.Key.CompareTo(key) < 0)
        {
            node.Right = Put(node.Right, key);
        }
        else
        {
            node.Left = Put(node.Left, key);
        }       
        
        // since each node has height property that is maintained through this Put method that creates the binary search tree.
        // calculate the height of this node by getting the max height of its left or right subtree and adding 1 to it.        
        node.Height = Math.Max(GetHeight(node.Left), GetHeight(node.Right)) + 1;
        return node;
    }

    private int GetHeight(Node node)
    {
        return node?.Height ?? 0;
    }

    public Node Get(Node node, string key)
    {
        if (node == null) return null;
        if (node.Key == key) return node;

        if (node.Key.CompareTo(key) < 0)
        {
            // node.Key = M, key = P which results in -1
            return Get(node.Right, key);
        }

        return Get(node.Left, key);
    }

    public bool ContainsKey(string key)
    {
        Node node = Get(RootNode, key);
        return node != null;
    }
}

Once we have added the key, values in the BST, we can just call Height property on the RootNode object that will return us the Height of the RootNode tree in constant time. The trick is to keep the height updated when a new node is added into the tree. Hope this helps someone out there in the wild world of computer science enthusiast!

Unit test:

[TestCase("SEARCHEXAMPLE", 6)]
[TestCase("SEBAQRCHGEXAMPLE", 6)]
[TestCase("STUVWXYZEBAQRCHGEXAMPLE", 8)]
public void HeightTest(string data, int expectedHeight)
{
    // Arrange.
    var runner = GetRootNode(data);

    
    //  Assert.
    Assert.AreEqual(expectedHeight, runner.RootNode.Height);
}

private BinarySearchTree GetRootNode(string data)
{
    var runner = new BinarySearchTree();
    foreach (char nextKey in data)
    {
        runner.Put(nextKey.ToString());
    }

    return runner;
}

Note: This idea of keeping the Height of tree maintained in every Put operation is inspired by the Size of BST method found in the 3rd chapter (page 399) of Algorithm (Fourth Edition) book.

Have a div cling to top of screen if scrolled down past it

The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.

Derived from the code viixii.com uses I ended up using this:

function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top)
        $('#sticky-element').addClass('sticky');
    else
        $('#sticky-element').removeClass('sticky');
}

$(function() {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.

Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.

Just place an empty div with a class acting like an anchor just above the element you want to have fixed.

Like so:

<div id="sticky-anchor"></div>
<div id="sticky-element">Your sticky content</div>

All credit for the code goes to viixii.com

Gradle, Android and the ANDROID_HOME SDK location

For whatever reason, the gradle script is not picking up the value of ANDROID_HOME from the environment. Try specifying it on the command line explicitly

$ ANDROID_HOME=<sdk location> ./gradlew

Get dates from a week number in T-SQL

The most votes answer works fine except the 1st week and last week of year. When datecol value is '2009-01-01', the result will be 01/03/2009 and 12/28/2008.

My solution:

DECLARE @Date date = '2009-03-01', @WeekNum int, @StartDate date;
SELECT @WeekNum = DATEPART(WEEK, @Date);
SELECT @StartDate = DATEADD(DAY, -(DATEPART(WEEKDAY, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0)) + 6), DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0));
SELECT CONVERT(nvarchar, CASE WHEN @WeekNum = 1 THEN CAST(DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0) AS date) ELSE DATEADD(DAY, 7 * @WeekNum, @StartDate) END, 101) AS StartOfWeek
      ,CONVERT(nvarchar, CASE WHEN @WeekNum = DATEPART(WEEK, DATEADD(DAY, -1, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date) + 1, 0))) THEN DATEADD(DAY, -1, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date) + 1, 0)) ELSE DATEADD(DAY, 7 * @WeekNum + 6, @StartDate) END, 101) AS EndOfWeek;

This will display 01/01/2009 and 01/03/2009 for the 1st week, and display 03/01/2009 and 03/07/2009 for the 10th week.

I think this would be what you want exactly. You can replace the variables with their expressions as you wish.

"unadd" a file to svn before commit

For Files - svn revert filename

For Folders - svn revert -R folder

How to stop C# console applications from closing automatically?

If you do not want the program to close even if a user presses anykey;

 while (true) {
      System.Console.ReadKey();                
 };//This wont stop app

call a static method inside a class?

Let's assume this is your class:

class Test
{
    private $baz = 1;

    public function foo() { ... }

    public function bar() 
    {
        printf("baz = %d\n", $this->baz);
    }

    public static function staticMethod() { echo "static method\n"; }
}

From within the foo() method, let's look at the different options:

$this->staticMethod();

So that calls staticMethod() as an instance method, right? It does not. This is because the method is declared as public static the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.

$this::staticMethod();

Since PHP 5.3 you can use $var::method() to mean <class-of-$var>::; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:

self::staticMethod();

Now, before you start thinking that the :: is the static call operator, let me give you another example:

self::bar();

This will print baz = 1, which means that $this->bar() and self::bar() do exactly the same thing; that's because :: is just a scope resolution operator. It's there to make parent::, self:: and static:: work and give you access to static variables; how a method is called depends on its signature and how the caller was called.

To see all of this in action, see this 3v4l.org output.

How to use `replace` of directive definition?

Replace [True | False (default)]

Effect

1.  Replace the directive element. 

Dependency:

1. When replace: true, the template or templateUrl must be required. 

Can you split/explode a field in a MySQL query?

Well, nothing I used worked, so I decided creating a real simple split function, hope it helps:

    DECLARE inipos INTEGER;
    DECLARE endpos INTEGER;
    DECLARE maxlen INTEGER;
    DECLARE item VARCHAR(100);
    DECLARE delim VARCHAR(1);

    SET delim = '|';
    SET inipos = 1;
    SET fullstr = CONCAT(fullstr, delim);
    SET maxlen = LENGTH(fullstr);

    REPEAT
        SET endpos = LOCATE(delim, fullstr, inipos);
        SET item =  SUBSTR(fullstr, inipos, endpos - inipos);

        IF item <> '' AND item IS NOT NULL THEN           
            USE_THE_ITEM_STRING;
        END IF;
        SET inipos = endpos + 1;
    UNTIL inipos >= maxlen END REPEAT;

How can I listen for a click-and-hold in jQuery?

Try this:

var thumbnailHold;

    $(".image_thumb").mousedown(function() {
        thumbnailHold = setTimeout(function(){
             checkboxOn(); // Your action Here

         } , 1000);
     return false;
});

$(".image_thumb").mouseup(function() {
    clearTimeout(thumbnailHold);
});

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

In the Hibernate mapping file for the id property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.

If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.

Check whether a variable is a string in Ruby

A more duck-typing approach would be to say

foo.respond_to?(:to_str)

to_str indicates that an object's class may not be an actual descendant of the String, but the object itself is very much string-like (stringy?).

retrieve links from web page using python and BeautifulSoup

Here's a short snippet using the SoupStrainer class in BeautifulSoup:

import httplib2
from bs4 import BeautifulSoup, SoupStrainer

http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')

for link in BeautifulSoup(response, parse_only=SoupStrainer('a')):
    if link.has_attr('href'):
        print(link['href'])

The BeautifulSoup documentation is actually quite good, and covers a number of typical scenarios:

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

Edit: Note that I used the SoupStrainer class because it's a bit more efficient (memory and speed wise), if you know what you're parsing in advance.

NavigationBar bar, tint, and title text color in iOS 8

If you want to set the tint color and bar color for the entire app, the following code can be added to AppDelegate.swift in

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

    var navigationBarAppearace = UINavigationBar.appearance()

    navigationBarAppearace.tintColor = UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0)
    navigationBarAppearace.barTintColor = UIColor(red:0.76, green:0.40, blue:0.40, alpha:1.0)
    navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
    return true
`

Navigation barTintColor and tintColor is set

Purge Kafka Topic

Temporarily update the retention time on the topic to one second:

kafka-topics.sh --zookeeper <zkhost>:2181 --alter --topic <topic name> --config retention.ms=1000

And in newer Kafka releases, you can also do it with kafka-configs --entity-type topics

kafka-configs.sh --zookeeper <zkhost>:2181 --entity-type topics --alter --entity-name <topic name> --add-config retention.ms=1000

then wait for the purge to take effect (about one minute). Once purged, restore the previous retention.ms value.

IF... OR IF... in a windows batch file

There is no IF <arg> OR or ELIF or ELSE IF in Batch, however...

Try nesting the other IF's inside the ELSE of the previous IF.

IF <arg> (
    ....
) ELSE (
    IF <arg> (
        ......
    ) ELSE (
        IF <arg> (
            ....
        ) ELSE (
    )
)

How to "z-index" to make a menu always on top of the content

Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute and right:0

#right { 
    background-color: red;
    height: 300px;
    width: 300px;
    z-index: 999999;
    margin-top: 0px;
    position: absolute;
    right:0;
}

here is the full code: http://jsfiddle.net/T9FJL/

When should one use a spinlock instead of mutex?

Continuing with Mecki's suggestion, this article pthread mutex vs pthread spinlock on Alexander Sandler's blog, Alex on Linux shows how the spinlock & mutexes can be implemented to test the behavior using #ifdef.

However, be sure to take the final call based on your observation, understanding as the example given is an isolated case, your project requirement, environment may be entirely different.

Function pointer to member function

Call member function on string command

#include <iostream>
#include <string>


class A 
{
public: 
    void call();
private:
    void printH();
    void command(std::string a, std::string b, void (A::*func)());
};

void A::printH()
{
    std::cout<< "H\n";
}

void A::call()
{
    command("a","a", &A::printH);
}

void A::command(std::string a, std::string b, void (A::*func)())
{
    if(a == b)
    {
        (this->*func)();
    }
}

int main()
{
    A a;
    a.call();
    return 0;
}

Pay attention to (this->*func)(); and the way to declare the function pointer with class name void (A::*func)()

How to generate a random string of 20 characters

public String randomString(String chars, int length) {
  Random rand = new Random();
  StringBuilder buf = new StringBuilder();
  for (int i=0; i<length; i++) {
    buf.append(chars.charAt(rand.nextInt(chars.length())));
  }
  return buf.toString();
}

Transparent CSS background color

now you can use rgba in CSS properties like this:

.class {
    background: rgba(0,0,0,0.5);
}

0.5 is the transparency, change the values according to your design.

Live demo http://jsfiddle.net/EeAaB/

more info http://css-tricks.com/rgba-browser-support/

How to use a variable in the replacement side of the Perl substitution operator?

# perl -de 0
$match="hi(.*)"
$sub='$1'
$res="hi1234"
$res =~ s/$match/$sub/gee
p $res
  1234

Be careful, though. This causes two layers of eval to occur, one for each e at the end of the regex:

  1. $sub --> $1
  2. $1 --> final value, in the example, 1234

Does an HTTP Status code of 0 have any meaning?

Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.

What is PAGEIOLATCH_SH wait type in SQL Server?

PAGEIOLATCH_SH wait type usually comes up as the result of fragmented or unoptimized index.

Often reasons for excessive PAGEIOLATCH_SH wait type are:

  • I/O subsystem has a problem or is misconfigured
  • Overloaded I/O subsystem by other processes that are producing the high I/O activity
  • Bad index management
  • Logical or physical drive misconception
  • Network issues/latency
  • Memory pressure
  • Synchronous Mirroring and AlwaysOn AG

In order to try and resolve having high PAGEIOLATCH_SH wait type, you can check:

  • SQL Server, queries and indexes, as very often this could be found as a root cause of the excessive PAGEIOLATCH_SH wait types
  • For memory pressure before jumping into any I/O subsystem troubleshooting

Always keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH can be expected.

You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types

Gulp command not found after install

If you're using tcsh (which is my default shell on Mac OS X), you probably just need to type rehash into the shell just after the install completes:

npm install -g gulp

followed immediately by:

rehash

Otherwise, if this is your very first time installing gulp, your shell may not recognize that there's a new executable installed -- so you either need to start a new shell, or type rehash in the current shell.

(This is basically a one-time thing for each command you install globally.)

jquery animate .css

The example from jQuery's website animates size AND font but you could easily modify it to fit your needs

$("#go").click(function(){
  $("#block").animate({ 
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em", 
    borderWidth: "10px"
  }, 1500 );

http://api.jquery.com/animate/

How to sum up an array of integers in C#

An alternative also it to use the Aggregate() extension method.

var sum = arr.Aggregate((temp, x) => temp+x);

PHP display current server path

If you call getcwd it should give you the path:

<?php
  echo getcwd();
?>

Using jq to parse and display multiple fields in a json serially

my approach will be (your json example is not well formed.. guess thats only a sample)

jq '.Front[] | [.Name,.Out,.In,.Groups] | join("|")'  front.json  > output.txt

returns something like this

"new.domain.com-80|8.8.8.8|192.168.2.2:80|192.168.3.29:80 192.168.3.30:80"
"new.domain.com -443|8.8.8.8|192.168.2.2:443|192.168.3.29:443 192.168.3.30:443"

and grep the output with regular expression.

How should I set the default proxy to use default credentials?

Is need in some systems set null the Proxy proprerty:

Net.WebRequest.DefaultWebProxy.Credentials = System.Net.CredentialCache.DefaultCredentials Dim request As WebRequest = WebRequest.Create(sRemoteFileURL) request.Proxy = Nothing

It's a bug.

Display all items in array using jquery

You can do it like this by iterating through the array in a loop, accumulating the new HTML into it's own array and then joining the HTML all together and inserting it into the DOM at the end:

var array = [...];
var newHTML = [];
for (var i = 0; i < array.length; i++) {
    newHTML.push('<span>' + array[i] + '</span>');
}
$(".element").html(newHTML.join(""));

Some people prefer to use jQuery's .each() method instead of the for loop which would work like this:

var array = [...];
var newHTML = [];
$.each(array, function(index, value) {
    newHTML.push('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

Or because the output of the array iteration is itself an array with one item derived from each item in the original array, jQuery's .map can be used like this:

var array = [...];
var newHTML = $.map(array, function(value) {
    return('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

Which you should use is a personal choice depending upon your preferred coding style, sensitivity to performance and familiarity with .map(). My guess is that the for loop would be the fastest since it has fewer function calls, but if performance was the main criteria, then you would have to benchmark the options to actually measure.

FYI, in all three of these options, the HTML is accumulated into an array, then joined together at the end and the inserted into the DOM all at once. This is because DOM operations are usually the slowest part of an operation like this so it's best to minimize the number of separate DOM operations. The results are accumulated into an array because adding items to an array and then joining them at the end is usually faster than adding strings as you go.


And, if you can live with IE9 or above (or install an ES5 polyfill for .map()), you can use the array version of .map like this:

var array = [...];
$(".element").html(array.map(function(value) {
    return('<span>' + value + '</span>');
}).join(""));

Note: this version also gets rid of the newHTML intermediate variable in the interest of compactness.

What is the meaning of polyfills in HTML5?

First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.

The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "

Source and example of polyfill here:

http://www.programmerinterview.com/index.php/html5/html5-polyfill/

How to Maximize window in chrome using webDriver (python)

Try

ChromeOptions options = new ChromeOptions();
options.addArguments("--start-fullscreen");

List append() in for loop

The list.append function does not return any value(but None), it just adds the value to the list you are using to call that method.

In the first loop round you will assign None (because the no-return of append) to a, then in the second round it will try to call a.append, as a is None it will raise the Exception you are seeing

You just need to change it to:

a=[]
for i in range(5):    
    a.append(i)
print(a)
# [0, 1, 2, 3, 4]

list.append is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).

If you would like to create a new list based in one list without destroying or mutating it you can do something like this:

a=['a', 'b', 'c']
result = a + ['d']

print result
# ['a', 'b', 'c', 'd']

print a
# ['a', 'b', 'c']

As a corollary only, you can mimic the append method by doing the following:

a=['a', 'b', 'c']
a = a + ['d']

print a
# ['a', 'b', 'c', 'd']

doGet and doPost in Servlets

Could it be that you are passing the data through get, not post?

<form method="get" ..>
..
</form>

Is it possible to change the package name of an Android app on Google Play?

Complete guide : https://developer.android.com/studio/build/application-id.html

As per Android official Blogs : https://android-developers.googleblog.com/2011/06/things-that-cannot-change.html

We can say that:

  • If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.

  • If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.

As per Google App Update check list : https://support.google.com/googleplay/android-developer/answer/113476?hl=en

Update your apps

Prepare your APK

When you're ready to make changes to your APK, make sure to update your app’s version code as well so that existing users will receive your update.

Use the following checklist to make sure your new APK is ready to update your existing users:

  • The package name of the updated APK needs to be the same as the current version.
  • The version code needs to be greater than that current version. Learn more about versioning your applications.
  • The updated APK needs to be signed with the same signature as the current version.

To verify that your APK is using the same certification as the previous version, you can run the following command on both APKs and compare the results:

$ jarsigner -verify -verbose -certs my_application.apk

If the results are identical, you’re using the same key and are ready to continue. If the results are different, you will need to re-sign the APK with the correct key.

Learn more about signing your applications

Upload your APK Once your APK is ready, you can create a new release.

How to fix syntax error, unexpected T_IF error in php?

Here is the issue

  $total_result = $result->num_rows;

try this

<?php
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
    if ($result->num_rows > 0)
    {
        $total_result = $result->num_rows;
        $total_pages = ceil($total_result / $per_page);

        if(isset($_GET['page']) && is_numeric($_GET['page']))
        {
            $show_page = $_GET['page'];

            if ($show_page > 0 && $show_page <= $total_pages)
            {
                $start = ($show_page - 1) * $per_page;
                $end = $start + $per_page;
            }
            else
            {
                $start = 0;
                $end = $per_page;
            }               

        }
        else
        {
            $start = 0;
            $end = $per_page;
        }


        //display paginations
        echo "<p> View pages: ";
        for ($i=1; $i < $total_pages; $i++)
        { 
            if (isset($_GET['page']) && $_GET['page'] == $i)
            {
                echo  $i . " ";
            }
            else
            {
                echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";
            }

        }
        echo "</p>";

    }
    else
    {
        echo "No result to display.";
    }

}
else
{
    echo "Error: " . $mysqli->error;
}


?>

Replace one character with another in Bash

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'

Is there a Visual Basic 6 decompiler?

http://www.program-transformation.org/Transform/VisualBasicDecompilers

This link provides a lot of resources for VB6 Decompiling, but it seems like it will depend greatly on what you DO have (do you still have the pre-link Object code [EDIT: er... p-code I mean], or just the EXE?) Either way, it looks like there's something, take a look in there.

How to build a JSON array from mysql database

Use this

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

On postback, how can I check which control cause postback in Page_Init event

Here's some code that might do the trick for you (taken from Ryan Farley's blog)

public static Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}

Splitting a list into N parts of approximately equal length

If you don't mind that the order will be changed, I recommend you to use @job solution, otherwise, you can use this:

def chunkIt(seq, num):
    steps = int(len(seq) / float(num))
    out = []
    last = 0.0

    while last < len(seq):
        if len(seq) - (last + steps) < steps:
            until = len(seq)
            steps = len(seq) - last
        else:
            until = int(last + steps)
        out.append(seq[int(last): until])
        last += steps
return out

Box shadow in IE7 and IE8

You could try this

box-shadow:
progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=10, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=10, OffY=20, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=20, OffY=30, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=30, OffY=40, Color='#19000000');

How to find the last day of the month from date?

The code using strtotime() will fail after year 2038. (as given in the first answer in this thread) For example try using the following:

$a_date = "2040-11-23";
echo date("Y-m-t", strtotime($a_date));

It will give answer as: 1970-01-31

So instead of strtotime, DateTime function should be used. Following code will work without Year 2038 problem:

$d = new DateTime( '2040-11-23' ); 
echo $d->format( 'Y-m-t' );

Setting button text via javascript

The value of a button element isn't the displayed text, contrary to what happens to input elements of type button.

You can do this :

 b.appendChild(document.createTextNode('test value'));

Demonstration

Specifying a custom DateTime format when serializing with Json.Net

There is another solution I've been using. Just create a string property and use it for json. This property wil return date properly formatted.

class JSonModel {
    ...

    [JsonIgnore]
    public DateTime MyDate { get; set; }

    [JsonProperty("date")]
    public string CustomDate {
        get { return MyDate.ToString("ddMMyyyy"); }
        // set { MyDate = DateTime.Parse(value); }
        set { MyDate = DateTime.ParseExact(value, "ddMMyyyy", null); }
    }

    ...
}

This way you don't have to create extra classes. Also, it allows you to create diferent data formats. e.g, you can easily create another Property for Hour using the same DateTime.

Only variables should be passed by reference

Since it raise a flag for over 10 years, but works just fine and return the expected value, a little stfu operator is the goodiest bad practice you are all looking for:

$file_extension = @end(explode('.', $file_name));

But warning, don't use in loops due to a performance hit. Newest version of php 7.3+ offer the method array_key_last() and array_key_first().

https://www.php.net/manual/en/function.array-key-last.php

How to insert current datetime in postgresql insert query

timestamp (or date or time columns) do NOT have "a format".

Any formatting you see is applied by the SQL client you are using.


To insert the current time use current_timestamp as documented in the manual:

INSERT into "Group" (name,createddate) 
VALUES ('Test', current_timestamp);

To display that value in a different format change the configuration of your SQL client or format the value when SELECTing the data:

select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"

For psql (the default command line client) you can configure the display format through the configuration parameter DateStyle: https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

There are three kinds of timeouts which can occur in such a case. It can be seen that each answer is focused on only one aspect of these possibilities. So, I thought to write it down so someone visiting here in future does not need to randomly check each answer and get success without knowing which worked.

  1. Timeout the request from requester - Need to set timeout header ( see the header configuration in requesting library)
  2. Timeout from nginx while making the request ( before forwarding to the proxied server) eg: Huge file being uploaded
  3. Timeout after forwarding to the proxied server, server does not reply back nginx in time. eg: Time consuming scripts running at server

So the fixes for each issue are as follows.

  1. set timeout header eg: in ajax

_x000D_
_x000D_
$.ajax({_x000D_
    url: "test.html",_x000D_
    error: function(){_x000D_
        // will fire when timeout is reached_x000D_
    },_x000D_
    success: function(){_x000D_
        //do something_x000D_
    },_x000D_
    timeout: 3000 // sets timeout to 3 seconds_x000D_
});
_x000D_
_x000D_
_x000D_

  1. nginx Client timeout

    http{
         #in seconds
        fastcgi_read_timeout 600;
        client_header_timeout 600;
        client_body_timeout 600;
     }
    
  2. nginx proxied server timeout

    http{
      #Time to wait for the replying server
       proxy_read_timeout 600s;
    
    }
    

So use the one that you need. Maybe in some cases, you need all these configurations. I needed.

Can I use if (pointer) instead of if (pointer != NULL)?

yes, of course! in fact, writing if(pointer) is a more convenient way of writing rather than if(pointer != NULL) because: 1. it is easy to debug 2. easy to understand 3. if accidently, the value of NULL is defined, then also the code will not crash

if (boolean condition) in Java

if (turnedOn) {
    //do stuff when the condition is false or true?
}
else {
    //do else of if
}

It can be written like:

if (turnedOn == true) {
        //do stuff when the condition is false or true?
    }
else { // turnedOn == false or !turnedOn
        //do else of if
}

So if your turnedOn variable is true, if will be called, if is assigned to false, else will be called. boolean values are implicitly assigned to false if you won't assign them explicitly e.q. turnedOn = true

Python, Pandas : write content of DataFrame into text File

You can use pandas.DataFrame.to_csv(), and setting both index and header to False:

In [97]: print df.to_csv(sep=' ', index=False, header=False)
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

pandas.DataFrame.to_csv can write to a file directly, for more info you can refer to the docs linked above.

How to convert Seconds to HH:MM:SS using T-SQL

DECLARE @TimeinSecond INT
SET @TimeinSecond = 340 -- Change the seconds
SELECT RIGHT('0' + CAST(@TimeinSecond / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((@TimeinSecond / 60) % 60 AS VARCHAR),2)  + ':' +
RIGHT('0' + CAST(@TimeinSecond % 60 AS VARCHAR),2)

What does ellipsize mean in android?

Text:

 This is my first android application and
 I am trying to make a funny game,
 It seems android is really very easy to play.

Suppose above is your text and if you are using ellipsize's start attribute it will seen like this

This is my first android application and
...t seems android is really very easy to play.

with end attribute

 This is my first android application and
 I am trying to make a funny game,...

How do I set specific environment variables when debugging in Visual Studio?

If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing

  1. Right click "My Computer"
  2. Select properties
  3. Select the "advanced" tab
  4. Click the "environment variables" button
  5. In the "System variables" section, add the new environment variable that you desire
  6. "Ok" all the way out to accept your changes

I don't know if you'd have to restart visual studio, but seems unlikely. HTH

curl usage to get header

google.com is not responding to HTTP HEAD requests, which is why you are seeing a hang for the first command.

It does respond to GET requests, which is why the third command works.

As for the second, curl just prints the headers from a standard request.

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

How do I delete multiple rows in Entity Framework (without foreach)

EF 6.1

public void DeleteWhere<TEntity>(Expression<Func<TEntity, bool>> predicate = null) 
where TEntity : class
{
    var dbSet = context.Set<TEntity>();
    if (predicate != null)
        dbSet.RemoveRange(dbSet.Where(predicate));
    else
        dbSet.RemoveRange(dbSet);

    context.SaveChanges();
} 

Usage:

// Delete where condition is met.
DeleteWhere<MyEntity>(d => d.Name == "Something");

Or:

// delete all from entity
DeleteWhere<MyEntity>();

Looking for a 'cmake clean' command to clear up CMake output

cmake mostly cooks a Makefile, one could add rm to the clean PHONY.

For example,

[root@localhost hello]# ls
CMakeCache.txt  CMakeFiles  cmake_install.cmake  CMakeLists.txt  hello  Makefile  test
[root@localhost hello]# vi Makefile
clean:
        $(MAKE) -f CMakeFiles/Makefile2 clean
        rm   -rf   *.o   *~   .depend   .*.cmd   *.mod    *.ko   *.mod.c   .tmp_versions *.symvers *.d *.markers *.order   CMakeFiles  cmake_install.cmake  CMakeCache.txt  Makefile

Bulk package updates using Conda

# list packages that can be updated
conda search --outdated

# update all packages prompted(by asking the user yes/no)
conda update --all

# update all packages unprompted
conda update --all -y

Checking letter case (Upper/Lower) within a string in Java

To determine if a String contains an upper case and a lower case char, you can use the following:

boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());

This allows you to check:

if(!hasUppercase)System.out.println("Must have an uppercase Character");
if(!hasLowercase)System.out.println("Must have a lowercase Character");

Essentially, this works by checking if the String is equal to its entirely lowercase, or uppercase equivalent. If this is not true, then there must be at least one character that is uppercase or lowercase.

As for your other conditions, these can be satisfied in a similar way:

boolean isAtLeast8   = password.length() >= 8;//Checks for at least 8 characters
boolean hasSpecial   = !password.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
boolean noConditions = !(password.contains("AND") || password.contains("NOT"));//Check that it doesn't contain AND or NOT

With suitable error messages as above.

Get gateway ip address in android

Go to terminal

$ adb -s UDID shell
$ ip addr | grep inet 
or
$ netcfg | grep inet

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

I had the exact same problem.

[ERROR] Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.5: Failure to find org.apache.maven.plugins:maven-resources-plugin:pom:2.5 in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]
...

Had maven 3.0.5, eclipse Kepler with JBoss Dev Studio 7 installed. Computer sitting on internal network with proxy to the internet. Here's what I did.

0. Check the maven repositiory server is up

1. Check Proxy is set up and working

First I thought it was a proxy problem, I made sure that maven settings.xml contained the proxy settings (settings.xml can exist in two places one in MAVEN_HOME. The other in %userprofile%.m2\ with the later having higher precedence):

<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <username>optional-proxyuser</username>
  <password>optional-proxypass</password>
  <host>proxy.host.net</host>
  <port>80</port>
  <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>

and checked that the proxy is working by trying to telnet to it:

telnet [proxy] [port number]

2. Check not Eclipse Issue

ran 'mvn compile' at command line level outside of eclipse - same issue.

If 'mvn compile' worked. But it doesn't work using the maven plugin in eclipse, see Maven plugin not using eclipse's proxy settings

3. Check not Cache Issue Deleted all contents in my local maven repository. (Default location: ~/.m2/repository) And then reran maven - same issue came up.

4. What worked for me

Automatically download & install missing plugin: By declaring the missing plugin in the POM file build section for pluginManagement Maven will automatically retrieve the required plugin. In the POM file, add this code for the version of the plugin you require:

  <build>
        <pluginManagement>
          <plugins>
            <plugin>
              <artifactId>maven-resources-plugin</artifactId>
              <version>2.7</version>
            </plugin>           
          </plugins>
        </pluginManagement>   
    </build>

Manually install missing plugin: I went to http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-resources-plugin/2.5 and downloaded maven-resources-plugin-2.5.jar and maven-resources-plugin-2.5.pom . Copied it directly into the maven repository into the correct folder ( ~/.m2/repository/org/apache/maven/plugins/maven-resources-plugin/2.5) and reran 'mvn compile'. This solved the problem.


Edit1

Following this I had another two problem with 'mvn install':

The POM for org.apache.maven.plugins:maven-surefire-plugin:jar:2.10 is missing, no dependency information available

The POM for org.apache.maven.plugins:maven-install-plugin:jar:2.3.1 is missing, no dependency information available

I approached this problem the same way as above, downloading from http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin/2.10 and http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-install-plugin/2.3.1

Where to place the 'assets' folder in Android Studio?

In Android Studio, click on the app folder, then the src folder, and then the main folder. Inside the main folder you can add the assets folder.

How to get input text value from inside td

I'm having a hard time figuring out what exactly you're looking for here, so hope I'm not way off base.

I'm assuming what you mean is that when a keyup event occurs on the input with class "start" you want to get the values of all the inputs in neighbouring <td>s:

    $('.start').keyup(function() {
        var otherInputs = $(this).parents('td').siblings().find('input');

        for(var i = 0; i < otherInputs.length; i++) {
            alert($(otherInputs[i]).val());
        }
        return false;
    });

How do I install a module globally using npm?

In Ubuntu, set path of node_modules in .bashrc file

export PATH="/home/username/node_modules/.bin:$PATH"

How to simulate a real mouse click using java?

You could create a simple AutoIt Script that does the job for you, compile it as an executable and perform a system call there.

in au3 Script:

; how to use: MouseClick ( "button" [, x, y [, clicks = 1 [, speed = 10]]] )
MouseClick ( "left" , $CmdLine[1], $CmdLine[1] )

Now find aut2exe in your au3 Folder or find 'Compile Script to .exe' in your Start Menu and create an executable.

in your Java class call:

Runtime.getRuntime().exec(
    new String[]{
        "yourscript.exe", 
        String.valueOf(mypoint.x),
        String.valueOf(mypoint.y)}
);

AutoIt will behave as if it was a human and won't be detected as a machine.

Find AutoIt here: https://www.autoitscript.com/

Epoch vs Iteration when training neural networks

I believe iteration is equivalent to a single batch forward+backprop in batch SGD. Epoch is going through the entire dataset once (as someone else mentioned).

Map vs Object in JavaScript

The key difference is that Objects only support string and Symbol keys where as Maps support more or less any key type.

If I do obj[123] = true and then Object.keys(obj) then I will get ["123"] rather than [123]. A Map would preserve the type of the key and return [123] which is great. Maps also allow you to use Objects as keys. Traditionally to do this you would have to give objects some kind of unique identifier to hash them (I don't think I've ever seen anything like getObjectId in JS as part of the standard). Maps also guarantee preservation of order so are all round better for preservation and can sometimes save you needing to do a few sorts.

Between maps and objects in practice there are several pros and cons. Objects gain both advantages and disadvantages being very tightly integrated into the core of JavaScript which sets them apart from significantly Map beyond the difference in key support.

An immediate advantage is that you have syntactical support for Objects making it easy to access elements. You also have direct support for it with JSON. When used as a hash it's annoying to get an object without any properties at all. By default if you want to use Objects as a hash table they will be polluted and you will often have to call hasOwnProperty on them when accessing properties. You can see here how by default Objects are polluted and how to create hopefully unpolluted objects for use as hashes:

({}).toString
    toString() { [native code] }
JSON.parse('{}').toString
    toString() { [native code] }
(Object.create(null)).toString
    undefined
JSON.parse('{}', (k,v) => (typeof v === 'object' && Object.setPrototypeOf(v, null) ,v)).toString
    undefined

Pollution on objects is not only something that makes code more annoying, slower, etc but can also have potential consequences for security.

Objects are not pure hash tables but are trying to do more. You have headaches like hasOwnProperty, not being able to get the length easily (Object.keys(obj).length) and so on. Objects are not meant to purely be used as hash maps but as dynamic extensible Objects as well and so when you use them as pure hash tables problems arise.

Comparison/List of various common operations:

    Object:
       var o = {};
       var o = Object.create(null);
       o.key = 1;
       o.key += 10;
       for(let k in o) o[k]++;
       var sum = 0;
       for(let v of Object.values(m)) sum += v;
       if('key' in o);
       if(o.hasOwnProperty('key'));
       delete(o.key);
       Object.keys(o).length
    Map:
       var m = new Map();
       m.set('key', 1);
       m.set('key', m.get('key') + 10);
       m.foreach((k, v) => m.set(k, m.get(k) + 1));
       for(let k of m.keys()) m.set(k, m.get(k) + 1);
       var sum = 0;
       for(let v of m.values()) sum += v;
       if(m.has('key'));
       m.delete('key');
       m.size();

There are a few other options, approaches, methodologies, etc with varying ups and downs (performance, terse, portable, extendable, etc). Objects are a bit strange being core to the language so you have a lot of static methods for working with them.

Besides the advantage of Maps preserving key types as well as being able to support things like objects as keys they are isolated from the side effects that objects much have. A Map is a pure hash, there's no confusion about trying to be an object at the same time. Maps can also be easily extended with proxy functions. Object's currently have a Proxy class however performance and memory usage is grim, in fact creating your own proxy that looks like Map for Objects currently performs better than Proxy.

A substantial disadvantage for Maps is that they are not supported with JSON directly. Parsing is possible but has several hangups:

JSON.parse(str, (k,v) => {
    if(typeof v !== 'object') return v;
    let m = new Map();
    for(k in v) m.set(k, v[k]);
    return m;
});

The above will introduce a serious performance hit and will also not support any string keys. JSON encoding is even more difficult and problematic (this is one of many approaches):

// An alternative to this it to use a replacer in JSON.stringify.
Map.prototype.toJSON = function() {
    return JSON.stringify({
        keys: Array.from(this.keys()),
        values: Array.from(this.values())
    });
};

This is not so bad if you're purely using Maps but will have problems when you are mixing types or using non-scalar values as keys (not that JSON is perfect with that kind of issue as it is, IE circular object reference). I haven't tested it but chances are that it will severely hurt performance compared to stringify.

Other scripting languages often don't have such problems as they have explicit non-scalar types for Map, Object and Array. Web development is often a pain with non-scalar types where you have to deal with things like PHP merges Array/Map with Object using A/M for properties and JS merges Map/Object with Array extending M/O. Merging complex types is the devil's bane of high level scripting languages.

So far these are largely issues around implementation but performance for basic operations is important as well. Performance is also complex because it depends on engine and usage. Take my tests with a grain of salt as I cannot rule out any mistake (I have to rush this). You should also run your own tests to confirm as mine examine only very specific simple scenarios to give a rough indication only. According to tests in Chrome for very large objects/maps the performance for objects is worse because of delete which is apparently somehow proportionate to the number of keys rather than O(1):

Object Set Took: 146
Object Update Took: 7
Object Get Took: 4
Object Delete Took: 8239
Map Set Took: 80
Map Update Took: 51
Map Get Took: 40
Map Delete Took: 2

Chrome clearly has a strong advantage with getting and updating but the delete performance is horrific. Maps use a tiny amount more memory in this case (overhead) but with only one Object/Map being tested with millions of keys the impact of overhead for maps is not expressed well. With memory management objects also do seem to free earlier if I am reading the profile correctly which might be one benefit in favor of objects.

In Firefox for this particular benchmark it is a different story:

Object Set Took: 435
Object Update Took: 126
Object Get Took: 50
Object Delete Took: 2
Map Set Took: 63
Map Update Took: 59
Map Get Took: 33
Map Delete Took: 1

I should immediately point out that in this particular benchmark deleting from objects in Firefox is not causing any problems, however in other benchmarks it has caused problems especially when there are many keys just as in Chrome. Maps are clearly superior in Firefox for large collections.

However this is not the end of the story, what about many small objects or maps? I have done a quick benchmark of this but not an exhaustive one (setting/getting) of which performs best with a small number of keys in the above operations. This test is more about memory and initialization.

Map Create: 69    // new Map
Object Create: 34 // {}

Again these figures vary but basically Object has a good lead. In some cases the lead for Objects over maps is extreme (~10 times better) but on average it was around 2-3 times better. It seems extreme performance spikes can work both ways. I only tested this in Chrome and creation to profile memory usage and overhead. I was quite surprised to see that in Chrome it appears that Maps with one key use around 30 times more memory than Objects with one key.

For testing many small objects with all the above operations (4 keys):

Chrome Object Took: 61
Chrome Map Took: 67
Firefox Object Took: 54
Firefox Map Took: 139

In terms of memory allocation these behaved the same in terms of freeing/GC but Map used 5 times more memory. This test used 4 keys where as in the last test I only set one key so this would explain the reduction in memory overhead. I ran this test a few times and Map/Object are more or less neck and neck overall for Chrome in terms of overall speed. In Firefox for small Objects there is a definite performance advantage over maps overall.

This of course doesn't include the individual options which could vary wildly. I would not advice micro-optimizing with these figures. What you can get out of this is that as a rule of thumb, consider Maps more strongly for very large key value stores and objects for small key value stores.

Beyond that the best strategy with these two it to implement it and just make it work first. When profiling it is important to keep in mind that sometimes things that you wouldn't think would be slow when looking at them can be incredibly slow because of engine quirks as seen with the object key deletion case.

How to hide elements without having them take space on the page?

use style instead like

<div style="display:none;"></div>

Get a list of resources from classpath directory

Here is the code
Source: forums.devx.com/showthread.php?t=153784

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * list resources available from the classpath @ *
 */
public class ResourceList{

    /**
     * for all elements of java.class.path get a Collection of resources Pattern
     * pattern = Pattern.compile(".*"); gets all resources
     * 
     * @param pattern
     *            the pattern to match
     * @return the resources in the order they are found
     */
    public static Collection<String> getResources(
        final Pattern pattern){
        final ArrayList<String> retval = new ArrayList<String>();
        final String classPath = System.getProperty("java.class.path", ".");
        final String[] classPathElements = classPath.split(System.getProperty("path.separator"));
        for(final String element : classPathElements){
            retval.addAll(getResources(element, pattern));
        }
        return retval;
    }

    private static Collection<String> getResources(
        final String element,
        final Pattern pattern){
        final ArrayList<String> retval = new ArrayList<String>();
        final File file = new File(element);
        if(file.isDirectory()){
            retval.addAll(getResourcesFromDirectory(file, pattern));
        } else{
            retval.addAll(getResourcesFromJarFile(file, pattern));
        }
        return retval;
    }

    private static Collection<String> getResourcesFromJarFile(
        final File file,
        final Pattern pattern){
        final ArrayList<String> retval = new ArrayList<String>();
        ZipFile zf;
        try{
            zf = new ZipFile(file);
        } catch(final ZipException e){
            throw new Error(e);
        } catch(final IOException e){
            throw new Error(e);
        }
        final Enumeration e = zf.entries();
        while(e.hasMoreElements()){
            final ZipEntry ze = (ZipEntry) e.nextElement();
            final String fileName = ze.getName();
            final boolean accept = pattern.matcher(fileName).matches();
            if(accept){
                retval.add(fileName);
            }
        }
        try{
            zf.close();
        } catch(final IOException e1){
            throw new Error(e1);
        }
        return retval;
    }

    private static Collection<String> getResourcesFromDirectory(
        final File directory,
        final Pattern pattern){
        final ArrayList<String> retval = new ArrayList<String>();
        final File[] fileList = directory.listFiles();
        for(final File file : fileList){
            if(file.isDirectory()){
                retval.addAll(getResourcesFromDirectory(file, pattern));
            } else{
                try{
                    final String fileName = file.getCanonicalPath();
                    final boolean accept = pattern.matcher(fileName).matches();
                    if(accept){
                        retval.add(fileName);
                    }
                } catch(final IOException e){
                    throw new Error(e);
                }
            }
        }
        return retval;
    }

    /**
     * list the resources that match args[0]
     * 
     * @param args
     *            args[0] is the pattern to match, or list all resources if
     *            there are no args
     */
    public static void main(final String[] args){
        Pattern pattern;
        if(args.length < 1){
            pattern = Pattern.compile(".*");
        } else{
            pattern = Pattern.compile(args[0]);
        }
        final Collection<String> list = ResourceList.getResources(pattern);
        for(final String name : list){
            System.out.println(name);
        }
    }
}  

If you are using Spring Have a look at PathMatchingResourcePatternResolver

If isset $_POST

Maybe you can try this one:

if (isset($_POST['mail']) && ($_POST['mail'] !=0)) { echo "Yes, mail is set"; } else { echo "No, mail is not set"; }

How to Update/Drop a Hive Partition?

You can either copy files into the folder where external partition is located or use

INSERT OVERWRITE TABLE tablename1 PARTITION (partcol1=val1, partcol2=val2...)...

statement.

postgresql - add boolean column to table set default

If you want an actual boolean column:

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

Error in strings.xml file in Android

You have to put \ before an apostrophe. Like this \' , Also check that you are editing strings.xml and not values.xml (android studio directs you to this file when shows the error). Because if you edit values.xml and try to compile again, the error persists. This was happening to me recently.

Angular checkbox and ng-click

You can use ng-change instead of ng-click:

<!doctype html>
<html>
<head>
  <script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
  <script>
        var app = angular.module('myapp', []);
        app.controller('mainController', function($scope) {
          $scope.vm = {};
          $scope.vm.myClick = function($event) {
                alert($event);
          }
        });     
  </script>  
</head>
<body ng-app="myapp">
  <div ng-controller="mainController">
    <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
  </div>
</body>
</html>

CSS @media print issues with background-color;

In some cases (blocks without any content, but with background) it can be overridden using borders, individually for every block.

For example:

.colored {
  background: #000;
  border: 1px solid #ccc;
  width: 8px;
  height: 8px;
}

@media print {
  .colored div {
    border: 4px solid #000;
    width: 0;
    height: 0;
  }
}

How can I kill all sessions connecting to my oracle database?

If you want to stop new users from connecting, but allow current sessions to continue until they are inactive, you can put the database in QUIESCE mode:

ALTER SYSTEM QUIESCE RESTRICTED;

From the Oracle Database Administrator's Guide:

Non-DBA active sessions will continue until they become inactive. An active session is one that is currently inside of a transaction, a query, a fetch, or a PL/SQL statement; or a session that is currently holding any shared resources (for example, enqueues). No inactive sessions are allowed to become active...Once all non-DBA sessions become inactive, the ALTER SYSTEM QUIESCE RESTRICTED statement completes, and the database is in a quiesced state

what's data-reactid attribute in html?

Custom Data attribute in HTML5

Would like to quote Ian's comment in my answer:

It's just an attribute (a valid one) on the element that you can use to store data/info about it.

This code then retrieves it later in the event handler, and uses it to find the target output element. It effectively stores the class of the div where its text should be outputted.

reactid is just a suffix, you can have any name here eg: data-Ayman.

If you want to find the difference check the fiddles in this SO answer and comment.

removing table border

.yourClass>tbody>tr>td{border: 1px solid #ffffff !important;}

Numpy how to iterate over columns of array?

Alternatively, you can use enumerate. It gives you the column number and the column values as well.

for num, column in enumerate(array.T):
    some_function(column) # column: Gives you the column value as asked in the question
    some_function(num) # num: Gives you the column number 


MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

how to select first N rows from a table in T-SQL?

select top(@count) * from users

If @count is a constant, you can drop the parentheses:

select top 42 * from users

(the latter works on SQL Server 2000 too, while the former requires at least 2005)

Can inner classes access private variables?

Anything that is part of Outer should have access to all of Outer's members, public or private.

Edit: your compiler is correct, var is not a member of Inner. But if you have a reference or pointer to an instance of Outer, it could access that.

Uploading Laravel Project onto Web Server

I believe - your Laravel files/folders should not be placed in root directory.

e.g. If your domain is pointed to public_html directory then all content should placed in that directory. How ? let me tell you

  1. Copy all files and folders ( including public folder ) in public html
  2. Copy all content of public folder and paste it in document root ( i.e. public_html )
  3. Remove the public folder
  4. Open your bootstrap/paths.php and then changed 'public' => __DIR__.'/../public', into 'public' => __DIR__.'/..',

  5. and finally in index.php,

    Change

require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/start.php';

into

require __DIR__.'/bootstrap/autoload.php';

$app = require_once __DIR__.'/bootstrap/start.php';

Your Laravel application should work now.

Why maven? What are the benefits?

I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.

It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.

Redirect on select option in select box

to make it as globally reuse function using jquery

HTML

<select class="select_location">
   <option value="http://localhost.com/app/page1.html">Page 1</option>
   <option value="http://localhost.com/app/page2.html">Page 2</option>
   <option value="http://localhost.com/app/page3.html">Page 3</option>
</select>

Javascript using jquery

$('.select_location').on('change', function(){
   window.location = $(this).val();
});

now you will able to reuse this function by adding .select_location class to any Select element class

converting a base 64 string to an image and saving it

Here is working code for converting an image from a base64 string to an Image object and storing it in a folder with unique file name:

public void SaveImage()
{
    string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; 

    //this is a simple white background image
    var myfilename= string.Format(@"{0}", Guid.NewGuid());

    //Generate unique filename
    string filepath= "~/UserImages/" + myfilename+ ".jpeg";
    var bytess = Convert.FromBase64String(strm);
    using (var imageFile = new FileStream(filepath, FileMode.Create))
    {
        imageFile.Write(bytess, 0, bytess.Length);
        imageFile.Flush();
    }
}

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I stumbled across the issue now, too. The application defined a pure virtual interface class and a user-defined class provided through a shared lib was supposed to implement the interface. When linking the application, the linker complained that the shared lib would not provide vtable and type_info for the base class, nor could they be found anywhere else. Turned out that I simply forgot to make one of the interface's methods pure virtual (i.e. omitted the " = 0" at the end of the declaration. Very rudimentary, still easy to overlook and puzzling if you can't connect the linker diagnostic to the root cause.

What is the difference between mocking and spying when using Mockito?

If there is an object with 8 methods and you have a test where you want to call 7 real methods and stub one method you have two options:

  1. Using a mock you would have to set it up by invoking 7 callRealMethod and stub one method
  2. Using a spy you have to set it up by stubbing one method

The official documentation on doCallRealMethod recommends using a spy for partial mocks.

See also javadoc spy(Object) to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.

How do you plot bar charts in gnuplot?

I would just like to expand upon the top answer, which uses GNUPlot to create a bar graph, for absolute beginners because I read the answer and was still confused from the deluge of syntax.

We begin by writing a text file of GNUplot commands. Lets call it commands.txt:

set term png
set output "graph.png"
set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes

set term png will set GNUplot to output a .png file and set output "graph.png" is the name of the file it will output to.

The next two lines are rather self explanatory. The fifth line contains a lot of syntax.

plot "data.dat" using 1:3:xtic(2) with boxes

"data.dat" is the data file we are operating on. 1:3 indicates we will be using column 1 of data.dat for the x-coordinates and column 3 of data.dat for the y-coordinates. xtic() is a function that is responsible for numbering/labeling the x-axis. xtic(2), therefore, indicates that we will be using column 2 of data.dat for labels.

"data.dat" looks like this:

0 label       100
1 label2      450
2 "bar label" 75

To plot the graph, enter gnuplot commands.txt in terminal.

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

How to draw text using only OpenGL methods?

Drawing text in plain OpenGL isn't a straigth-forward task. You should probably have a look at libraries for doing this (either by using a library or as an example implementation).

Some good starting points could be GLFont, OpenGL Font Survey and NeHe Tutorial for Bitmap Fonts (Windows).

Note that bitmaps are not the only way of achieving text in OpenGL as mentioned in the font survey.

What's the most efficient way to test two integer ranges for overlap?

If you were dealing with, given two ranges [x1:x2] and [y1:y2], natural / anti-natural order ranges at the same time where:

  • natural order: x1 <= x2 && y1 <= y2 or
  • anti-natural order: x1 >= x2 && y1 >= y2

then you may want to use this to check:

they are overlapped <=> (y2 - x1) * (x2 - y1) >= 0

where only four operations are involved:

  • two subtractions
  • one multiplication
  • one comparison

Use sudo with password as parameter

You can set the s bit for your script so that it does not need sudo and runs as root (and you do not need to write your root password in the script):

sudo chmod +s myscript

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

How to fix "The ConnectionString property has not been initialized"

I stumbled in the same problem while working on a web api Asp Net Core project. I followed the suggestion to change the reference in my code to:

ConfigurationManager.ConnectionStrings["NameOfTheConnectionString"].ConnectionString

but adding the reference to System.Configuration.dll caused the error "Reference not valid or not supported".

Configuration manager error

To fix the problem I had to download the package System.Configuration.ConfigurationManager using NuGet (Tools -> Nuget Package-> Manage Nuget packages for the solution)

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

Easy way to convert a unicode list to a list containing python strings?

Just simply use this code

EmployeeList = eval(EmployeeList)
EmployeeList = [str(x) for x in EmployeeList]

How to set width of a div in percent in JavaScript?

testjs2

    $(document).ready(function() { 
      $("#form1").validate({ 
        rules: { 
          name: "required", //simple rule, converted to {required:true} 
          email: { //compound rule 
          required: true, 
          email: true 
        }, 
        url: { 
          url: true 
        }, 
        comment: { 
          required: true 
        } 
        }, 
        messages: { 
          comment: "Please enter a comment." 
        } 
      }); 
    }); 

    function()
    {
    var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
    if (ok)
    location="http://www.yahoo.com"
    else
    location="http://www.hotmail.com"
    }

    function changeWidth(){
    var e1 = document.getElementById("e1");
    e1.style.width = 400;
} 

  </script> 

  <style type="text/css"> 
    * { font-family: Verdana; font-size: 11px; line-height: 14px; } 
    .submit { margin-left: 125px; margin-top: 10px;} 
    .label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; } 
    .form-row { padding: 5px 0; clear: both; width: 700px; } 
    .label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; } 
    .input[type=text], textarea { width: 250px; float: left; } 
    .textarea { height: 50px; } 
  </style> 

  </head> 
  <body> 

    <form id="form1" method="post" action=""> 
      <div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div> 
      <div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div> 
      <div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div> 
      <div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div> 
      <div class="form-row"><input class="submit" type="submit" value="Submit"></div> 
      <input type="button" value="change width" onclick="changeWidth()"/>
      <div id="e1" style="width:20px;height:20px; background-color:#096"></div>
    </form> 



  </body> 
</html> 

Select from where field not equal to Mysql Php

select * from table where fiels1 NOT LIKE 'x' AND field2 NOT LIKE 'y'

//this work in case insensitive manner

How to have a default option in Angular.js select box

Depending on how many options you have, you could put your values in an array and auto-populate your options like this

<select ng-model="somethingHere.values" ng-options="values for values in [5,4,3,2,1]">
   <option value="">Pick a Number</option>
</select>

Facebook API: Get fans of / people who like a page

There is a "way" to get some part of fan list with their profile ids of some fanpage without token.

  1. Get id of a fanpage with public graph data: http://graph.facebook.com/cocacola - Coca-Cola has 40796308305. UPDATE 2016.04.30: Facebook now requires access token to get page_id through graph so you can parse fanpage HTML syntax to get this id without any authorization from https://www.facebook.com/{PAGENAME} as in example below based on og tags present on the fanpage.
  2. Get Coca-Cola's "like plugin" iframe display directly with some modified params: http://www.facebook.com/plugins/fan.php?connections=100&id=40796308305
  3. Now check the page sources, there are a lot of fans with links to their profiles, where you can find their profile ids or nicknames like: http://www.facebook.com/michal.semeniuk .
  4. If you are interested only in profile ids use the graph api again - it will give you profile id directly: http://graph.facebook.com/michal.semeniuk UPDATE 2016.04.30: Facebook now requires access token to get such info. You can parse profile HTML syntax, just like in the first step meta tag is your best friend: <meta property="al:android:url" content="fb://profile/{PROFILE_ID}" />

And now is the best part: try to refresh (F5) the link in point 2.. There is a new full set of another fans of Coca-Cola. Take only uniques and you will be able to get some nice, almost full list of fans.

-- UPDATE 2013.08.06 --

Why don't you use my ready PHP script to fetch some fans? :)

UPDATE 2016.04.30: Updated example script to use new methods after Facebook started to require access token to get public data from graph api.

function fetch_fb_fans($fanpage_name, $no_of_retries = 10, $pause = 500000 /* 500ms */){
    $ret = array();
    // prepare real like user agent and accept headers
    $context = stream_context_create(array('http' => array('header' => 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-encoding: gzip, deflate, sdch\r\nAccept-language: en-US,en;q=0.8,pl;q=0.6\r\n')));
    // get page id from facebook html og tags for mobile apps
    $fanpage_html = file_get_contents('https://www.facebook.com/' . $fanpage_name, false, $context);
    if(!preg_match('{fb://page/(\d+)}', $fanpage_html, $id_matches)){
        // invalid fanpage name
        return $ret;
    }
    $url = 'http://www.facebook.com/plugins/fan.php?connections=100&id=' . $id_matches[1];
    for($a = 0; $a < $no_of_retries; $a++){
        $like_html = file_get_contents($url, false, $context);
        preg_match_all('{href="https?://www\.facebook\.com/([a-zA-Z0-9\._-]+)" class="link" data-jsid="anchor" target="_blank"}', $like_html, $matches);
        if(empty($matches[1])){
            // failed to fetch any fans - convert returning array, cause it might be not empty
            return array_keys($ret);
        }else{
            // merge profiles as array keys so they will stay unique
            $ret = array_merge($ret, array_flip($matches[1]));
        }
        // don't get banned as flooder
        usleep($pause);
    }
    return array_keys($ret);
}

print_r(fetch_fb_fans('TigerPolska', 2, 400000));

Purpose of installing Twitter Bootstrap through npm?

  1. Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt. If you only want to add precompiled libraries feel free to manually include files to project.

  2. No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Maybe it is simple, try this if you have a DataFrame. then make sure that both matrices or vectros that you're trying to combine have the same rows_name/index

I had the same issue. I changed the name indices of the rows to make them match each other here is an example for a matrix (principal component) and a vector(target) have the same row indicies (I circled them in the blue in the leftside of the pic)

Before, "when it was not working", I had the matrix with normal row indicies (0,1,2,3) while I had the vector with row indices (ID0, ID1, ID2, ID3) then I changed the vector's row indices to (0,1,2,3) and it worked for me.

enter image description here

Truststore and Keystore Definitions

A keystore contains private keys, and the certificates with their corresponding public keys.

A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.

How to add Active Directory user group as login in SQL Server

You can use T-SQL:

use master
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName

I use this as a part of restore from production server to testing machine:

USE master
GO
ALTER DATABASE yourDbName SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE yourDbName FROM DISK = 'd:\DropBox\backup\myDB.bak'
ALTER DATABASE yourDbName SET ONLINE
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO

You will need to use localized name of services in case of German or French Windows, see How to create a SQL Server login for a service account on a non-English Windows?

Limit on the WHERE col IN (...) condition

You did not specify the database engine in question; in Oracle, an option is to use tuples like this:

SELECT * FROM table WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)

This ugly hack only works in Oracle SQL, see https://asktom.oracle.com/pls/asktom/asktom.search?tag=limit-and-conversion-very-long-in-list-where-x-in#9538075800346844400

However, a much better option is to use stored procedures and pass the values as an array.

Find duplicate characters in a String and count the number of occurances using Java

public class DuplicateValue {

    public static void main(String[] args) {

        String s = "hezzz";

        char []st=s.toCharArray();

        int count=0;

        Set<Character> ch=new HashSet<>();
        for(Character cg:st){
            if(ch.add(cg)==false){
                int occurrences = Collections.frequency(ch, cg);
                count+=occurrences;
                if(count>1){
                System.out.println(cg + ": This character exist more than one time");
                }
                else{
                System.out.println(cg);
                }
            }
        }

        System.out.println(count);
    }
}

How to analyze disk usage of a Docker container

To see the file size of your containers, you can use the --size argument of docker ps:

docker ps --size

Accessing the web page's HTTP Headers in JavaScript

Allain Lalonde's link made my day. Just adding some simple working html code here.
Works with any reasonable browser since ages plus IE9+ and Presto-Opera 12.

<!DOCTYPE html>
<title>(XHR) Show all response headers</title>

<h1>All Response Headers with XHR</h1>
<script>
 var X= new XMLHttpRequest();
 X.open("HEAD", location);
 X.send();
 X.onload= function() { 
   document.body.appendChild(document.createElement("pre")).textContent= X.getAllResponseHeaders();
 }
</script>

Note: You get headers of a second request, the result may differ from the initial request.


Another way
is the more modern fetch() API
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
Per caniuse.com it's supported by Firefox 40, Chrome 42, Edge 14, Safari 11
Working example code:

<!DOCTYPE html>
<title>fetch() all Response Headers</title>

<h1>All Response Headers with fetch()</h1>
<script>
 var x= "";
 if(window.fetch)
    fetch(location, {method:'HEAD'})
    .then(function(r) {
       r.headers.forEach(
          function(Value, Header) { x= x + Header + "\n" + Value + "\n\n"; }
       );
    })
    .then(function() {
       document.body.appendChild(document.createElement("pre")).textContent= x;
    });
 else
   document.write("This does not work in your browser - no support for fetch API");
</script>

How to run Tensorflow on CPU

The environment variable solution doesn't work for me running tensorflow 2.3.1. I assume by the comments in the github thread that the below solution works for versions >=2.1.0.

From tensorflow github:

import tensorflow as tf

# Hide GPU from visible devices
tf.config.set_visible_devices([], 'GPU')

Make sure to do this right after the import with fresh tensorflow instance (if you're running jupyter notebook, restart the kernel).

And to check that you're indeed running on the CPU:

# To find out which devices your operations and tensors are assigned to
tf.debugging.set_log_device_placement(True)

# Create some tensors and perform an operation
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)

print(c)

Expected output:

2.3.1
Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
tf.Tensor(
[[22. 28.]
 [49. 64.]], shape=(2, 2), dtype=float32)

How to bring an activity to foreground (top of stack)?

I think a combination of Intent flags should do the trick. In particular, Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK.

Add these flags to your intent before calling startActvity.

PHPExcel - creating multiple sheets by iteration

You dont need call addSheet() method. After creating sheet, it already add to excel. Here i fixed some codes:

    //First sheet
    $sheet = $objPHPExcel->getActiveSheet();

    //Start adding next sheets
    $i=0;
    while ($i < 10) {

      // Add new sheet
      $objWorkSheet = $objPHPExcel->createSheet($i); //Setting index when creating

      //Write cells
      $objWorkSheet->setCellValue('A1', 'Hello'.$i)
                   ->setCellValue('B2', 'world!')
                   ->setCellValue('C1', 'Hello')
                   ->setCellValue('D2', 'world!');

      // Rename sheet
      $objWorkSheet->setTitle("$i");

      $i++;
    }

how to fire event on file select

Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm

  $('#myFile').change(function () {
    LoadFile("myFile");//function to do processing of file.
    $('#myFile').val('');// set the value to empty of myfile control.
    });

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

The last argument of CONVERT seems to determine the format used for parsing. Consult MSDN docs for CONVERT.

111 - the one you are using is Japan yy/mm/dd.

I guess the one you are looking for is 103, that is dd/mm/yyyy.

So you should try:

 SELECT convert(datetime, '23/07/2009', 103)

Downcasting in Java

Using your example, you could do:

public void doit(A a) {
    if(a instanceof B) {
        // needs to cast to B to access draw2 which isn't present in A
        // note that this is probably not a good OO-design, but that would
        // be out-of-scope for this discussion :)
        ((B)a).draw2();
    }
    a.draw();
}

Create Pandas DataFrame from a string

Split Method

data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)

List of zeros in python

The easiest way to create a list where all values are the same is multiplying a one-element list by n.

>>> [0] * 4
[0, 0, 0, 0]

So for your loop:

for i in range(10):
    print [0] * i