Programs & Examples On #Chipmunk

Chipmunk is an open-source physics library written in C.

UIButton: set image for selected-highlighted state

Correct me if I am wrong. By doing

   [button setSelected:YES];

you are clearly changing the state of the buttons as selected. So naturally by the code you have provided the image will that for the selected state in your case checked.png

R: "Unary operator error" from multiline ggplot2 command

This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source() a script to when you copy-and-paste the lines, both with multiline and comments)

Rule: always put the dangling '+' at the end of a line so R knows the command is unfinished:

ggplot(...) + geom_whatever1(...) +
  geom_whatever2(...) +
  stat_whatever3(...) +
  geom_title(...) + scale_y_log10(...)

Don't put the dangling '+' at the start of the line, since that tickles the error:

Error in "+ geom_whatever2(...) invalid argument to unary operator"

And obviously don't put dangling '+' at both end and start since that's a syntax error.

So, learn a habit of being consistent: always put '+' at end-of-line.

cf. answer to "Split code over multiple lines in an R script"

Adding system header search path to Xcode

Follow up to Eonil's answer related to project level settings. With the target selected and the Build Settings tab selected, there may be no listing under Search Paths for Header Search Paths. In this case, you can change to "All" from "Basic" in the search bar and Header Search Paths will show up in the Search Paths section.

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

Check if string contains only whitespace

Resemblence with c# string static method isNullOrWhiteSpace.

def isNullOrWhiteSpace(str):
  """Indicates whether the specified string is null or empty string.
     Returns: True if the str parameter is null, an empty string ("") or contains 
     whitespace. Returns false otherwise."""
  if (str is None) or (str == "") or (str.isspace()):
    return True
  return False

isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("")   -> True
isNullOrWhiteSpace(" ")  -> True

How to print a string in C++

While using string, the best possible way to print your message is:

#include <iostream>
#include <string>
using namespace std;

int main(){
  string newInput;
  getline(cin, newInput);
  cout<<newInput;
  return 0;
}


this can simply do the work instead of doing the method you adopted.

How To have Dynamic SQL in MySQL Stored Procedure

You can pass thru outside the dynamic statement using User-Defined Variables

Server version: 5.6.25-log MySQL Community Server (GPL)

mysql> PREPARE stmt FROM 'select "AAAA" into @a';
Query OK, 0 rows affected (0.01 sec)
Statement prepared

mysql> EXECUTE stmt;
Query OK, 1 row affected (0.01 sec)

DEALLOCATE prepare stmt;
Query OK, 0 rows affected (0.01 sec)

mysql> select @a;
+------+
| @a   |
+------+
|AAAA  |
+------+
1 row in set (0.01 sec)

How to call another controller Action From a controller in Mvc

I know it's old, but you can:

  • Create a service layer
  • Move method there
  • Call method in both controllers

How to change the Text color of Menu item in Android?

i found it Eureka !!

in your app theme:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/ActionBarTheme</item>
    <!-- backward compatibility -->          
    <item name="actionBarStyle">@style/ActionBarTheme</item>        
</style>

here is your action bar theme:

<style name="ActionBarTheme" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
   <item name="android:background">@color/actionbar_bg_color</item>
   <item name="popupTheme">@style/ActionBarPopupTheme</item
   <!-- backward compatibility -->
   <item name="background">@color/actionbar_bg_color</item>
</style>

and here is your popup theme:

 <style name="ActionBarPopupTheme">
    <item name="android:textColor">@color/menu_text_color</item>
    <item name="android:background">@color/menu_bg_color</item>
 </style>

Cheers ;)

How to prevent the "Confirm Form Resubmission" dialog?

I found an unorthodox way to accomplish this.

Just put the script page in an iframe. Doing so allows the page to be refreshed, seemingly even on older browsers without the "confirm form resubmission" message ever appearing.

document.getElementByID is not a function

It's document.getElementById() and not document.getElementByID(). Check the casing for Id.

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:

HTML

<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"   
  type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $("select#mySelect").change(function(){
      //$("#selText").html($($(this).children("option:selected")[0]).text());
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
    });
});
</script>

PS:- Set height of div#selText otherwise it will keep shifting select list downward.

References with text in LaTeX

I think you can do this with the hyperref package, although I've not tried it myself. From the relevant LaTeX Wikibook section:

The hyperref package introduces another useful command; \autoref{}. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command \autoref{sec:intro} would create a hyperlink to the \label{sec:intro} command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining \typeautorefname to the prefix you want, as in:

\def\subsectionautorefname{section}

HTML Upload MAX_FILE_SIZE does not appear to work

MAX_FILE_SIZE is in KB not bytes. You were right, it is in bytes. So, for a limit of 4MB convert 4MB in bytes {1024 * (1024 * 4)} try:

<input type="hidden" name="MAX_FILE_SIZE" value="4194304" /> 

enter image description here

Update 1

As explained by others, you will never get a warning for this. It's there just to impose a soft limit on server side.

Update 2

To answer your sub-question. Yes, there is a difference, you NEVER trust the user input. If you want to always impose a limit, you always must check its size. Don't trust what MAX_FILE_SIZE does, because it can be changed by a user. So, yes, you should check to make sure it's always up to or above the size you want it to be.

The difference is that if you have imposed a MAX_FILE_SIZE of 2MB and the user tries to upload a 4MB file, once they reach roughly the first 2MB of upload, the transfer will terminate and the PHP will stop accepting more data for that file. It will report the error on the files array.

What's the difference between SortedList and SortedDictionary?

Enough is said already on the topic, however to keep it simple, here's my take.

Sorted dictionary should be used when-

  • More inserts and delete operations are required.
  • Data in un-ordered.
  • Key access is enough and index access is not required.
  • Memory is not a bottleneck.

On the other side, Sorted List should be used when-

  • More lookups and less inserts and delete operations are required.
  • Data is already sorted (if not all, most).
  • Index access is required.
  • Memory is an overhead.

Hope this helps!!

How to get number of video views with YouTube API?

look at yt:statistics tag. It provides viewCount, videoWatchCount, favoriteCount etc.

npm install from Git in a specific version

My example comment to @qubyte above got chopped, so here's something that's easier to read...

The method @surjikal described above works for branch commits, but it didn't work for a tree commit I was trying include.


The archive mode also works for commits. For example, fetch @ a2fbf83

npm:

npm install  https://github.com/github/fetch/archive/a2fbf834773b8dc20eef83bb53d081863d3fc87f.tar.gz

yarn:

yarn add  https://github.com/github/fetch/archive/a2fbf834773b8dc20eef83bb53d081863d3fc87f.tar.gz

format:

 https://github.com/<owner>/<repo>/archive/<commit-id>.tar.gz


Here's the tree commit that required the /archive/ mode:

yarn add  https://github.com/vuejs/vuex/archive/c3626f779b8ea902789dd1c4417cb7d7ef09b557.tar.gz

for the related vuex commit

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Forget trying to decipher the example .ts - as others have said it is often incomplete.

Instead just click on the 'pop-out' icon circled here and you'll get a fully working StackBlitz example.

enter image description here

You can quickly confirm the required modules:

enter image description here

Comment out any instances of ReactiveFormsModule, and sure enough you'll get the error:

Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. 

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Python: Open file in zip without temporarily extracting it

Vincent Povirk's answer won't work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

How to draw a graph in LaTeX?

Aside from the (excellent) suggestion to use TikZ, you could use gastex. I used this before TikZ was available and it did its job too.

Set style for TextView programmatically

I met the problem too, and I found the way to set style programatically. Maybe you all need it, So I update there.

The third param of View constructor accepts a type of attr in your theme as the source code below:

public TextView(Context context, AttributeSet attrs) {
    this(context, attrs, com.android.internal.R.attr.textViewStyle);
}

So you must pass a type of R.attr.** rather than R.style.**

In my codes, I did following steps:

First, customize a customized attr to be used by themes in attr.xml.

<attr name="radio_button_style" format="reference" />

Second, specific your style in your used theme in style.xml.

 <style name="AppTheme" parent="android:Theme.Translucent">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="radio_button_style">@style/radioButtonStyle</item>
</style>
<style name="radioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">64dp</item>
    <item name="android:background">#000</item>
    <item name="android:button">@null</item>
    <item name="android:gravity">center</item>
    <item name="android:saveEnabled">false</item>
    <item name="android:textColor">@drawable/option_text_color</item>
    <item name="android:textSize">9sp</item>
</style>

At the end, use it!

            RadioButton radioButton = new RadioButton(mContext, null, R.attr.radio_button_style);

the view created programatically will use the specified style in your theme.

You can have a try, and hope it can work for you perfectly.

Can I nest a <button> element inside an <a> using HTML5?

You can add a class to the button and put some script redirecting it.

I do it this way:

<button class='buttonClass'>button name</button>

<script>
$(".buttonClass').click(function(){
window.location.href = "http://stackoverflow.com";
});
</script>

Auto-center map with multiple markers in Google Maps API v3

I've tryied all answers of this topic, but just this below worked fine on my project.

Angular 7 and AGM Core 1.0.0-beta.7

<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
  <agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
    *ngFor="let localizacao of localizacoesTec">
  </agm-marker>
</agm-map>

The properties [agmFitBounds]="true" at agm-marker and [fitBounds]="true" at agm-map does the job

How to get last 7 days data from current datetime to last 7 days in sql server

I don't think you have data for every single day for the past seven days. Days for which no data exist, will obviously not show up.

Try this and validate that you have data for EACH day for the past 7 days

SELECT DISTINCT CreatedDate
FROM News 
WHERE CreatedDate >= DATEADD(day,-7, GETDATE())
ORDER BY CreatedDate

EDIT - Copied from your comment

i have dec 19th -1 row data,18th -2 rows,17th -3 rows,16th -3 rows,15th -3 rows,12th -2 rows, 11th -4 rows,9th -1 row,8th -1 row

You don't have data for all days. That is your problem and not the query. If you execute the query today - 22nd - you will only get data for 19th, 18th,17th,16th and 15th. You have no data for 20th, 21st and 22nd.

EDIT - To get data for the last 7 days, where data is available you can try

select id,    
NewsHeadline as news_headline,    
NewsText as news_text,    
state,    
CreatedDate as created_on      
from News    
WHERE CreatedDate IN (SELECT DISTINCT TOP 7 CreatedDate from News
order by createddate DESC)

SQL: How to get the id of values I just INSERTed?

Again no language agnostic response, but in Java it goes like this:

Connection conn = Database.getCurrent().getConnection();  
PreparedStatement ps =  conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
try {  
    ps.executeUpdate();  
    ResultSet rs = ps.getGeneratedKeys();  
    rs.next();  
    long primaryKey = rs.getLong(1);  
} finally {  
    ps.close();  
}  

Get git branch name in Jenkins Pipeline/Jenkinsfile

This is for simple Pipeline type - not multibranch. Using Jenkins 2.150.1

environment { FULL_PATH_BRANCH = "${sh(script:'git name-rev --name-only HEAD', returnStdout: true)}" GIT_BRANCH = FULL_PATH_BRANCH.substring(FULL_PATH_BRANCH.lastIndexOf('/') + 1, FULL_PATH_BRANCH.length()) }

then use it env.GIT_BRANCH

Boolean checking in the 'if' condition

It really also depends on how you name your variable.

When people are asking "which is better practice" - this implicitly implies that both are correct, so it's just a matter of which is easier to read and maintain.

If you name your variable "status" (which is the case in your example code), I would much prefer to see

if(status == false) // if status is false

On the other hand, if you had named your variable isXXX (e.g. isReadableCode), then the former is more readable. consider:

if(!isReadable) { // if not readable
  System.out.println("I'm having a headache reading your code");
}

Bootstrap 3: How do you align column content to bottom of row

When working with bootsrap usually face three main problems:

  1. How to place the content of the column to the bottom?
  2. How to create a multi-row gallery of columns of equal height in one .row?
  3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

To solve first two problems download this small plugin https://github.com/codekipple/conformity

The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

Common code

<style>
    [class*=col-] {position: relative}
    .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
    .row-centered {text-align:center}   
    .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
</style>

<script src="assets/conformity/conformity.js"></script>
<script>
    $(document).ready(function () {
        $('.row-conformity > [class*=col-]').conformity();
        $(window).on('resize', function() {
            $('.row-conformity > [class*=col-]').conformity();
        });
    });
</script>

1. Aligning content of the column to the bottom

