Programs & Examples On #Beginreceive

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

Most likely the socket is held by some process. Use netstat -o to find which one.

Storing Images in PostgreSQL

Updating to 2012, when we see that image sizes, and number of images, are growing and growing, in all applications...

We need some distinction between "original image" and "processed image", like thumbnail.

As Jcoby's answer says, there are two options, then, I recommend:

  • use blob (Binary Large OBject): for original image store, at your table. See Ivan's answer (no problem with backing up blobs!), PostgreSQL additional supplied modules, How-tos etc.

  • use a separate database with DBlink: for original image store, at another (unified/specialized) database. In this case, I prefer bytea, but blob is near the same. Separating database is the best way for a "unified image webservice".

  • use bytea (BYTE Array): for caching thumbnail images. Cache the little images to send it fast to the web-browser (to avoiding rendering problems) and reduce server processing. Cache also essential metadata, like width and height. Database caching is the easiest way, but check your needs and server configs (ex. Apache modules): store thumbnails at file system may be better, compare performances. Remember that it is a (unified) web-service, then can be stored at a separate database (with no backups), serving many tables. See also PostgreSQL binary data types manual, tests with bytea column, etc.

NOTE1: today the use of "dual solutions" (database+filesystem) is deprecated (!). There are many advantages to using "only database" instead dual. PostgreSQL have comparable performance and good tools for export/import/input/output.

NOTE2: remember that PostgreSQL have only bytea, not have a default Oracle's BLOB: "The SQL standard defines (...) BLOB. The input format is different from bytea, but the provided functions and operators are mostly the same",Manual.


EDIT 2014: I have not changed the original text above today (my answer was Apr 22 '12, now with 14 votes), I am opening the answer for your changes (see "Wiki mode", you can edit!), for proofreading and for updates.
The question is stable (@Ivans's '08 answer with 19 votes), please, help to improve this text.

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

Just to add to the other answers, the documentation gives this explanation:

  • KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

  • A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.

  • A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY. The name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.

How to increment a JavaScript variable using a button press event

<script type="text/javascript">
var i=0;

function increase()
{
    i++;
    return false;
}</script><input type="button" onclick="increase();">

Visual Studio 2017 errors on standard headers

I upgraded VS2017 from version 15.2 to 15.8. With version 15.8 here's what happened:

Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0 no longer worked for me! I had to change it to 10.0.17134.0 and then everything built again. After the upgrade and without making this change, I was getting the same header file errors.

I would have submitted this as a comment on one of the other answers but I don't have enough reputation yet.

Saving results with headers in Sql Server Management Studio

Got here when looking for a way to make SSMS properly escape CSV separators when exporting results.

Guess what? - this is actually an option, and it is unchecked by default. So by default, you get broken CSV files (and may not even realize it, esp. if your export is large and your data doesn't have commas normally) - and you have to go in and click a checkbox so that your CSVs export correctly!

To me, this seems like a monumentally stupid design choice and an apt metaphor for Microsoft's approach to software in general ("broken by default, requires meaningless ritualistic actions to make trivial functionality work").

But I will gladly donate $100 to a charity of respondent's choice if someone can give me one valid real-life reason for this option to exist (i.e., an actual scenario where it was useful).

How to get a variable type in Typescript?

I suspect you can adjust your approach a little and use something along the lines of the example here:

https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

Tools to search for strings inside files without indexing

I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.

enter image description here

Difference between 2 dates in seconds

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

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

POST Content-Length exceeds the limit

I suggest that you should change to post_max_size from 8M to 32M in the php.ini file.

What is the meaning of the word logits in TensorFlow?

Here is a concise answer for future readers. Tensorflow's logit is defined as the output of a neuron without applying activation function:

logit = w*x + b,

x: input, w: weight, b: bias. That's it.


The following is irrelevant to this question.

For historical lectures, read other answers. Hats off to Tensorflow's "creatively" confusing naming convention. In PyTorch, there is only one CrossEntropyLoss and it accepts un-activated outputs. Convolutions, matrix multiplications and activations are same level operations. The design is much more modular and less confusing. This is one of the reasons why I switched from Tensorflow to PyTorch.

How to set up ES cluster?

I tried the steps that @KannarKK suggested on ES 2.0.2, however, I could not bring the cluster up and running. Evidently, I figured out something, as I had set tcp port number on Master, on the Slave configuration discovery.zen.ping.unicast.hosts needs Master's port number along with IP address ( tcp port number ) for discovery. So when I try following configuration it works for me.

Node 1

cluster.name: mycluster
node.name: "node1"
node.master: true
node.data: true
http.port : 9200
tcp.port : 9300
discovery.zen.ping.multicast.enabled: false
# I think unicast.host on master is redundant.
discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2

cluster.name: mycluster
node.name: "node2"
node.master: false
node.data: true
http.port : 9201
tcp.port : 9301
discovery.zen.ping.multicast.enabled: false
# The port number of Node 1
discovery.zen.ping.unicast.hosts: ["node1.example.com:9300"]

How do I increase modal width in Angular UI Bootstrap?

You can do this in very simple way using size property of angular modal.

var modal = $modal.open({
                    templateUrl: "/partials/welcome",
                    controller: "welcomeCtrl",
                    backdrop: "static",
                    scope: $scope,
                    size:'lg' // you can try different width like 'sm', 'md'
                });

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

The recent openssh version deprecated DSA keys by default. You should suggest to your GIT provider to add some reasonable host key. Relying only on DSA is not a good idea.

As a workaround, you need to tell your ssh client that you want to accept DSA host keys, as described in the official documentation for legacy usage. You have few possibilities, but I recommend to add these lines into your ~/.ssh/config file:

Host your-remote-host
    HostkeyAlgorithms +ssh-dss

Other possibility is to use environment variable GIT_SSH to specify these options:

GIT_SSH_COMMAND="ssh -oHostKeyAlgorithms=+ssh-dss" git clone ssh://user@host/path-to-repository

How does one set up the Visual Studio Code compiler/debugger to GCC?

Caution

A friendly reminder: The following tutorial is for Linux user instead of Windows

Tutorial

If you want to debug your c++ code with GDB

You can read this ( Debugging your code ) article from Visual Studio Code official website.

Step 1: Compilation

You need to set up task.json for compilation of your cpp file

or simply type in the following command in the command window

g++ -g file.cpp -o file.exe

to generate a debuggable .exe file

Step 2: Set up the launch.json file

To enable debugging, you will need to generate a launch.json file

follow the launch.json example or google others

Step 3: Press (Ctrl+F5) to start compiling

this launch.json file will launch the configuration when you press the shortcut (Ctrl+F5)

Enjoy it!

ps. For those who want to set up tasks.json, you can read this from vscode official (-> TypeScript Hello World)

How to add "Maven Managed Dependencies" library in build path eclipse?

If you imported an existing maven project and Maven dependencies are not showing in the build path in eclipse then right click on project--> Maven--> 'update Project' will resolve the issue.

MySQL match() against() - order by relevance and column?

Just adding for who might need.. Don't forget to alter the table!

ALTER TABLE table_name ADD FULLTEXT(column_name);

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Now there is official FAQ for using Google Play in How do I install Google Play Services?, here the FAQ text:

For intellectual property reasons, Google Play Services are not included by default in Genymotion virtual devices. However, if you really need them, you can use the packages provided by OpenGapps. Simply follow these steps:

  1. Visit opengapps.org
  2. Select x86 as platform
  3. Choose the Android version corresponding to your virtual device
  4. Select nano as variant
  5. Download the zip file
  6. Drag & Drop the zip installer in new Genymotion virtual device (2.7.2 and above only)
  7. Follow the pop-up instructions

Please note Genymobile Inc. and Genymotion assume no liability whatsoever resulting from the download, install and use of Google Play Services within your virtual devices. You are solely responsible for the use and assume all liability related thereto. Moreover, we disclaim any warranties of any kind for a particular purpose regarding the compatibility of the OpenGapps packages with any version of Genymotion.

Django database query: How to get object by id?

I got here for the same problem, but for a different reason:

Class.objects.get(id=1)

This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:

Class.objects.all()

Tail of the traceback for the get() method:

File "django/db/models/loading.py", line 197, in get_models
    self._populate()
File "django/db/models/loading.py", line 72, in _populate
    self.load_app(app_name, True)
File "django/db/models/loading.py", line 94, in load_app
    app_module = import_module(app_name)
File "django/utils/importlib.py", line 35, in import_module
    __import__(name)
ImportError: No module named myapp

Reading the code inside Django's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.

Here is my settings.py with the corrected path:

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    # ...
    'mywebproject.myapp',

)

All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

How to Find Item in Dictionary Collection?

It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:

class Program
{
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    static void Main(string[] args)
    {
        string strValue;

        _tags.Add("101", "C#");
        _tags.Add("102", "ASP.NET");

        if (_tags.ContainsKey("101"))
        {
            strValue = _tags["101"];
            Console.WriteLine(strValue);
        }

        if (_tags.TryGetValue("101", out strValue))
        {
            Console.WriteLine(strValue);
        }
    }
}

Is there a way to have printf() properly print out an array (of floats, say)?

To be Honest All Are good but it will be easy if or more efficient if someone use n time numbers and show them in out put.so prefer this will be a good option. Do not predefined array variable let user define and show the result. Like this..

int main()
{
    int i,j,n,t;
int arry[100];
    scanf("%d",&n);
   for (i=0;i<n;i++)
   { scanf("%d",&t);
       arry[i]=t;
   }
for(j=0;j<n;j++)
    printf("%d",arry[j]);

return 0;
}

How can I properly use a PDO object for a parameterized SELECT query

if you are using inline coding in single page and not using oops than go with this full example, it will sure help

//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw); 

//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";

//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);

//view the entire array (for testing)
print_r($result);

//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

C# guid and SQL uniqueidentifier

Store it in the database in a field with a data type of uniqueidentifier.

Hiding and Showing TabPages in tabControl

you can always hide or show the tabpage.

'in VB
myTabControl.TabPages(9).Hide() 'to hide the tabpage that has index 9
myTabControl.TabPages(9).Show() 'to show the tabpage that has index 9

Git push hangs when pushing to Github?

This occurred for me, here is how I fixed. I used Cygwin and it hanged so I tried prompting for username/password on commit :

git config --global core.askpass "git-gui--askpass"

Once I executed git push -u origin master and entered username password, it still did hang but appeared to commit to GitHub.

Used same command from dos prompt : git push -u origin master Git does not hang. So perhaps issue related to CygWin in my case.

Using the slash character in Git branch name

I could be wrong, but I thought that slashes only appeared in branch names when they related to a remote repo, for example origin/master.

How to start and stop android service from a adb shell?

am startservice <INTENT>   

or actually from the OS shell

adb shell am startservice <INTENT>

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

How to scroll table's "tbody" independent of "thead"?

try this.

table 
{
    background-color: #aaa;
}

tbody 
{
    background-color: #ddd;
    height: 100px;
    overflow-y: scroll;
    position: absolute;
}

td 
{
    padding: 3px 10px;
    color: green;
    width: 100px;
}

How can one use multi threading in PHP applications

The Thread class is available since PECL pthreads = 2.0.0.

How to insert new cell into UITableView in Swift

Here is your code for add data into both tableView:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var table1Text: UITextField!
    @IBOutlet weak var table2Text: UITextField!
    @IBOutlet weak var table1: UITableView!
    @IBOutlet weak var table2: UITableView!

    var table1Data = ["a"]
    var table2Data = ["1"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func addData(sender: AnyObject) {

        //add your data into tables array from textField
        table1Data.append(table1Text.text)
        table2Data.append(table2Text.text)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //reload your tableView
            self.table1.reloadData()
            self.table2.reloadData()
        })


        table1Text.resignFirstResponder()
        table2Text.resignFirstResponder()
    }

    //delegate methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == table1 {
            return table1Data.count
        }else if tableView == table2 {
            return table2Data.count
        }
        return Int()
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if tableView == table1 {
            let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table1Data[row]

            return cell
        }else if tableView == table2 {

            let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table2Data[row]

            return cell
        }

        return UITableViewCell()
    }
}

