Programs & Examples On #Next

Coming immediately after in a sequence; subsequent. Often refers to iterators, that provide next() and hasNext() methods.

How to read one single line of csv data in Python?

You can use Pandas library to read the first few lines from the huge dataset.

import pandas as pd

data = pd.read_csv("names.csv", nrows=1)

You can mention the number of lines to be read in the nrows parameter.

"Continue" (to next iteration) on VBScript

A solution I decided on involved the use of a boolean variable to track if the for loop should process its instructions or skip to the next iteration:

Dim continue

For Each item In collection
    continue = True

    If condition1 Then continue = False End If

    If continue Then
        'Do work
    End If
Next

I found the nested loop solutions to be somewhat confusing readability wise. This method also has its own pitfalls since the loop doesn't immediately skip to the next iteration after encountering continue. It would be possible for a later condition to reverse the state of continue. It also has a secondary construct within the initial loop, and requires the declaration of an extra var.

Oh, VBScript...sigh.

Also, if you want to use the accepted answer, which isn't too bad readability wise, you could couple that with the use of : to merge the two loops into what appears to be one:

Dim i

For i = 0 To 10 : Do
    If i = 4 Then Exit Do
    WScript.Echo i
Loop While False : Next

I found it useful to eliminate the extra level of indentation.

jquery, find next element by class

In this case you need to go up to the <tr> then use .next(), like this:

$(obj).closest('tr').next().find('.class');

Or if there may be rows in-between without the .class inside, you can use .nextAll(), like this:

$(obj).closest('tr').nextAll(':has(.class):first').find('.class');

iterrows pandas get next rows value

I would use shift() function as follows:

df['value_1'] = df.value.shift(-1)
[print(x) for x in df.T.unstack().dropna(how = 'any').values];

which produces

AA
BB
BB
CC
CC

This is how the code above works:

Step 1) Use shift function

df['value_1'] = df.value.shift(-1)
print(df)

produces

value value_1
0    AA      BB
1    BB      CC
2    CC     NaN

step 2) Transpose:

df = df.T
print(df)

produces:

          0   1    2
value    AA  BB   CC
value_1  BB  CC  NaN

Step 3) Unstack:

df = df.unstack()
print(df)

produces:

0  value       AA
   value_1     BB
1  value       BB
   value_1     CC
2  value       CC
   value_1    NaN
dtype: object

Step 4) Drop NaN values

df = df.dropna(how = 'any')
print(df)

produces:

0  value      AA
   value_1    BB
1  value      BB
   value_1    CC
2  value      CC
dtype: object

Step 5) Return a Numpy representation of the DataFrame, and print value by value:

df = df.values
[print(x) for x in df];

produces:

AA
BB
BB
CC
CC

Passing variables to the next middleware using next() in Express.js

I don't think that best practice will be passing a variable like req.YOUR_VAR. You might want to consider req.YOUR_APP_NAME.YOUR_VAR or req.mw_params.YOUR_VAR.

It will help you avoid overwriting other attributes.

Update May 31, 2020

res.locals is what you're looking for, the object is scoped to the request.

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

Getting next element while cycling through a list

A rather different way to solve this:

   li = [0,1,2,3]

   for i in range(len(li)):

       if i < len(li)-1:

           # until end is reached
           print 'this', li[i]
           print 'next', li[i+1]

       else:

           # end
           print 'this', li[i]

Android Button click go to another xml page

Write below code in your MainActivity.java file instead of your code.

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button mBtn1 = (Button) findViewById(R.id.mBtn1);
        mBtn1.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        Log.i("clicks","You Clicked B1");
        Intent i=new Intent(MainActivity.this, MainActivity2.class);
        startActivity(i);
    }
}

And Declare MainActivity2 into your Androidmanifest.xml file using below code.

<activity
    android:name=".MainActivity2"
    android:label="@string/title_activity_main">
</activity>

javascript node.js next()

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

Continue For loop

I sometimes do a double do loop:

Do

    Do

        If I_Don't_Want_to_Finish_This_Loop Then Exit Do

        Exit Do

    Loop

Loop Until Done

This avoids having "goto spaghetti"

Deleting all records in a database table

If your model is called BlogPost, it would be:

BlogPost.all.map(&:destroy)

Maximum request length exceeded.

The maximum request size is, by default, 4MB (4096 KB)

This is explained here.

The above article also explains how to fix this issue :)

What is the difference between an int and an Integer in Java and C#?

This has already been answered for Java, here's the C# answer:

"Integer" is not a valid type name in C# and "int" is just an alias for System.Int32. Also, unlike in Java (or C++) there aren't any special primitive types in C#, every instance of a type in C# (including int) is an object. Here's some demonstrative code:

void DoStuff()
{
    System.Console.WriteLine( SomeMethod((int)5) );
    System.Console.WriteLine( GetTypeName<int>() );
}

string SomeMethod(object someParameter)
{
    return string.Format("Some text {0}", someParameter.ToString());
}

string GetTypeName<T>()
{
    return (typeof (T)).FullName;
}

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

How to get the first item from an associative PHP array?

Fake loop that breaks on the first iteration:

$key = $value = NULL;
foreach ($array as $key => $value) {
    break;
}

echo "$key = $value\n";

Or use each() (warning: deprecated as of PHP 7.2.0):

reset($array);
list($key, $value) = each($array);

echo "$key = $value\n";

List<String> to ArrayList<String> conversion issue

First of all, why is the map a HashMap<String, ArrayList<String>> and not a HashMap<String, List<String>>? Is there some reason why the value must be a specific implementation of interface List (ArrayList in this case)?

Arrays.asList does not return a java.util.ArrayList, so you can't assign the return value of Arrays.asList to a variable of type ArrayList.

Instead of:

allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));

Try this:

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

How to make "if not true condition"?

Here is an answer by way of example:

In order to make sure data loggers are online a cron script runs every 15 minutes that looks like this:

#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
  echo "SUBJECT:  SOLAR is not responding to ping" | ssmtp [email protected]
  echo "SOLAR is not responding to ping" | ssmtp [email protected]
else
  echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
  echo "SUBJECT:  OUTSIDE is not responding to ping" | ssmtp [email protected]
  echo "OUTSIDE is not responding to ping" | ssmtp [email protected]
else
  echo "OUTSIDE is up"
fi
#

...and so on for each data logger that you can see in the montage at http://www.SDsolarBlog.com/montage


FYI, using &>/dev/null redirects all output from the command, including errors, to /dev/null

(The conditional only requires the exit status of the ping command)

Also FYI, note that since cron jobs run as root there is no need to use sudo ping in a cron script.

Run/install/debug Android applications over Wi-Fi?

For Ubuntu / Linux:

  1. Make sure your device is working for debugging: http://developer.android.com/tools/help/adb.html#Enabling
  2. Go to your sdk folder and find the folder platform-tools
  3. Use ./adb devices to list the connected devices. Make sure it is only one device connected and no emulator running.
  4. Find your device IP address, you can find it in your device: http://developer.android.com/tools/help/adb.html#wireless, or got adb shell like this: ./adb shell then netcfg. You will see a list of IP addresses. Find wlan0, in my case 192.168.100.3/2.
  5. ./adb tcpip 5555
  6. Finally enter ./adb connect <Your device IP Address>:5555 in your terminal. You can now deploy the application to your device over Wi-Fi.

How can I insert data into a MySQL database?

#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()

try:
   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
   conn.commit()
except:
   conn.rollback()

conn.close()

edit working for me:

>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>> 
>>> #setup cursor
... cursor = db.cursor()
>>> 
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>> 
>>> sql = """CREATE TABLE anooog1 (
...          COL1 INT,  
...          COL2 INT )"""
>>> cursor.execute(sql)
0L
>>> 
>>> #insert to table
... try:
...     cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
...     db.commit()
... except:     
...     db.rollback()
... 
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>> 
>>> db.close()

table in mysql;

mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
|  188 |   90 |
+------+------+
1 row in set (0.00 sec)

mysql> 

WebView link click open default browser

you can use Intent for this:

Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("your Url"));
startActivity(browserIntent);

How to get distinct results in hibernate with joins and row-based limiting (paging)?

if you want to use ORDER BY, just add:

criteria.setProjection(
    Projections.distinct(
        Projections.projectionList()
        .add(Projections.id())
        .add(Projections.property("the property that you want to ordered by"))
    )
);

$rootScope.$broadcast vs. $scope.$emit

Use RxJS in a Service

What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately

Build a service with RxJS Extensions for Angular.

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

app.factory("DataService", function(rx) {
  var subject = new rx.Subject(); 
  var data = "Initial";

  return {
      set: function set(d){
        data = d;
        subject.onNext(d);
      },
      get: function get() {
        return data;
      },
      subscribe: function (o) {
         return subject.subscribe(o);
      }
  };
});

Then simply subscribe to the changes.

app.controller('displayCtrl', function(DataService) {
  var $ctrl = this;

  $ctrl.data = DataService.get();
  var subscription = DataService.subscribe(function onNext(d) {
      $ctrl.data = d;
  });

  this.$onDestroy = function() {
      subscription.dispose();
  };
});

Clients can subscribe to changes with DataService.subscribe and producers can push changes with DataService.set.

The DEMO on PLNKR.

Write string to output stream

OutputStream writes bytes, String provides chars. You need to define Charset to encode string to byte[]:

outputStream.write(string.getBytes(Charset.forName("UTF-8")));

Change UTF-8 to a charset of your choice.

How can I reconcile detached HEAD with master/origin?

If you did some commits on top of master and just want to "backwards merge" master there (i.e. you want master to point to HEAD), the one-liner would be:

git checkout -B master HEAD
  1. That creates a new branch named master, even if it exists already (which is like moving master and that's what we want).
  2. The newly created branch is set to point to HEAD, which is where you are.
  3. The new branch is checked out, so you are on master afterwards.

I found this especially useful in the case of sub-repositories, which also happen to be in a detached state rather often.

Replace text in HTML page with jQuery

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

creating a table in ionic

This is the way i use it. It's very simple and work very well.. Ionic html:

  <ion-content>
 

  <ion-grid class="ion-text-center">

    <ion-row class="ion-margin">
      <ion-col>
        <ion-title>
          <ion-text color="default">
            Your title remove if don't want use
          </ion-text>
        </ion-title>
      </ion-col>
    </ion-row>

    <ion-row class="header-row">
      <ion-col>
        <ion-text>Data</ion-text>
      </ion-col>

      <ion-col>
        <ion-text>Cliente</ion-text>
      </ion-col>

      <ion-col>
        <ion-text>Pagamento</ion-text>
      </ion-col>
    </ion-row>


    <ion-row>
      <ion-col>
        <ion-text>
            19/10/2020
        </ion-text>
      </ion-col>

        <ion-col>
          <ion-text>
            Nome
          </ion-text>
        </ion-col>
  
        <ion-col>
          <ion-text>
            R$ 200
          </ion-text>
        </ion-col>
    </ion-row>

  </ion-grid>
</ion-content>

CSS:

.header-row {
  background: #7163AA;
  color: #fff;
  font-size: 18px;
}

ion-col {
  border: 1px solid #ECEEEF;
}

Result of the code

Why does Math.Round(2.5) return 2 instead of 3?

Simple way is:

Math.Ceiling(decimal.Parse(yourNumber + ""));

Online SQL syntax checker conforming to multiple databases

I haven't ever seen such a thing, but there is this dev tool that includes a syntax checker for oracle, mysql, db2, and sql server... http://www.sqlparser.com/index.php

However this seems to be just the library. You'd need to build an app to leverage the parser to do what you want. And the Enterprise edition that includes all of the databases would cost you $450... ouch!

EDIT: And, after saying that - it looks like someone might already have done what you want using that library: http://www.wangz.net/cgi-bin/pp/gsqlparser/sqlpp/sqlformat.tpl

The online tool doesn't automatically check against each DB though, you need to run each manually. Nor can I say how good it is at checking the syntax. That you'd need to investigate yourself.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I had this error because of some typo in an alias of a column that contained a questionmark (e.g. contract.reference as contract?ref)

Scanning Java annotations at runtime

With Spring you can also just write the following using AnnotationUtils class. i.e.:

Class<?> clazz = AnnotationUtils.findAnnotationDeclaringClass(Target.class, null);

For more details and all different methods check official docs: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/AnnotationUtils.html

How to run console application from Windows Service?

As pierre said, there is no way to have a user interface for a windows service (or no easy way). What I do in that kind of situation is to have a settings file that is read from the service on whatever interval the service operates on and have a standalone application that makes changes to the settings file.

Precision String Format Specifier In Swift

Swift 4 Xcode 10 Update

extension Double {
    var asNumber:String {
        if self >= 0 {
            let formatter = NumberFormatter()
            formatter.numberStyle = .none
            formatter.percentSymbol = ""
            formatter.maximumFractionDigits = 2
            return "\(formatter.string(from: NSNumber(value: self)) ?? "")"
        }
        return ""
    }
}

Set title background color

you can use it.

  toolbar.setTitleTextColor(getResources().getColor(R.color.white));

How to get file creation date/time in Bash/Debian?

mikyra's answer is good.The fact just like what he said.

[jason@rh5 test]$ stat test.txt
  File: `test.txt'
  Size: 0               Blocks: 8          IO Block: 4096   regular empty file
Device: 802h/2050d      Inode: 588720      Links: 1
Access: (0664/-rw-rw-r--)  Uid: (  500/   jason)   Gid: (  500/   jason)
Access: 2013-03-14 01:58:12.000000000 -0700
Modify: 2013-03-14 01:58:12.000000000 -0700
Change: 2013-03-14 01:58:12.000000000 -0700

if you want to verify wich file was created first,you can structure your file name by appending system date when you create a series of files.

CSS Border Not Working

AFAIK, there's no such shorthand for border. You have to define each border separately:

border: 0 solid #000;
border-left: 1px solid #000;
border-right: 1px solid #000;

Press enter in textbox to and execute button command

In WPF apps This code working perfectly

private void txt1_KeyDown(object sender, KeyEventArgs e)
  {
     if (Keyboard.IsKeyDown(Key.Enter) )
         {
              Button_Click(this, new RoutedEventArgs());
         }
   }

How do I see the commit differences between branches in git?

You can easily do that with

git log master..branch-X

That will show you commits that branch-X has but master doesn't.

Is there a limit to the length of a GET request?

As Requested By User Erickson, I Post My comment As Answer:

I have done some more testing with IE8, IE9, FF14, Opera11, Chrome20 and Tomcat 6.0.32 (fresh installation), Jersey 1.13 on the server side. I used the jQuery function $.getJson and JSONP. Results: All Browsers allowed up to around 5400 chars. FF and IE9 did up to around 6200 chars. Everything above returned "400 Bad request". I did not further investigate what was responsible for the 400. I was fine with the maximum I found, because I needed around 2000 chars in my case.

How can I open Java .class files in a human-readable way?

jd-gui is the best decompiler at the moment. it can handle newer features in Java, as compared to the getting-dusty JAD.

How to convert upper case letters to lower case

You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.

w.strip(',.').lower()

Get loop counter/index using for…of syntax in JavaScript

In ES6, it is good to use for - of loop. You can get index in for of like this

for (let [index, val] of array.entries()) {
        // your code goes here    
}

Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.

Start script missing error when running npm start

Installing create-react-app globally is now discouraged. Instead uninstall globally installed create-react-app package by doing: npm uninstall -g create-react-app (you may have to manually delete package folder if this command didn't work for you. Some users have reported they had to delete folders manually)

Then you can run npx create-react-app my-app to create react app again.

ref: https://github.com/facebook/create-react-app/issues/8086

How can I get the current page's full URL on a Windows/IIS server?

$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} 
else 
{
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;

Check if element at position [x] exists in the list

int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

Difference between Inheritance and Composition

In Simple Word Aggregation means Has A Relationship ..

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Why Use Aggregation

Code Reusability

When Use Aggregation

Code reuse is also best achieved by aggregation when there is no is a Relation ship

Inheritance

Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Using inheritance in Java 1 Code Reusability. 2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).

Is there any JSON Web Token (JWT) example in C#?

After all these months have passed after the original question, it's now worth pointing out that Microsoft has devised a solution of their own. See http://blogs.msdn.com/b/vbertocci/archive/2012/11/20/introducing-the-developer-preview-of-the-json-web-token-handler-for-the-microsoft-net-framework-4-5.aspx for details.

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

Default Activity not found in Android Studio

  1. In Android Studio

  2. Go to edit Configuration .

  3. Select the app.

  4. choose the lunch Activity path.

  5. apply, OK.

    Thanks!!

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

'nuget' is not recognized but other nuget commands working

The nuget commandline tool does not come with the vsix file, it's a separate download

https://github.com/nuget/home

Checking whether a variable is an integer or not

You can use this function:

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

Test:

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

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Surprise to see no one mentioned about event.preventDefault()

$("input[type=file]").mouseover(function(event) {
    event.preventDefault();
    // This will disable the default behavior of browser
 });

How do I see which checkbox is checked?

Try this

index.html

<form action="form.php" method="post">
    Do you like stackoverflow?
    <input type="checkbox" name="like" value="Yes" />  
    <input type="submit" name="formSubmit" value="Submit" /> 
</form>

form.php

<html>
<head>
</head>
<body>

<?php
    if(isset($_POST['like']))
    {
        echo "<h1>You like Stackoverflow.<h1>";
    }
    else
    {
        echo "<h1>You don't like Stackoverflow.</h1>";
    }   
?>

</body>
</html>

Or this

<?php
    if(isset($_POST['like'])) && 
    $_POST['like'] == 'Yes') 
    {
        echo "You like Stackoverflow.";
    }
    else
    {
        echo "You don't like Stackoverflow.";
    }   
?>

Fastest check if row exists in PostgreSQL

How about simply:

select 1 from tbl where userid = 123 limit 1;

where 123 is the userid of the batch that you're about to insert.

The above query will return either an empty set or a single row, depending on whether there are records with the given userid.

If this turns out to be too slow, you could look into creating an index on tbl.userid.

if even a single row from batch exists in table, in that case I don't have to insert my rows because I know for sure they all were inserted.

For this to remain true even if your program gets interrupted mid-batch, I'd recommend that you make sure you manage database transactions appropriately (i.e. that the entire batch gets inserted within a single transaction).

SQL DELETE with JOIN another table for WHERE condition

Try this sample SQL scripts for easy understanding,

CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))

--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2

INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'

INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'

SELECT * FROM TABLE1
SELECT * FROM TABLE2

DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO

Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

Multiple IF statements between number ranges

Shorter than accepted A, easily extensible and addresses 0 and below:

=if(or(A2<=0,A2>2000),"?",if(A2<500,"Less than 500","Between "&500*int(A2/500)&" and "&500*(int(A2/500)+1))) 

Convert String to Type in C#

Try:

Type type = Type.GetType(inputString); //target type
object o = Activator.CreateInstance(type); // an instance of target type
YourType your = (YourType)o;

Jon Skeet is right as usually :)

Update: You can specify assembly containing target type in various ways, as Jon mentioned, or:

YourType your = (YourType)Activator.CreateInstance("AssemblyName", "NameSpace.MyClass");

How to check list A contains any value from list B?

I write a faster method for it can make the small one to set. But I test it in some data that some time it's faster that Intersect but some time Intersect fast that my code.

    public static bool Contain<T>(List<T> a, List<T> b)
    {
        if (a.Count <= 10 && b.Count <= 10)
        {
            return a.Any(b.Contains);
        }

        if (a.Count > b.Count)
        {
            return Contain((IEnumerable<T>) b, (IEnumerable<T>) a);
        }
        return Contain((IEnumerable<T>) a, (IEnumerable<T>) b);
    }

    public static bool Contain<T>(IEnumerable<T> a, IEnumerable<T> b)
    {
        HashSet<T> j = new HashSet<T>(a);
        return b.Any(j.Contains);
    }

The Intersect calls Set that have not check the second size and this is the Intersect's code.

        Set<TSource> set = new Set<TSource>(comparer);
        foreach (TSource element in second) set.Add(element);
        foreach (TSource element in first)
            if (set.Remove(element)) yield return element;

The difference in two methods is my method use HashSet and check the count and Intersect use set that is faster than HashSet. We dont warry its performance.

The test :

   static void Main(string[] args)
    {
        var a = Enumerable.Range(0, 100000);
        var b = Enumerable.Range(10000000, 1000);
        var t = new Stopwatch();
        t.Start();
        Repeat(()=> { Contain(a, b); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//490ms

        var a1 = Enumerable.Range(0, 100000).ToList();
        var a2 = b.ToList();
        t.Restart();
        Repeat(()=> { Contain(a1, a2); });
        t.Stop();

        Console.WriteLine(t.ElapsedMilliseconds);//203ms

        t.Restart();
        Repeat(()=>{ a.Intersect(b).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//190ms

        t.Restart();
        Repeat(()=>{ b.Intersect(a).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//497ms

        t.Restart();
        a.Any(b.Contains);
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//600ms

    }

    private static void Repeat(Action a)
    {
        for (int i = 0; i < 100; i++)
        {
            a();
        }
    }

Need to perform Wildcard (*,?, etc) search on a string using Regex

d* means that it should match zero or more "d" characters. So any string is a valid match. Try d+ instead!

In order to have support for wildcard patterns I would replace the wildcards with the RegEx equivalents. Like * becomes .* and ? becomes .?. Then your expression above becomes d.*

Matplotlib scatterplot; colour as a function of a third variable

There's no need to manually set the colors. Instead, specify a grayscale colormap...

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()

enter image description here

Or, if you'd prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the "_r" version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()

Update Eclipse with Android development tools v. 23

I have followed instructions found here and tried to fix my old Eclipse + SDK + ADT, but with no luck. The basic problem keeps beeing the same; I still get the error message:

This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.

But my eclipse can't find updates and can't install ADT 23 as new software. So I can't compile my old project in my workspace.

I tested a fresh eclipode bundle for Windows 8, followed instructions found from Android's developers page, step by step, and it worked fine. So it seems that the Windows Eclipse build is not broken. But I wan't use my Linux installation, my old Ubuntu 10. It seems obvious, that to getting the Linux Eclipse environment working again, I must install a new Eclipse bundle, my old Eclipse won't ever see updates for ADT 23 to get things working. Again, these intructions are for Linux developers that wan't to get their old workspace projects working again without changes in the developing environment, except you must install a new Eclipse bundle, but after that your projects will work as well as before the version 23 SDK/ADT-mess.

  1. If you are an Android developer you want to be sure, that you developing environment won't be messed up. Backup:
    • ~./android (Here are your developer keys)
    • Your old SDK dirrectory
    • Your workspace
  2. Download the Eclipse bundle, Get the Android SDK.
  3. Follow instructions, create directory ~/Development and unzip bundle there. You get Eclipse and SDK directories.
  4. Start Eclipse from that directory
  5. Eclipse asks for a workspace. You can give it the old one.
  6. In Eclipse settings set SDK as downloaded SDK.
  7. Start Android SDK manager and download tools, Android versions you use and extras said in the Android developer tool page instructions
  8. You should now be ready to compile your old projects again, but for me it was not that simple. My old projects had errors. So open problems windows and you get to know that annotation.jar is missing. So you must copy annotations.jar from your old SDK, from, the backup you made, or from the older sdk.zip explained in this thread to <new SDK>/tools/support/annotations.jar

After that I could use my old workspace in Ubuntu and compile and launch applications to Android devices. It was that simple. Thanks Google ;-(

Styling twitter bootstrap buttons

I found the simplest way is to put this in your overrides. Sorry for my unimaginative color choice

Bootstrap 4-Alpha SASS

.my-btn {
  //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  @include button-variant(red, white, blue);
}

Bootstrap 4 Alpha SASS Example

Bootstrap 3 LESS

.my-btn {
  //.button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
  .button-variant(red; white; blue);
}

Bootstrap 3 LESS Example

Bootstrap 3 SASS

.my-btn {
  //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  @include button-variant(red, white, blue);
}

Bootstrap 3 SASS Example

Bootstrap 2.3 LESS

.btn-primary {
  //.buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75));
  .buttonBackground(red, white);
}

Bootstrap 2.3 LESS Example

Bootstrap 2.3 SASS

.btn-primary {
  //@include buttonBackground($btnPrimaryBackground, $btnPrimaryBackgroundHighlight); 
  @include buttonBackground(red, white); 
}

It will take care of the hover/actives for you

From the comments, if you want to lighten the button instead of darken when using black (or just want to inverse) you need to extend the class a bit further like so:

Bootstrap 3 SASS Ligthen

.my-btn {
  // @include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  $color: #fff;
  $background: #000;
  $border: #333;
  @include button-variant($color, $background, $border);
  // override the default darkening with lightening
  &:hover,
  &:focus,
  &.focus,
  &:active,
  &.active,
  .open > &.dropdown-toggle {
    color: $color;
    background-color: lighten($background, 20%); //10% default
    border-color: lighten($border, 22%); // 12% default
  }
}

Bootstrap 3 SASS Lighten Example

Graphical user interface Tutorial in C

My favourite UI tutorials all come from zetcode.com:

These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.

Installing Homebrew on OS X

Not sure why nobody mentioned this : when you run the installation command from the official site, in the final lines you would see something like below, and you need to follow the ==> Next steps:

==> Installation successful!

==> Homebrew has enabled anonymous aggregate formulae and cask analytics.
Read the analytics documentation (and how to opt-out) here:
  https://docs.brew.sh/Analytics
No analytics data has been sent yet (or will be during this `install` run).

==> Homebrew is run entirely by unpaid volunteers. Please consider donating:
  https://github.com/Homebrew/brew#donations

==> Next steps:
- Add Homebrew to your PATH in /Users/{YOUR USER NAME}/.bash_profile:
    echo 'eval $(/opt/homebrew/bin/brew shellenv)' >> /Users/{YOUR USER NAME}/.bash_profile
    eval $(/opt/homebrew/bin/brew shellenv)

This is for bash shell. You will see different steps for every different shell, but the source of the steps are same.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

1) in a query window in SQL Server Management Studio, run the command:

SET SHOWPLAN_ALL ON

2) run your slow query

3) your query will not run, but the execution plan will be returned. store this output

4) run your fast version of the query

5) your query will not run, but the execution plan will be returned. store this output

6) compare the slow query version output to the fast query version output.

7) if you still don't know why one is slower, post both outputs in your question (edit it) and someone here can help from there.

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

How to search a Git repository by commit message?

Though a bit late, there is :/ which is the dedicated notation to specify a commit (or revision) based on the commit message, just prefix the search string with :/, e.g.:

git show :/keyword(s)

Here <keywords> can be a single word, or a complex regex pattern consisting of whitespaces, so please make sure to quote/escape when necessary, e.g.:

git log -1 -p ":/a few words"

Alternatively, a start point can be specified, to find the closest commit reachable from a specific point, e.g.:

git show 'HEAD^{/fix nasty bug}'

See: git revisions manual.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven

Parsing ISO 8601 date in Javascript

The Date object handles 8601 as it's first parameter:

_x000D_
_x000D_
var d = new Date("2014-04-07T13:58:10.104Z");_x000D_
console.log(d.toString());
_x000D_
_x000D_
_x000D_

Android: I lost my android key store, what should I do?

I want to refine this a little bit because down-votes indicate to me that people don't understand that these suggestions are like "last hope" approach for someone who got into the state described in the question.

Check your console input history and/or ant scripts you have been using if you have them. Keep in mind that the console history will not be saved if you were promoted for password but if you entered it within for example signing command you can find it.

You mentioned you have a zip with a password in which your certificate file is stored, you could try just brute force opening that with many tools available. People will say "Yea but what if you used strong password, you should bla,bla,bla..." Unfortunately in that case tough-luck. But people are people and they sometimes use simple passwords. For you any tool that can provide dictionary attacks in which you can enter your own words and set them to some passwords you suspect might help you. Also if password is short enough with today CPUs even regular brute force guessing might work since your zip file does not have any limitation on number of guesses so you will not get blocked as if you tried to brute force some account on a website.

How to set a cell to NaN in a pandas dataframe

df.replace('columnvalue',np.NaN,inplace=True)

trim left characters in sql server?

For 'Hello' at the start of the string:

SELECT STUFF('Hello World', 1, 6, '')

This will work for 'Hello' anywhere in the string:

SELECT REPLACE('Hello World', 'Hello ', '')

Export Postgresql table data using pgAdmin

Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.

pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.

It uses something like this:

pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.

Using Pipes within ngModel on INPUT Elements in Angular

I tried the solutions above yet the value that goes to the model were the formatted value then returning and giving me currencyPipe errors. So i had to

  [ngModel]="transfer.amount | currency:'USD':true"
                                   (blur)="addToAmount($event.target.value)"
                                   (keypress)="validateOnlyNumbers($event)"

And on the function of addToAmount -> change on blur cause the ngModelChange was giving me cursor issues.

removeCurrencyPipeFormat(formatedNumber){
    return formatedNumber.replace(/[$,]/g,"")
  }

And removing the other non numeric values.

validateOnlyNumbers(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }

What are all codecs and formats supported by FFmpeg?

The formats and codecs supported by your build of ffmpeg can vary due the version, how it was compiled, and if any external libraries, such as libx264, were supported during compilation.

Formats (muxers and demuxers):

List all formats:

ffmpeg -formats

Display options specific to, and information about, a particular muxer:

ffmpeg -h muxer=matroska

Display options specific to, and information about, a particular demuxer:

ffmpeg -h demuxer=gif

Codecs (encoders and decoders):

List all codecs:

ffmpeg -codecs

List all encoders:

ffmpeg -encoders

List all decoders:

ffmpeg -decoders

Display options specific to, and information about, a particular encoder:

ffmpeg -h encoder=mpeg4

Display options specific to, and information about, a particular decoder:

ffmpeg -h decoder=aac

Reading the results

There is a key near the top of the output that describes each letter that precedes the name of the format, encoder, decoder, or codec:

$ ffmpeg -encoders
[…]
Encoders:
 V..... = Video
 A..... = Audio
 S..... = Subtitle
 .F.... = Frame-level multithreading
 ..S... = Slice-level multithreading
 ...X.. = Codec is experimental
 ....B. = Supports draw_horiz_band
 .....D = Supports direct rendering method 1
 ------
[…]
 V.S... mpeg4                MPEG-4 part 2

In this example V.S... indicates that the encoder mpeg4 is a Video encoder and supports Slice-level multithreading.

Also see

What is a codec and how does it differ from a format?

awk without printing newline

I guess many people are entering in this question looking for a way to avoid the new line in awk. Thus, I am going to offer a solution to just that, since the answer to the specific context was already solved!

In awk, print automatically inserts a ORS after printing. ORS stands for "output record separator" and defaults to the new line. So whenever you say print "hi" awk prints "hi" + new line.

This can be changed in two different ways: using an empty ORS or using printf.

Using an empty ORS

awk -v ORS= '1' <<< "hello
man"

This returns "helloman", all together.

The problem here is that not all awks accept setting an empty ORS, so you probably have to set another record separator.

awk -v ORS="-" '{print ...}' file

For example:

awk -v ORS="-" '1' <<< "hello
man"

Returns "hello-man-".

Using printf (preferable)

While print attaches ORS after the record, printf does not. Thus, printf "hello" just prints "hello", nothing else.

$ awk 'BEGIN{print "hello"; print "bye"}'
hello
bye
$ awk 'BEGIN{printf "hello"; printf "bye"}'
hellobye

Finally, note that in general this misses a final new line, so that the shell prompt will be in the same line as the last line of the output. To clean this, use END {print ""} so a new line will be printed after all the processing.

$ seq 5 | awk '{printf "%s", $0}'
12345$
#    ^ prompt here

$ seq 5 | awk '{printf "%s", $0} END {print ""}'
12345

How to set java.net.preferIPv4Stack=true at runtime?

Another approach, if you're desperate and don't have access to (a) the code or (b) the command line, then you can use environment variables:

http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/plugin.html.

Specifically for java web start set the environment variable:

JAVAWS_VM_ARGS

and for applets:

_JPI_VM_OPTIONS

e.g.

_JPI_VM_OPTIONS=-Djava.net.preferIPv4Stack=true

Additionally, under Windows global options (for general Java applications) can be set in the Java control plan page under the "Java" tab.

How do you debug MySQL stored procedures?

I'm late to the party, but brought more beer:

http://ocelot.ca/blog/blog/2015/03/02/the-ocelotgui-debugger/ and https://github.com/ocelot-inc/ocelotgui

I tried, and it seems pretty stable, supporting Breakpoints and Variable inspection.

It's not a complete suite (just 4,1 Mb) but helped me a lot!

How it works: It integrates with your mysql client (I'm using Ubuntu 14.04), and after you execute:

$install
$setup yourFunctionName

It installs a new database at your server, that control the debugging process. So:

$debug yourFunctionName('yourParameter')

will give you a chance to step by step walk your code, and "refreshing" your variables you can better view what is going on inside your code.

Important Tip: while debugging, maybe you will change (re-create the procedure). After a re-creation, execute: $exit and $setup before a new $debug

This is an alternative to "insert" and "log" methods. Your code remains free of additional "debug" instructions.

Screenshot:

ocelot breakpoint stepping

How to run a Runnable thread in Android at defined intervals?

If I understand correctly the documentation of Handler.post() method:

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

So examples provided by @alex2k8, even though are working correctly, are not the same. In case, where Handler.post() is used, no new threads are created. You just post Runnable to the thread with Handler to be executed by EDT. After that, EDT only executes Runnable.run(), nothing else.

Remember: Runnable != Thread.

how to check if List<T> element contains an item with a Particular Property Value

bool contains = pricePublicList.Any(p => p.Size == 200);

Automatically capture output of last command into a variable using Bash?

Bash is kind of an ugly language. Yes, you can assign the output to variable

MY_VAR="$(find -name foo.txt)"
echo "$MY_VAR"

But better hope your hardest that find only returned one result and that that result didn't have any "odd" characters in it, like carriage returns or line feeds, as they will be silently modified when assigned to a Bash variable.

But better be careful to quote your variable correctly when using it!

It's better to act on the file directly, e.g. with find's -execdir (consult the manual).

find -name foo.txt -execdir vim '{}' ';'

or

find -name foo.txt -execdir rename 's/\.txt$/.xml/' '{}' ';'

How to allow users to check for the latest app version from inside the app?

To save time writing for check new version update for android app, I written it as library and open source at https://github.com/winsontan520/Android-WVersionManager

Aligning textviews on the left and right edges in Android layout

You can use the gravity property to "float" views.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal">

        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:gravity="left"
            android:layout_weight="1"
            android:text="Left Aligned"
            />

        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:gravity="right"
            android:layout_weight="1"
            android:text="Right Aligned"
            />
    </LinearLayout>

</LinearLayout>

starting file download with JavaScript

I suggest to make an invisible iframe on the page and set it's src to url that you've received from the server - download will start without page reloading.

Or you can just set the current document.location.href to received url address. But that's can cause for user to see an error if the requested document actually does not exists.

Rails 4: List of available datatypes

You might also find it useful to know generally what these data types are used for:

There's also references used to create associations. But, I'm not sure this is an actual data type.

New Rails 4 datatypes available in PostgreSQL:

  • :hstore - storing key/value pairs within a single value (learn more about this new data type)
  • :array - an arrangement of numbers or strings in a particular row (learn more about it and see examples)
  • :cidr_address - used for IPv4 or IPv6 host addresses
  • :inet_address - used for IPv4 or IPv6 host addresses, same as cidr_address but it also accepts values with nonzero bits to the right of the netmask
  • :mac_address - used for MAC host addresses

Learn more about the address datatypes here and here.

Also, here's the official guide on migrations: http://edgeguides.rubyonrails.org/migrations.html

Windows equivalent of OS X Keychain?

Credential dumping on Windows, even with "Credential Manager" is still an issue, and I don't think there is any way to prevent it outside of special hardware. MacOS keychain doesn't have this problem and so I don't think there is an exact equivalent.

Excel - Shading entire row based on change of value

I had to do something similar for my users, with a small variant that they want to have a running number grouping the similar items. Thought I'd share it here.

  • Make a new column A
  • Assuming the first row of data is in row 2 (row 1 being header), put 1 in A2
  • Assuming your File No is in column B, in the second row (in this case A3) make the formula =IF(B3=B2,A2,A2+1)
  • Fill/copy-paste cell A3 down the column to the last row (be careful not to copy A2 by accident; that will populate all cells with 1)
  • Select the data range
  • In the Home ribbon select Conditional Formatting -> New Rule
  • Choose Use a formula to determine which cells to format
  • In the formula cell, put =MOD($A1, 2)=1 as the formula
  • Click Format, select the Fill tab
  • Select the Background Color you want, then click OK
  • Click OK

enter image description here

How to get Activity's content view?

You can also override onContentChanged() which is among others fired when setContentView() has been called.

How to use not contains() in xpath?

Should be xpath with not contains() method, //production[not(contains(category,'business'))]

horizontal line and right way to code it in html, css

_x000D_
_x000D_
hr {_x000D_
    display: block;_x000D_
    height: 1px;_x000D_
    border: 0;_x000D_
    border-top: 1px solid #ccc;_x000D_
    margin: 1em 0;_x000D_
    padding: 0;_x000D_
}
_x000D_
<div>Hello</div>_x000D_
<hr/>_x000D_
<div>World</div>
_x000D_
_x000D_
_x000D_ emphasized text

How to display items side-by-side without using tables?

What about display:inline?

<html>
      <img src='#' style='display:inline;'/>
      <p style='display:inline;'> Some text </p>
</html>

DataGridView - Focus a specific cell

I had a similar problem. I've hidden some columns and afterwards I tried to select the first row. This didn't really work:

datagridview1.Rows[0].Selected = true;

So I tried selecting cell[0,0], but it also didn't work, because this cell was not displayed. Now my final solution is working very well:

datagridview1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    
datagridview1.CurrentCell = datagridview1.FirstDisplayedCell;

So this selects the complete first row.

Writing List of Strings to Excel CSV File in Python

Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])

How to convert a Django QuerySet to a list

Why not just call list() on the Queryset?

answers_list = list(answers)

This will also evaluate the QuerySet/run the query. You can then remove/add from that list.

Remove trailing zeros

Use the hash (#) symbol to only display trailing 0's when necessary. See the tests below.

decimal num1 = 13.1534545765;
decimal num2 = 49.100145;
decimal num3 = 30.000235;

num1.ToString("0.##");       //13.15%
num2.ToString("0.##");       //49.1%
num3.ToString("0.##");       //30%

How to POST a FORM from HTML to ASPX page

This is very possible. I mocked up 3 pages which should give you a proof of concept:

.aspx page:

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox TextMode="password" ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
</form>

code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each s As String In Request.Form.AllKeys
        Response.Write(s & ": " & Request.Form(s) & "<br />")
    Next
End Sub

Separate HTML page:

<form action="http://localhost/MyTestApp/Default.aspx" method="post">
    <input name="TextBox1" type="text" value="" id="TextBox1" />
    <input name="TextBox2" type="password" id="TextBox2" />
    <input type="submit" name="Button1" value="Button" id="Button1" />
</form>

...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.

CSS ''background-color" attribute not working on checkbox inside <div>

You can use peseudo elements like this:

_x000D_
_x000D_
input[type=checkbox] {_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  margin-right: 8px;_x000D_
  cursor: pointer;_x000D_
  font-size: 27px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:after {_x000D_
  content: " ";_x000D_
  background-color: #9FFF9D;_x000D_
  display: inline-block;_x000D_
  visibility: visible;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:after {_x000D_
  content: "\2714";_x000D_
}
_x000D_
<label>Checkbox label_x000D_
      <input type="checkbox">_x000D_
    </label>
_x000D_
_x000D_
_x000D_

How do you manually execute SQL commands in Ruby On Rails using NuoDB

The working command I'm using to execute custom SQL statements is:

results = ActiveRecord::Base.connection.execute("foo")

with "foo" being the sql statement( i.e. "SELECT * FROM table").

This command will return a set of values as a hash and put them into the results variable.

So on my rails application_controller.rb I added this:

def execute_statement(sql)
  results = ActiveRecord::Base.connection.execute(sql)

  if results.present?
    return results
  else
    return nil
  end
end

Using execute_statement will return the records found and if there is none, it will return nil.

This way I can just call it anywhere on the rails application like for example:

records = execute_statement("select * from table")

"execute_statement" can also call NuoDB procedures, functions, and also Database Views.

How does += (plus equal) work?

1) 1 += 2 // equals ?

That is syntactically invalid. The left side must be a variable. For example.

var mynum = 1;
mynum += 2;
// now mynum is 3.

mynum += 2; is just a short form for mynum = mynum + 2;

2)

var data = [1,2,3,4,5];
var sum = 0;
data.forEach(function(value) {
    sum += value; 
});

Sum is now 15. Unrolling the forEach we have:

var sum = 0;
sum += 1; // sum is 1
sum += 2; // sum is 3
sum += 3; // sum is 6
sum += 4; // sum is 10
sum += 5; // sum is 15

nodejs mongodb object id to string

I faced the same problem and .toString() worked for me. I'm using mongojs driver. Here was my question

Mongodb find is not working with the Objectid

How to export settings?

Often there are questions about the java settings in vsCode. This is a big question and can involve advanced user knowledge to accmplish. But there is simple way to get the existing java settings from vsCode and copy these setting for use on another PC. This post is using recent versions of vsCode and JDK in mid-December 2020.

There are several screen shots (below) that accompany this post which should provide enough information for the visual learners.

First things first, open vsCode and either open an existing java folder-file or create a new java file in vsCode. Then look at the lower right corner of vsCode (on the blue command bar). The vsCode should be displaying an icon showing the version of the Java Standard Edition ( Java SE ) being used. The version being on this PC today is JavaSE-15. (link 1)

Click on that icon (JAVASE-15) which then opens a new window named "java.configuration.runtimes". There should be two tabs below this name: User and Workspace. Below these tabs is a link named, "Edit in settings.json". Click on that link. (link 2)

Two json files should then open: Default settings and settings.json. This post only focuses on the "settings.json" file. The settings.json file shows various settings used for coding different programming languages (Python, R, and java). Near the bottom of the settings.json file shows the settings this User uses in vsCode for programming java.

These java settings are the settings that can be "backed up" - meaning these settings get copied and pasted to another PC for creating a java programming environment similar to the java programming environment on this PC. (link 3)

link 1

link 2

link 3

Combine two arrays

If you are using PHP 7.4 or above, you can use the spread operator ... as the following examples from the PHP Docs:

$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]

function getArr() {
  return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; //['a', 'b', 'c']

$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; //['a', 'b', 'c']

function arrGen() {
    for($i = 11; $i < 15; $i++) {
        yield $i;
    }
}
$arr8 = [...arrGen()]; //[11, 12, 13, 14]

It works like in JavaScript ES6.

See more on https://wiki.php.net/rfc/spread_operator_for_array.

AngularJS - Find Element with attribute

Your use-case isn't clear. However, if you are certain that you need this to be based on the DOM, and not model-data, then this is a way for one directive to have a reference to all elements with another directive specified on them.

The way is that the child directive can require the parent directive. The parent directive can expose a method that allows direct directive to register their element with the parent directive. Through this, the parent directive can access the child element(s). So if you have a template like:

<div parent-directive>
  <div child-directive></div>
  <div child-directive></div>
</div>

Then the directives can be coded like:

app.directive('parentDirective', function($window) {
  return {
    controller: function($scope) {
      var registeredElements = [];
      this.registerElement = function(childElement) {
        registeredElements.push(childElement);
      }
    }
  };
});

app.directive('childDirective', function() {
  return {
    require: '^parentDirective',
    template: '<span>Child directive</span>',
    link: function link(scope, iElement, iAttrs, parentController) {
      parentController.registerElement(iElement);
    }
   };
});

You can see this in action at http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview

Have log4net use application config file for configuration data

All appender names must be reflected in the root section.
In your case the appender name is EventLogAppender but in the <root> <appender-ref .. section it is named as ConsoleAppender. They need to match.

You can add multiple appenders to your log config but you need to register each of them in the <root> section.

<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />

You can also refer to the apache documentation on configuring log4net.

Checking password match while typing

Probably invalid syntax in your onChange event, I avoid using like this (within the html) as I think it is messy and it is hard enough keeping JavaScript tidy at the best of times.

I would rather register the event on the document ready event in javascript. You will also definitely want to use keyup event too if you want the validation as the user is typing:

$(document).ready(function () {
   $("#txtConfirmPassword").keyup(checkPasswordMatch);
});

Here is a working example


Personally I would prefer to do the check when either password field changes, that way if they re-type the original password then you still get the same validation check:

$(document).ready(function () {
   $("#txtNewPassword, #txtConfirmPassword").keyup(checkPasswordMatch);
});

Here is a working example

Return datetime object of previous month

I think the simple way is to use DateOffset from Pandas like so:

import pandas as pd
date_1 = pd.to_datetime("2013-03-31", format="%Y-%m-%d") - pd.DateOffset(months=1)

The result will be a Timestamp object

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

Adding a rule in iptables in debian to open a new port

(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)

Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:

iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT

Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).

pandas: to_numeric for multiple columns

If you are looking for a range of columns, you can try this:

df.iloc[7:] = df.iloc[7:].astype(float)

The examples above will convert type to be float, for all the columns begin with the 7th to the end. You of course can use different type or different range.

I think this is useful when you have a big range of columns to convert and a lot of rows. It doesn't make you go over each row by yourself - I believe numpy do it more efficiently.

This is useful only if you know that all the required columns contain numbers only - it will not change "bad values" (like string) to be NaN for you.

Passing arrays as parameters in bash

This one works even with spaces:

format="\t%2s - %s\n"

function doAction
{
  local_array=("$@")
  for (( i = 0 ; i < ${#local_array[@]} ; i++ ))
    do
      printf "${format}" $i "${local_array[$i]}"
  done
  echo -n "Choose: "
  option=""
  read -n1 option
  echo ${local_array[option]}
  return
}

#the call:
doAction "${tools[@]}"

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

From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.

The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.

If you wanted to use different proxy settings to the current user then you would need to code

WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);

or

WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);

You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call

webRequest.Proxy.GetProxy(new Uri("http://google.com.au")) to see the actual details of the proxy server that would be used.

There seems to be some debate about whether you can set webRequest.Proxy or WebRequest.DefaultWebProxy = null to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy() with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.

The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.

How to Check whether Session is Expired or not in asp.net

I prefer not to check session variable in code instead use FormAuthentication. They have inbuilt functionlity to redirect to given LoginPage specified in web.config.

However if you want to explicitly check the session you can check for NULL value for any of the variable you created in session earlier as Pranay answered.

You can create Login.aspx page and write your message there , when session expires FormAuthentication automatically redirect to loginUrl given in FormAuthentication section

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" protection="All" timeout="30">
  </forms>
</authentication>

The thing is that you can't give seperate page for Login and SessionExpire , so you have to show/hide some section on Login.aspx to act it both ways.

There is another way to redirect to sessionexpire page after timeout without changing formauthentication->loginurl , see the below link for this : http://www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html

Dropping connected users in Oracle database

Do a query:

SELECT * FROM v$session s;

Find your user and do the next query (with appropriate parameters):

ALTER SYSTEM KILL SESSION '<SID>, <SERIAL>';

Can you center a Button in RelativeLayout?

Its easy, dont Align it to anything

_x000D_
_x000D_
<Button_x000D_
        android:id="@+id/the_button"_x000D_
        android:layout_width="wrap_content"_x000D_
        android:layout_height="wrap_content" _x000D_
        android:layout_centerInParent="true"_x000D_
        android:text="Centered Button"/>
_x000D_
_x000D_
_x000D_

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

The output in your first printline is using your formatter. The output in your second (the date created from your parsed string) is output using Date#toString which formats according to its own rules. That is, you're not using a formatter.

The rules are as per what you're seeing and described here: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString()

python dictionary sorting in descending order based on values

You can use the operator to sort the dictionary by values in descending order.

import operator

d = {"a":1, "b":2, "c":3}
cd = sorted(d.items(),key=operator.itemgetter(1),reverse=True)

The Sorted dictionary will look like,

cd = {"c":3, "b":2, "a":1}

Here, operator.itemgetter(1) takes the value of the key which is at the index 1.

How to "log in" to a website using Python's Requests module?

The requests.Session() solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token is required as a hidden field and add it to the payload with the username and password:

import requests
from bs4 import BeautifulSoup

payload = {
    'email': '[email protected]',
    'password': 'passw0rd'
}     

with requests.Session() as sess:
    res = sess.get(server_name + '/signin')
    signin = BeautifulSoup(res._content, 'html.parser')
    payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
    res = sess.post(server_name + '/auth/login', data=payload)

Encrypt and decrypt a String in java

Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.

I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.

If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

JQuery, Spring MVC @RequestBody and JSON - making it work together

In addition to the answers here...

if you are using jquery on the client side, this worked for me:

Java:

@RequestMapping(value = "/ajax/search/sync") 
public String sync(@RequestBody Foo json) {

Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):

$.ajax({
    type: "post",
    url: "sync", //your valid url
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
    data: JSON.stringify(jsonobject), //json object or array of json objects
    success: function(result) {
        //do nothing
    },
    error: function(){
        alert('failure');
    }
});

Colouring plot by factor in R

The col argument in the plot function assign colors automatically to a vector of integers. If you convert iris$Species to numeric, notice you have a vector of 1,2 and 3s So you can apply this as:

plot(iris$Sepal.Length, iris$Sepal.Width, col=as.numeric(iris$Species))

Suppose you want red, blue and green instead of the default colors, then you can simply adjust it:

plot(iris$Sepal.Length, iris$Sepal.Width, col=c('red', 'blue', 'green')[as.numeric(iris$Species)])

You can probably see how to further modify the code above to get any unique combination of colors.

Java: Get last element after split

With Guava:

final Splitter splitter = Splitter.on("-").trimResults();
assertEquals("Günnewig Uebachs", Iterables.getLast(splitter.split(one)));
assertEquals("Madison", Iterables.getLast(splitter.split(two)));

Splitter, Iterables

For vs. while in C programming?

For the sake of readability

List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20

How to run vi on docker container?

To install within your Docker container you can run command

docker exec apt-get update && apt-get install -y vim

But this will be limited to the container in which vim is installed. To make it available to all the containers, edit the Dockerfile and add

RUN apt-get update && apt-get install -y vim

or you can also extend the image in the new Dockerfile and add above command. Eg.

FROM < image name >

RUN apt-get update && apt-get install -y vim

Align HTML input fields by :

http://jsfiddle.net/T6zhj/1/

Using display table-cell/row will do the job without any width needed.

The html :

 <html>
  <div>
      <div class="row"><label>Name:</label><input type="text"></div>
      <div class="row"><label>Email Address:</label><input type = "text"></div>
      <div class="row"><label>Description of the input value:</label><input type="text"></div>
  </div>
 </html>

The Css :

label{
    display: table-cell;
    text-align: right;
}
input {
  display: table-cell;
}
div.row{
    display:table-row;
}

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Another possible cause of similar issue could be wrong processorArchitecture in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:

https://bitbucket.org/anthony_tuininga/cx_freeze/pull-request/71/changed-x86-in-windows-manifest-to/diff

How do operator.itemgetter() and sort() work?

You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter returns a callable:

>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8

To do it in a different way, you can use lambda:

a.sort(key=lambda x: x[1])

And reverse it:

a.sort(key=operator.itemgetter(1), reverse=True)

Sort by more than one column:

a.sort(key=operator.itemgetter(1,2))

See the sorting How To.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

Here is another option which did the trick for me: https://dba.stackexchange.com/a/44340

There I used Option B. This is not my idea so all credit goes to the original author. I am just putting it in here also as I know that sometimes links don't function and it is recommended to have the full story handy.

Just one tip from me: First resolve the schema incompatibilities if any. Then pouring in the data should be a breeze.


Option A: Script out database in compatibility mode using Generate script option:

Note: If you script out database with schema and data, depending on your data size, the script will be massive and wont be handled by SSMS, sqlcmd or osql (might be in GB as well).

enter image description here

Option B:

First script out tables first with all Indexes, FK's, etc and create blank tables in the destination database - option with SCHEMA ONLY (No data).

Use BCP to insert data

I. BCP out the data using below script. Set SSMS in Text Mode and copy the output generated by below script in a bat file.

-- save below output in a bat file by executing below in SSMS in TEXT mode

-- clean up: create a bat file with this command --> del D:\BCP\*.dat 

select '"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp.exe" ' /* path to BCP.exe */
    +  QUOTENAME(DB_NAME())+ '.' /* Current Database */
    +  QUOTENAME(SCHEMA_NAME(SCHEMA_ID))+'.'            
    +  QUOTENAME(name)  
    +  ' out D:\BCP\'  /* Path where BCP out files will be stored */
    +  REPLACE(SCHEMA_NAME(schema_id),' ','') + '_' 
    +  REPLACE(name,' ','') 
    + '.dat -T -E -SServerName\Instance -n' /* ServerName, -E will take care of Identity, -n is for Native Format */
from sys.tables
where is_ms_shipped = 0 and name <> 'sysdiagrams'                       /* sysdiagrams is classified my MS as UserTable and we dont want it */
/*and schema_name(schema_id) <> 'unwantedschema'    */                             /* Optional to exclude any schema  */
order by schema_name(schema_id)

II. Run the bat file that will generate the .dat files in the folder that you have specified.

III. Run below script on the destination server with SSMS in text mode again.

--- Execute this on the destination server.database from SSMS.

--- Make sure the change the @Destdbname and the bcp out path as per your environment.

declare @Destdbname sysname
set @Destdbname = 'destinationDB' /* Destination Database Name where you want to Bulk Insert in */
select 'BULK INSERT '
/*Remember Tables must be present on destination database */ 
+ QUOTENAME(@Destdbname) + '.' 
+ QUOTENAME(SCHEMA_NAME(SCHEMA_ID)) 
+ '.' + QUOTENAME(name) 
+ ' from ''D:\BCP\' /* Change here for bcp out path */ 
+ REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '') 
+ '.dat'' with ( KEEPIDENTITY, DATAFILETYPE = ''native'', TABLOCK )' 
+ char(10) 
+ 'print ''Bulk insert for ' + REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '') + ' is done... ''' 
+ char(10) + 'go'
from sys.tables
where is_ms_shipped = 0
and name <> 'sysdiagrams' /* sysdiagrams is classified my MS as UserTable and we dont want it */
--and schema_name(schema_id) <> 'unwantedschema' /* Optional to exclude any schema */
    order by schema_name(schema_id)

IV. Run the output using SSMS to insert data back in the tables.

This is very fast BCP method as it uses Native mode.

How to programmatically close a JFrame

If you have done this to make sure the user can't close the window:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Then you should change your pullThePlug() method to be

public void pullThePlug() {
    // this will make sure WindowListener.windowClosing() et al. will be called.
    WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);

    // this will hide and dispose the frame, so that the application quits by
    // itself if there is nothing else around. 
    setVisible(false);
    dispose();
    // if you have other similar frames around, you should dispose them, too.

    // finally, call this to really exit. 
    // i/o libraries such as WiiRemoteJ need this. 
    // also, this is what swing does for JFrame.EXIT_ON_CLOSE
    System.exit(0); 
}

I found this to be the only way that plays nice with the WindowListener and JFrame.DO_NOTHING_ON_CLOSE.

Convert utf8-characters to iso-88591 and back in PHP

In my case after files with names containing those characters were uploaded, they were not even visible with Filezilla! In Cpanel filemanager they were shown with ? (under black background). And this combination made it shown correctly on the browser (HTML document is Western-encoded):

$dspFileName = utf8_decode(htmlspecialchars(iconv(mb_internal_encoding(), 'utf-8', basename($thisFile['path']))) );

Android set height and width of Custom view programmatically

If you know the exact size of the view, just use setLayoutParams():

graphView.setLayoutParams(new LayoutParams(width, height));

Or in Kotlin:

graphView.layoutParams = LayoutParams(width, height)

However, if you need a more flexible approach you can override onMeasure() to measure the view more precisely depending on the space available and layout constraints (wrap_content, match_parent, or a fixed size). You can find more details about onMeasure() in the android docs.

How can you get the first digit in an int (C#)?

int start = curr;
while (start >= 10)
  start /= 10;

This is more efficient than a ToString() approach which internally must implement a similar loop and has to construct (and parse) a string object on the way ...

String concatenation in MySQL

That's not the way to concat in MYSQL. Use the CONCAT function Have a look here: http://dev.mysql.com/doc/refman/4.1/en/string-functions.html#function_concat

How to break lines in PowerShell?

If escaping doesn't work, you can try this:

$str += $("" | Out-String)

It just adds nothing, but as an Out-String, which creates a new line.

Best way to test for a variable's existence in PHP; isset() is clearly broken

If I run the following:

echo '<?php echo $foo; ?>' | php

I get an error:

PHP Notice:  Undefined variable: foo in /home/altern8/- on line 1

If I run the following:

echo '<?php if ( isset($foo) ) { echo $foo; } ?>' | php

I do not get the error.

If I have a variable that should be set, I usually do something like the following.

$foo = isset($foo) ? $foo : null;

or

if ( ! isset($foo) ) $foo = null;

That way, later in the script, I can safely use $foo and know that it "is set", and that it defaults to null. Later I can if ( is_null($foo) ) { /* ... */ } if I need to and know for certain that the variable exists, even if it is null.

The full isset documentation reads a little more than just what was initially pasted. Yes, it returns false for a variable that was previously set but is now null, but it also returns false if a variable has not yet been set (ever) and for any variable that has been marked as unset. It also notes that the NULL byte ("\0") is not considered null and will return true.

Determine whether a variable is set.

If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.

How to show android checkbox at right side?

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/location_permissions"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="@android:color/black" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <CheckBox
                android:id="@+id/location_permission_checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="8dp"
                android:onClick="onLocationPermissionClicked" />

        </RelativeLayout>
    </LinearLayout>

Seconds CountDown Timer

Hey please add code in your project,it is easy and i think will solve your problem.

    int count = 10;

    private void timer1_Tick(object sender, EventArgs e)
    {
        count--;
        if (count != 0 && count > 0)
        {
            label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
        }
        else
        {
            label1.Text = "game over";

        }

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Interval = 1;

        timer1.Tick += new EventHandler(timer1_Tick);

    }

Background position, margin-top?

 background-image: url(/images/poster.png);
 background-position: center;
 background-position-y: 50px;
 background-repeat: no-repeat;

How to find the Target *.exe file of *.appref-ms

The easiest thing is to run the program, open the task manager, right-click the process and select properties, here is the full address

Generate a UUID on iOS from Swift

Each time the same will be generated:

if let uuid = UIDevice.current.identifierForVendor?.uuidString {
    print(uuid)
}

Each time a new one will be generated:

let uuid = UUID().uuidString
print(uuid)

Bring element to front using CSS

In my case i had to move the html code of the element i wanted at the front at the end of the html file, because if one element has z-index and the other doesn't have z index it doesn't work.

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

AngularJS : Why ng-bind is better than {{}} in angular?

There is some flickering problem in {{ }} like when you refresh the page then for a short spam of time expression is seen.So we should use ng-bind instead of expression for data depiction.

Convert string (without any separator) to list

I know this question has been answered, but just to point out what timeit has to say about the solutions efficiency. Using these parameters:

size = 30
s = [str(random.randint(0, 9)) for i in range(size)] + (size/3) * ['-']
random.shuffle(s)
s = ''.join(['+'] + s)
timec = 1000

That is the "phone number" has 30 digits, 1 plus sing and 10 '-'. I've tested these approaches:

def justdigits(s):
    justdigitsres = ""
    for char in s:
        if char.isdigit():
            justdigitsres += str(char)
    return justdigitsres

re_compiled = re.compile(r'\D')

print('Filter: %ss' % timeit.Timer(lambda : ''.join(filter(str.isdigit, s))).timeit(timec))
print('GE: %ss' % timeit.Timer(lambda : ''.join(n for n in s if n.isdigit())).timeit(timec))
print('LC: %ss' % timeit.Timer(lambda : ''.join([n for n in s if n.isdigit()])).timeit(timec))
print('For loop: %ss' % timeit.Timer(lambda : justdigits(s)).timeit(timec))
print('RE: %ss' % timeit.Timer(lambda : re.sub(r'\D', '', s)).timeit(timec))
print('REC: %ss' % timeit.Timer(lambda : re_compiled.sub('', s)).timeit(timec))
print('Translate: %ss' % timeit.Timer(lambda : s.translate(None, '+-')).timeit(timec))

And came out with these results:

Filter: 0.0145790576935s
GE: 0.0185861587524s
LC: 0.0151798725128s
For loop: 0.0242128372192s
RE: 0.0120108127594s
REC: 0.00868797302246s
Translate: 0.00118899345398s

Apparently GEs and LCs are still slower than a regex or a compiled regex. And apparently my CPython 2.6.6 didn't optimize the string addition that much. translate appears to be the fastest (which is expected as the problem is stated as "ignore these two symbols", rather than "get these numbers" and I believe is quite low-level).

And for size = 100:

Filter: 0.0357120037079s
GE: 0.0465779304504s
LC: 0.0428011417389s
For loop: 0.0733139514923s
RE: 0.0213229656219s
REC: 0.0103371143341s
Translate: 0.000978946685791s

And for size = 1000:

Filter: 0.212141036987s
GE: 0.198996067047s
LC: 0.196880102158s
For loop: 0.365696907043s
RE: 0.0880808830261s
REC: 0.086804151535s
Translate: 0.00587010383606s

How to find topmost view controller on iOS

Yet another Swift solution

func topController() -> UIViewController? {

    // recursive follow
    func follow(from:UIViewController?) -> UIViewController? {
        if let to = (from as? UITabBarController)?.selectedViewController {
            return follow(to)
        } else if let to = (from as? UINavigationController)?.visibleViewController {
            return follow(to)
        } else if let to = from?.presentedViewController {
            return follow(to)
        }
        return from
    }

    let root = UIApplication.sharedApplication().keyWindow?.rootViewController

    return follow(root)

}

How to change HTML Object element data attribute value in javascript

and in jquery:

$('element').attr('some attribute','some attributes value')

i.e

$('a').attr('href','http://www.stackoverflow.com/')

PHP Converting Integer to Date, reverse of strtotime

I guess you are asking why is 1388516401 equal to 2014-01-01...?

There is an historical reason for that. There is a 32-bit integer variable, called time_t, that keeps the count of the time elapsed since 1970-01-01 00:00:00. Its value expresses time in seconds. This means that in 2014-01-01 00:00:01 time_t will be equal to 1388516401.

This leads us for sure to another interesting fact... In 2038-01-19 03:14:07 time_t will reach 2147485547, the maximum value for a 32-bit number. Ever heard about John Titor and the Year 2038 problem? :D

Using custom fonts using CSS?

Today there are four font container formats in use on the web: EOT, TTF, WOFF,andWOFF2.

Unfortunately, despite the wide range of choices, there isn't a single universal format that works across all old and new browsers:

  • EOT is IE only,
  • TTF has partial IE support,
  • WOFF enjoys the widest support but is not available in some older browsers
  • WOFF 2.0 support is a work in progress for many browsers.

If you want your web app to have the same font across all browsers then you might want to provide all 4 font type in CSS

 @font-face {
      font-family: 'besom'; !important
      src: url('fonts/besom/besom.eot');
      src: url('fonts/besom/besom.eot?#iefix') format('embedded-opentype'),
           url('fonts/besom/besom.woff2') format('woff2'),
           url('fonts/besom/besom.woff') format('woff'),
           url('fonts/besom/besom.ttf') format('truetype'),
           url('fonts/besom/besom.svg#besom_2regular') format('svg');
      font-weight: normal;
      font-style: normal;
  }

show loading icon until the page is load?

HTML page

<div id="overlay">
<img src="<?php echo base_url()?>assest/website/images/loading1.gif" alt="Loading" />
 Loading...
</div>

Script

$(window).load(function(){ 
 //PAGE IS FULLY LOADED 
 //FADE OUT YOUR OVERLAYING DIV
 $('#overlay').fadeOut();
});

How to browse localhost on Android device?

I used ngrok but now it need registration and it also has a connections request limit. Now I'm using LocalTunnel and so far it's much better.

Adding a month to a date in T SQL

select * from Reference where reference_dt = DateAdd(month,1,another_date_reference)

Maven not found in Mac OSX mavericks

if you don't want to install homebrew (or any other package manager) just for installing maven, you can grab the binary from their site:

http://maven.apache.org/download.cgi

extract the content to a folder (e.g. /Applications/apache-maven-3.1.1) with

$ tar -xvf apache-maven-3.1.1-bin.tar.gz

and finally adjust your ~/.bash_profile with any texteditor you like to include

export M2_HOME=/Applications/apache-maven-3.1.1
export PATH=$PATH:$M2_HOME/bin

restart the terminal and test it with

$ mvn -version

Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-17 17:22:22+0200)
Maven home: /Applications/apache-maven-3.1.1
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: de_DE, platform encoding: MacRoman
OS name: "mac os x", version: "10.9", arch: "x86_64", family: "mac"

T-SQL stored procedure that accepts multiple Id values

Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: Arrays and Lists in SQL Server.

There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons.

I really can't recommend enough to read the article to learn about the tradeoffs among all these options.

Can I display the value of an enum with printf()?

As a string, no. As an integer, %d.

Unless you count:

static char* enumStrings[] = { /* filler 0's to get to the first value, */
                               "enum0", "enum1", 
                               /* filler for hole in the middle: ,0 */
                               "enum2", "enum3", .... };

...

printf("The value is %s\n", enumStrings[thevalue]);

This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.

deny directory listing with htaccess

There are two ways :

  1. using .htaccess : Options -Indexes

  2. create blank index.html

Fatal error: Call to a member function query() on null

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

HTML/JavaScript: Simple form validation on submit

You have several errors there.

First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">

Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
        return false;
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) {
        alert("Please enter only alphanumeric values for your advertisement title");
        return false;
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
        return false;
    }
  return true;
}

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

How should I do integer division in Perl?

Hope it works

int(9/4) = 2.

Thanks Manojkumar

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

How to drop a table if it exists?

I use:

if exists (select * 
           from sys.tables 
           where name = 'tableName' 
           and schema_id = schema_id('dbo'))
begin
    drop table dbo.tableName
end

How to remove selected commit log entries from a Git repository while keeping their changes?

# detach head and move to D commit
git checkout <SHA1-for-D>

# move HEAD to A, but leave the index and working tree as for D
git reset --soft <SHA1-for-A>

# Redo the D commit re-using the commit message, but now on top of A
git commit -C <SHA1-for-D>

# Re-apply everything from the old D onwards onto this new place 
git rebase --onto HEAD <SHA1-for-D> master

sql how to cast a select query

And when you use a case :

CASE
WHEN TB1.COD IS NULL THEN
    TB1.COD || ' - ' || TB1.NAME
ELSE
    TB1.COD || ' - ' || TB1.NAME || ' - ' || TB.NM_TABELAFRETE
END AS NR_FRETE,

CSS table td width - fixed, not flexible

you also can try to use that:

table {
    table-layout:fixed;
}
table td {
    width: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
}

http://www.w3schools.com/cssref/pr_tab_table-layout.asp

Programmatically getting the MAC of an Android device

As was already pointed out in the comment, the MAC address can be received via the WifiManager.

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();

Also do not forget to add the appropriate permissions into your AndroidManifest.xml

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

Please refer to Android 6.0 Changes.

To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.

Moving Average Pandas

A moving average can also be calculated and visualized directly in a line chart by using the following code:

Example using stock price data:

import pandas_datareader.data as web
import matplotlib.pyplot as plt
import datetime
plt.style.use('ggplot')

# Input variables
start = datetime.datetime(2016, 1, 01)
end = datetime.datetime(2018, 3, 29)
stock = 'WFC'

# Extrating data
df = web.DataReader(stock,'morningstar', start, end)
df = df['Close']

print df 

plt.plot(df['WFC'],label= 'Close')
plt.plot(df['WFC'].rolling(9).mean(),label= 'MA 9 days')
plt.plot(df['WFC'].rolling(21).mean(),label= 'MA 21 days')
plt.legend(loc='best')
plt.title('Wells Fargo\nClose and Moving Averages')
plt.show()

Tutorial on how to do this: https://youtu.be/XWAPpyF62Vg

Make new column in Panda dataframe by adding values from other columns

Concerning n00b's comment: "I get the following warning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"

I was getting the same error. In my case it was because I was trying to perform the column addition on a dataframe that was created like this:

df_b = df[['colA', 'colB', 'colC']]

instead of:

df_c = pd.DataFrame(df, columns=['colA', 'colB', 'colC'])

df_b is a copy of a slice from df
df_c is an new dataframe. So

df_c['colD'] = df['colA'] + df['colB']+ df['colC']

will add the columns and won't raise any warning. Same if .sum(axis=1) is used.

How to know if two arrays have the same values

You can use reduce instead of loops to appear clever, but at the risk of having your fellow developers think of you as a smart-ass.

function isArrayContentSame(a, b) {
  if (Array.isArray(a) && Array.isArray(b) && a.length == b.length) {
    a = a.concat().sort()
    b = b.concat().sort()
    return a.reduce((acc,e,i) => acc && e === b[i], true)
  } else {
    return false;
  }
}

Benefits of using the conditional ?: (ternary) operator

If you need multiple branches on the same condition, use an if:

if (A == 6)
  f(1, 2, 3);
else
  f(4, 5, 6);

If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:

f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );

Also, you can use the ternary operator in initialization.

const int i = (A == 6)? 1 : 4;

Doing that with if is very messy:

int i_temp;
if (A == 6)
   i_temp = 1;
else
   i_temp = 4;
const int i = i_temp;

You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.

Best way to get hostname with php

For PHP >= 5.3.0 use this:

$hostname = gethostname();

For PHP < 5.3.0 but >= 4.2.0 use this:

$hostname = php_uname('n');

For PHP < 4.2.0 use this:

$hostname = getenv('HOSTNAME'); 
if(!$hostname) $hostname = trim(`hostname`); 
if(!$hostname) $hostname = exec('echo $HOSTNAME');
if(!$hostname) $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); 

multiple conditions for JavaScript .includes() method

How about ['hello', 'hi', 'howdy'].includes(str)?

NPM doesn't install module dependencies

happens with old node version. use latest version of node like this:

$ nvm use 8.0
$ rm -rf node_modules
$ npm install
$ npm i somemodule

edit: also make sure you save.
eg: npm install yourmoduleName --save

Regarding 'main(int argc, char *argv[])'

argc is the number of command line arguments given to the program at runtime, and argv is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void argument, instead:

int main(void) {
    /* ... */ 
}

Those are the only two prototypes defined for main as per the standards, but some compilers allow a return type of void as well. More on this on Wikipedia.

How can I check the size of a collection within a Django template?

See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:

{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% else %}
    No athletes.
{% endif %}

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I finally found the problem. The error was not the good one.

Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Strange Bug, Hope it will help other people.

Why isn't my Pandas 'apply' function referencing multiple columns working?

Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df

def add5(x):
    return x+5

df[['a', 'b']].apply(add5)

How do I print the type or class of a variable in Swift?

let i: Int = 20


  func getTypeName(v: Any) -> String {
    let fullName = _stdlib_demangleName(_stdlib_getTypeName(i))
    if let range = fullName.rangeOfString(".") {
        return fullName.substringFromIndex(range.endIndex)
    }
    return fullName
}

println("Var type is \(getTypeName(i)) = \(i)")

Property 'value' does not exist on type 'Readonly<{}>'

According to the official ReactJs documentation, you need to pass argument in the default format witch is:

P = {} // default for your props
S = {} // default for yout state

interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }

Or to define your own type like below: (just an exp)

interface IProps {
    clients: Readonly<IClientModel[]>;

    onSubmit: (data: IClientModel) => void;
}

interface IState {
   clients: Readonly<IClientModel[]>;
   loading: boolean;
}

class ClientsPage extends React.Component<IProps, IState> {
  // ...
}

typescript and react whats react component P S mean

how to statically type react components with typescript

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

My Solution in laravel 5.2

{{ Form::open(['route' => ['votes.submit', $video->id],  'method' => 'POST']) }}
    <button type="submit" class="btn btn-primary">
        <span class="glyphicon glyphicon-thumbs-up"></span> Votar
    </button>
{{ Form::close() }}

My Routes File (under middleware)

Route::post('votar/{id}', [
    'as' => 'votes.submit',
    'uses' => 'VotesController@submit'
]);

Route::delete('votar/{id}', [
    'as' => 'votes.destroy',
    'uses' => 'VotesController@destroy'
]);

Hide header in stack navigator React navigation

In your targeted screen you have to code this !

 static navigationOptions = ({ navigation }) => {
    return {
       header: null
    }
 }

curl POST format for CURLOPT_POSTFIELDS

It depends on the content-type

url-encoded or multipart/form-data

To send data the standard way, as a browser would with a form, just pass an associative array. As stated by PHP's manual:

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

JSON encoding

Neverthless, when communicating with JSON APIs, content must be JSON encoded for the API to understand our POST data.

In such cases, content must be explicitely encoded as JSON :

CURLOPT_POSTFIELDS => json_encode(['param1' => $param1, 'param2' => $param2]),

When communicating in JSON, we also usually set accept and content-type headers accordingly:

CURLOPT_HTTPHEADER => [
    'accept: application/json',
    'content-type: application/json'
]

What is a software framework?

A framework has some functions that you may need. you maybe need some sort of arrays that have inbuilt sorting mechanisms. Or maybe you need a window where you want to place some controls, all that you can find in a framework. it's a kind of WORK that spans a FRAME around your own work.

EDIT: OK I m about to dig what you guys were trying to tell me ;) you perhaps havent noticed the information between the lines "WORK that spans a FRAME around ..." before this is getting fallen deeper n deeper. I try to give a floor to it hoping you're gracfully:
a good explanation to the question "Difference between a Library and a Framework" I found here
http://ifacethoughts.net/2007/06/04/difference-between-a-library-and-a-framework/

Best way to list files in Java, sorted by Date Modified?

If the files you are sorting can be modified or updated at the same time the sort is being performed:


Java 8+

private static List<Path> listFilesOldestFirst(final String directoryPath) throws IOException {
    try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {
        return fileStream
            .map(Path::toFile)
            .collect(Collectors.toMap(Function.identity(), File::lastModified))
            .entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue())
//            .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))  // replace the previous line with this line if you would prefer files listed newest first
            .map(Map.Entry::getKey)
            .map(File::toPath)  // remove this line if you would rather work with a List<File> instead of List<Path>
            .collect(Collectors.toList());
    }
}

Java 7

private static List<File> listFilesOldestFirst(final String directoryPath) throws IOException {
    final List<File> files = Arrays.asList(new File(directoryPath).listFiles());
    final Map<File, Long> constantLastModifiedTimes = new HashMap<File,Long>();
    for (final File f : files) {
        constantLastModifiedTimes.put(f, f.lastModified());
    }
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(final File f1, final File f2) {
            return constantLastModifiedTimes.get(f1).compareTo(constantLastModifiedTimes.get(f2));
        }
    });
    return files;
}


Both of these solutions create a temporary map data structure to save off a constant last modified time for each file in the directory. The reason we need to do this is that if your files are being updated or modified while your sort is being performed then your comparator will be violating the transitivity requirement of the comparator interface's general contract because the last modified times may be changing during the comparison.

If, on the other hand, you know the files will not be updated or modified during your sort, you can get away with pretty much any other answer submitted to this question, of which I'm partial to:

Java 8+ (No concurrent modifications during sort)

private static List<Path> listFilesOldestFirst(final String directoryPath) throws IOException {
    try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {
        return fileStream
            .map(Path::toFile)
            .sorted(Comparator.comparing(File::lastModified))
            .map(File::toPath)  // remove this line if you would rather work with a List<File> instead of List<Path>
            .collect(Collectors.toList());
    }
}

Note: I know you can avoid the translation to and from File objects in the above example by using Files::getLastModifiedTime api in the sorted stream operation, however, then you need to deal with checked IO exceptions inside your lambda which is always a pain. I'd say if performance is critical enough that the translation is unacceptable then I'd either deal with the checked IOException in the lambda by propagating it as an UncheckedIOException or I'd forego the Files api altogether and deal only with File objects:

final List<File> sorted = Arrays.asList(new File(directoryPathString).listFiles());
sorted.sort(Comparator.comparing(File::lastModified));

Storing Python dictionaries

For completeness, we should include ConfigParser and configparser which are part of the standard library in Python 2 and 3, respectively. This module reads and writes to a config/ini file and (at least in Python 3) behaves in a lot of ways like a dictionary. It has the added benefit that you can store multiple dictionaries into separate sections of your config/ini file and recall them. Sweet!

Python 2.7.x example.

import ConfigParser

config = ConfigParser.ConfigParser()

dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}

# Make each dictionary a separate section in the configuration
config.add_section('dict1')
for key in dict1.keys():
    config.set('dict1', key, dict1[key])
   
config.add_section('dict2')
for key in dict2.keys():
    config.set('dict2', key, dict2[key])

config.add_section('dict3')
for key in dict3.keys():
    config.set('dict3', key, dict3[key])

# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()

# Read the configuration from a file
config2 = ConfigParser.ConfigParser()
config2.read('config.ini')

dictA = {}
for item in config2.items('dict1'):
    dictA[item[0]] = item[1]

dictB = {}
for item in config2.items('dict2'):
    dictB[item[0]] = item[1]

dictC = {}
for item in config2.items('dict3'):
    dictC[item[0]] = item[1]

print(dictA)
print(dictB)
print(dictC)

Python 3.X example.

import configparser

config = configparser.ConfigParser()

dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}

# Make each dictionary a separate section in the configuration
config['dict1'] = dict1
config['dict2'] = dict2
config['dict3'] = dict3

# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()

# Read the configuration from a file
config2 = configparser.ConfigParser()
config2.read('config.ini')

# ConfigParser objects are a lot like dictionaries, but if you really
# want a dictionary you can ask it to convert a section to a dictionary
dictA = dict(config2['dict1'] )
dictB = dict(config2['dict2'] )
dictC = dict(config2['dict3'])

print(dictA)
print(dictB)
print(dictC)

Console output

{'key2': 'keyinfo2', 'key1': 'keyinfo'}
{'k1': 'hot', 'k2': 'cross', 'k3': 'buns'}
{'z': '3', 'y': '2', 'x': '1'}

Contents of config.ini

[dict1]
key2 = keyinfo2
key1 = keyinfo

[dict2]
k1 = hot
k2 = cross
k3 = buns

[dict3]
z = 3
y = 2
x = 1

slashes in url variables

You could easily replace the forward slashes / with something like an underscore _ such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.

How to dynamically change header based on AngularJS partial view?

Here's a different way to do title changes. Maybe not as scalable as a factory function (which could conceivably handle unlimited pages) but it was easier for me to understand:

In my index.html I started like this:

    <!DOCTYPE html>
      <html ng-app="app">
        <head>
          <title ng-bind-template="{{title}}">Generic Title That You'll Never See</title>

Then I made a partial called "nav.html":

<div ng-init="$root.title = 'Welcome'">
    <ul class="unstyled">
        <li><a href="#/login" ng-click="$root.title = 'Login'">Login</a></li>
        <li><a href="#/home" ng-click="$root.title = 'Home'">Home</a></li>
        <li><a href="#/admin" ng-click="$root.title = 'Admin'">Admin</a></li>
        <li><a href="#/critters" ng-click="$root.title = 'Crispy'">Critters</a></li>
    </ul>
</div>

Then I went back to "index.html" and added the nav.html using ng-include and the ng-view for my partials:

<body class="ng-cloak" ng-controller="MainCtrl">
    <div ng-include="'partials/nav.html'"></div>
    <div>
        <div ng-view></div>
    </div>

Notice that ng-cloak? It doesn't have anything to do with this answer but it hides the page until it's done loading, a nice touch :) Learn how here: Angularjs - ng-cloak/ng-show elements blink

Here's the basic module. I put it in a file called "app.js":

(function () {
    'use strict';
    var app = angular.module("app", ["ngResource"]);

    app.config(function ($routeProvider) {
        // configure routes
        $routeProvider.when("/", {
            templateUrl: "partials/home.html",
            controller:"MainCtrl"
        })
            .when("/home", {
            templateUrl: "partials/home.html",
            controller:"MainCtrl"
        })
            .when("/login", {
            templateUrl:"partials/login.html",
            controller:"LoginCtrl"
        })
            .when("/admin", {
            templateUrl:"partials/admin.html",
            controller:"AdminCtrl"
        })
            .when("/critters", {
            templateUrl:"partials/critters.html",
            controller:"CritterCtrl"
        })
            .when("/critters/:id", {
            templateUrl:"partials/critter-detail.html",
            controller:"CritterDetailCtrl"
        })
            .otherwise({redirectTo:"/home"});
    });

}());

If you look toward the end of the module, you'll see that I have a critter-detail page based on :id. It's a partial that is used from the Crispy Critters page. [Corny, I know - maybe it's a site that celebrates all kinds of chicken nuggets ;) Anyway, you could update the title when a user clicks on any link, so in my main Crispy Critters page that leads to the critter-detail page, that's where the $root.title update would go, just like you saw in the nav.html above:

<a href="#/critters/1" ng-click="$root.title = 'Critter 1'">Critter 1</a>
<a href="#/critters/2" ng-click="$root.title = 'Critter 2'">Critter 2</a>
<a href="#/critters/3" ng-click="$root.title = 'Critter 3'">Critter 3</a>

Sorry so windy but I prefer a post that gives enough detail to get it up and running. Note that the example page in the AngularJS docs is out of date and shows a 0.9 version of ng-bind-template. You can see that it's not that much different.

Afterthought: you know this but it's here for anyone else; at the bottom of the index.html, one must include the app.js with the module:

        <!-- APP -->
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>

Basic example of using .ajax() with JSONP?

In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.

Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.

This does not work any more - as an exercise, see if you can replace it with the Github API:

$('document').ready(function() {
    var pm_url = 'http://twitter.com/status';
    pm_url += '/user_timeline/stephenfry.json';
    pm_url += '?count=10&callback=photos';
    $.ajax({
        url: pm_url,
        dataType: 'jsonp',
        jsonpCallback: 'photos',
        jsonp: 'callback',
    });
});
function photos (data) {
    alert(data);
    console.log(data);
};

although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing

alert(JSON.stringify(data));

You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JQuery (cross-domain) JSONP Twitter example</title>
        <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.getJSON('https://api.github.com/gists?callback=?', function(response){
                    $.each(response.data, function(i, gist){
                        $('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" + 
                            (gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
                    });
                });
            });
        </script>
    </head>
    <body>
        <ul id="gists"></ul>
    </body>
</html>

How can I disable inherited css styles?

The cleanest solution is probably to specify your divs as exact children.

Try changing this:

div.rounded div div {
    background: url('bl.gif') no-repeat bottom left;
}

To this:

div.rounded > div > div {
    background: url('bl.gif') no-repeat bottom left;
}

Is it wrong to place the <script> tag after the </body> tag?

Modern browsers will take script tags in the body like so:

<body>
    <script src="scripts/main.js"></script>
</body>

Basically, it means that the script will be loaded once the page has finished, which may be useful in certain cases (namely DOM manipulation). However, I highly recommend you take the same script and put it in the head tag with "defer", as it will give the same effect.

<head>
    <script src="scripts/main.js" defer></script>
</head>

Regex Named Groups in Java

What kind of problem do you get with jregex? It worked well for me under java5 and java6.

Jregex does the job well (even if the last version is from 2002), unless you want to wait for javaSE 7.

How to copy an object by value, not by reference

You need to do a deep copy from user to usercopy, and then after your login you can reassign your userCopy reference to user.

User userCopy = new User();
userCopy.Age = user.Age
userCopy.ID = user.ID

foreach(...) 
{ 
  user.Age = 1; 
  user.ID = -1; 

  UserDao.Update(user)     

  user = userCopy;       
}

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

Getting Serial Port Information

I combined previous answers and used structure of Win32_PnPEntity class which can be found found here. Got solution like this:

using System.Management;
public static void Main()
{
     GetPortInformation();
}

public string GetPortInformation()
    {
        ManagementClass processClass = new ManagementClass("Win32_PnPEntity");
        ManagementObjectCollection Ports = processClass.GetInstances();           
        foreach (ManagementObject property in Ports)
        {
            var name = property.GetPropertyValue("Name");               
            if (name != null && name.ToString().Contains("USB") && name.ToString().Contains("COM"))
            {
                var portInfo = new SerialPortInfo(property);
                //Thats all information i got from port.
                //Do whatever you want with this information
            }
        }
        return string.Empty;
    }

SerialPortInfo class:

public class SerialPortInfo
{
    public SerialPortInfo(ManagementObject property)
    {
        this.Availability = property.GetPropertyValue("Availability") as int? ?? 0;
        this.Caption = property.GetPropertyValue("Caption") as string ?? string.Empty;
        this.ClassGuid = property.GetPropertyValue("ClassGuid") as string ?? string.Empty;
        this.CompatibleID = property.GetPropertyValue("CompatibleID") as string[] ?? new string[] {};
        this.ConfigManagerErrorCode = property.GetPropertyValue("ConfigManagerErrorCode") as int? ?? 0;
        this.ConfigManagerUserConfig = property.GetPropertyValue("ConfigManagerUserConfig") as bool? ?? false;
        this.CreationClassName = property.GetPropertyValue("CreationClassName") as string ?? string.Empty;
        this.Description = property.GetPropertyValue("Description") as string ?? string.Empty;
        this.DeviceID = property.GetPropertyValue("DeviceID") as string ?? string.Empty;
        this.ErrorCleared = property.GetPropertyValue("ErrorCleared") as bool? ?? false;
        this.ErrorDescription = property.GetPropertyValue("ErrorDescription") as string ?? string.Empty;
        this.HardwareID = property.GetPropertyValue("HardwareID") as string[] ?? new string[] { };
        this.InstallDate = property.GetPropertyValue("InstallDate") as DateTime? ?? DateTime.MinValue;
        this.LastErrorCode = property.GetPropertyValue("LastErrorCode") as int? ?? 0;
        this.Manufacturer = property.GetPropertyValue("Manufacturer") as string ?? string.Empty;
        this.Name = property.GetPropertyValue("Name") as string ?? string.Empty;
        this.PNPClass = property.GetPropertyValue("PNPClass") as string ?? string.Empty;
        this.PNPDeviceID = property.GetPropertyValue("PNPDeviceID") as string ?? string.Empty;
        this.PowerManagementCapabilities = property.GetPropertyValue("PowerManagementCapabilities") as int[] ?? new int[] { };
        this.PowerManagementSupported = property.GetPropertyValue("PowerManagementSupported") as bool? ?? false;
        this.Present = property.GetPropertyValue("Present") as bool? ?? false;
        this.Service = property.GetPropertyValue("Service") as string ?? string.Empty;
        this.Status = property.GetPropertyValue("Status") as string ?? string.Empty;
        this.StatusInfo = property.GetPropertyValue("StatusInfo") as int? ?? 0;
        this.SystemCreationClassName = property.GetPropertyValue("SystemCreationClassName") as string ?? string.Empty;
        this.SystemName = property.GetPropertyValue("SystemName") as string ?? string.Empty;
    }

    int Availability;
    string Caption;
    string ClassGuid;
    string[] CompatibleID;
    int ConfigManagerErrorCode;
    bool ConfigManagerUserConfig;
    string CreationClassName;
    string Description;
    string DeviceID;
    bool ErrorCleared;
    string ErrorDescription;
    string[] HardwareID;
    DateTime InstallDate;
    int LastErrorCode;
    string Manufacturer;
    string Name;
    string PNPClass;
    string PNPDeviceID;
    int[] PowerManagementCapabilities;
    bool PowerManagementSupported;
    bool Present;
    string Service;
    string Status;
    int StatusInfo;
    string SystemCreationClassName;
    string SystemName;       

}

Best practice to look up Java Enum

If you want the lookup to be case insensitive you can loop through the values making it a little more friendly:

 public enum MyEnum {
   A, B, C, D;

      public static MyEnum lookup(String id) {
        boolean found = false;
        for(MyEnum enum: values()){
           if(enum.toString().equalsIgnoreCase(id)) found = true;
        }  
        if(!found) throw new RuntimeException("Invalid value for my enum: " +id);
       }
}

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Select From all tables - MySQL

SELECT product FROM Your_table_name WHERE Product LIKE '%XYZ%';

The above statement will show result from a single table. If you want to add more tables then simply use the UNION statement.

SELECT product FROM Table_name_1 
WHERE Product LIKE '%XYZ%'  
UNION  
SELECT product FROM Table_name_2 
WHERE Product LIKE '%XYZ%'  
UNION  
SELECT product FROM Table_name_3 
WHERE Product LIKE '%XYZ%' 

... and so on

Hide div element when screen size is smaller than a specific size

I don't know about CSS but this Javascript code should work:

    function getBrowserSize(){
       var w, h;

         if(typeof window.innerWidth != 'undefined')
         {
          w = window.innerWidth; //other browsers
          h = window.innerHeight;
         } 
         else if(typeof document.documentElement != 'undefined' && typeof      document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) 
         {
          w =  document.documentElement.clientWidth; //IE
          h = document.documentElement.clientHeight;
         }
         else{
          w = document.body.clientWidth; //IE
          h = document.body.clientHeight;
         }
       return {'width':w, 'height': h};
}

if(parseInt(getBrowserSize().width) < 1026){
 document.getElementById("fadeshow1").style.display = "none";
}

What is the easiest way to parse an INI File in C++?

this question is a bit old, but I will post my answer. I have tested various INI classes (you can see them on my website) and I also use simpleIni because I want to work with INI files on both windows and winCE. Window's GetPrivateProfileString() works only with the registry on winCE.

It is very easy to read with simpleIni. Here is an example:

#include "SimpleIni\SimpleIni.h"    
CSimpleIniA ini;
ini.SetUnicode();
ini.LoadFile(FileName);
const char * pVal = ini.GetValue(section, entry, DefaultStr);

Go to beginning of line without opening new line in VI

There is another way:

|

That is the "pipe" - the symbol found under the backspace in ANSI layout.

Vim quickref (:help quickref) describes it as:

N      |      to column N (default: 1)

What about wrapped lines?

If you have wrap lines enabled, 0 and | will no longer take you to the beginning of the screen line. In that case use:

g0

Again, vim quickref doc:

 g0   to first character in screen line (differs from "0"
      when lines wrap)

Nodejs convert string into UTF-8

I'd recommend using the Buffer class:

var someEncodedString = Buffer.from('someString', 'utf-8');

This avoids any unnecessary dependencies that other answers require, since Buffer is included with node.js, and is already defined in the global scope.

Accessing Google Spreadsheets with C# using Google Data API

I wrote a simple wrapper around Google's .Net client library, it exposes a simpler database-like interface, with strongly-typed record types. Here's some sample code:

public class Entity {
    public int IntProp { get; set; }
    public string StringProp { get; set; }
}

var e1 = new Entity { IntProp = 2 };
var e2 = new Entity { StringProp = "hello" };
var client = new DatabaseClient("[email protected]", "password");
const string dbName = "IntegrationTests";
Console.WriteLine("Opening or creating database");
db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName); // databases are spreadsheets
const string tableName = "IntegrationTests";
Console.WriteLine("Opening or creating table");
table = db.GetTable<Entity>(tableName) ?? db.CreateTable<Entity>(tableName); // tables are worksheets
table.DeleteAll();
table.Add(e1);
table.Add(e2);
var r1 = table.Get(1);

There's also a LINQ provider that translates to google's structured query operators:

var q = from r in table.AsQueryable()
        where r.IntProp > -1000 && r.StringProp == "hello"
        orderby r.IntProp
        select r;

How to secure RESTful web services?

If choosing between OAuth versions, go with OAuth 2.0.

OAuth bearer tokens should only be used with a secure transport.

OAuth bearer tokens are only as secure or insecure as the transport that encrypts the conversation. HTTPS takes care of protecting against replay attacks, so it isn't necessary for the bearer token to also guard against replay.

While it is true that if someone intercepts your bearer token they can impersonate you when calling the API, there are plenty of ways to mitigate that risk. If you give your tokens a long expiration period and expect your clients to store the tokens locally, you have a greater risk of tokens being intercepted and misused than if you give your tokens a short expiration, require clients to acquire new tokens for every session, and advise clients not to persist tokens.

If you need to secure payloads that pass through multiple participants, then you need something more than HTTPS/SSL, since HTTPS/SSL only encrypts one link of the graph. This is not a fault of OAuth.

Bearer tokens are easy to for clients to obtain, easy for clients to use for API calls and are widely used (with HTTPS) to secure public facing APIs from Google, Facebook, and many other services.