<div class="row row-conformity">
    <div class="col-sm-3">
        I<br>create<br>highest<br>column
    </div>
    <div class="col-sm-3">
        <div class="to-bottom">
            I am on the bottom
        </div>
    </div>
</div>

2. Gallery of columns of equal height

<div class="row row-conformity">
    <div class="col-sm-4">We all have equal height</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
</div>

3. Horizontal alignment of columns to the center (less than 12 col units)

<div class="row row-centered">
    <div class="col-sm-3">...</div>
    <div class="col-sm-4">...</div>
</div>

All classes can work together

<div class="row row-conformity row-centered">
    ...
</div>

Use mysql_fetch_array() with foreach() instead of while()

You could just do it like this

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;"; 

$result_select = mysql_query($query_select) or die(mysql_error());

 foreach($result_select as $row){
    $ename = stripslashes($row['name']);
    $eemail = stripcslashes($row['email']);
    $epost = stripslashes($row['post']);
    $eid = $row['id'];

    $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

    echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

    echo $eid . '<br/>';

    echo $ename . '<br/>';

    echo $eemail . '<br/>';

    echo $epost . '<br/><br/><br/><br/>';
 }

Display a jpg image on a JPanel

I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

Use cases for the 'setdefault' dict method

As most answers state setdefault or defaultdict would let you set a default value when a key doesn't exist. However, I would like to point out a small caveat with regard to the use cases of setdefault. When the Python interpreter executes setdefaultit will always evaluate the second argument to the function even if the key exists in the dictionary. For example:

In: d = {1:5, 2:6}

In: d
Out: {1: 5, 2: 6}

In: d.setdefault(2, 0)
Out: 6

In: d.setdefault(2, print('test'))
test
Out: 6

As you can see, print was also executed even though 2 already existed in the dictionary. This becomes particularly important if you are planning to use setdefault for example for an optimization like memoization. If you add a recursive function call as the second argument to setdefault, you wouldn't get any performance out of it as Python would always be calling the function recursively.

Since memoization was mentioned, a better alternative is to use functools.lru_cache decorator if you consider enhancing a function with memoization. lru_cache handles the caching requirements for a recursive function better.

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

onclick go full screen

I realize this is a very old question, and that the answers provided were adequate, since is active and I came across this by doing some research on fullscreen, I leave here one update to this topic:

There is a way to "simulate" the F11 key, but cannot be automated, the user actually needs to click a button for example, in order to trigger the full screen mode.

  • Toggle Fullscreen status on button click

    With this example, the user can switch to and from fullscreen mode by clicking a button:

    HTML element to act as trigger:

    <input type="button" value="click to toggle fullscreen" onclick="toggleFullScreen()">
    

    JavaScript:

    function toggleFullScreen() {
      if ((document.fullScreenElement && document.fullScreenElement !== null) ||    
       (!document.mozFullScreen && !document.webkitIsFullScreen)) {
        if (document.documentElement.requestFullScreen) {  
          document.documentElement.requestFullScreen();  
        } else if (document.documentElement.mozRequestFullScreen) {  
          document.documentElement.mozRequestFullScreen();  
        } else if (document.documentElement.webkitRequestFullScreen) {  
          document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);  
        }  
      } else {  
        if (document.cancelFullScreen) {  
          document.cancelFullScreen();  
        } else if (document.mozCancelFullScreen) {  
          document.mozCancelFullScreen();  
        } else if (document.webkitCancelFullScreen) {  
          document.webkitCancelFullScreen();  
        }  
      }  
    }
    
  • Go to Fullscreen on button click

    This example allows you to enable full screen mode without making alternation, ie you switch to full screen but to return to the normal screen will have to use the F11 key:

    HTML element to act as trigger:

    <input type="button" value="click to go fullscreen" onclick="requestFullScreen()">
    

    JavaScript:

    function requestFullScreen() {
    
      var el = document.body;
    
      // Supports most browsers and their versions.
      var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen 
      || el.mozRequestFullScreen || el.msRequestFullScreen;
    
      if (requestMethod) {
    
        // Native full screen.
        requestMethod.call(el);
    
      } else if (typeof window.ActiveXObject !== "undefined") {
    
        // Older IE.
        var wscript = new ActiveXObject("WScript.Shell");
    
        if (wscript !== null) {
          wscript.SendKeys("{F11}");
        }
      }
    }
    

Sources found along with useful information on this subject:

Mozilla Developer Network

How to make in Javascript full screen windows (stretching all over the screen)

How to make browser full screen using F11 key event through JavaScript

Chrome Fullscreen API

jQuery fullscreen event plugin, version 0.2.0

jquery-fullscreen-plugin

How to post data to specific URL using WebClient in C#

There is a built in method called UploadValues that can send HTTP POST (or any kind of HTTP methods) AND handles the construction of request body (concatenating parameters with "&" and escaping characters by url encoding) in proper form data format:

using(WebClient client = new WebClient())
{
    var reqparm = new System.Collections.Specialized.NameValueCollection();
    reqparm.Add("param1", "<any> kinds & of = ? strings");
    reqparm.Add("param2", "escaping is already handled");
    byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
    string responsebody = Encoding.UTF8.GetString(responsebytes);
}

return results from a function (javascript, nodejs)

function routeToRoom(userId, passw, cb) {
    var roomId = 0;
    var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
    var users = nStore.new('data/users.db', function() {
        users.find({
            user: userId,
            pass: passw
        }, function(err, results) {
            if (err) {
                roomId = -1;
            } else {
                roomId = results.creationix.room;
            }
            cb(roomId);
        });
    });
}
routeToRoom("alex", "123", function(id) {
    console.log(id);    
});

You need to use callbacks. That's how asynchronous IO works. Btw sys.puts is deprecated

Automatically create an Enum based on values in a database lookup table?

I'm doing this exact thing, but you need to do some kind of code generation for this to work.

In my solution, I added a project "EnumeratedTypes". This is a console application which gets all of the values from the database and constructs the enums from them. Then it saves all of the enums to an assembly.

The enum generation code is like this:

// Get the current application domain for the current thread
AppDomain currentDomain = AppDomain.CurrentDomain;

// Create a dynamic assembly in the current application domain,
// and allow it to be executed and saved to disk.
AssemblyName name = new AssemblyName("MyEnums");
AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(name,
                                      AssemblyBuilderAccess.RunAndSave);

// Define a dynamic module in "MyEnums" assembly.
// For a single-module assembly, the module has the same name as the assembly.
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name,
                                  name.Name + ".dll");

// Define a public enumeration with the name "MyEnum" and an underlying type of Integer.
EnumBuilder myEnum = moduleBuilder.DefineEnum("EnumeratedTypes.MyEnum",
                         TypeAttributes.Public, typeof(int));

// Get data from database
MyDataAdapter someAdapter = new MyDataAdapter();
MyDataSet.MyDataTable myData = myDataAdapter.GetMyData();

foreach (MyDataSet.MyDataRow row in myData.Rows)
{
    myEnum.DefineLiteral(row.Name, row.Key);
}

// Create the enum
myEnum.CreateType();

// Finally, save the assembly
assemblyBuilder.Save(name.Name + ".dll");

My other projects in the solution reference this generated assembly. As a result, I can then use the dynamic enums in code, complete with intellisense.

Then, I added a post-build event so that after this "EnumeratedTypes" project is built, it runs itself and generates the "MyEnums.dll" file.

By the way, it helps to change the build order of your project so that "EnumeratedTypes" is built first. Otherwise, once you start using your dynamically generated .dll, you won't be able to do a build if the .dll ever gets deleted. (Chicken and egg kind of problem -- your other projects in the solution need this .dll to build properly, and you can't create the .dll until you build your solution...)

I got most of the above code from this msdn article.

Hope this helps!

Magento: Set LIMIT on collection

The way to do was looking at the code in code/core/Mage/Catalog/Model/Resource/Category/Flat/Collection.php at line 380 in Magento 1.7.2 on the function setPage($pageNum, $pageSize)

 $collection = Mage::getModel('model')
     ->getCollection()
     ->setCurPage(2) // 2nd page
     ->setPageSize(10); // 10 elements per pages

I hope this will help someone.

How to load/reference a file as a File instance from the classpath

I find this one-line code as most efficient and useful:

File file = new File(ClassLoader.getSystemResource("com/path/to/file.txt").getFile());

Works like a charm.

How to use external ".js" files

In your head element add

<script type="text/javascript" src="myscript.js"></script>

Get page title with Selenium WebDriver using Java

It could be done by getting the page title by Selenium and do assertion by using TestNG.

  1. Import Assert class in the import section:

    `import org.testng.Assert;`
    
  2. Create a WebDriver object:

    WebDriver driver=new FirefoxDriver();

  3. Apply this to assert the title of the page:

    Assert.assertEquals("Expected page title", driver.getTitle());

Generate ER Diagram from existing MySQL database, created for CakePHP

Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).

This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.

What does the "assert" keyword do?

assert is a debugging tool that will cause the program to throw an AssertionFailed exception if the condition is not true. In this case, the program will throw an exception if either of the two conditions following it evaluate to false. Generally speaking, assert should not be used in production code

What is the C# equivalent of NaN or IsNumeric?

You can still use the Visual Basic function in C#. The only thing you have to do is just follow my instructions shown below:

  1. Add the reference to the Visual Basic Library by right clicking on your project and selecting "Add Reference":

enter image description here

  1. Then import it in your class as shown below:

    using Microsoft.VisualBasic;

  2. Next use it wherever you want as shown below:

                if (!Information.IsNumeric(softwareVersion))
            {
                throw new DataException(string.Format("[{0}] is an invalid App Version!  Only numeric values are supported at this time.", softwareVersion));
            }
    

Hope, this helps and good luck!

from list of integers, get number closest to a given value

Expanding upon Gustavo Lima's answer. The same thing can be done without creating an entirely new list. The values in the list can be replaced with the differentials as the FOR loop progresses.

def f_ClosestVal(v_List, v_Number):
"""Takes an unsorted LIST of INTs and RETURNS INDEX of value closest to an INT"""
for _index, i in enumerate(v_List):
    v_List[_index] = abs(v_Number - i)
return v_List.index(min(v_List))

myList = [1, 88, 44, 4, 4, -2, 3]
v_Num = 5
print(f_ClosestVal(myList, v_Num)) ## Gives "3," the index of the first "4" in the list.

Styling HTML email for Gmail

Gmail started basic support for style tags in the head area. Found nothing official yet but you can easily try it yourself.
It seems to ignore class and id selectors but basic element selectors work.

<!doctype html>
<html>
  <head>
    <style type="text/css">
      p{font-family:Tahoma,sans-serif;font-size:12px;margin:0}  
    </style>
  </head>
  <body>
    <p>Email content here</p>
  </body>
</html>

it will create a style tag in its own head area limited to the div containing the mail body

<style>div.m14623dcb877eef15 p{font-family:Tahoma,sans-serif;font-size:12px;margin:0}</style>

Create a new RGB OpenCV image using Python?

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

oracle - what statements need to be committed?

In mechanical terms a COMMIT makes a transaction. That is, a transaction is all the activity (one or more DML statements) which occurs between two COMMIT statements (or ROLLBACK).

In Oracle a DDL statement is a transaction in its own right simply because an implicit COMMIT is issued before the statement is executed and again afterwards. TRUNCATE is a DDL command so it doesn't need an explicit commit because calling it executes an implicit commit.

From a system design perspective a transaction is a business unit of work. It might consist of a single DML statement or several of them. It doesn't matter: only full transactions require COMMIT. It literally does not make sense to issue a COMMIT unless or until we have completed a whole business unit of work.

This is a key concept. COMMITs don't just release locks. In Oracle they also release latches, such as the Interested Transaction List. This has an impact because of Oracle's read consistency model. Exceptions such as ORA-01555: SNAPSHOT TOO OLD or ORA-01002: FETCH OUT OF SEQUENCE occur because of inappropriate commits. Consequently, it is crucial for our transactions to hang onto locks for as long as they need them.

How is Docker different from a virtual machine?

Docker isn't a virtualization methodology. It relies on other tools that actually implement container-based virtualization or operating system level virtualization. For that, Docker was initially using LXC driver, then moved to libcontainer which is now renamed as runc. Docker primarily focuses on automating the deployment of applications inside application containers. Application containers are designed to package and run a single service, whereas system containers are designed to run multiple processes, like virtual machines. So, Docker is considered as a container management or application deployment tool on containerized systems.

In order to know how it is different from other virtualizations, let's go through virtualization and its types. Then, it would be easier to understand what's the difference there.