And your result will be:

enter image description here

How do I write a custom init for a UIView subclass in Swift?

Here is how I do a Subview on iOS in Swift -

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

I am just going to put this here. If you are looking for a compact function without using Arrays and you have no issue with mutability/immutability :

var g =x=>{/*your code goes here*/x-1>0?g(x-1):null};
 

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

Removing "http://" from a string

preg_replace('/^[^:\/?]+:\/\//','',$url); 

some results:

input: http://php.net/preg_replace output: php.net/preg_replace  input: https://www.php.net/preg_replace output: www.php.net/preg_replace  input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace  input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com 

Change a Django form field to a hidden field

For normal form you can do

class MyModelForm(forms.ModelForm):
    slug = forms.CharField(widget=forms.HiddenInput())

If you have model form you can do the following

class MyModelForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        fields = ('slug', 'ext')
        widgets = {'slug': forms.HiddenInput()}

You can also override __init__ method

class Myform(forms.Form):
    def __init__(self, *args, **kwargs):
        super(Myform, self).__init__(*args, **kwargs)
        self.fields['slug'].widget = forms.HiddenInput()

Custom format for time command

To use the Bash builtin time rather than /bin/time you can set this variable:

TIMEFORMAT='%3R'

which will output the real time that looks like this:

5.009

or

65.233

The number specifies the precision and can range from 0 to 3 (the default).

You can use:

TIMEFORMAT='%3lR'

to get output that looks like:

3m10.022s

The l (ell) gives a long format.

Reading a simple text file

try this,

package example.txtRead;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class txtRead extends Activity {
    String labels="caption";
    String text="";
    String[] s;
    private Vector<String> wordss;
    int j=0;
    private StringTokenizer tokenizer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wordss = new Vector<String>();
        TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
        helloTxt.setText(readTxt());
 }

    private String readTxt(){

     InputStream inputStream = getResources().openRawResource(R.raw.toc);
//     InputStream inputStream = getResources().openRawResource(R.raw.internals);
     System.out.println(inputStream);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

     int i;
  try {
   i = inputStream.read();
   while (i != -1)
      {
       byteArrayOutputStream.write(i);
       i = inputStream.read();
      }
      inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

     return byteArrayOutputStream.toString();
    }
}

How to find GCD, LCM on a set of numbers

There are no build in function for it. You can find the GCD of two numbers using Euclid's algorithm.

For a set of number

GCD(a_1,a_2,a_3,...,a_n) = GCD( GCD(a_1, a_2), a_3, a_4,..., a_n )

Apply it recursively.

Same for LCM:

LCM(a,b) = a * b / GCD(a,b)
LCM(a_1,a_2,a_3,...,a_n) = LCM( LCM(a_1, a_2), a_3, a_4,..., a_n )

Limit Decimal Places in Android EditText

This implementation of InputFilter solves the problem.

import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.DigitsKeyListener;

public class MoneyValueFilter extends DigitsKeyListener {
    public MoneyValueFilter() {
        super(false, true);
    }

    private int digits = 2;

    public void setDigits(int d) {
        digits = d;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {
        CharSequence out = super.filter(source, start, end, dest, dstart, dend);

        // if changed, replace the source
        if (out != null) {
            source = out;
            start = 0;
            end = out.length();
        }

        int len = end - start;

        // if deleting, source is empty
        // and deleting can't break anything
        if (len == 0) {
            return source;
        }

        int dlen = dest.length();

        // Find the position of the decimal .
        for (int i = 0; i < dstart; i++) {
            if (dest.charAt(i) == '.') {
                // being here means, that a number has
                // been inserted after the dot
                // check if the amount of digits is right
                return (dlen-(i+1) + len > digits) ? 
                    "" :
                    new SpannableStringBuilder(source, start, end);
            }
        }

        for (int i = start; i < end; ++i) {
            if (source.charAt(i) == '.') {
                // being here means, dot has been inserted
                // check if the amount of digits is right
                if ((dlen-dend) + (end-(i + 1)) > digits)
                    return "";
                else
                    break;  // return new SpannableStringBuilder(source, start, end);
            }
        }

        // if the dot is after the inserted part,
        // nothing can break
        return new SpannableStringBuilder(source, start, end);
    }
}

To use:

editCoin.setFilters(new InputFilter[] {new MoneyValueFilter(2)});

Why do I get a warning icon when I add a reference to an MEF plugin project?

I also faced the same problem but my case was a bit different the ones above. I tried to open a project created in a different computer. I found that the path to package folder is not updated when you add a reference so restarting VS, changing .NET version, or any mentioned recommendation does not solve the problem. I opened the csproj file in notepad++ and corrected all the relative paths to packages folder. Then; all the warnings are gone. Hope it helps.

What does DIM stand for in Visual Basic and BASIC?

It's short for Dimension, as it was originally used in BASIC to specify the size of arrays.

DIM — (short for dimension) define the size of arrays

Ref: http://en.wikipedia.org/wiki/Dartmouth_BASIC

A part of the original BASIC compiler source code, where it would jump when finding a DIM command, in which you can clearly see the original intention for the keyword:

DIM    LDA XR01             BACK OFF OBJECT POINTER
       SUB N3
       STA RX01
       LDA L        2       GET VARIABLE TO BE DIMENSIONED
       STA 3
       LDA S        3
       CAB N36              CHECK FOR $ ARRAY
       BRU *+7              NOT $
       ...

Ref: http://dtss.dartmouth.edu/scans/BASIC/BASIC%20Compiler.pdf

Later on it came to be used to declare all kinds of variables, when the possibility to specify the type for variables was added in more recent implementations.

Get Enum from Description attribute

rather than extension methods, just try a couple of static methods

public static class Utility
{
    public static string GetDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof (DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }

    public static T GetEnumValueFromDescription<T>(string description)
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException();
        FieldInfo[] fields = type.GetFields();
        var field = fields
                        .SelectMany(f => f.GetCustomAttributes(
                            typeof(DescriptionAttribute), false), (
                                f, a) => new { Field = f, Att = a })
                        .Where(a => ((DescriptionAttribute)a.Att)
                            .Description == description).SingleOrDefault();
        return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
    }
}

and use here

var result1 = Utility.GetDescriptionFromEnumValue(
    Animal.GiantPanda);
var result2 = Utility.GetEnumValueFromDescription<Animal>(
    "Lesser Spotted Anteater");

Making a POST call instead of GET using urllib2

The requests module may ease your pain.

url = 'http://myserver/post_service'
data = dict(name='joe', age='10')

r = requests.post(url, data=data, allow_redirects=True)
print r.content

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:

Subject: Claiming (?P...) regex syntax extensions

From: Guido van Rossum ([email protected])

Date: Dec 10, 1997 3:36:19 pm

I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.

You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)

As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:

(?P<foo>...) Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".

(?P=foo) Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.

I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)

to which Larry Wall replied:

[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)

Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]

So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.

In Go's http package, how do I get the query string on a POST request?

A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL (doc). The URL object has a Query() method (doc) that returns a Values type, which is simply a map[string][]string of the QueryString parameters.

If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm() and then use req.Form field to get the map of key-value pairs, but you can also call FormValue(key) to get the value of a specific key. This calls ParseForm() if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).

Simple regular expression for a decimal with a precision of 2

Main answer is WRONG because it valids 5. or 5, inputs

this code handle it (but in my example negative numbers are forbidden):

/^[0-9]+([.,][0-9]{1,2})?$/;

results are bellow:

true => "0" / true => "0.00" / true => "0.0" / true => "0,00" / true => "0,0" / true => "1,2" true => "1.1"/ true => "1" / true => "100" true => "100.00"/ true => "100.0" / true => "1.11" / true => "1,11"/ false => "-5" / false => "-0.00" / true => "101" / false => "0.00.0" / true => "0.000" / true => "000.25" / false => ".25" / true => "100.01" / true => "100.2" / true => "00" / false => "5." / false => "6," / true => "82" / true => "81,3" / true => "7" / true => "7.654"

How to convert "0" and "1" to false and true

Or if the Boolean value is not been returned, you can do something like this:

bool boolValue = (returnValue == "1");

Get filename and path from URI from mediastore

This works for me perfectly if your system version is above 19, Hope this can help you.

  @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {
        final boolean isOverKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isOverKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

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

CMake 3.X

CMake 3.X offers a 'clean' target.

cmake --build C:/foo/build/ --target clean

From the CMake docs for 3.0.2:

--clean-first  = Build target 'clean' first, then build.
                 (To clean only, use --target 'clean'.)

CMake 2.X

There is no cmake clean in CMake version 2.X

I usually build the project in a single folder like "build". So if I want to make clean, I can just rm -rf build.

The "build" folder in the same directory as the root "CMakeLists.txt" is usually a good choice. To build your project, you simply give cmake the location of the CMakeLists.txt as an argument. For example: cd <location-of-cmakelists>/build && cmake ... (From @ComicSansMS)

How do I open an .exe from another C++ .exe?

Try this:

#include <windows.h>

int main ()

{
    system ("start notepad.exe") // As an example. Change [notepad] to any executable file //

    return 0 ;
}

JavaFX "Location is required." even though it is in the same package

In my case all of the above were not the problem at all.

My problem was solved when I replaced :

getClass().getResource("ui_layout.fxml")

with :

getClass().getClassLoader().getResource("ui_layout.fxml")

How to implement onBackPressed() in Fragments?

Here is my solution for that issue:

in Activity A:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE)
    {
        if(resultCode == Activity.RESULT_OK)
        {
            tvTitle.setText(data.getExtras().getString("title", ""));
        }
    }
}

in Activity B:

@Override
public void onBackPressed() 
{
    setResult(Activity.RESULT_OK, getIntent());

    super.onBackPressed();
}

activity b holds the fragment.

in fragment:

private void setText(String text)
    {
        Intent intent = new Intent();
        intent.putExtra("title", text);
        getActivity().setIntent(intent);
    }

in that way the Intent Object "data" in activity A will get the string from the fragment

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

Callback functions in C++

Boost's signals2 allows you to subscribe generic member functions (without templates!) and in a threadsafe way.

Example: Document-View Signals can be used to implement flexible Document-View architectures. The document will contain a signal to which each of the views can connect. The following Document class defines a simple text document that supports mulitple views. Note that it stores a single signal to which all of the views will be connected.

class Document
{
public:
    typedef boost::signals2::signal<void ()>  signal_t;

public:
    Document()
    {}

    /* Connect a slot to the signal which will be emitted whenever
      text is appended to the document. */
    boost::signals2::connection connect(const signal_t::slot_type &subscriber)
    {
        return m_sig.connect(subscriber);
    }

    void append(const char* s)
    {
        m_text += s;
        m_sig();
    }

    const std::string& getText() const
    {
        return m_text;
    }

private:
    signal_t    m_sig;
    std::string m_text;
};

Next, we can begin to define views. The following TextView class provides a simple view of the document text.

class TextView
{
public:
    TextView(Document& doc): m_document(doc)
    {
        m_connection = m_document.connect(boost::bind(&TextView::refresh, this));
    }

    ~TextView()
    {
        m_connection.disconnect();
    }

    void refresh() const
    {
        std::cout << "TextView: " << m_document.getText() << std::endl;
    }
private:
    Document&               m_document;
    boost::signals2::connection  m_connection;
};

Read response headers from API response - Angular 5 + TypeScript

Have you exposed the X-Token from server side using access-control-expose-headers? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side

Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'} like

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

Merge a Branch into Trunk

Do an svn update in the trunk, note the revision number.

From the trunk:

svn merge -r<revision where branch was cut>:<revision of trunk> svn://path/to/branch/branchName

You can check where the branch was cut from the trunk by doing an svn log

svn log --stop-on-copy

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

The fillOval fits an oval inside a rectangle, with width=r, height = r you get a circle. If you want fillOval(x,y,r,r) to draw a circle with the center at (x,y) you will have to displace the rectangle by half its width and half its height.

public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
  x = x-(r/2);
  y = y-(r/2);
  g.fillOval(x,y,r,r);
}

This will draw a circle with center at x,y

Correct way to write line to file?

One can also use the io module as in:

import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)

Clear text from textarea with selenium

It is general syntax

driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();

OwinStartup not firing

In my case, my web.config had

<authorization>
  <allow users="?" />
</authorization>

To force it to fall back to Owin, I needed it to be

<authorization>
  <deny users="*" />
</authorization>

Bootstrap 3 Align Text To Bottom of Div

Here's another solution: http://jsfiddle.net/6WvUY/7/.

HTML:

<div class="container">
    <div class="row">
        <div class="col-sm-6">
            <img src="//placehold.it/600x300" alt="Logo" class="img-responsive"/>
        </div>
        <div class="col-sm-6">
            <h3>Some Text</h3>
        </div>
    </div>
</div>

CSS:

.row {
    display: table;
}

.row > div {
    float: none;
    display: table-cell;
}

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

Oracle select most recent date record

you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)

also you cannot use OVER clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from docs.oracle.com)

select *
from (select
  staff_id, site_id, pay_level, date, 
  max(date) over (partition by staff_id) max_date
  from owner.table
  where end_enrollment_date is null
)
where date = max_date

Setup a Git server with msysgit on Windows

I just wanted to add my experiences with the PATH setup that Steve and timc mentions above: I got permission problems using shell tools (like mv and cp) having Git's shell executables first in the path.

Appending them after the existing PATH instead this solved my problems. Example:

GITPATH='/cygdrive/c/Program Files (x86)/Git/bin' GITCOREPATH='/cygdrive/c/Program Files (x86)/Git/libexec/git-core' PATH=${PATH}:${GITPATH}:${GITCOREPATH}

I guess CopSSH doesn't go along well with all of msysgit's shell executables...

What is the best way to add a value to an array in state

If you are using ES6 syntax you can use the spread operator to add new items to an existing array as a one liner.

// Append an array
const newArr = [1,2,3,4]
this.setState(prevState => ({
  arr: [...prevState.arr, ...newArr]
}));

// Append a single item
this.setState(prevState => ({
  arr: [...prevState.arr, 'new item']
}));

Convert string to decimal, keeping fractions

Hello i was have the same issue, but it is easly, just do this:

string cadena="96.23";

decimal NoDecimal=decimal.parse(cadena.replace(".",","))

I think this is beacuse the notation that accept C# on decimal numbers are with a ","

Use Fieldset Legend with bootstrap

That's because Bootstrap by default sets the width of the legend element to 100%. You can fix this by changing your legend.scheduler-border to also use:

legend.scheduler-border {
    width:inherit; /* Or auto */
    padding:0 10px; /* To give a bit of padding on the left and right */
    border-bottom:none;
}

JSFiddle example.

You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.

You may also want to add margin-bottom:0; to it as well to reduce the gap between the legend and the divider.

How to Display blob (.pdf) in an AngularJS app

Most recent answer (for Angular 8+):

this.http.post("your-url",params,{responseType:'arraybuffer' as 'json'}).subscribe(
  (res) => {
    this.showpdf(res);
  }
)};

public Content:SafeResourceUrl;
showpdf(response:ArrayBuffer) {
  var file = new Blob([response], {type: 'application/pdf'});
  var fileURL = URL.createObjectURL(file);
  this.Content = this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
}

  HTML :

  <embed [src]="Content" style="width:200px;height:200px;" type="application/pdf" />

Trim Cells using VBA in Excel

Only thing that worked for me is this function:

Sub DoTrim()
Dim cell As Range
Dim str As String
For Each cell In Selection.Cells
    If cell.HasFormula = False Then
        str = Left(cell.Value, 1) 'space
        While str = " " Or str = Chr(160)
            cell.Value = Right(cell.Value, Len(cell.Value) - 1)
            str = Left(cell.Value, 1) 'space
        Wend
        str = Right(cell.Value, 1) 'space
        While str = " " Or str = Chr(160)
            cell.Value = Left(cell.Value, Len(cell.Value) - 1)
            str = Right(cell.Value, 1) 'space
        Wend
    End If
Next cell
End Sub

ReferenceError: $ is not defined

Add jQuery library before your script which uses $ or jQuery so that $ can be identified in scripts.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

Where can I get Google developer key

in https://code.google.com/apis/console/ , in SERVICES, turn on YOUTUBE API, then click API ACCESS in the left menu.

Sending mass email using PHP

You may consider using CRON for that kind of operation. Sending mass mail at once is certainly not good, it may be detected as spam, ddos, crash your server etc.

So CRON could be a great solution, send 100 mails at once, then wait a few minutes, next 100, etc.

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

As every developer have a common habit, not to read the complete error, just read the first line and start looking for answer from someone else :):) I am also one of them, that's why I am here:

Read the error, clearly saying:

Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

What more we need to understand this error?

Use any one option everything will work smooth.

How to use JavaScript regex over multiple lines?

You do not specify your environment and version of Javascript (ECMAscript), and I realise this post was from 2009, but just for completeness, with the release of ECMA2018 we can now use the s flag to cause . to match '\n', see https://stackoverflow.com/a/36006948/141801

Thus:

let s = 'I am a string\nover several\nlines.';
console.log('String: "' + s + '".');

let r = /string.*several.*lines/s; // Note 's' modifier
console.log('Match? ' + r.test(s); // 'test' returns true

This is a recent addition and will not work in many current environments, for example Node v8.7.0 does not seem to recognise it, but it works in Chromium, and I'm using it in a Typescript test I'm writing and presumably it will become more mainstream as time goes by.

How do you make a deep copy of an object?

BeanUtils does a really good job deep cloning beans.

BeanUtils.cloneBean(obj);

jQuery - Click event on <tr> elements with in a table and getting <td> element values

$(this).find('td') will give you an array of td's in the tr.

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

There are only 3 joins:

  • A) Cross Join = Cartesian (E.g: Table A, Table B)
  • B) Inner Join = JOIN (E.g: Table A Join/Inner Join Table B)
  • C) Outer join:

       There are three type of outer join
       1)  Left Outer Join     = Left Join
       2)  Right Outer Join    = Right Join
       3)  Full Outer Join     = Full Join    
    

Hope it'd help.

How do I split a string on a delimiter in Bash?

Taken from Bash shell script split array:

IN="[email protected];[email protected]"
arrIN=(${IN//;/ })
echo ${arrIN[1]}                  # Output: [email protected]

Explanation:

This construction replaces all occurrences of ';' (the initial // means global replace) in the string IN with ' ' (a single space), then interprets the space-delimited string as an array (that's what the surrounding parentheses do).

The syntax used inside of the curly braces to replace each ';' character with a ' ' character is called Parameter Expansion.

There are some common gotchas:

  1. If the original string has spaces, you will need to use IFS:
  • IFS=':'; arrIN=($IN); unset IFS;
  1. If the original string has spaces and the delimiter is a new line, you can set IFS with:
  • IFS=$'\n'; arrIN=($IN); unset IFS;

Is it possible to compile a program written in Python?

You dont have to compile it. the first you use it (import) it is compiled by the CPython interpreter. But if you really want to compile there are several options.

To compile to exe

Or 2 compile just a specific *.py file, you can just use

import py_compile
py_compile.compile("yourpythoncode.py")

Android: how to convert whole ImageView to Bitmap?

You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.

just make sure it built.

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();

there's your bitmap as the screen saw it.

How to store Emoji Character in MySQL Database

If you use command line interface for inserting sql file to database.

Be sure your table charset utf8mb4 and column collation utf8mb4_unicode_ci or utf8mb4_bin

mysql -u root -p123456 my_database < profiles.sql

ERROR 1366 (HY000) at line 1679: Incorrect string value: '\xF0\x9F\x98\x87\xF0\x9F...' for column 'note' at row 328

we can solve the problem with this parameter --default-character-set=name (Set the default character set)

mysql -u root -p123456 --default-character-set=utf8mb4 my_database < profiles.sql

JavaScript checking for null vs. undefined and difference between == and ===

Ad 1. null is not an identifier for a property of the global object, like undefined can be

_x000D_
_x000D_
let x;      // undefined_x000D_
let y=null; // null_x000D_
let z=3;    // has value_x000D_
// 'w'      // is undeclared_x000D_
_x000D_
if(!x) console.log('x is null or undefined');_x000D_
if(!y) console.log('y is null or undefined');_x000D_
if(!z) console.log('z is null or undefined');_x000D_
_x000D_
try { if(w) 0 } catch(e) { console.log('w is undeclared') }_x000D_
// typeof not throw exception for undelared variabels_x000D_
if(typeof w === 'undefined') console.log('w is undefined');
_x000D_
_x000D_
_x000D_

Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

If you are a Windows user, Tweepy API can generate an empty line between data objects. Because of this situation, you can get "JSONDecodeError: Expecting value: line 1 column 1 (char 0)" error. To avoid this error, you can delete empty lines.

For example:

 def on_data(self, data):
        try:
            with open('sentiment.json', 'a', newline='\n') as f:
                f.write(data)
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True

Reference: Twitter stream API gives JSONDecodeError("Expecting value", s, err.value) from None

How to get the selected index of a RadioGroup in Android

try this

        RadioGroup  group= (RadioGroup) getView().findViewById(R.id.radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                View radioButton = radioGroup.findViewById(i);
                int index = radioGroup.indexOfChild(radioButton);
            }
        });

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

There is slight change in mysql_real_escape_string mysqli_real_escape_string. below syntax

mysql_real_escape_string syntax will be mysql_real_escape_string($_POST['sample_var'])

mysqli_real_escape_string syntax will be mysqli_real_escape_string($conn,$_POST['sample_var'])

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Using Thread.sleep(2000); is an unconditional wait. If your test loads faster you will still have to wait. So in principle using implicitlyWait is the better solution.

However, I don't see why implicitlyWait does not work in your case. Did you measure if the findElement actually takes two seconds before throwing an exception. If so, can you try to use WebDriver's conditional wait as described in this answer?

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Try this:

    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
    {
        // comboBox1 is readonly
        e.SuppressKeyPress = true;
    }

LINQ Contains Case Insensitive

Honestly, this doesn't need to be difficult. It may seem that on the onset, but it's not. Here's a simple linq query in C# that does exactly as requested.

In my example, I'm working against a list of persons that have one property called FirstName.

var results = ClientsRepository().Where(c => c.FirstName.ToLower().Contains(searchText.ToLower())).ToList();

This will search the database on lower case search but return full case results.

How to add a line break within echo in PHP?

You may want to try \r\n for carriage return / line feed

Manually map column names with class properties

Before you open the connection to your database, execute this piece of code for each of your poco classes:

// Section
SqlMapper.SetTypeMap(typeof(Section), new CustomPropertyTypeMap(
    typeof(Section), (type, columnName) => type.GetProperties().FirstOrDefault(prop =>
    prop.GetCustomAttributes(false).OfType<ColumnAttribute>().Any(attr => attr.Name == columnName))));

Then add the data annotations to your poco classes like this:

public class Section
{
    [Column("db_column_name1")] // Side note: if you create aliases, then they would match this.
    public int Id { get; set; }
    [Column("db_column_name2")]
    public string Title { get; set; }
}

After that, you are all set. Just make a query call, something like:

using (var sqlConnection = new SqlConnection("your_connection_string"))
{
    var sqlStatement = "SELECT " +
                "db_column_name1, " +
                "db_column_name2 " +
                "FROM your_table";

    return sqlConnection.Query<Section>(sqlStatement).AsList();
}

How to list the tables in a SQLite database file that was opened with ATTACH?

It appears you need to go through the sqlite_master table, like this:

SELECT * FROM dbname.sqlite_master WHERE type='table';

And then manually go through each table with a SELECT or similar to look at the rows.

The .DUMP and .SCHEMA commands doesn't appear to see the database at all.

CORS header 'Access-Control-Allow-Origin' missing

You have to modify your server side code, as given below

public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set

If you wanted to get the username, you would do:

Environ("username")

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")

References

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

How to create nested directories using Mkdir in Golang?

An utility method like the following can be used to solve this.

import (
  "os"
  "path/filepath"
  "log"
)

func ensureDir(fileName string) {
  dirName := filepath.Dir(fileName)
  if _, serr := os.Stat(dirName); serr != nil {
    merr := os.MkdirAll(dirName, os.ModePerm)
    if merr != nil {
        panic(merr)
    }
  }
}



func main() {
  _, cerr := os.Create("a/b/c/d.txt")
  if cerr != nil {
    log.Fatal("error creating a/b/c", cerr)
  }
  log.Println("created file in a sub-directory.")
}

How to access the elements of a function's return array?

here is the best way in a similar function

 function cart_stats($cart_id){

$sql = "select sum(price) sum_bids, count(*) total_bids from carts_bids where cart_id = '$cart_id'";
$rs = mysql_query($sql);
$row = mysql_fetch_object($rs);
$total_bids = $row->total_bids;
$sum_bids = $row->sum_bids;
$avarage = $sum_bids/$total_bids;

 $array["total_bids"] = "$total_bids";
 $array["avarage"] = " $avarage";

 return $array;
}  

and you get the array data like this

$data = cart_stats($_GET['id']); 
<?=$data['total_bids']?>

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

Missing Push Notification Entitlement

In XCode 8 you need to enable push in the Capabilities tab on your target, on top of enabling everything on the provisions and certificates: Xcode 8 "the aps-environment entitlement is missing from the app's signature" on submit

My blog post about this here.

CMD what does /im (taskkill)?

If you type the executable name and a /? switch at the command line, there is typically help information available. Doing so with taskkill /? provides the following, for instance:

TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]

Description:
    This tool is used to terminate tasks by process id (PID) or image name.

Parameter List:
    /S    system           Specifies the remote system to connect to.

    /U    [domain\]user    Specifies the user context under which the
                           command should execute.

    /P    [password]       Specifies the password for the given user
                           context. Prompts for input if omitted.

    /FI   filter           Applies a filter to select a set of tasks.
                           Allows "*" to be used. ex. imagename eq acme*

    /PID  processid        Specifies the PID of the process to be terminated.
                           Use TaskList to get the PID.

    /IM   imagename        Specifies the image name of the process
                           to be terminated. Wildcard '*' can be used
                           to specify all tasks or image names.

    /T                     Terminates the specified process and any
                           child processes which were started by it.

    /F                     Specifies to forcefully terminate the process(es).

    /?                     Displays this help message.

Filters:
    Filter Name   Valid Operators           Valid Value(s)
    -----------   ---------------           -------------------------
    STATUS        eq, ne                    RUNNING |
                                            NOT RESPONDING | UNKNOWN
    IMAGENAME     eq, ne                    Image name
    PID           eq, ne, gt, lt, ge, le    PID value
    SESSION       eq, ne, gt, lt, ge, le    Session number.
    CPUTIME       eq, ne, gt, lt, ge, le    CPU time in the format
                                            of hh:mm:ss.
                                            hh - hours,
                                            mm - minutes, ss - seconds
    MEMUSAGE      eq, ne, gt, lt, ge, le    Memory usage in KB
    USERNAME      eq, ne                    User name in [domain\]user
                                            format
    MODULES       eq, ne                    DLL name
    SERVICES      eq, ne                    Service name
    WINDOWTITLE   eq, ne                    Window title

    NOTE
    ----
    1) Wildcard '*' for /IM switch is accepted only when a filter is applied.
    2) Termination of remote processes will always be done forcefully (/F).
    3) "WINDOWTITLE" and "STATUS" filters are not considered when a remote
       machine is specified.

Examples:
    TASKKILL /IM notepad.exe
    TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
    TASKKILL /F /IM cmd.exe /T 
    TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
    TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
    TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
    TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"

You can also find this information, as well as documentation for most of the other command-line utilities, in the Microsoft TechNet Command-Line Reference

pass post data with window.location.href

Short answer: no. window.location.href is not capable of passing POST data.

Somewhat more satisfying answer: You can use this function to clone all your form data and submit it.

var submitMe = document.createElement("form");
submitMe.action = "YOUR_URL_HERE"; // Remember to change me
submitMe.method = "post";
submitMe.enctype = "multipart/form-data";
var nameJoiner = "_";
// ^ The string used to join form name and input name
//   so that you can differentiate between forms when
//   processing the data server-side.
submitMe.importFields = function(form){
    for(k in form.elements){
        if(input = form.elements[k]){
            if(input.type!="submit"&&
                     (input.nodeName=="INPUT"
                    ||input.nodeName=="TEXTAREA"
                    ||input.nodeName=="BUTTON"
                    ||input.nodeName=="SELECT")
                     ){
                var output = input.cloneNode(true);
                output.name = form.name + nameJoiner + input.name;
                this.appendChild(output);
            }
        }
    }
}
  • Do submitMe.importFields(form_element); for each of the three forms you want to submit.
  • This function will add each form's name to the names of its child inputs (If you have an <input name="email"> in <form name="login">, the submitted name will be login_name.
  • You can change the nameJoiner variable to something other than _ so it doesn't conflict with your input naming scheme.
  • Once you've imported all the necessary forms, do submitMe.submit();

Android Material and appcompat Manifest merger failed

  1. Please go to Refactor->Migrate->Migrate to Android X.

  2. Please add this to your gradle.properties file:

    android.enableJetifier=true
    android.useAndroidX=true
    

And perform Sync.

Disabling Strict Standards in PHP 5.4

As the commenters have stated the best option is to fix the errors, but with limited time or knowledge, that's not always possible. In your php.ini change

error_reporting = E_ALL

to

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

If you don't have access to the php.ini, you can potentially put this in your .htaccess file:

php_value error_reporting 30711

This is the E_ALL value (32767) and the removing the E_STRICT (2048) and E_NOTICE (8) values.

If you don't have access to the .htaccess file or it's not enabled, you'll probably need to put this at the top of the PHP section of any script that gets loaded from a browser call:

error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);

One of those should help you be able to use the software. The notices and strict stuff are indicators of problems or potential problems though and you may find some of the code is not working correctly in PHP 5.4.

How does `scp` differ from `rsync`?

The major difference between these tools is how they copy files.

scp basically reads the source file and writes it to the destination. It performs a plain linear copy, locally, or over a network.

rsync also copies files locally or over a network. But it employs a special delta transfer algorithm and a few optimizations to make the operation a lot faster. Consider the call.

rsync A host:B
  • rsync will check files sizes and modification timestamps of both A and B, and skip any further processing if they match.

  • If the destination file B already exists, the delta transfer algorithm will make sure only differences between A and B are sent over the wire.

  • rsync will write data to a temporary file T, and then replace the destination file B with T to make the update look "atomic" to processes that might be using B.

Another difference between them concerns invocation. rsync has a plethora of command line options, allowing the user to fine tune its behavior. It supports complex filter rules, runs in batch mode, daemon mode, etc. scp has only a few switches.

In summary, use scp for your day to day tasks. Commands that you type once in a while on your interactive shell. It's simpler to use, and in those cases rsync optimizations won't help much.

For recurring tasks, like cron jobs, use rsync. As mentioned, on multiple invocations it will take advantage of data already transferred, performing very quickly and saving on resources. It is an excellent tool to keep two directories synchronized over a network.