Virtualization

In its conceived form, it was considered a method of logically dividing mainframes to allow multiple applications to run simultaneously. However, the scenario drastically changed when companies and open source communities were able to provide a method of handling the privileged instructions in one way or another and allow for multiple operating systems to be run simultaneously on a single x86 based system.

Hypervisor

The hypervisor handles creating the virtual environment on which the guest virtual machines operate. It supervises the guest systems and makes sure that resources are allocated to the guests as necessary. The hypervisor sits in between the physical machine and virtual machines and provides virtualization services to the virtual machines. To realize it, it intercepts the guest operating system operations on the virtual machines and emulates the operation on the host machine's operating system.

The rapid development of virtualization technologies, primarily in cloud, has driven the use of virtualization further by allowing multiple virtual servers to be created on a single physical server with the help of hypervisors, such as Xen, VMware Player, KVM, etc., and incorporation of hardware support in commodity processors, such as Intel VT and AMD-V.

Types of Virtualization

The virtualization method can be categorized based on how it mimics hardware to a guest operating system and emulates a guest operating environment. Primarily, there are three types of virtualization:

  • Emulation
  • Paravirtualization
  • Container-based virtualization

Emulation

Emulation, also known as full virtualization runs the virtual machine OS kernel entirely in software. The hypervisor used in this type is known as Type 2 hypervisor. It is installed on the top of the host operating system which is responsible for translating guest OS kernel code to software instructions. The translation is done entirely in software and requires no hardware involvement. Emulation makes it possible to run any non-modified operating system that supports the environment being emulated. The downside of this type of virtualization is an additional system resource overhead that leads to a decrease in performance compared to other types of virtualizations.

Emulation

Examples in this category include VMware Player, VirtualBox, QEMU, Bochs, Parallels, etc.

Paravirtualization

Paravirtualization, also known as Type 1 hypervisor, runs directly on the hardware, or “bare-metal”, and provides virtualization services directly to the virtual machines running on it. It helps the operating system, the virtualized hardware, and the real hardware to collaborate to achieve optimal performance. These hypervisors typically have a rather small footprint and do not, themselves, require extensive resources.

Examples in this category include Xen, KVM, etc.

Paravirtualization

Container-based Virtualization

Container-based virtualization, also known as operating system-level virtualization, enables multiple isolated executions within a single operating system kernel. It has the best possible performance and density and features dynamic resource management. The isolated virtual execution environment provided by this type of virtualization is called a container and can be viewed as a traced group of processes.

Container-based virtualization

The concept of a container is made possible by the namespaces feature added to Linux kernel version 2.6.24. The container adds its ID to every process and adding new access control checks to every system call. It is accessed by the clone() system call that allows creating separate instances of previously-global namespaces.

Namespaces can be used in many different ways, but the most common approach is to create an isolated container that has no visibility or access to objects outside the container. Processes running inside the container appear to be running on a normal Linux system although they are sharing the underlying kernel with processes located in other namespaces, same for other kinds of objects. For instance, when using namespaces, the root user inside the container is not treated as root outside the container, adding additional security.

The Linux Control Groups (cgroups) subsystem, the next major component to enable container-based virtualization, is used to group processes and manage their aggregate resource consumption. It is commonly used to limit the memory and CPU consumption of containers. Since a containerized Linux system has only one kernel and the kernel has full visibility into the containers, there is only one level of resource allocation and scheduling.

Several management tools are available for Linux containers, including LXC, LXD, systemd-nspawn, lmctfy, Warden, Linux-VServer, OpenVZ, Docker, etc.

Containers vs Virtual Machines

Unlike a virtual machine, a container does not need to boot the operating system kernel, so containers can be created in less than a second. This feature makes container-based virtualization unique and desirable than other virtualization approaches.

Since container-based virtualization adds little or no overhead to the host machine, container-based virtualization has near-native performance

For container-based virtualization, no additional software is required, unlike other virtualizations.

All containers on a host machine share the scheduler of the host machine saving need of extra resources.

Container states (Docker or LXC images) are small in size compared to virtual machine images, so container images are easy to distribute.

Resource management in containers is achieved through cgroups. Cgroups does not allow containers to consume more resources than allocated to them. However, as of now, all resources of host machine are visible in virtual machines, but can't be used. This can be realized by running top or htop on containers and host machine at the same time. The output across all environments will look similar.

Update:

How does Docker run containers in non-Linux systems?

If containers are possible because of the features available in the Linux kernel, then the obvious question is how do non-Linux systems run containers. Both Docker for Mac and Windows use Linux VMs to run the containers. Docker Toolbox used to run containers in Virtual Box VMs. But, the latest Docker uses Hyper-V in Windows and Hypervisor.framework in Mac.

Now, let me describe how Docker for Mac runs containers in detail.

Docker for Mac uses https://github.com/moby/hyperkit to emulate the hypervisor capabilities and Hyperkit uses hypervisor.framework in its core. Hypervisor.framework is Mac's native hypervisor solution. Hyperkit also uses VPNKit and DataKit to namespace network and filesystem respectively.

The Linux VM that Docker runs in Mac is read-only. However, you can bash into it by running:

screen ~/Library/Containers/com.docker.docker/Data/vms/0/tty.

Now, we can even check the Kernel version of this VM:

# uname -a Linux linuxkit-025000000001 4.9.93-linuxkit-aufs #1 SMP Wed Jun 6 16:86_64 Linux.

All containers run inside this VM.

There are some limitations to hypervisor.framework. Because of that Docker doesn't expose docker0 network interface in Mac. So, you can't access containers from the host. As of now, docker0 is only available inside the VM.

Hyper-v is the native hypervisor in Windows. They are also trying to leverage Windows 10's capabilities to run Linux systems natively.

In android how to set navigation drawer header image and name programmatically in class file?

I know this is an old post but i am sure that this might help someone down the road.

You can simply get the headerView element of the Navigation view by doing this:

 NavigationView mView = ( NavigationView ) findViewById( R.id.nav_view );

 if( mView != null ){
     LinearLayout mParent = ( LinearLayout ) mView.getHeaderView( 0 );

     if( mParent != null ){
        // Set your values to the image and text view by declaring and setting as you need to here. 
     }
 }

I hope that this helps someone.

Working with SQL views in Entity Framework Core

The EF Core doesn't create DBset for the SQL views automatically in the context calss, we can add them manually as below.

public partial class LocalDBContext : DbContext
{ 

    public LocalDBContext(DbContextOptions<LocalDBContext> options) : base(options)
    {

    }

    public virtual DbSet<YourView> YourView { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<YourView>(entity => {
            entity.HasKey(e => e.ID);
            entity.ToTable("YourView");
            entity.Property(e => e.Name).HasMaxLength(50);
        });
    }

}

The sample view is defined as below with few properties

using System;
using System.Collections.Generic;

namespace Project.Entities
{
    public partial class YourView
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }
}

After adding a class for the view and DB set in the context class, you are good to use the view object through your context object in the controller.

Javascript Regexp dynamic generation from variables?

The RegExp constructor creates a regular expression object for matching text with a pattern.

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
    str.match(regex);

Above code works perfectly for me...

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

This is a common problem. You're almost certainly running into permissions issues. To solve it, make sure that the apache user has read/write access to your entire repository. To do that, chown -R apache:apache *, chmod -R 664 * for everything under your svn repository.

Also, see here and here if you're still stuck.


Update to answer OP's additional question in comments:

The "664" string is an octal (base 8) representation of the permissions. There are three digits here, representing permissions for the owner, group, and everyone else (sometimes called "world"), respectively, for that file or directory.

Notice that each base 8 digit can be represented with 3 bits (000 for '0' through 111 for '7'). Each bit means something:

  • first bit: read permissions
  • second bit: write permissions
  • third bit: execute permissions

For example, 764 on a file would mean that:

  • the owner (first digit) has read/write/execute (7) permission
  • the group (second digit) has read/write (6) permission
  • everyone else (third digit) has read (4) permission

Hope that clears things up!

Oracle - How to generate script from sql developer

I did not know about DMBS_METADATA, but your answers prompted me to create a utility to script all objects owned by an Oracle user.

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

Creating dummy variables in pandas for python

Handling categorical features scikit-learn expects all features to be numeric. So how do we include a categorical feature in our model?

Ordered categories: transform them to sensible numeric values (example: small=1, medium=2, large=3) Unordered categories: use dummy encoding (0/1) What are the categorical features in our dataset?

Ordered categories: weather (already encoded with sensible numeric values) Unordered categories: season (needs dummy encoding), holiday (already dummy encoded), workingday (already dummy encoded) For season, we can't simply leave the encoding as 1 = spring, 2 = summer, 3 = fall, and 4 = winter, because that would imply an ordered relationship. Instead, we create multiple dummy variables:

# An utility function to create dummy variable
`def create_dummies( df, colname ):
col_dummies = pd.get_dummies(df[colname], prefix=colname)
col_dummies.drop(col_dummies.columns[0], axis=1, inplace=True)
df = pd.concat([df, col_dummies], axis=1)
df.drop( colname, axis = 1, inplace = True )
return df`

Windows Batch: How to add Host-Entries?

Well I write a script which works very well.

> @echo off TITLE Modifying your HOSTS file COLOR F0 ECHO.
> 
> :LOOP SET Choice= SET /P Choice="Do you want to modify HOSTS file ?
> (Y/N)"
> 
> IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
> 
> ECHO. IF /I '%Choice%'=='Y' GOTO ACCEPTED IF /I '%Choice%'=='N' GOTO
> REJECTED ECHO Please type Y (for Yes) or N (for No) to proceed! ECHO.
> GOTO Loop
> 
> 
> :REJECTED ECHO Your HOSTS file was left
> unchanged>>%systemroot%\Temp\hostFileUpdate.log ECHO Finished. GOTO
> END
> 
> 
> :ACCEPTED SET NEWLINE=^& echo. ECHO Carrying out requested
> modifications to your HOSTS file FIND /C /I "www.youtube.com"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1    www.youtube.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "youtube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.facebook.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "facebook.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1    www.4everproxy.com
> >>%WINDIR%\system32\drivers\etc\hosts FIND /C /I "4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1    4everproxy.com >>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockvideos.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> unblockvideos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxyone.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxyone.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kuvia.eu" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    kuvia.eu>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "kuvia.eu/facebook-proxy"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> kuvia.eu/facebook-proxy>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "hidemytraxproxy.ca" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> hidemytraxproxy.ca>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "github.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> github.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "funproxy.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> funproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "en.wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> en.wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dronten.proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> dronten.proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zfreez.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> zfreez.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zendproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zendproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zalmos.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> zalmos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeunblockproxy.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubeunblockproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "youtubefreeproxy.net" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubefreeproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youliaoren.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youliaoren.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "xitenow.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> xitenow.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.vobas.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    vobas.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> www.unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.maddw.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    maddw.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND
> /C /I "facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.dolopo.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.dolopo.net>>%WINDIR%\system32\drivers\etc\hosts ECHO Finished GOTO
> END
> 
> 
> :END ECHO. ping -n 11 127.0.0.1 > nul EXIT

What are some resources for getting started in operating system development?

Movitz is a Lisp environment written in Common Lisp and running "on the metal". Unfortunately, some links on the Movitz main page deny access, but you can find instructions on how to download and compile the source code from the trac page. Also, a ready image can be found on the archive of this page.

IMHO this is utmost interesting, as it brings back the Lisp machine concept on the currently available hardware. It failed commercially, but this does not prove to me that the idea was bad.

The Unix haters handbook is a fun book that semi-seriously berates the concept of Unix and its derivatives. Many sections argument about how better the Lisp machine concept was.

How to list AD group membership for AD users using input list?

The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc

$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
  $output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
  $users[$i] + " " + $output 
  $z =  $users[$i] + " " + $output 
  add-content $location $z
}

Sample Output:

Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners
Guest Domain Guests Guests
krbtgt Domain Users Denied RODC Password Replication Group
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production

How to style the option of an html "select" element?

Some properties can be styled for<option> tag:

  • font-family
  • color
  • font-*
  • background-color

Also you can use custom font for individual <option> tag, for example any google font, Material Icons or other icon fonts from icomoon or alike. (That may come handy for font selectors etc.)

Considering that, you can create font-family stack and insert icons in <option> tags, eg.

    <select>
        <option style="font-family: 'Icons', 'Roboto', sans-serif;">a    ???</option>
        <option style="font-family: 'Icons', 'Roboto', sans-serif;">b    ????</option>
    </select>

where ? is taken from Icons and the rest is from Roboto.

Note though that custom fonts do not work for mobile select.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I do some quick tests and have the following findings:

1) if using SynchronousQueue:

After the threads reach the maximum size, any new work will be rejected with the exception like below.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)

2) if using LinkedBlockingQueue:

The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.

Uncaught TypeError: Cannot assign to read only property

When you use Object.defineProperties, by default writable is set to false, so _year and edition are actually read only properties.

Explicitly set them to writable: true:

_year: {
    value: 2004,
    writable: true
},

edition: {
    value: 1,
    writable: true
},

Check out MDN for this method.

writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.

How to add colored border on cardview?

my solution:

create a file card_view_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white_background"/>
<stroke android:width="2dp" 
    android:color="@color/red" />
<corners android:radius="20dip"/>
</shape>

and set programmatically

cardView.setBackgroundResource(R.drawable.card_view_border);

Cannot open include file 'afxres.h' in VC2010 Express

a similar issue is for Visual studio 2015 RC. Sometimes it loses the ability to open RC: you double click but editor do not one menus and dialogs.

Right click on the file *.rc, it will open:

enter image description here

And change as following:

enter image description here

pass post data with window.location.href

You can use GET instead of pass, but don't use this method for important values,

function passIDto(IDval){    
window.location.href = "CustomerBasket.php?oridd=" +  IDval ;
}   

In the CustomerBasket.php

<?php
  $value = $_GET["oridd"];
  echo  $value;
?>

How to display a date as iso 8601 format with PHP

Procedural style :

echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00

Object oriented style :

$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00

Hybrid 1 :

echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00

Hybrid 2 :

echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00

Notes :

1) You could also use 'Y-m-d\TH:i:sP' as an alternative to 'c' for your format.

2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :

echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00

3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :

echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00

hasNext in Python iterators?

No. The most similar concept is most likely a StopIteration exception.

C# Version Of SQL LIKE

Check out this question - How to do SQL Like % in Linq?

Also, for more advanced string pattern searching, there are lots of tutorials on using Regular Expressions - e.g. http://www.codeproject.com/KB/dotnet/regextutorial.aspx

How to fix "unable to write 'random state' " in openssl

Is it possible to use jQuery to read meta tags

Would this parser help you?

https://github.com/fiann/jquery.ogp

It parses meta OG data to JSON, so you can just use the data directly. If you prefer, you can read/write them directly using JQuery, of course. For example:

$("meta[property='og:title']").attr("content", document.title);
$("meta[property='og:url']").attr("content", location.toString());

Note the single-quotes around the attribute values; this prevents parse errors in jQuery.

npm - EPERM: operation not permitted on Windows

I had the same problem, after updating npm. Solved it by re-installing latest npm again with:

npm i -g npm

but this time with cmd running in administrating mode.

i did all this because i suspected there was an issue with the update, mostly some missing files.

jQuery jump or scroll to certain position, div or target on the page from button onclick

$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used

babel-loader jsx SyntaxError: Unexpected token

Add "babel-preset-react"

npm install babel-preset-react

and add "presets" option to babel-loader in your webpack.config.js

(or you can add it to your .babelrc or package.js: http://babeljs.io/docs/usage/babelrc/)

Here is an example webpack.config.js:

{ 
    test: /\.jsx?$/,         // Match both .js and .jsx files
    exclude: /node_modules/, 
    loader: "babel", 
    query:
      {
        presets:['react']
      }
}

Recently Babel 6 was released and there was a major change: https://babeljs.io/blog/2015/10/29/6.0.0

If you are using react 0.14, you should use ReactDOM.render() (from require('react-dom')) instead of React.render(): https://facebook.github.io/react/blog/#changelog

UPDATE 2018

Rule.query has already been deprecated in favour of Rule.options. Usage in webpack 4 is as follows:

npm install babel-loader babel-preset-react

Then in your webpack configuration (as an entry in the module.rules array in the module.exports object)

{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: ['react']
        }
      }
    ],
  }

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

How do I enable logging for Spring Security?

Basic debugging using Spring's DebugFilter can be configured like this:

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.debug(true);
    }
}

Print all but the first three columns

As I was annoyed by the first highly upvoted but wrong answer I found enough to write a reply there, and here the wrong answers are marked as such, here is my bit. I do not like proposed solutions as I can see no reason to make answer so complex.

I have a log where after $5 with an IP address can be more text or no text. I need everything from the IP address to the end of the line should there be anything after $5. In my case, this is actualy withn an awk program, not an awk oneliner so awk must solve the problem. When I try to remove the first 4 fields using the old nice looking and most upvoted but completely wrong answer:

echo "  7 27.10.16. Thu 11:57:18 37.244.182.218 one two three" | awk '{$1=$2=$3=$4=""; printf "[%s]\n", $0}'

it spits out wrong and useless response (I added [] to demonstrate):

[    37.244.182.218 one two three]

Instead, if columns are fixed width until the cut point and awk is needed, the correct and quite simple answer is:

echo "  7 27.10.16. Thu 11:57:18 37.244.182.218 one two three" | awk '{printf "[%s]\n", substr($0,28)}'

which produces the desired output:

[37.244.182.218 one two three]

java.io.IOException: Broken pipe

increase the response.getBufferSize() get the buffer size and compare with the bytes you want to transfer !

Best way to check if a drop down list contains a value?

//you can use the ? operator instead of if

ddlCustomerNumber.SelectedValue = ddlType.Items.FindByValue(GetCustomerNumberCookie().ToString()) != null ? GetCustomerNumberCookie().ToString() : "0";

How to view kafka message

On server where your admin run kafka find kafka-console-consumer.sh by command find . -name kafka-console-consumer.sh then go to that directory and run for read message from your topic

./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning --max-messages 10

note that in topic may be many messages in that case I use --max-messages key

How to see query history in SQL Server Management Studio

you can use "Automatically generate script on every save", if you are using management studio. This is not certainly logging. Check if useful for you.. ;)

Python, creating objects

Create a class and give it an __init__ method:

class Student:
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

    def is_old(self):
        return self.age > 100

Now, you can initialize an instance of the Student class:

>>> s = Student('John', 88, None)
>>> s.name
    'John'
>>> s.age
    88

Although I'm not sure why you need a make_student student function if it does the same thing as Student.__init__.

TypeError: 'list' object is not callable in python

Before you can fully understand what the error means and how to solve, it is important to understand what a built-in name is in Python.

What is a built-in name?

In Python, a built-in name is a name that the Python interpreter already has assigned a predefined value. The value can be either a function or class object. These names are always made available by default, no matter the scope. Some of the values assigned to these names represent fundamental types of the Python language, while others are simple useful.

As of the latest version of Python - 3.6.2 - there are currently 61 built-in names. A full list of the names and how they should be used, can be found in the documentation section Built-in Functions.

An important point to note however, is that Python will not stop you from re-assigning builtin names. Built-in names are not reserved, and Python allows them to be used as variable names as well.

Here is an example using the dict built-in:

>>> dict = {}
>>> dict
{}
>>>

As you can see, Python allowed us to assign the dict name, to reference a dictionary object.

What does "TypeError: 'list' object is not callable" mean?

To put it simply, the reason the error is occurring is because you re-assigned the builtin name list in the script:

list = [1, 2, 3, 4, 5]

When you did this, you overwrote the predefined value of the built-in name. This means you can no longer use the predefined value of list, which is a class object representing Python list.

Thus, when you tried to use the list class to create a new list from a range object:

myrange = list(range(1, 10))

Python raised an error. The reason the error says "'list' object is not callable", is because as said above, the name list was referring to a list object. So the above would be the equivalent of doing:

[1, 2, 3, 4, 5](range(1, 10))

Which of course makes no sense. You cannot call a list object.

How can I fix the error?

Suppose you have code such as the following:

list = [1, 2, 3, 4, 5]
myrange = list(range(1, 10))

for number in list:
    if number in myrange:
        print(number, 'is between 1 and 10')

Running the above code produces the following error:

Traceback (most recent call last):
  File "python", line 2, in <module>
TypeError: 'list' object is not callable

If you are getting a similar error such as the one above saying an "object is not callable", chances are you used a builtin name as a variable in your code. In this case and other cases the fix is as simple as renaming the offending variable. For example, to fix the above code, we could rename our list variable to ints:

ints = [1, 2, 3, 4, 5] # Rename "list" to "ints"
myrange = list(range(1, 10))

for number in ints: # Renamed "list" to "ints"
    if number in myrange:
        print(number, 'is between 1 and 10')

PEP8 - the official Python style guide - includes many recommendations on naming variables.

This is a very common error new and old Python users make. This is why it's important to always avoid using built-in names as variables such as str, dict, list, range, etc.

Many linters and IDEs will warn you when you attempt to use a built-in name as a variable. If your frequently make this mistake, it may be worth your time to invest in one of these programs.

I didn't rename a built-in name, but I'm still getting "TypeError: 'list' object is not callable". What gives?

Another common cause for the above error is attempting to index a list using parenthesis (()) rather than square brackets ([]). For example:

>>> lst = [1, 2]
>>> lst(0)

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    lst(0)
TypeError: 'list' object is not callable

For an explanation of the full problem and what can be done to fix it, see TypeError: 'list' object is not callable while trying to access a list.

Android fastboot waiting for devices

The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)

Accessing a Dictionary.Keys Key through a numeric index

To expand on Daniels post and his comments regarding the key, since the key is embedded within the value anyway, you could resort to using a KeyValuePair<TKey, TValue> as the value. The main reasoning for this is that, in general, the Key isn't necessarily directly derivable from the value.

Then it'd look like this:

public sealed class CustomDictionary<TKey, TValue>
  : KeyedCollection<TKey, KeyValuePair<TKey, TValue>>
{
  protected override TKey GetKeyForItem(KeyValuePair<TKey, TValue> item)
  {
    return item.Key;
  }
}

To use this as in the previous example, you'd do:

CustomDictionary<string, int> custDict = new CustomDictionary<string, int>();

custDict.Add(new KeyValuePair<string, int>("key", 7));

int valueByIndex = custDict[0].Value;
int valueByKey = custDict["key"].Value;
string keyByIndex = custDict[0].Key;

Remove leading and trailing spaces?

Starting file:

     line 1
   line 2
line 3  
      line 4 

Code:

with open("filename.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        stripped = line.strip()
        print(stripped)

Output:

line 1
line 2
line 3
line 4

Add comma to numbers every three digits

You can also look at the jquery FormatCurrency plugin (of which I am the author); it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.

$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });

Why aren't variable-length arrays part of the C++ standard?

There are situations where allocating heap memory is very expensive compared to the operations performed. An example is matrix math. If you work with smallish matrices say 5 to 10 elements and do a lot of arithmetics the malloc overhead will be really significant. At the same time making the size a compile time constant does seem very wasteful and inflexible.

I think that C++ is so unsafe in itself that the argument to "try to not add more unsafe features" is not very strong. On the other hand, as C++ is arguably the most runtime efficient programming language features which makes it more so are always useful: People who write performance critical programs will to a large extent use C++, and they need as much performance as possible. Moving stuff from heap to stack is one such possibility. Reducing the number of heap blocks is another. Allowing VLAs as object members would one way to achieve this. I'm working on such a suggestion. It is a bit complicated to implement, admittedly, but it seems quite doable.

In C++, what is a virtual base class?

A virtual base class is a class that cannot be instantiated : you cannot create direct object out of it.

I think you are confusing two very different things. Virtual inheritance is not the same thing as an abstract class. Virtual inheritance modifies the behaviour of function calls; sometimes it resolves function calls that otherwise would be ambiguous, sometimes it defers function call handling to a class other than that one would expect in a non-virtual inheritance.

What is the command for cut copy paste a file from one directory to other directory

E:>move "blogger code.txt" d:/"blogger code.txt"

    1 file(s) moved.

"blogger code.txt" is a file name

The file move from E: drive to D: drive

Java RegEx meta character (.) and ordinary dot?

I am doing some basic array in JGrasp and found that with an accessor method for a char[][] array to use ('.') to place a single dot.

How do you remove the title text from the Android ActionBar?

In your Manifest

<activity android:name=".ActivityHere"
     android:label="">

Convert row to column header for Pandas DataFrame,

It would be easier to recreate the data frame. This would also interpret the columns types from scratch.