Also, when dealing with large files, use rsync with the -P option. If the transfer is interrupted, you can resume it where it stopped by reissuing the command. See Sid Kshatriya's answer.

Favicon dimensions?

favicon.ico is 16x16

<link rel="shortcut icon" href="favicon.ico"/>

And I use these ones to be beautiful in mobile and tablet:

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="img/ico144.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/ico114.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/ico72.png">
<link rel="apple-touch-icon-precomposed" href="img/ico57.png">

It's important to use the name "favicon.ico" in the root because many browsers will try to find there first.

Django: Display Choice Value

For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

In Views

person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()

In Template

{{ person.get_gender_display }}

Documentation of get_FOO_display()

Showing an image from an array of images - Javascript

Here's your problem:

if(imgArray[i] == img)

You're comparing an array element to a DOM object.

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

There is way to do that ;)

Thanks to "http://it.toolbox.com/wiki/index.php/Use_curl_from_PHP_-_processing_response_headers":

<?php

    /**
     * Facebook user photo downloader
     */

    class sfFacebookPhoto {

        private $useragent = 'Loximi sfFacebookPhoto PHP5 (cURL)';
        private $curl = null;
        private $response_meta_info = array();
        private $header = array(
                "Accept-Encoding: gzip,deflate",
                "Accept-Charset: utf-8;q=0.7,*;q=0.7",
                "Connection: close"
            );

        public function __construct() {
            $this->curl = curl_init();
            register_shutdown_function(array($this, 'shutdown'));
        }

        /**
         * Get the real URL for the picture to use after
         */
        public function getRealUrl($photoLink) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, false);
            curl_setopt($this->curl, CURLOPT_HEADER, false);
            curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
            curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->curl, CURLOPT_URL, $photoLink);

            //This assumes your code is into a class method, and
            //uses $this->readHeader as the callback function.
            curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, array(&$this, 'readHeader'));
            $response = curl_exec($this->curl);
            if (!curl_errno($this->curl)) {
                $info = curl_getinfo($this->curl);
                var_dump($info);
                if ($info["http_code"] == 302) {
                    $headers = $this->getHeaders();
                    if (isset($headers['fileUrl'])) {
                        return $headers['fileUrl'];
                    }
                }
            }
            return false;
        }


        /**
         * Download Facebook user photo
         *
         */
        public function download($fileName) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($this->curl, CURLOPT_HEADER, false);
            curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
            curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->curl, CURLOPT_URL, $fileName);
            $response = curl_exec($this->curl);
            $return = false;
            if (!curl_errno($this->curl)) {
                $parts = explode('.', $fileName);
                $ext = array_pop($parts);
                $return = sfConfig::get('sf_upload_dir') . '/tmp/' . uniqid('fbphoto') . '.' . $ext;
                file_put_contents($return, $response);
            }
            return $return;
        }

        /**
         * cURL callback function for reading and processing headers.
         * Override this for your needs.
         *
         * @param object $ch
         * @param string $header
         * @return integer
         */
        private function readHeader($ch, $header) {

            //Extracting example data: filename from header field Content-Disposition
            $filename = $this->extractCustomHeader('Location: ', '\n', $header);
            if ($filename) {
                $this->response_meta_info['fileUrl'] = trim($filename);
            }
            return strlen($header);
        }

        private function extractCustomHeader($start, $end, $header) {
            $pattern = '/'. $start .'(.*?)'. $end .'/';
            if (preg_match($pattern, $header, $result)) {
                return $result[1];
            }
            else {
                return false;
            }
        }

        public function getHeaders() {
            return $this->response_meta_info;
        }

        /**
         * Cleanup resources
         */
        public function shutdown() {
            if($this->curl) {
                curl_close($this->curl);
            }
        }
    }

How can I auto increment the C# assembly version via our CI platform (Hudson)?

Here's what I did, for stamping the AssemblyFileVersion attribute.

Removed the AssemblyFileVersion from AssemblyInfo.cs

Add a new, empty, file called AssemblyFileInfo.cs to the project.

Install the MSBuild community tasks toolset on the hudson build machine or as a NuGet dependency in your project.

Edit the project (csproj) file , it's just an msbuild file, and add the following.

Somewhere there'll be a <PropertyGroup> stating the version. Change that so it reads e.g.

 <Major>1</Major>
 <Minor>0</Minor>
 <!--Hudson sets BUILD_NUMBER and SVN_REVISION -->
 <Build>$(BUILD_NUMBER)</Build>
 <Revision>$(SVN_REVISION)</Revision>

Hudson provides those env variables you see there when the project is built on hudson (assuming it's fetched from subversion).

At the bottom of the project file, add

 <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')" />
  <Target Name="BeforeBuild" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')">
    <Message Text="Version: $(Major).$(Minor).$(Build).$(Revision)" />
    <AssemblyInfo CodeLanguage="CS" OutputFile="AssemblyFileInfo.cs" AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" AssemblyConfiguration="$(Configuration)" Condition="$(Revision) != '' " />
  </Target>

This uses the MSBuildCommunityTasks to generate the AssemblyFileVersion.cs to include an AssemblyFileVersion attribute before the project is built. You could do this for any/all of the version attributes if you want.

The result is, whenever you issue a hudson build, the resulting assembly gets an AssemblyFileVersion of 1.0.HUDSON_BUILD_NR.SVN_REVISION e.g. 1.0.6.2632 , which means the 6'th build # in hudson, buit from the subversion revision 2632.

How to write dynamic variable in Ansible playbook

I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

   vars:
    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"

PHP substring extraction. Get the string before the first '/' or the whole string

why not use:

function getwhatiwant($s)
{
    $delimiter='/';
    $x=strstr($s,$delimiter,true);
    return ($x?$x:$s);
}

OR:

   function getwhatiwant($s)
   {
       $delimiter='/';
       $t=explode($delimiter, $s);
       return ($t[1]?$t[0]:$s);
   }

Calculate the number of business days between two dates?

Here is an approach if you are using MVC. I have also calculated national holidays or any festive days to be excluded by fetching it from holidayscalendar which you will need to make one.

        foreach (DateTime day in EachDay(model))
        {
            bool key = false;
            foreach (LeaveModel ln in holidaycalendar)
            {
                if (day.Date == ln.Date && day.DayOfWeek != DayOfWeek.Saturday && day.DayOfWeek != DayOfWeek.Sunday)
                {
                    key = true; break;
                }
            }
            if (day.DayOfWeek == DayOfWeek.Saturday || day.DayOfWeek == DayOfWeek.Sunday)
            {
                key = true;
            }
            if (key != true)
            {
                leavecount++;
            }
        }

Leavemodel is a list here

String concatenation in MySQL

Use concat() function instead of + like this:

select concat(firstname, lastname) as "Name" from test.student

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.

Meaning of "487 Request Terminated"

It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).

Here is a nice CANCEL SIP Call Flow illustration.

How can I find an element by CSS class with XPath?

Most easy way..

//div[@class="Test"]

Assuming you want to find <div class="Test"> as described.

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

This totally worked:

gem install --http-proxy http://COMPANY.PROXY.ADDRESS $gem_name

Android intent for playing video?

following code works just fine for me.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(movieurl));
startActivity(intent);

How to enable directory listing in apache web server

This one solved my issue which is SELinux setting:

chcon -R -t httpd_sys_content_t /home/*

When to use margin vs padding in CSS

I always use this principle:

box model image

This is the box model from the inspect element feature in Firefox. It works like an onion:

  • Your content is in the middle.
  • Padding is space between your content and edge of the tag it is inside.
  • The border and its specifications
  • The margin is the space around the tag.

So bigger margins will make more space around the box that contains your content.

Larger padding will increase the space between your content and the box of which it is inside.

Neither of them will increase or decrease the size of the box if it is set to a specific value.

vertical & horizontal lines in matplotlib

The pyplot functions you are calling, axhline() and axvline() draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin or ymin use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.

Instead, use plt.plot((x1, x2), (y1, y2), 'k-') to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot.

GCC -fPIC option

I'll try to explain what has already been said in a simpler way.

Whenever a shared lib is loaded, the loader (the code on the OS which load any program you run) changes some addresses in the code depending on where the object was loaded to.

In the above example, the "111" in the non-PIC code is written by the loader the first time it was loaded.

For not shared objects, you may want it to be like that because the compiler can make some optimizations on that code.

For shared object, if another process will want to "link" to that code he must read it to the same virtual addresses or the "111" will make no sense. but that virtual-space may already be in use in the second process.

Eclipse does not start when I run the exe?

If eclipse (none of them) doesn't launch at all and there's not even an error message, uninstall Java 8 Updater and reinstall Java 8 from scratch, this should work. Have luck!

Generate a UUID on iOS from Swift

You could also just use the NSUUID API:

let uuid = NSUUID()

If you want to get the string value back out, you can use uuid.UUIDString.

Note that NSUUID is available from iOS 6 and up.

How do I filter ForeignKey choices in a Django ModelForm?

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.

So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.

form.rate.queryset = Rate.objects.filter(company_id=the_company.id)

If you take the default ModelForm object, form.fields["rate"].queryset = ...

This is done explicitly in the view. No hacking around.

How do I do a case-insensitive string comparison?

This is another regex which I have learned to love/hate over the last week so usually import as (in this case yes) something that reflects how im feeling! make a normal function.... ask for input, then use ....something = re.compile(r'foo*|spam*', yes.I)...... re.I (yes.I below) is the same as IGNORECASE but you cant make as many mistakes writing it!

You then search your message using regex's but honestly that should be a few pages in its own , but the point is that foo or spam are piped together and case is ignored. Then if either are found then lost_n_found would display one of them. if neither then lost_n_found is equal to None. If its not equal to none return the user_input in lower case using "return lost_n_found.lower()"

This allows you to much more easily match up anything thats going to be case sensitive. Lastly (NCS) stands for "no one cares seriously...!" or not case sensitive....whichever

if anyone has any questions get me on this..

    import re as yes

    def bar_or_spam():

        message = raw_input("\nEnter FoO for BaR or SpaM for EgGs (NCS): ") 

        message_in_coconut = yes.compile(r'foo*|spam*',  yes.I)

        lost_n_found = message_in_coconut.search(message).group()

        if lost_n_found != None:
            return lost_n_found.lower()
        else:
            print ("Make tea not love")
            return

    whatz_for_breakfast = bar_or_spam()

    if whatz_for_breakfast == foo:
        print ("BaR")

    elif whatz_for_breakfast == spam:
        print ("EgGs")

How to delete from multiple tables in MySQL?

Use this

DELETE FROM `articles`, `comments` 
USING `articles`,`comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

or

DELETE `articles`, `comments` 
FROM `articles`, `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

numpy.where() detailed, step-by-step explanation / examples

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

Convert to/from DateTime and Time in Ruby

While making such conversions one should take into consideration the behavior of timezones while converting from one object to the other. I found some good notes and examples in this stackoverflow post.

How to margin the body of the page (html)?

For start you can use:

<body style="margin:0;padding:0">

Once you study a bit about css, you can change it to:

body {margin:0;padding:0}

in your stylesheet.

Assign variable value inside if-statement

Variables can be assigned but not declared inside the conditional statement:

int v;
if((v = someMethod()) != 0) return true;

Matplotlib: "Unknown projection '3d'" error

Import mplot3d whole to use "projection = '3d'".

Insert the command below in top of your script. It should run fine.

from mpl_toolkits import mplot3d

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

Well the first option I could think of is that you could send a list request with search parameters for your file, like title="File_1.xml" and fileExtension="xml". It will either return an empty list of files (there isn't one matching the serach criteria), or return a list with at least one file. If it's only one - it's easy. But if there are more - you'll have to select one of them based on some other fields. Remember that in gdrive you could have more than 1 file with the same name. So the more search parameters you provide, the better.

How do you get a directory listing in C?

I've created an open source (BSD) C header that deals with this problem. It currently supports POSIX and Windows. Please check it out:

https://github.com/cxong/tinydir

tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");

while (dir.has_next)
{
    tinydir_file file;
    tinydir_readfile(&dir, &file);

    printf("%s", file.name);
    if (file.is_dir)
    {
        printf("/");
    }
    printf("\n");

    tinydir_next(&dir);
}

tinydir_close(&dir);

How to change an input button image using CSS?

Here is what worked for me on Internet Explorer, a slight modification to the solution by Philoye.

>#divbutton
{
    position:relative;
    top:-64px;
    left:210px;
    background: transparent url("../../images/login_go.png") no-repeat;
    line-height:3000;
    width:33px;
    height:32px;
    border:none;
    cursor:pointer;
}

Run "mvn clean install" in Eclipse

Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there

Using ConfigurationManager to load config from an arbitrary location

For ASP.NET use WebConfigurationManager:

var config = WebConfigurationManager.OpenWebConfiguration("~/Sites/" + requestDomain + "/");
(..)
config.AppSettings.Settings["xxxx"].Value;

YouTube: How to present embed video with sound muted

Just pass mute=1.

For example:

<iframe id="myVideo" src="https://www.youtube.com/embed/k0DN-BZrM4o?rel=0&amp;autoplay=1;mute=1" width="100%" height="600" frameborder="0" allowfullscreen></iframe>

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

And use where is different:

GroupMember.where(member_id: 4, group_id: 7).first_or_create

This will call create on GroupMember.where(member_id: 4, group_id: 7):

GroupMember.where(member_id: 4, group_id: 7).create

On the contrary, the find_or_create_by(member_id: 4, group_id: 7) will call create on GroupMember:

GroupMember.create(member_id: 4, group_id: 7)

Please see this relevant commit on rails/rails.

Replace console output in Python

Added a little bit more functionality to the example of Aravind Voggu:

def progressBar(name, value, endvalue, bar_length = 50, width = 20):
        percent = float(value) / endvalue
        arrow = '-' * int(round(percent*bar_length) - 1) + '>'
        spaces = ' ' * (bar_length - len(arrow))
        sys.stdout.write("\r{0: <{1}} : [{2}]{3}%".format(\
                         name, width, arrow + spaces, int(round(percent*100))))
        sys.stdout.flush()
        if value == endvalue:     
             sys.stdout.write('\n\n')

Now you are able to generate multiple progressbars without replacing the previous one.

I've also added name as a value with a fixed width.

For two loops and two times the use of progressBar() the result will look like:

progress bar animation

Disabled UIButton not faded or grey

Set title color for different states:

@IBOutlet weak var loginButton: UIButton! {
        didSet {
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 0.3), for: .disabled)
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 1), for: .normal)
        }
    }

Usage: (text color will get change automatically)

loginButton.isEnabled = false

enter image description here

Copy a file from one folder to another using vbscripting

Just posted my finished code for a similar project. It copies files of certain extensions in my code its pdf tif and tiff you can change them to whatever you want copied or delete the if statements if you only need 1 or 2 types. When a file is created or modified it gets the archive attribute this code also looks for that attribute and only copies it if it exists and then removes it after its copied so you dont copy unneeded files. It also has a log setup in it so that you will see a log of what time and day evetrything was transfered from the last time you ran the script. Hope it helps! the link is Error: Object Required; 'objDIR' Code: 800A01A8

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

I was having the same error while I was doing AngularJS application. I did not see any error from my terminalcompiled successfully but when I debug with google developer tool, I have got this errorerror message.

After having this error, I reviewed my routing module first , since I was not seeing anything while requesting local host /login.

I found out that I misspelled the login as lgin and when I correct it works fine. I am just sharing this just to pay attention for any typo error we might encounter with put us in a great time loose! after correcting the typo error

Change placeholder text

If you wanna use Javascript then you can use getElementsByName() method to select the input fields and to change the placeholder for each one... see the below code...

document.getElementsByName('Email')[0].placeholder='new text for email';
document.getElementsByName('First Name')[0].placeholder='new text for fname';
document.getElementsByName('Last Name')[0].placeholder='new text for lname';

Otherwise use jQuery:

$('input:text').attr('placeholder','Some New Text');

Check if a Class Object is subclass of another Class Object in Java

In addition to @To-kra's answer. If someone doesn't like recurrence:

    public static boolean isSubClassOf(Class<?> clazz, Class<?> superClass) {
        if(Object.class.equals(superClass)) {
            return true;
        }

        for(; !Object.class.equals(clazz); clazz = clazz.getSuperclass()) {
            if(clazz.getSuperclass().equals(superClass)) {
                return true;
            }
        }

        return false;
    }

NOTE: no null checking for clarity.

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

Is it possible to embed animated GIFs in PDFs?

I haven't tested it but apparently you can add quicktime animations to a pdf (no idea why). So the solution would be to export the animated gif to quicktime and add it to the pdf.

Here the solution that apparently works:

  1. Open the GIF in Quicktime and save as MOV (Apparently it works with other formats too, you'll have to try it out).
  2. Insert the MOV into the PDF (with Adobe InDesign (make sure to set Object> Interactive> film options > Embed in PDF) - It should work with Adobe Acrobat Pro DC too: see link
  3. Save the PDF.

See this link (German)

How do I create a URL shortener?

Here is my PHP 5 class.

<?php
class Bijective
{
    public $dictionary = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public function __construct()
    {
        $this->dictionary = str_split($this->dictionary);
    }

    public function encode($i)
    {
        if ($i == 0)
        return $this->dictionary[0];

        $result = '';
        $base = count($this->dictionary);

        while ($i > 0)
        {
            $result[] = $this->dictionary[($i % $base)];
            $i = floor($i / $base);
        }

        $result = array_reverse($result);

        return join("", $result);
    }

    public function decode($input)
    {
        $i = 0;
        $base = count($this->dictionary);

        $input = str_split($input);

        foreach($input as $char)
        {
            $pos = array_search($char, $this->dictionary);

            $i = $i * $base + $pos;
        }

        return $i;
    }
}

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

Convert Swift string to array

Updated for Swift 4

Here are 3 ways.

//array of Characters
let charArr1 = [Character](myString)

//array of String.element
let charArr2 = Array(myString)

for char in myString {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

//array of String
var strArr = myString.map { String($0)}

Swift 3

Here are 3 ways.

let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

var strArr = myString.characters.map { String($0)}

Or you can add an extension to String.

extension String {
   func letterize() -> [Character] {
     return Array(self.characters)
  }
}

Then you can call it like this:

let charArr = "Cat".letterize()

how to change any data type into a string in python

I see all answers recommend using str(object). It might fail if your object have more than ascii characters and you will see error like ordinal not in range(128). This was the case for me while I was converting list of string in language other than English

I resolved it by using unicode(object)

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

All p tags with class some_class which are direct children of a div tag.

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

Getting title and meta tags from external website

<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

You must cast your integers as string when trying to concatenate them into a varchar.

i.e.

 SELECT  @ActualWeightDIMS = CAST(@Actual_Dims_Lenght AS varchar(10)) 
                              + 'x' + 
                             CAST(@Actual_Dims_Width as varchar(10)) 
                             + 'x' + CAST(@Actual_Dims_Height as varchar(10));

In SQL Server 2008, you can use the STR function:

   SELECT  @ActualWeightDIMS = STR(@Actual_Dims_Lenght) 
                              + 'x' + STR(@Actual_Dims_Width) 
                              + 'x' + STR(@Actual_Dims_Height);

How to resolve the C:\fakepath?

seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path

Can I loop through a table variable in T-SQL?

Here's another answer, similar to Justin's, but doesn't need an identity or aggregate, just a primary (unique) key.

declare @table1 table(dataKey int, dataCol1 varchar(20), dataCol2 datetime)
declare @dataKey int
while exists select 'x' from @table1
begin
    select top 1 @dataKey = dataKey 
    from @table1 
    order by /*whatever you want:*/ dataCol2 desc

    -- do processing

    delete from @table1 where dataKey = @dataKey
end

Release generating .pdb files, why?