headers = df.iloc[0]
new_df  = pd.DataFrame(df.values[1:], columns=headers)

adding multiple entries to a HashMap at once in one statement

Here's a simple class that will accomplish what you want

import java.util.HashMap;

public class QuickHash extends HashMap<String,String> {
    public QuickHash(String...KeyValuePairs) {
        super(KeyValuePairs.length/2);
        for(int i=0;i<KeyValuePairs.length;i+=2)
            put(KeyValuePairs[i], KeyValuePairs[i+1]);
    }
}

And then to use it

Map<String, String> Foo=QuickHash(
    "a", "1",
    "b", "2"
);

This yields {a:1, b:2}

How to automatically generate N "distinct" colors?

If N is big enough, you're going to get some similar-looking colors. There's only so many of them in the world.

Why not just evenly distribute them through the spectrum, like so:

IEnumerable<Color> CreateUniqueColors(int nColors)
{
    int subdivision = (int)Math.Floor(Math.Pow(nColors, 1/3d));
    for(int r = 0; r < 255; r += subdivision)
        for(int g = 0; g < 255; g += subdivision)
            for(int b = 0; b < 255; b += subdivision)
                yield return Color.FromArgb(r, g, b);
}

If you want to mix up the sequence so that similar colors aren't next to each other, you could maybe shuffle the resulting list.

Am I underthinking this?

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

Something like gunzip using the -r flag?....

Travel the directory structure recursively. If any of the file names specified on the command line are directories, gzip will descend into the directory and compress all the files it finds there (or decompress them in the case of gunzip ).

http://www.computerhope.com/unix/gzip.htm

Setting public class variables

You're "setting" the value of that variable/attribute. Not overriding or overloading it. Your code is very, very common and normal.

All of these terms ("set", "override", "overload") have specific meanings. Override and Overload are about polymorphism (subclassing).

From http://en.wikipedia.org/wiki/Object-oriented_programming :

Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism.

How to detect the device orientation using CSS media queries?

CSS to detect screen orientation:

 @media screen and (orientation:portrait) { … }
 @media screen and (orientation:landscape) { … }

The CSS definition of a media query is at http://www.w3.org/TR/css3-mediaqueries/#orientation

WebService Client Generation Error with JDK8

When using Maven with IntelliJ IDE you can add -Djavax.xml.accessExternalSchema=all to Maven setting under JVM Options for Maven Build Tools Runner configuration

How to tag an older commit in Git?

The answer by @Phrogz is great, but doesn't work on Windows. Here's how to tag an old commit with the commit's original date using Powershell:

git checkout 9fceb02
$env:GIT_COMMITTER_DATE = git show --format=%aD | Select -First 1
git tag v1.2
git checkout master

Where is the visual studio HTML Designer?

The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.

I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

Error: stray '\240' in program

It appears you have illegal characters in your source. I cannot figure out what character \240 should be but apparently it is around the start of line 10

In the code you posted, the issue does not exist: Live On Coliru

Create a CSV File for a user in PHP

In addition to all already said, you might need to add:

header("Content-Transfer-Encoding: UTF-8");

It's very useful when handling files with multiple languages in them, like people's names, or cities.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Difference between OData and REST web services

From the OData documentation:

The OData Protocol is an application-level protocol for interacting with data via RESTful web services.

...

The OData Protocol is different from other REST-based web service approaches in that it provides a uniform way to describe both the data and the data model.

7-zip commandline

Since 7-zip version 9.25 alpha there is a new -spf switch that can be used to store the full file paths including drive letter to the archive.

7zG.exe a -spf c:\BAckup\backup.zip @c:\temp\tmpFileList.txt

should be working just fine now.

Class 'ViewController' has no initializers in swift

The error could be improved, but the problem with your first version is you have a member variable, delegate, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.

When you make it optional, you allow it to be nil by default, removing the need to explicitly give it a value or initialize it.

CodeIgniter - how to catch DB errors?

Maybe this:

$db_debug = $this->db->db_debug; //save setting

$this->db->db_debug = FALSE; //disable debugging for queries

$result = $this->db->query($sql); //run query

//check for errors, etc

$this->db->db_debug = $db_debug; //restore setting

How to quickly clear a JavaScript Object?

This bugged me for ages so here is my version as I didn't want an empty object, I wanted one with all the properties but reset to some default value. Kind of like a new instantiation of a class.

_x000D_
_x000D_
let object1 = {_x000D_
  a: 'somestring',_x000D_
  b: 42,_x000D_
  c: true,_x000D_
  d:{_x000D_
    e:1,_x000D_
    f:2,_x000D_
    g:true,_x000D_
    h:{_x000D_
      i:"hello"_x000D_
    }_x000D_
  },_x000D_
  j: [1,2,3],_x000D_
  k: ["foo", "bar"],_x000D_
  l:["foo",1,true],_x000D_
  m:[{n:10, o:"food", p:true }, {n:11, o:"foog", p:true }],_x000D_
  q:null,_x000D_
  r:undefined_x000D_
};_x000D_
_x000D_
let boolDefault = false;_x000D_
let stringDefault = "";_x000D_
let numberDefault = 0;_x000D_
_x000D_
console.log(object1);_x000D_
//document.write("<pre>");_x000D_
//document.write(JSON.stringify(object1))_x000D_
//document.write("<hr />");_x000D_
cleanObject(object1);_x000D_
console.log(object1);_x000D_
//document.write(JSON.stringify(object1));_x000D_
//document.write("</pre>");_x000D_
_x000D_
function cleanObject(o) {_x000D_
  for (let [key, value] of Object.entries(o)) {_x000D_
    let propType = typeof(o[key]);_x000D_
_x000D_
    //console.log(key, value, propType);_x000D_
_x000D_
    switch (propType) {_x000D_
      case "number" :_x000D_
        o[key] = numberDefault;_x000D_
        break;_x000D_
_x000D_
      case "string":_x000D_
        o[key] = stringDefault;_x000D_
        break;_x000D_
_x000D_
      case "boolean":_x000D_
        o[key] = boolDefault;    _x000D_
        break;_x000D_
_x000D_
      case "undefined":_x000D_
        o[key] = undefined;   _x000D_
        break;_x000D_
_x000D_
      default:_x000D_
        if(value === null) {_x000D_
            continue;_x000D_
        }_x000D_
_x000D_
        cleanObject(o[key]);_x000D_
        break;_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
// EXPECTED OUTPUT_x000D_
// Object { a: "somestring", b: 42, c: true, d: Object { e: 1, f: 2, g: true, h: Object { i: "hello" } }, j: Array [1, 2, 3], k: Array ["foo", "bar"], l: Array ["foo", 1, true], m: Array [Object { n: 10, o: "food", p: true }, Object { n: 11, o: "foog", p: true }], q: null, r: undefined }_x000D_
// Object { a: "", b: 0, c: undefined, d: Object { e: 0, f: 0, g: undefined, h: Object { i: "" } }, j: Array [0, 0, 0], k: Array ["", ""], l: Array ["", 0, undefined], m: Array [Object { n: 0, o: "", p: undefined }, Object { n: 0, o: "", p: undefined }], q: null, r: undefined }
_x000D_
_x000D_
_x000D_

Why should a Java class implement comparable?

Here is a real life sample. Note that String also implements Comparable.

class Author implements Comparable<Author>{
    String firstName;
    String lastName;

    @Override
    public int compareTo(Author other){
        // compareTo should return < 0 if this is supposed to be
        // less than other, > 0 if this is supposed to be greater than 
        // other and 0 if they are supposed to be equal
        int last = this.lastName.compareTo(other.lastName);
        return last == 0 ? this.firstName.compareTo(other.firstName) : last;
    }
}

later..

/**
 * List the authors. Sort them by name so it will look good.
 */
public List<Author> listAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    Collections.sort(authors);
    return authors;
}

/**
 * List unique authors. Sort them by name so it will look good.
 */
public SortedSet<Author> listUniqueAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    return new TreeSet<Author>(authors);
}

Best way to combine two or more byte arrays in C#

    public static bool MyConcat<T>(ref T[] base_arr, ref T[] add_arr)
    {
        try
        {
            int base_size = base_arr.Length;
            int size_T = System.Runtime.InteropServices.Marshal.SizeOf(base_arr[0]);
            Array.Resize(ref base_arr, base_size + add_arr.Length);
            Buffer.BlockCopy(add_arr, 0, base_arr, base_size * size_T, add_arr.Length * size_T);
        }
        catch (IndexOutOfRangeException ioor)
        {
            MessageBox.Show(ioor.Message);
            return false;
        }
        return true;
    }

Which HTTP methods match up to which CRUD methods?

The building blocks of REST are mainly the resources (and URI) and the hypermedia. In this context, GET is the way to get a representation of the resource (which can indeed be mapped to a SELECT in CRUD terms).

However, you shouldn't necessarily expect a one-to-one mapping between CRUD operations and HTTP verbs. The main difference between PUT and POST is about their idempotent property. POST is also more commonly used for partial updates, as PUT generally implies sending a full new representation of the resource.

I'd suggest reading this:

The HTTP specification is also a useful reference:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

[...]

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

How to apply multiple transforms in CSS?

I'm adding this answer not because it's likely to be helpful but just because it's true.

In addition to using the existing answers explaining how to make more than one translation by chaining them, you can also construct the 4x4 matrix yourself

I grabbed the following image from some random site I found while googling which shows rotational matrices:

Rotation around x axis: Rotation around x axis
Rotation around y axis: Rotation around y axis
Rotation around z axis: Rotation around z axis

I couldn't find a good example of translation, so assuming I remember/understand it right, translation:

[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[x y z 1]

See more at the Wikipedia article on transformation as well as the Pragamatic CSS3 tutorial which explains it rather well. Another guide I found which explains arbitrary rotation matrices is Egon Rath's notes on matrices

Matrix multiplication works between these 4x4 matrices of course, so to perform a rotation followed by a translation, you make the appropriate rotation matrix and multiply it by the translation matrix.

This can give you a bit more freedom to get it just right, and will also make it pretty much completely impossible for anyone to understand what it's doing, including you in five minutes.

But, you know, it works.

Edit: I just realized that I missed mentioning probably the most important and practical use of this, which is to incrementally create complex 3D transformations via JavaScript, where things will make a bit more sense.

Node.js - use of module.exports as a constructor

The example code is:

in main

square(width,function (data)
{
   console.log(data.squareVal);
});

using the following may works

exports.square = function(width,callback)
{
     var aa = new Object();
     callback(aa.squareVal = width * width);    
}

How to store a command in a variable in a shell script?

For bash, store your command like this:

command="ls | grep -c '^'"

Run your command like this:

echo $command | bash

Iterating each character in a string using Python

If you ever run in a situation where you need to get the next char of the word using __next__(), remember to create a string_iterator and iterate over it and not the original string (it does not have the __next__() method)

In this example, when I find a char = [ I keep looking into the next word while I don't find ], so I need to use __next__

here a for loop over the string wouldn't help

myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
    if char == "'":
        continue

    processedInput+=char

    if char == '[':
        next_char=word_iterator.__next__()
        while(next_char != "]"):
          processedInput+=next_char
          next_char=word_iterator.__next__()
        else:
          processedInput+=next_char

How to add footnotes to GitHub-flavoured Markdown?

GitHub Flavored Markdown doesn't support footnotes, but you can manually fake it¹ with Unicode characters or superscript tags, e.g. <sup>1</sup>.

¹Of course this isn't ideal, as you are now responsible for maintaining the numbering of your footnotes. It works reasonably well if you only have one or two, though.

How to increment a datetime by one day?

Most Simplest solution

from datetime import timedelta, datetime
date = datetime(2003,8,1,12,4,5)
for i in range(5):
    date += timedelta(days=1)
    print(date)

jQuery onclick event for <li> tags

You can get the ID, or any other attribute, using jQuery's attrib function.

$('ul.art-vmenu li').attrib('id');

To get the menu text, which is in the t span, you can do this:

$('ul.art-vmenu li').children('span.t').html();

To change the HTML is just as easy:

$('ul.art-vmenu li').children('span.t').html("I'm different");

Of course, if you wanted to get all the span.t's in the first place, it would be simpler to do:

$('ul.art-vemnu li span.t').html();

But I'm assuming you've already got the li's, and want to use child() to find something within that element.

row-level trigger vs statement-level trigger

if you want to execute the statement when number of rows are modified then it can be possible by statement level triggers.. viseversa... when you want to execute your statement each modification on your number of rows then you need to go for row level triggers..

for example: statement level triggers works for when table is modified..then more number of records are effected. and row level triggers works for when each row updation or modification..

How should I remove all the leading spaces from a string? - swift

extension String {

    var removingWhitespaceAndNewLines: String {
        return removing(.whitespacesAndNewlines)
    }

    func removing(_ forbiddenCharacters: CharacterSet) -> String {
        return String(unicodeScalars.filter({ !forbiddenCharacters.contains($0) }))
    }
}

Uncaught TypeError: undefined is not a function on loading jquery-min.js

Yes, i also I fixed it changing in the js libraries to the unminified.

For example, in the tag, change:

<script type="text/javascript" src="js/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.min.js"></script>

For:

<script type="text/javascript" src="js/jquery.ui.core.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.js"></script>

Quiting the 'min' as unminified.

Thanks for the idea.

Calling the base constructor in C#

As per some of the other answers listed here, you can pass parameters into the base class constructor. It is advised to call your base class constructor at the beginning of the constructor for your inherited class.

public class MyException : Exception
{
    public MyException(string message, string extraInfo) : base(message)
    {
    }
}

I note that in your example you never made use of the extraInfo parameter, so I assumed you might want to concatenate the extraInfo string parameter to the Message property of your exception (it seems that this is being ignored in the accepted answer and the code in your question).

This is simply achieved by invoking the base class constructor, and then updating the Message property with the extra info.

public class MyException: Exception
{
    public MyException(string message, string extraInfo) : base($"{message} Extra info: {extraInfo}")
    {
    }
}

Docker error: invalid reference format: repository name must be lowercase

had a space in the current working directory and usign $(pwd) to map volumes. Doesn't like spaces in directory names.

How to convert JSON to string?

JSON.stringify()

Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

Does delete on a pointer to a subclass call the base class destructor?

You have something like

class B
{
   A * a;
}
B * b = new B;
b->a = new A;

If you then call delete b;, nothing happens to a, and you have a memory leak. Trying to remember to delete b->a; is not a good solution, but there are a couple of others.

B::~B() {delete a;}

This is a destructor for B that will delete a. (If a is 0, that delete does nothing. If a is not 0 but doesn't point to memory from new, you get heap corruption.)

auto_ptr<A> a;
...
b->a.reset(new A);

This way you don't have a as a pointer, but rather an auto_ptr<> (shared_ptr<> will do as well, or other smart pointers), and it is automatically deleted when b is.

Either of these ways works well, and I've used both.

Stack, Static, and Heap in C++

An advantage of GC in some situations is an annoyance in others; reliance on GC encourages not thinking much about it. In theory, waits until 'idle' period or until it absolutely must, when it will steal bandwidth and cause response latency in your app.

But you don't have to 'not think about it.' Just as with everything else in multithreaded apps, when you can yield, you can yield. So for example, in .Net, it is possible to request a GC; by doing this, instead of less frequent longer running GC, you can have more frequent shorter running GC, and spread out the latency associated with this overhead.

But this defeats the primary attraction of GC which appears to be "encouraged to not have to think much about it because it is auto-mat-ic."

If you were first exposed to programming before GC became prevalent and were comfortable with malloc/free and new/delete, then it might even be the case that you find GC a little annoying and/or are distrustful(as one might be distrustful of 'optimization,' which has had a checkered history.) Many apps tolerate random latency. But for apps that don't, where random latency is less acceptable, a common reaction is to eschew GC environments and move in the direction of purely unmanaged code (or god forbid, a long dying art, assembly language.)

I had a summer student here a while back, an intern, smart kid, who was weaned on GC; he was so adament about the superiorty of GC that even when programming in unmanaged C/C++ he refused to follow the malloc/free new/delete model because, quote, "you shouldn't have to do this in a modern programming language." And you know? For tiny, short running apps, you can indeed get away with that, but not for long running performant apps.

How to get video duration, dimension and size in PHP?

getID3 supports video formats. See: http://getid3.sourceforge.net/

Edit: So, in code format, that'd be like:

include_once('pathto/getid3.php');
$getID3 = new getID3;
$file = $getID3->analyze($filename);
echo("Duration: ".$file['playtime_string'].
" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
" / Filesize: ".$file['filesize']." bytes<br />");

Note: You must include the getID3 classes before this will work! See the above link.

Edit: If you have the ability to modify the PHP installation on your server, a PHP extension for this purpose is ffmpeg-php. See: http://ffmpeg-php.sourceforge.net/

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

How to detect query which holds the lock in Postgres?

Since 9.6 this is a lot easier as it introduced the function pg_blocking_pids() to find the sessions that are blocking another session.

So you can use something like this:

select pid, 
       usename, 
       pg_blocking_pids(pid) as blocked_by, 
       query as blocked_query
from pg_stat_activity
where cardinality(pg_blocking_pids(pid)) > 0;

PhpMyAdmin not working on localhost

Same Object Not Found problem here - both in Xampp as well as in Wamp. It turns out the root name of "phpmyadmin" was "PhpMyAdmin". I got rid of all the capitals, renaming the folder to "phpmyadmin", and after a couple of reloads phpmyadmin was working.

How to search JSON data in MySQL?

If your are using MySQL Latest version following may help to reach your requirement.

select * from products where attribs_json->"$.feature.value[*]" in (1,3)

Why do we use web.xml?

It's the default configuration for a Java web application; it's required.

WicketFilter

is applied to every HTTP request that's sent to this web app.

How to go from one page to another page using javascript?

hope this would help:

window.location.href = '/url_after_domain';

Cannot edit in read-only editor VS Code

I had the Cannot edit in read-only editor error when trying to edit code after stopping the debug mode (for 2-3 minutes after pressing Shift+F5).

Turns out the default Node version (v9.11.1) wasn't exiting gracefully, leaving VScode stuck on read-only.
Simply adding "runtimeVersion": "12.4.0" to my launch.json file fixed it.

alternatively, change your default Node version to the latest stable version (you can see the current version on the DEBUG CONSOLE when starting debug mode).

What are NR and FNR and what does "NR==FNR" imply?

There are awk built-in variables.

NR - It gives the total number of records processed.

FNR - It gives the total number of records for each input file.

ASP.NET MVC3 Razor - Html.ActionLink style

VB sample:

 @Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})

Sample Css:

.someClass
{
    color: Green !important;
}

In my case, I found that I need the !important attribute to over ride the site.css a:link css class

Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

    <form id="formAddName">
      <fieldset>
        <legend>Add Name </legend>
            <label for="firstName">First Name</label>
            <input type="text" id="firstName" name="firstName" />

        <button>Add</button>
      </fieldset>
    </form>

      <ol id="demo"></ol>

<script>
    var list = document.getElementById('demo');
    var entry = document.getElementById('formAddName');
    entry.onsubmit = function(evt) {
    evt.preventDefault();
    var firstName = document.getElementById('firstName').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstName));
    list.appendChild(entry);
  }
</script>

What is the best way to access redux store outside a react component?

Doing it with hooks. I ran into a similar problem, but I was using react-redux with hooks. I did not want to lard up my interface code (i.e., react components) with lots of code dedicated to retrieving/sending information from/to the store. Rather, I wanted functions with generic names to retrieve and update the data. My path was to put the app's

const store = createSore(
   allReducers,
   window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
 );

into a module named store.js and adding export before const and adding the usual react-redux imports in the store.js. file. Then, I imported to index.js at the app level, which I then imported into index.js with the usual import {store} from "./store.js" The child components then accessed the store using the useSelector() and useDispatch() hooks.

To access the store in non-component front end code, I used the analogous import (i.e., import {store} from "../../store.js") and then used store.getState() and store.dispatch({*action goes here*}) to handled retrieving and updating (er, sending actions to) the store.

Use grep to report back only line numbers

try:

grep -n "text to find" file.ext | cut -f1 -d:

Get MIME type from filename extension

My take at those mimetypes, using the apache list, the below script will give you a dictionary with all the mimetypes.

var mimeTypeListUrl = "http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types";
var webClient = new WebClient();
var rawData = webClient.DownloadString(mimeTypeListUrl).Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);

var extensionToMimeType = new Dictionary<string, string>();
var mimeTypeToExtension = new Dictionary<string, string[]>();

foreach (var row in rawData)
{
    if (row.StartsWith("#")) continue;

    var rowData = row.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
    if (rowData.Length != 2) continue;

    var extensions = rowData[1].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
    if (!mimeTypeToExtension.ContainsKey(rowData[0]))
    {
        mimeTypeToExtension.Add(rowData[0], extensions);
    }

    foreach (var extension in extensions)
    {
        if (!extensionToMimeType.ContainsKey(extension))
        {
            extensionToMimeType.Add(extension, rowData[0]);
        }
    }

}

mysql: SOURCE error 2?

May be the file name or path you are used may be incorrect

In my system i created file abcd.sql at c:\

and used command mysql> source c:\abcd.sql Then i got result

Can't install any package with node npm

npm install <packagename> --registry http://registry.npmjs.org/

Try specifying the registry with the install command. Solved my problem.

How to create an array from a CSV file using PHP and the fgetcsv function

Old question, but still relevant for PHP 5.2 users. str_getcsv is available from PHP 5.3. I've written a small function that works with fgetcsv itself.

Below is my function from https://gist.github.com/4152628:

function parse_csv_file($csvfile) {
    $csv = Array();
    $rowcount = 0;
    if (($handle = fopen($csvfile, "r")) !== FALSE) {
        $max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000;
        $header = fgetcsv($handle, $max_line_length);
        $header_colcount = count($header);
        while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
            $row_colcount = count($row);
            if ($row_colcount == $header_colcount) {
                $entry = array_combine($header, $row);
                $csv[] = $entry;
            }
            else {
                error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
                return null;
            }
            $rowcount++;
        }
        //echo "Totally $rowcount rows found\n";
        fclose($handle);
    }
    else {
        error_log("csvreader: Could not read CSV \"$csvfile\"");
        return null;
    }
    return $csv;
}

Returns

Begin Reading CSV

Array
(
    [0] => Array
        (
            [vid] => 
            [agency] => 
            [division] => Division
            [country] => 
            [station] => Duty Station
            [unit] => Unit / Department
            [grade] => 
            [funding] => Fund Code
            [number] => Country Office Position Number
            [wnumber] => Wings Position Number
            [title] => Position Title
            [tor] => Tor Text
            [tor_file] => 
            [status] => 
            [datetime] => Entry on Wings
            [laction] => 
            [supervisor] => Supervisor Index Number
            [asupervisor] => Alternative Supervisor Index
            [author] => 
            [category] => 
            [parent] => Reporting to Which Position Number
            [vacant] => Status (Vacant / Filled)
            [index] => Index Number
        )

    [1] => Array
        (
            [vid] => 
            [agency] => WFP
            [division] => KEN Kenya, The Republic Of
            [country] => 
            [station] => Nairobi
            [unit] => Human Resources Officer P4
            [grade] => P-4
            [funding] => 5000001
            [number] => 22018154
            [wnumber] => 
            [title] => Human Resources Officer P4
            [tor] => 
            [tor_file] => 
            [status] => 
            [datetime] => 
            [laction] => 
            [supervisor] => 
            [asupervisor] => 
            [author] => 
            [category] => Professional
            [parent] => 
            [vacant] => 
            [index] => xxxxx
        )
) 

Visual Studio: Relative Assembly References Paths

Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.

I have done this several times under svn and under cvs.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

The character encoding of the plain text document was not declared - mootool script

FireFox is reporting that the response did not even specify the character encoding in the header, eg. Content-Type: text/html; charset=utf-8 and not just Content-Type: text/plain;.

What web server are you using? Are you sure you are not requesting a non-existing page (404) that responds poorly?

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

How to change date format in JavaScript

Use your mydate object and call getMonth() and getFullYear()