Also, you can utilize crash dumps to debug your software. The customer sends it to you and then you can use it to identify the exact version of your source - and Visual Studio will even pull the right set of debugging symbols (and source if you're set up correctly) using the crash dump. See Microsoft's documentation on Symbol Stores.

Add a properties file to IntelliJ's classpath

Try this:

  • Go to Project Structure.
  • Select your module.
  • Find the folder in the tree on the right and select it.
  • Click the Sources button above that tree (with the blue folder) to make that folder a sources folder.

How can I convert a VBScript to an executable (EXE) file?

You can use VBSedit software to convert your VBS code to .exe file. You can download free version from Internet and installtion vbsedit applilcation on your system and convert the files to exe format.

Vbsedit is a good application for VBscripter's

CURL alternative in Python

Some example, how to use urllib for that things, with some sugar syntax. I know about requests and other libraries, but urllib is standard lib for python and doesn't require anything to be installed separately.

Python 2/3 compatible.

import sys
if sys.version_info.major == 3:
  from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, Request, build_opener
  from urllib.parse import urlencode
else:
  from urllib2 import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, Request, build_opener
  from urllib import urlencode


def curl(url, params=None, auth=None, req_type="GET", data=None, headers=None):
  post_req = ["POST", "PUT"]
  get_req = ["GET", "DELETE"]

  if params is not None:
    url += "?" + urlencode(params)

  if req_type not in post_req + get_req:
    raise IOError("Wrong request type \"%s\" passed" % req_type)

  _headers = {}
  handler_chain = []

  if auth is not None:
    manager = HTTPPasswordMgrWithDefaultRealm()
    manager.add_password(None, url, auth["user"], auth["pass"])
    handler_chain.append(HTTPBasicAuthHandler(manager))

  if req_type in post_req and data is not None:
    _headers["Content-Length"] = len(data)

  if headers is not None:
    _headers.update(headers)

  director = build_opener(*handler_chain)

  if req_type in post_req:
    if sys.version_info.major == 3:
      _data = bytes(data, encoding='utf8')
    else:
      _data = bytes(data)

    req = Request(url, headers=_headers, data=_data)
  else:
    req = Request(url, headers=_headers)

  req.get_method = lambda: req_type
  result = director.open(req)

  return {
    "httpcode": result.code,
    "headers": result.info(),
    "content": result.read()
  }


"""
Usage example:
"""

Post data:
  curl("http://127.0.0.1/", req_type="POST", data='cascac')

Pass arguments (http://127.0.0.1/?q=show):
  curl("http://127.0.0.1/", params={'q': 'show'}, req_type="POST", data='cascac')

HTTP Authorization:
  curl("http://127.0.0.1/secure_data.txt", auth={"user": "username", "pass": "password"})

Function is not complete and possibly is not ideal, but shows a basic representation and concept to use. Additional things could be added or changed by taste.

12/08 update

Here is a GitHub link to live updated source. Currently supporting:

  • authorization

  • CRUD compatible

  • automatic charset detection

  • automatic encoding(compression) detection

Is there any method to get the URL without query string?

To get every part of the URL except for the query:

var url = (location.origin).concat(location.pathname).concat(location.hash);

Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash).

It's better practice to use concat to join Javascript strings together (rather than +): in some situations it avoids problems such as type confusion.

How to grep for two words existing on the same line?

you could use awk. like this...

cat <yourFile> | awk '/word1/ && /word2/'

Order is not important. So if you have a file and...

a file named , file1 contains:

word1 is in this file as well as word2
word2 is in this file as well as word1
word4 is in this file as well as word1
word5 is in this file as well as word2

then,

/tmp$ cat file1| awk '/word1/ && /word2/'

will result in,

word1 is in this file as well as word2
word2 is in this file as well as word1

yes, awk is slower.

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

The correct syntax is:

FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
                                   , LCASE( SUBSTRING( NEW.bname, 2 ) ) )

Add and remove attribute with jquery

It's because you've removed the id which is how you're finding the element. This line of code is trying to add id="page_navigation1" to an element with the id named page_navigation1, but it doesn't exist (because you deleted the attribute):

$("#page_navigation1").attr("id","page_navigation1");

Demo: jsFiddle

If you want to add and remove a class that makes your <div> red use:

$( '#page_navigation1' ).addClass( 'red-class' );

And:

$( '#page_navigation1' ).removeClass( 'red-class' );

Where red-class is:

.red-class {
    background-color: red;
}

Load image with jQuery and append it to the DOM

Here is the code I use when I want to preload images before appending them to the page.

It is also important to check if the image is already loaded from the cache (for IE).

    //create image to preload:
    var imgPreload = new Image();
    $(imgPreload).attr({
        src: photoUrl
    });

    //check if the image is already loaded (cached):
    if (imgPreload.complete || imgPreload.readyState === 4) {

        //image loaded:
        //your code here to insert image into page

    } else {
        //go fetch the image:
        $(imgPreload).load(function (response, status, xhr) {
            if (status == 'error') {

                //image could not be loaded:

            } else {

                //image loaded:
                //your code here to insert image into page

            }
        });
    }

SQL Server: Get data for only the past year

Look up dateadd in BOL

dateadd(yy,-1,getdate())

How to set height property for SPAN

Why do you need a span in this case? If you want to style the height could you just use a div? You might try a div with display: inline, although that might have the same issue since you'd in effect be doing the same thing as a span.

How can I get Git to follow symlinks?

I used to add files beyond symlinks for quite some time now. This used to work just fine, without making any special arrangements. Since I updated to Git 1.6.1, this does not work any more.

You may be able to switch to Git 1.6.0 to make this work. I hope that a future version of Git will have a flag to git-add allowing it to follow symlinks again.

What exactly does += do in python?

The short answer is += can be translated as "add whatever is to the right of the += to the variable on the left of the +=".

Ex. If you have a = 10 then a += 5 would be: a = a + 5

So, "a" now equal to 15.

How to make HTML open a hyperlink in another window or tab?

You can also accomplish this by adding the following to your page's header:

<base target="_blank">

This will make ALL links on your page open in a new tab

Reading from stdin

From the man read:

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

Input parameters:

  • int fd file descriptor is an integer and not a file pointer. The file descriptor for stdin is 0

  • void *buf pointer to buffer to store characters read by the read function

  • size_t count maximum number of characters to read

So you can read character by character with the following code:

char buf[1];

while(read(0, buf, sizeof(buf))>0) {
   // read() here read from stdin charachter by character
   // the buf[0] contains the character got by read()
   ....
}

ASP.NET Core Identity - get current user

For context, I created a project using the ASP.NET Core 2 Web Application template. Then, select the Web Application (MVC) then hit the Change Authentication button and select Individual User accounts.

There is a lot of infrastructure built up for you from this template. Find the ManageController in the Controllers folder.

This ManageController class constructor requires this UserManager variable to populated:

private readonly UserManager<ApplicationUser> _userManager;

Then, take a look at the the [HttpPost] Index method in this class. They get the current user in this fashion:

var user = await _userManager.GetUserAsync(User);

As a bonus note, this is where you want to update any custom fields to the user Profile you've added to the AspNetUsers table. Add the fields to the view, then submit those values to the IndexViewModel which is then submitted to this Post method. I added this code after the default logic to set the email address and phone number:

user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.Address1 = model.Address1;
user.Address2 = model.Address2;
user.City = model.City;
user.State = model.State;
user.Zip = model.Zip;
user.Company = model.Company;
user.Country = model.Country;
user.SetDisplayName();
user.SetProfileID();

_dbContext.Attach(user).State = EntityState.Modified;
_dbContext.SaveChanges();

Can you force a React component to rerender without calling setState?

You could do it a couple of ways:

1. Use the forceUpdate() method:

There are some glitches that may happen when using the forceUpdate() method. One example is that it ignores the shouldComponentUpdate() method and will re-render the view regardless of whether shouldComponentUpdate() returns false. Because of this using forceUpdate() should be avoided when at all possible.

2. Passing this.state to the setState() method

The following line of code overcomes the problem with the previous example:

this.setState(this.state);

Really all this is doing is overwriting the current state with the current state which triggers a re-rendering. This still isn't necessarily the best way to do things, but it does overcome some of the glitches you might encounter using the forceUpdate() method.

How to set the java.library.path from Eclipse

Another solution would be to open the 'run configuration' and then in the 'Environment' tab, set the couple {Path,Value}.

For instance to add a 'lib' directory located at the root of the project,

    Path  <-  ${workspace_loc:name_of_the_project}\lib

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

Convert timedelta to total seconds

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.