See this for more info: http://www.w3schools.com/jsref/jsref_obj_date.asp

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Use ` backticks for MYSQL reserved words...

table name "table" is reserved word for MYSQL...

so your query should be as follows...

$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Make a link use POST instead of GET

Instead using javascript, you could also use a label sending a hidden form. Very simple and small solution. The label can be anywhere in your html.

_x000D_
_x000D_
<form style="display: none" action="postUrl" method="post">_x000D_
  <button type="submit" id="button_to_link"> </button>_x000D_
</form>_x000D_
<label style="text-decoration: underline" for="button_to_link">  link that posts </label>
_x000D_
_x000D_
_x000D_

What is the dual table in Oracle?

More Facts about the DUAL....

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1562813956388

Thrilling experiments done here, and more thrilling explanations by Tom

Upgrade python in a virtualenv

I wasn't able to create a new virtualenv on top of the old one. But there are tools in pip which make it much faster to re-install requirements into a brand new venv. Pip can build each of the items in your requirements.txt into a wheel package, and store that in a local cache. When you create a new venv and run pip install in it, pip will automatically use the prebuilt wheels if it finds them. Wheels install much faster than running setup.py for each module.

My ~/.pip/pip.conf looks like this:

[global]
download-cache = /Users/me/.pip/download-cache
find-links =
/Users/me/.pip/wheels/

[wheel]
wheel-dir = /Users/me/.pip/wheels

I install wheel (pip install wheel), then run pip wheel -r requirements.txt. This stores the built wheels in the wheel-dir in my pip.conf.

From then on, any time I pip install any of these requirements, it installs them from the wheels, which is pretty quick.

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

If you're wondering specifically about the examples in the JUnit FAQ, such as the basic test template, I think the best practice being shown off there is that the class under test should be instantiated in your setUp method (or in a test method).

When the JUnit examples create an ArrayList in the setUp method, they all go on to test the behavior of that ArrayList, with cases like testIndexOutOfBoundException, testEmptyCollection, and the like. The perspective there is of someone writing a class and making sure it works right.

You should probably do the same when testing your own classes: create your object in setUp or in a test method, so that you'll be able to get reasonable output if you break it later.

On the other hand, if you use a Java collection class (or other library class, for that matter) in your test code, it's probably not because you want to test it--it's just part of the test fixture. In this case, you can safely assume it works as intended, so initializing it in the declaration won't be a problem.

For what it's worth, I work on a reasonably large, several-year-old, TDD-developed code base. We habitually initialize things in their declarations in test code, and in the year and a half that I've been on this project, it has never caused a problem. So there's at least some anecdotal evidence that it's a reasonable thing to do.

Java ArrayList of Arrays?

This works very well.

ArrayList<String[]> a = new ArrayList<String[]>();
    a.add(new String[3]);
    a.get(0)[0] = "Zubair";
    a.get(0)[1] = "Borkala";
    a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);

Result will be

Borkala

Writing a large resultset to an Excel file using POI

You can using SXSSFWorkbook implementation of Workbook, if you use style in your excel ,You can caching style by Flyweight Pattern to improve your performance. enter image description here

What does upstream mean in nginx?

If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.

PHP: How to check if image file exists?

There is a major difference between is_file and file_exists.

is_file returns true for (regular) files:

Returns TRUE if the filename exists and is a regular file, FALSE otherwise.

file_exists returns true for both files and directories:

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.


Note: Check also this stackoverflow question for more information on this topic.

Where is web.xml in Eclipse Dynamic Web Project

When you open Eclipse you should click File ? New ? Dynamic Web Project, and make sure you checked Generate web.xml, as described above.

If you have already created the project, you should go to the WebContent/WEB-INF folder, open web.xml, and put the following lines:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>Application Name </display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

How to wrap async function calls into a sync function in Node.js or Javascript?

If function Fiber really turns async function sleep into sync

Yes. Inside the fiber, the function waits before logging ok. Fibers do not make async functions synchronous, but allow to write synchronous-looking code that uses async functions and then will run asynchronously inside a Fiber.

From time to time I find the need to encapsulate an async function into a sync function in order to avoid massive global re-factoring.

You cannot. It is impossible to make asynchronous code synchronous. You will need to anticipate that in your global code, and write it in async style from the beginning. Whether you wrap the global code in a fiber, use promises, promise generators, or simple callbacks depends on your preferences.

My objective is to minimize impact on the caller when data acquisition method is changed from sync to async

Both promises and fibers can do that.

Print text instead of value from C enum

There is another solution: Create your own dynamic enumeration class. Means you have a struct and some function to create a new enumeration, which stores the elements in a struct and each element has a string for the name. You also need some type to store a individual elements, functions to compare them and so on. Here is an example:

#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


struct Enumeration_element_T
{
  size_t index;
  struct Enumeration_T *parrent;
  char *name;
};

struct Enumeration_T
{
  size_t len;
  struct Enumeration_element_T elements[];
};
  


void enumeration_delete(struct Enumeration_T *self)
{
  if(self)
  {
    while(self->len--)
    {
      free(self->elements[self->len].name);
    }
    free(self);
  }
}

struct Enumeration_T *enumeration_create(size_t len,...)
{
  //We do not check for size_t overflows, but we should.
  struct Enumeration_T *self=malloc(sizeof(self)+sizeof(self->elements[0])*len);
  if(!self)
  {
    return NULL;
  }
  self->len=0;
  va_list l; 
  va_start(l,len);
  for(size_t i=0;i<len;i++)
  {
    const char *name=va_arg(l,const char *);
    self->elements[i].name=malloc(strlen(name)+1);
    if(!self->elements[i].name)
    {
      enumeration_delete(self);
      return NULL;
    }
    strcpy(self->elements[i].name,name);
    self->len++;
  }
  return self;
}


bool enumeration_isEqual(struct Enumeration_element_T *a,struct Enumeration_element_T *b)
{
  return a->parrent==b->parrent && a->index==b->index;
}

bool enumeration_isName(struct Enumeration_element_T *a, const char *name)
{
  return !strcmp(a->name,name);
}

const char *enumeration_getName(struct Enumeration_element_T *a)
{
  return a->name;
}

struct Enumeration_element_T *enumeration_getFromName(struct Enumeration_T *self, const char *name)
{
  for(size_t i=0;i<self->len;i++)
  {
    if(enumeration_isName(&self->elements[i],name))
    {
      return &self->elements[i];
    }
  }
  return NULL;
}
  
struct Enumeration_element_T *enumeration_get(struct Enumeration_T *self, size_t index)
{
  return &self->elements[index];
}

size_t enumeration_getCount(struct Enumeration_T *self)
{
  return self->len;
}

bool enumeration_isInRange(struct Enumeration_T *self, size_t index)
{
  return index<self->len;
}



int main(void)
{
  struct Enumeration_T *weekdays=enumeration_create(7,"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
  if(!weekdays)
  {
    return 1;
  }
    
  printf("Please enter the day of the week (0 to 6)\n");
  size_t j = 0;
  if(scanf("%zu",&j)!=1)
  {
    enumeration_delete(weekdays);
    return 1;
  }
  // j=j%enumeration_getCount(weekdays); //alternative way to make sure j is in range
  if(!enumeration_isInRange(weekdays,j))
  {
    enumeration_delete(weekdays);
    return 1;
  }

  struct Enumeration_element_T *day=enumeration_get(weekdays,j);
  

  printf("%s\n",enumeration_getName(day));
  
  enumeration_delete(weekdays);

  return 0;
}

The functions of enumeration should be in their own translation unit, but i combined them here to make it simpler.

The advantage is that this solution is flexible, follows the DRY principle, you can store information along with each element, you can create new enumerations during runtime and you can add new elements during runtime. The disadvantage is that this is complex, needs dynamic memory allocation, can't be used in switch-case, needs more memory and is slower. The question is if you should not use a higher level language in cases where you need this.

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

I resolved my problem doing this:

  • The .php file is encoded to ANSI. In this file is the function to create the .json file.
  • I use json_encode($array, JSON_UNESCAPED_UNICODE) to encode the data;

The result is a .json file encoded to ANSI as UTF-8.

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

How can I get javascript to read from a .json file?

Assuming you mean "file on a local filesystem" when you say .json file.

You'll need to save the json data formatted as jsonp, and use a file:// url to access it.

Your HTML will look like this:

<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
  function updateMe(){
    var x = 0;
    var activity=jsonstr;
    foreach (i in activity) {
        date = document.getElementById(i.date).innerHTML = activity.date;
        event = document.getElementById(i.event).innerHTML = activity.event;
    }
  }
</script>

And the file c:\data\activity.jsonp contains the following line:

jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];

How to get detailed list of connections to database in sql server 2005?

There is also who is active?:

Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids

How to prevent vim from creating (and leaving) temporary files?

I have this setup in my Ubuntu .vimrc. I don't see any swap files in my project files.

set undofile
set undolevels=1000         " How many undos
set undoreload=10000        " number of lines to save for undo

set backup                        " enable backups
set swapfile                      " enable swaps
set undodir=$HOME/.vim/tmp/undo     " undo files
set backupdir=$HOME/.vim/tmp/backup " backups
set directory=$HOME/.vim/tmp/swap   " swap files

" Make those folders automatically if they don't already exist.
if !isdirectory(expand(&undodir))
    call mkdir(expand(&undodir), "p")
endif
if !isdirectory(expand(&backupdir))
    call mkdir(expand(&backupdir), "p")
endif
if !isdirectory(expand(&directory))
    call mkdir(expand(&directory), "p")
endif

How to change package name in flutter?

For Android App Name

Change the label name in your AndroidManifest.xml file:

 <application
    android:name="io.flutter.app.FlutterApplication"
    android:label="TheNameOfYourApp"   

For Package Name

Change the package name in your AndroidManifest.xml (in 3 of them, folders: main, debug and profile, according what environment you want to deploy) file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name">

Also in your build.gradle file inside app folder

defaultConfig {
    applicationId "your.package.name"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Finally, change the package in your MainActivity.java class (if the MainActivity.java is not available, check the MainActivity.kt)

    package your.package.name;

    import android.os.Bundle;
    import io.flutter.app.FlutterActivity;
    import io.flutter.plugins.GeneratedPluginRegistrant;
    public class MainActivity extends FlutterActivity {

Change the directory name:

From:

  android\app\src\main\java\com\example\name

To:

  android\app\src\main\java\your\package\name
  

EDITED : 27-Dec-18

for package name just change in build build.gradle only

defaultConfig {
    applicationId "your.package.name"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

For iOS

Change the bundle identifier from your Info.plist file inside your ios/Runner directory.

<key>CFBundleIdentifier</key>
<string>com.your.packagename</string>

UPDATE

To avoid renaming the package and bundle identifier, you can start your project using this command in your terminal:

flutter create --org com.yourdomain appname

How to print number with commas as thousands separators?

I'm surprised that no one has mentioned that you can do this with f-strings in Python 3.6+ as easy as this:

>>> num = 10000000
>>> print(f"{num:,}")
10,000,000

... where the part after the colon is the format specifier. The comma is the separator character you want, so f"{num:_}" uses underscores instead of a comma.

This is equivalent of using format(num, ",") for older versions of python 3.

How to get URI from an asset File?

Worked for me Try this code

   uri = Uri.fromFile(new File("//assets/testdemo.txt"));
   String testfilepath = uri.getPath();
    File f = new File(testfilepath);
    if (f.exists() == true) {
    Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
    } else {
   Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
 }

How to analyze a JMeter summary report?

A Jmeter Test Plan must have listener to showcase the result of performance test execution.

  • Listeners capture the response coming back from Server while Jmeter runs and showcase in the form of – tree, tables, graphs and log files.

  • It also allows you to save the result in a file for future reference. There are many types of listeners Jmeter provides. Some of them are: Summary Report, Aggregate Report, Aggregate Graph, View Results Tree, View Results in Table etc.

Here is the detailed understanding of each parameter in Summary report.

By referring to the figure:

image

Label: It is the name/URL for the specific HTTP(s) Request. If you have selected “Include group name in label?” option then the name of the Thread Group is applied as the prefix to each label.

Samples: This indicates the number of virtual users per request.

Average: It is the average time taken by all the samples to execute specific label. In our case, the average time for Label 1 is 942 milliseconds & total average time is 584 milliseconds.

Min: The shortest time taken by a sample for specific label. If we look at Min value for Label 1 then, out of 20 samples shortest response time one of the sample had was 584 milliseconds.

Max: The longest time taken by a sample for specific label. If we look at Max value for Label 1 then, out of 20 samples longest response time one of the sample had was 2867 milliseconds.

Std. Dev.: This shows the set of exceptional cases which were deviating from the average value of sample response time. The lesser this value more consistent the data. Standard deviation should be less than or equal to half of the average time for a label.

Error%: Percentage of Failed requests per Label.

Throughput: Throughput is the number of request that are processed per time unit(seconds, minutes, hours) by the server. This time is calculated from the start of first sample to the end of the last sample. Larger throughput is better.

KB/Sec: This indicates the amount of data downloaded from server during the performance test execution. In short, it is the Throughput measured in Kilobytes per second.

For more information: http://www.testingjournals.com/understand-summary-report-jmeter/

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

This happened to me because I hadn't added the conf.configure(); before beginning the session:

Configuration conf = new Configuration();
conf.configure();

Can't use System.Windows.Forms

Adding System.Windows.Forms reference requires .NET Framework project type:

I was using .NET Core project type. This project type doesn't allow us to add assemblies into its project references. I had to move to .NET Framework project type before adding System.Windows.Forms assembly to my references as described in Kendall Frey answer.

Note: There is reference System_Windows_Forms available under COM tab (for both .NET Core and .NET Framework). It is not the right one. It has to be System.Windows.Forms under Assemblies tab.

What is makeinfo, and how do I get it?

In (at least) Ubuntu when using bash, it tells you what package you need to install if you type in a command and its not found in your path. My terminal says you need to install 'texinfo' package.

sudo apt-get install texinfo

The requested resource does not support HTTP method 'GET'

Please use the attributes from the System.Web.Http namespace on your WebAPI actions:

    [System.Web.Http.AcceptVerbs("GET", "POST")]
    [System.Web.Http.HttpGet]
    public string Auth(string username, string password)
    {...}

The reason why it doesn't work is because you were using the attributes that are from the MVC namespace System.Web.Mvc. The classes in the System.Web.Http namespace are for WebAPI.

How do I convert two lists into a dictionary?

If you need to transform keys or values before creating a dictionary then a generator expression could be used. Example:

>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3])) 

Take a look Code Like a Pythonista: Idiomatic Python.

Collections.sort with multiple fields

A lot of answers above have fields compared in single comparator method which is not actually working. There are some answers though with different comparators implemented for each field, I am posting this because this example would be much more clearer and simple to understand I am believing.

class Student{
    Integer bornYear;
    Integer bornMonth;
    Integer bornDay;
    public Student(int bornYear, int bornMonth, int bornDay) {

        this.bornYear = bornYear;
        this.bornMonth = bornMonth;
        this.bornDay = bornDay;
    }
    public Student(int bornYear, int bornMonth) {

        this.bornYear = bornYear;
        this.bornMonth = bornMonth;

    }
    public Student(int bornYear) {

        this.bornYear = bornYear;

    }
    public Integer getBornYear() {
        return bornYear;
    }
    public void setBornYear(int bornYear) {
        this.bornYear = bornYear;
    }
    public Integer getBornMonth() {
        return bornMonth;
    }
    public void setBornMonth(int bornMonth) {
        this.bornMonth = bornMonth;
    }
    public Integer getBornDay() {
        return bornDay;
    }
    public void setBornDay(int bornDay) {
        this.bornDay = bornDay;
    }
    @Override
    public String toString() {
        return "Student [bornYear=" + bornYear + ", bornMonth=" + bornMonth + ", bornDay=" + bornDay + "]";
    }


}
class TestClass
{       

    // Comparator problem in JAVA for sorting objects based on multiple fields 
    public static void main(String[] args)
    {
        int N,c;// Number of threads

        Student s1=new Student(2018,12);
        Student s2=new Student(2018,12);
        Student s3=new Student(2018,11);
        Student s4=new Student(2017,6);
        Student s5=new Student(2017,4);
        Student s6=new Student(2016,8);
        Student s7=new Student(2018);
        Student s8=new Student(2017,8);
        Student s9=new Student(2017,2);
        Student s10=new Student(2017,9);

        List<Student> studentList=new ArrayList<>();
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        studentList.add(s4);
        studentList.add(s5);
        studentList.add(s6);
        studentList.add(s7);
        studentList.add(s8);
        studentList.add(s9);
        studentList.add(s10);

        Comparator<Student> byMonth=new Comparator<Student>() {
            @Override
            public int compare(Student st1,Student st2) {
                if(st1.getBornMonth()!=null && st2.getBornMonth()!=null) {
                    return st2.getBornMonth()-st1.getBornMonth();
                }
                else if(st1.getBornMonth()!=null) {
                    return 1;
                }
                else {
                    return -1;
                }
        }};

        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student st1,Student st2) {
                return st2.getBornYear()-st1.getBornYear();
        }}.thenComparing(byMonth));

        System.out.println("The sorted students list in descending is"+Arrays.deepToString(studentList.toArray()));



    }

}

OUTPUT

The sorted students list in descending is[Student [bornYear=2018, bornMonth=null, bornDay=null], Student [bornYear=2018, bornMonth=12, bornDay=null], Student [bornYear=2018, bornMonth=12, bornDay=null], Student [bornYear=2018, bornMonth=11, bornDay=null], Student [bornYear=2017, bornMonth=9, bornDay=null], Student [bornYear=2017, bornMonth=8, bornDay=null], Student [bornYear=2017, bornMonth=6, bornDay=null], Student [bornYear=2017, bornMonth=4, bornDay=null], Student [bornYear=2017, bornMonth=2, bornDay=null], Student [bornYear=2016, bornMonth=8, bornDay=null]]

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

First save your program file type as "example.py then run your code its working fine.

CSS to make table 100% of max-width

Like this

demo

css

table{
    width:100%;
}

Utility of HTTP header "Content-Type: application/force-download" for mobile?

To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type

$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php

How to debug PDO database queries?

How to debug PDO mysql database queries in Ubuntu

TL;DR Log all your queries and tail the mysql log.

These directions are for my install of Ubuntu 14.04. Issue command lsb_release -a to get your version. Your install might be different.

Turn on logging in mysql

  1. Go to your dev server cmd line
  2. Change directories cd /etc/mysql. You should see a file called my.cnf. That’s the file we’re gonna change.
  3. Verify you’re in the right place by typing cat my.cnf | grep general_log. This filters the my.cnf file for you. You should see two entries: #general_log_file = /var/log/mysql/mysql.log && #general_log = 1.
  4. Uncomment those two lines and save via your editor of choice.
  5. Restart mysql: sudo service mysql restart.
  6. You might need to restart your webserver too. (I can’t recall the sequence I used). For my install, that’s nginx: sudo service nginx restart.

Nice work! You’re all set. Now all you have to do is tail the log file so you can see the PDO queries your app makes in real time.

Tail the log to see your queries

Enter this cmd tail -f /var/log/mysql/mysql.log.

Your output will look something like this:

73 Connect  xyz@localhost on your_db
73 Query    SET NAMES utf8mb4
74 Connect  xyz@localhost on your_db
75 Connect  xyz@localhost on your_db
74 Quit 
75 Prepare  SELECT email FROM customer WHERE email=? LIMIT ?
75 Execute  SELECT email FROM customer WHERE email='[email protected]' LIMIT 5
75 Close stmt   
75 Quit 
73 Quit 

Any new queries your app makes will automatically pop into view, as long as you continue tailing the log. To exit the tail, hit cmd/ctrl c.

Notes

  1. Careful: this log file can get huge. I’m only running this on my dev server.
  2. Log file getting too big? Truncate it. That means the file stays, but the contents are deleted. truncate --size 0 mysql.log.
  3. Cool that the log file lists the mysql connections. I know one of those is from my legacy mysqli code from which I'm transitioning. The third is from my new PDO connection. However, not sure where the second is coming from. If you know a quick way to find it, let me know.

Credit & thanks

Huge shout out to Nathan Long’s answer above for the inspo to figure this out on Ubuntu. Also to dikirill for his comment on Nathan’s post which lead me to this solution.

Love you stackoverflow!

ValueError: not enough values to unpack (expected 11, got 1)

For the line

line.split()

What are you splitting on? Looks like a CSV, so try

line.split(',')

Example:

"one,two,three".split()  # returns one element ["one,two,three"]
"one,two,three".split(',')  # returns three elements ["one", "two", "three"]

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

How do I delete an entity from symfony2

From what I understand, you struggle with what to put into your template.

I'll show an example:

<ul>
    {% for guest in guests %}
    <li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
    {% endfor %}
</ul>

Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.

SQL: How To Select Earliest Row

Simply use min()

SELECT company, workflow, MIN(date) 
FROM workflowTable 
GROUP BY company, workflow

How do I get the latest version of my code?

try this code

cd /go/to/path
git pull origin master

Smooth scroll without the use of jQuery

Modern browsers has support for CSS "scroll-behavior: smooth" property. So, we even don't need any Javascript at all for this. Just add this to the body element, and use usual anchors and links. scroll-behavior MDN docs

How to make <input type="date"> supported on all browsers? Any alternatives?

I was having problems with this, maintaining the UK dd/mm/yyyy format, I initially used the answer from adeneo https://stackoverflow.com/a/18021130/243905 but that didnt work in safari for me so changed to this, which as far as I can tell works all over - using the jquery-ui datepicker, jquery validation.

if ($('[type="date"]').prop('type') !== 'date') {
    //for reloading/displaying the ISO format back into input again
    var val = $('[type="date"]').each(function () {
        var val = $(this).val();
        if (val !== undefined && val.indexOf('-') > 0) {
            var arr = val.split('-');
            $(this).val(arr[2] + '/' + arr[1] + '/' + arr[0]);
        }
    });

    //add in the datepicker
    $('[type="date"]').datepicker(datapickeroptions);

    //stops the invalid date when validated in safari
    jQuery.validator.methods["date"] = function (value, element) {
        var shortDateFormat = "dd/mm/yy";
        var res = true;
        try {
            $.datepicker.parseDate(shortDateFormat, value);
        } catch (error) {
            res = false;
        }
        return res;
    }
}

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I noticed the exact same issue when logging onto servers running Red Hat from an OSX Lion machine.

Try adding or editing the ~/.profile file for it to correctly export your locale settings upon initiating a new session.

export LC_ALL=en_US.UTF-8  
export LANG=en_US.UTF-8

These two lines added to the file should suffice to set the locale [replace en_US for your desired locale, and check beforehand that it is indeed installed on your system (locale -a)].

After that, you can start a new session and check using locale:

$ locale

The following should be the output:

LANG="en_US.UTF-8"  
LC_COLLATE="en_US.UTF-8"  
LC_CTYPE="en_US.UTF-8"  
LC_MESSAGES="en_US.UTF-8"  
LC_MONETARY="en_US.UTF-8"  
LC_NUMERIC="en_US.UTF-8"  
LC_TIME="en_US.UTF-8"  
LC_ALL="en_US.UTF-8"  

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

SQL query question: SELECT ... NOT IN

Given it's SQL 2005, you can also try this It's similar to Oracle's MINUS command (opposite of UNION)

But I would also suggest adding the DATEPART ( hour, insertDate) column for debug

SELECT idCustomer FROM reservations 
EXCEPT
SELECT idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2

plot.new has not been called yet

plot.new() error occurs when only part of the function is ran.

Please find the attachment for an example to correct error With error....When abline is ran without plot() above enter image description here Error-free ...When both plot and abline ran together enter image description here

Can lambda functions be templated?

I've been playing with the latest clang version 5.0.1 compiling with the -std=c++17 flag and there is now some nice support for auto type parameters for lambdas:

#include <iostream>
#include <vector>
#include <stdexcept>

int main() {
    auto slice = [](auto input, int beg, int end) {
        using T = decltype(input);
        const auto size = input.size();
        if (beg > size || end > size || beg < 0 || end < 0) {
            throw std::out_of_range("beg/end must be between [0, input.size())");
        }
        if (beg > end) {
            throw std::invalid_argument("beg must be less than end");
        }
        return T(input.begin() + beg, input.begin() + end);
    };
    auto v = std::vector<int> { 1,2,3,4,5 };
    for (auto e : slice(v, 1, 4)) {
        std::cout << e << " ";
    }
    std::cout << std::endl;
}

How can I do a BEFORE UPDATED trigger with sql server?

To do a BEFORE UPDATE in SQL Server I use a trick. I do a false update of the record (UPDATE Table SET Field = Field), in such way I get the previous image of the record.

Online code beautifier and formatter

For PHP, Java, C++, C, Perl, JavaScript, CSS you can try:

http://www.prettyprinter.de/index.php

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

In short, yes, the order is preserved. In long:

In general the following definitions will always apply to objects like lists:

A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca") and duplicates in the content of the string are certainly permitted ("aaa" can exist and != "a").

A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).

Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.

This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).

If there is any confusion left in your case due to the specifics of how the + sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the + sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.

If we have

list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]

Then

list1 + list2

Is the same as

[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]

Which evaluates to

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Much like

"abdcde" + "fghijk"

Produces

"abdcdefghijk"