(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.

(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:

gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.

I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow() which won't jump by an hour when DST goes on/off and may give you more precision than time.time()

Disable mouse scroll wheel zoom on embedded Google Maps

I was having the same problem: when scrolling the page then the pointer becomes over the map, it starts to zoom in/out the map instead of continuing scrolling the page. :(

So I solved this putting a div with an .overlay exactly before each gmap iframe insertion, see:

<html>
  <div class="overlay" onClick="style.pointerEvents='none'"></div>
  <iframe src="https://mapsengine.google.com/map/embed?mid=some_map_id" width="640" height="480"></iframe>
</html>

In my CSS i created the class:

.overlay {
   background:transparent; 
   position:relative; 
   width:640px;
   height:480px; /* your iframe height */
   top:480px;  /* your iframe height */
   margin-top:-480px;  /* your iframe height */
}

The div will cover the map, preventing pointer events from getting to it. But if you click on the div, it becomes transparent to pointer events, activating the map again!

I hope get helped you :)

unsigned APK can not be installed

You can test the unsigned-apk only on Emulator. And as its step of application deployment and distribution, you should read this article atleast once, i suggest: http://developer.android.com/guide/publishing/app-signing.html.

For your question, you can find the below line in above article:

All applications must be signed. The system will not install an application that is not signed.

so you have to have signed-apk before the distribution of your application.

To generate Signed-apk of your application, there is a simple wizard procedure, click on File -> Export -> Android -> Export Android application.

enter image description here

What is the iPhone 4 user-agent?

  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/7D11
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A306 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2 like Mac OS X; en_us) AppleWebKit/525.18.1 (KHTML, like Gecko)
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5

...for now

HTML-encoding lost when attribute read from input field

For those who prefer plain javascript, here is the method I have used successfully:

function escapeHTML (str)
{
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

How to reload the current state?

Probably the cleaner approach would be the following :

<a data-ui-sref="directory.organisations.details" data-ui-sref-opts="{reload: true}">Details State</a>

We can reload the state from the HTML only.

Count textarea characters

They say IE has issues with the input event but other than that, the solution is rather straightforward.

_x000D_
_x000D_
ta = document.querySelector("textarea");_x000D_
count = document.querySelector("label");_x000D_
_x000D_
ta.addEventListener("input", function (e) {_x000D_
  count.innerHTML = this.value.length;_x000D_
});
_x000D_
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">_x000D_
</textarea>_x000D_
<label for="my-textarea"></label>
_x000D_
_x000D_
_x000D_

How to change date format using jQuery?

You can use date.js to achieve this:

var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');

Alternatively, you can do it natively like this:

_x000D_
_x000D_
var dateAr = '2014-01-06'.split('-');_x000D_
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);_x000D_
_x000D_
console.log(newDate);
_x000D_
_x000D_
_x000D_

Error handling in getJSON calls

I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question

The getJSON structure is as follows (found on http://api.jqueri.com):

$(selector).getJSON(url,data,success(data,status,xhr))

most people implement that using

$.getJSON(url, datatosend, function(data){
    //do something with the data
});

where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.

You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object (found on w3schools)

$.getJSON(url, datatosend, function(data, status, xhr){
    if (status == "success"){
        //do something with the data
    }else if (status == "timeout"){
        alert("Something is wrong with the connection");
    }else if (status == "error" || status == "parsererror" ){
        alert("An error occured");
    }else{
        alert("datatosend did not change");
    }         
});

This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.

Hope this helps someone still looking for an answer to this question.

Need to find element in selenium by css

By.cssSelector(".ban") or By.cssSelector(".hot") or By.cssSelector(".ban.hot") should all select it unless there is another element that has those classes.

In CSS, .name means find an element that has a class with name. .foo.bar.baz means to find an element that has all of those classes (in the same element).

However, each of those selectors will select only the first element that matches it on the page. If you need something more specific, please post the HTML of the other elements that have those classes.

Bash script processing limited number of commands in parallel

See parallel. Its syntax is similar to xargs, but it runs the commands in parallel.

How to change font size on part of the page in LaTeX?

Example:

\Large\begin{verbatim}
   <how to set font size here to 10 px ? />
\end{verbatim}
\normalsize

\Large can be obviously substituted by one of:

\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge

If you need arbitrary font sizes:

How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?

A formal analysis has been done by Phil Rogaway in 2011, here. Section 1.6 gives a summary that I transcribe here, adding my own emphasis in bold (if you are impatient, then his recommendation is use CTR mode, but I suggest that you read my paragraphs about message integrity versus encryption below).

Note that most of these require the IV to be random, which means non-predictable and therefore should be generated with cryptographic security. However, some require only a "nonce", which does not demand that property but instead only requires that it is not re-used. Therefore designs that rely on a nonce are less error prone than designs that do not (and believe me, I have seen many cases where CBC is not implemented with proper IV selection). So you will see that I have added bold when Rogaway says something like "confidentiality is not achieved when the IV is a nonce", it means that if you choose your IV cryptographically secure (unpredictable), then no problem. But if you do not, then you are losing the good security properties. Never re-use an IV for any of these modes.

Also, it is important to understand the difference between message integrity and encryption. Encryption hides data, but an attacker might be able to modify the encrypted data, and the results can potentially be accepted by your software if you do not check message integrity. While the developer will say "but the modified data will come back as garbage after decryption", a good security engineer will find the probability that the garbage causes adverse behaviour in the software, and then he will turn that analysis into a real attack. I have seen many cases where encryption was used but message integrity was really needed more than the encryption. Understand what you need.

I should say that although GCM has both encryption and message integrity, it is a very fragile design: if you re-use an IV, you are screwed -- the attacker can recover your key. Other designs are less fragile, so I personally am afraid to recommend GCM based upon the amount of poor encryption code that I have seen in practice.

If you need both, message integrity and encryption, you can combine two algorithms: usually we see CBC with HMAC, but no reason to tie yourself to CBC. The important thing to know is encrypt first, then MAC the encrypted content, not the other way around. Also, the IV needs to be part of the MAC calculation.

I am not aware of IP issues.

Now to the good stuff from Professor Rogaway:

Block ciphers modes, encryption but not message integrity

ECB: A blockcipher, the mode enciphers messages that are a multiple of n bits by separately enciphering each n-bit piece. The security properties are weak, the method leaking equality of blocks across both block positions and time. Of considerable legacy value, and of value as a building block for other schemes, but the mode does not achieve any generally desirable security goal in its own right and must be used with considerable caution; ECB should not be regarded as a “general-purpose” confidentiality mode.

CBC: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is merely a nonce, nor if it is a nonce enciphered under the same key used by the scheme, as the standard incorrectly suggests to do. Ciphertexts are highly malleable. No chosen ciphertext attack (CCA) security. Confidentiality is forfeit in the presence of a correct-padding oracle for many padding methods. Encryption inefficient from being inherently serial. Widely used, the mode’s privacy-only security properties result in frequent misuse. Can be used as a building block for CBC-MAC algorithms. I can identify no important advantages over CTR mode.

CFB: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is predictable, nor if it is made by a nonce enciphered under the same key used by the scheme, as the standard incorrectly suggests to do. Ciphertexts are malleable. No CCA-security. Encryption inefficient from being inherently serial. Scheme depends on a parameter s, 1 = s = n, typically s = 1 or s = 8. Inefficient for needing one blockcipher call to process only s bits . The mode achieves an interesting “self-synchronization” property; insertion or deletion of any number of s-bit characters into the ciphertext only temporarily disrupts correct decryption.

OFB: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is a nonce, although a fixed sequence of IVs (eg, a counter) does work fine. Ciphertexts are highly malleable. No CCA security. Encryption and decryption inefficient from being inherently serial. Natively encrypts strings of any bit length (no padding needed). I can identify no important advantages over CTR mode.

CTR: An IV-based encryption scheme, the mode achieves indistinguishability from random bits assuming a nonce IV. As a secure nonce-based scheme, the mode can also be used as a probabilistic encryption scheme, with a random IV. Complete failure of privacy if a nonce gets reused on encryption or decryption. The parallelizability of the mode often makes it faster, in some settings much faster, than other confidentiality modes. An important building block for authenticated-encryption schemes. Overall, usually the best and most modern way to achieve privacy-only encryption.

XTS: An IV-based encryption scheme, the mode works by applying a tweakable blockcipher (secure as a strong-PRP) to each n-bit chunk. For messages with lengths not divisible by n, the last two blocks are treated specially. The only allowed use of the mode is for encrypting data on a block-structured storage device. The narrow width of the underlying PRP and the poor treatment of fractional final blocks are problems. More efficient but less desirable than a (wide-block) PRP-secure blockcipher would be.

MACs (message integrity but not encryption)

ALG1–6: A collection of MACs, all of them based on the CBC-MAC. Too many schemes. Some are provably secure as VIL PRFs, some as FIL PRFs, and some have no provable security. Some of the schemes admit damaging attacks. Some of the modes are dated. Key-separation is inadequately attended to for the modes that have it. Should not be adopted en masse, but selectively choosing the “best” schemes is possible. It would also be fine to adopt none of these modes, in favor of CMAC. Some of the ISO 9797-1 MACs are widely standardized and used, especially in banking. A revised version of the standard (ISO/IEC FDIS 9797-1:2010) will soon be released [93].

CMAC: A MAC based on the CBC-MAC, the mode is provably secure (up to the birthday bound) as a (VIL) PRF (assuming the underlying blockcipher is a good PRP). Essentially minimal overhead for a CBCMAC-based scheme. Inherently serial nature a problem in some application domains, and use with a 64-bit blockcipher would necessitate occasional re-keying. Cleaner than the ISO 9797-1 collection of MACs.

HMAC: A MAC based on a cryptographic hash function rather than a blockcipher (although most cryptographic hash functions are themselves based on blockciphers). Mechanism enjoys strong provable-security bounds, albeit not from preferred assumptions. Multiple closely-related variants in the literature complicate gaining an understanding of what is known. No damaging attacks have ever been suggested. Widely standardized and used.

GMAC: A nonce-based MAC that is a special case of GCM. Inherits many of the good and bad characteristics of GCM. But nonce-requirement is unnecessary for a MAC, and here it buys little benefit. Practical attacks if tags are truncated to = 64 bits and extent of decryption is not monitored and curtailed. Complete failure on nonce-reuse. Use is implicit anyway if GCM is adopted. Not recommended for separate standardization.

authenticated encryption (both encryption and message integrity)

CCM: A nonce-based AEAD scheme that combines CTR mode encryption and the raw CBC-MAC. Inherently serial, limiting speed in some contexts. Provably secure, with good bounds, assuming the underlying blockcipher is a good PRP. Ungainly construction that demonstrably does the job. Simpler to implement than GCM. Can be used as a nonce-based MAC. Widely standardized and used.

GCM: A nonce-based AEAD scheme that combines CTR mode encryption and a GF(2128)-based universal hash function. Good efficiency characteristics for some implementation environments. Good provably-secure results assuming minimal tag truncation. Attacks and poor provable-security bounds in the presence of substantial tag truncation. Can be used as a nonce-based MAC, which is then called GMAC. Questionable choice to allow nonces other than 96-bits. Recommend restricting nonces to 96-bits and tags to at least 96 bits. Widely standardized and used.

VBA - Range.Row.Count

Have you tried :-

Sub test()

    k = Cells(Rows.Count, "A").End(xlUp).Row

    MsgBox (k)

End Sub

The /only/ catch is that if there is no data it still returns 1.

How to recover deleted rows from SQL server table?

You have Full data + Transaction log backups, right? You can restore to another Database from backups and then sync the deleted rows back. Lots of work though...

(Have you looked at Redgate's SQL Log Rescue? Update: it's SQL Server 2000 only)

There is Log Explorer

How do I rename a Git repository?

With Github As Your Remote

Renaming the Remote Repo on Github

Regarding the remote repository, if you are using Github or Github Enterprise as the server location for saving/distributing your repository remotely, you can simply rename the repository directly in the repo settings.

From the main repo page, the settings tab is on the right, and the repo name is the first item on the page:

enter image description here

Github will redirect requests to the new URL

One very nice feature in Github when you rename a repo, is that Github will save the old repo name and all the related URLs and redirect traffic to the new URLs. Since your username/org and repo name are a part of the URL, a rename will change the URL.

Since Github saves the old repo name and redirects requests to the new URLs, if anyone uses links based on the old repo name when trying to access issues, wiki, stars, or followers they will still arrive at the new location on the Github website. Github also redirects lower level Git commands like git clone, git fetch, etc.

More information is in the Github Help for Renaming a Repo

Renaming the Local Repo Name

As others have mentioned, the local "name" of your repo is typically considered to be the root folder/directory name, and you can change that, move, or copy the folder to any location and it will not affect the repo at all.

Git is designed to only worry about files inside the root folder.

jQuery UI Slider (setting programmatically)

In my case with jquery slider with 2 handles only following way worked.

$('#Slider').slider('option',{values: [0.15, 0.6]});

How to embed images in email

Correct way of embedding images into Outlook and avoiding security problems is the next:

  1. Use interop for Outlook 2003;
  2. Create new email and set it save folder;
  3. Do not use base64 embedding, outlook 2007 does not support it; do not reference files on your disk, they won't be send; do not use word editor inspector because you will get security warnings on some machines;
  4. Attachment must have png/jpg extension. If it will have for instance tmp extension - Outlook will warn user;
  5. Pay attention how CID is generated without mapi;
  6. Do not access properties via getters or you will get security warnings on some machines.

    public static void PrepareEmail()
    {
        var attachFile = Path.Combine(
            Application.StartupPath, "mySuperImage.png"); // pay attention that image must not contain spaces, because Outlook cannot inline such images
    
        Microsoft.Office.Interop.Outlook.Application outlook = null;
        NameSpace space = null;
        MAPIFolder folder = null;
        MailItem mail = null;
        Attachment attachment = null;
        try
        {
            outlook = new Microsoft.Office.Interop.Outlook.Application();
            space = outlook.GetNamespace("MAPI");
            space.Logon(null, null, true, true);
    
            folder = space.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
            mail = (MailItem) outlook.CreateItem(OlItemType.olMailItem);
    
            mail.SaveSentMessageFolder = folder;
            mail.Subject = "Hi Everyone";
            mail.Attachments.Add(attachFile, OlAttachmentType.olByValue, 0, Type.Missing); 
            // Last Type.Missing - is for not to show attachment in attachments list.
    
            string attachmentId = Path.GetFileName(attachFile);
            mail.BodyFormat = OlBodyFormat.olFormatHTML;
    
             mail.HTMLBody = string.Format("<br/><img src=\'cid:{0}\' />", attachmentId);
    
            mail.Display(false);
        }
        finally
        {
            ReleaseComObject(outlook, space, folder, mail, attachment);
        }
    }
    

How to upgrade rubygems

Install rubygems-update

gem install rubygems-update
update_rubygems
gem update --system

run this commands as root or use sudo.