Programs & Examples On #Directory permissions

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

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

var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
   // There exists one with size 200 and is stored in item now
}
else {
  // There is no PricePublicModel with size 200
}

How to create a list of objects?

I have some hacky answers that are likely to be terrible... but I have very little experience at this point.

a way:

class myClass():
    myInstances = []
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02
        self.__class__.myInstances.append(self)

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

for thisObj in myClass.myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

A hack way to get this done:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
    thisStep += 1
    if "myClass object at" in thisLocalsLine:
        print(thisLocalsLine)
        print(myLocals[(thisStep - 2)])
        #myInstances.append(myLocals[(thisStep - 2)])
        print(myInstances)
        myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

Another more 'clever' hack:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myInstances = []
myClasses = {
    "myObj01": ["Foo", "Bar"],
    "myObj02": ["FooBar",  "Baz"]
    }

for thisClass in myClasses.keys():
    exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
    myInstances.append(getattr(sys.modules[__name__], thisClass))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

SQL - Query to get server's IP address

It is possible to use the host_name() function

select HOST_NAME()

Length of a JavaScript object

@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".

And in fairness to @palmsey he was quite correct. They aren't associative arrays; they're definitely objects :) - doing the job of an associative array. But as regards to the wider point, you definitely seem to have the right of it according to this rather fine article I found:

JavaScript “Associative Arrays” Considered Harmful

But according to all this, the accepted answer itself is bad practice?

Specify a prototype size() function for Object

If anything else has been added to Object .prototype, then the suggested code will fail:

<script type="text/javascript">
Object.prototype.size = function () {
  var len = this.length ? --this.length : -1;
    for (var k in this)
      len++;
  return len;
}
Object.prototype.size2 = function () {
  var len = this.length ? --this.length : -1;
    for (var k in this)
      len++;
  return len;
}
var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
alert("age is " + myArray["age"]);
alert("length is " + myArray.size());
</script>

I don't think that answer should be the accepted one as it can't be trusted to work if you have any other code running in the same execution context. To do it in a robust fashion, surely you would need to define the size method within myArray and check for the type of the members as you iterate through them.

Better way to cast object to int

Use Int32.TryParse as follows.

  int test;
  bool result = Int32.TryParse(value, out test);
  if (result)
  {
     Console.WriteLine("Sucess");         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Failure");
  }

How to upgrade all Python packages with pip

The shortest and easiest I can find:

pip install -U $(pip freeze | cut -d"=" -f1)

The $(cmd) key allows you to wrap any shell command line (it returns its output).

@Value annotation type casting to Integer from String

I had the same issue I solved using this. Refer this Spring MVC: @Value annotation to get int value defined in *.properties file

@Value(#{propertyfileId.propertyName})

works

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Simple fix for me was

  1. Build > Clean project
  2. Restart Android Studio

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

A beginner's guide to SQL database design

These are questions which, in my opionion, requires different knowledge from different domains.

  1. You just can't know in advance "which" tables to build, you have to know the problem you have to solve and design the schema accordingly;
  2. This is a mix of database design decision and your database vendor custom capabilities (ie. you should check the documentation of your (r)dbms and eventually learn some "tips & tricks" for scaling), also the configuration of your dbms is crucial for scaling (replication, data partitioning and so on);
  3. again, almost every rdbms comes with a particular "dialect" of the SQL language, so if you want efficient queries you have to learn that particular dialect --btw. much probably write elegant query which are also efficient is a big deal: elegance and efficiency are frequently conflicting goals--

That said, maybe you want to read some books, personally I've used this book in my datbase university course (and found a decent one, but I've not read other books in this field, so my advice is to check out for some good books in database design).

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

Why does the program give "illegal start of type" error?

You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.

android - how to convert int to string and place it in a EditText?

try Integer.toString(integer value); method as

ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));

Convert seconds to hh:mm:ss in Python

You can calculate the number of minutes and hours from the number of seconds by simple division:

seconds = 12345
minutes = seconds // 60
hours = minutes // 60

print "%02d:%02d:%02d" % (hours, minutes % 60, seconds % 60)
print "%02d:%02d" % (minutes, seconds % 60)

Here // is Python's integer division.

Visual Studio: ContextSwitchDeadlock

The ContextSwitchDeadlock doesn't necessarily mean your code has an issue, just that there is a potential. If you go to Debug > Exceptions in the menu and expand the Managed Debugging Assistants, you will find ContextSwitchDeadlock is enabled. If you disable this, VS will no longer warn you when items are taking a long time to process. In some cases you may validly have a long-running operation. It's also helpful if you are debugging and have stopped on a line while this is processing - you don't want it to complain before you've had a chance to dig into an issue.

jquery if div id has children

The jQuery way

In jQuery, you can use $('#id').children().length > 0 to test if an element has children.

Demo

_x000D_
_x000D_
var test1 = $('#test');_x000D_
var test2 = $('#test2');_x000D_
_x000D_
if(test1.children().length > 0) {_x000D_
    test1.addClass('success');_x000D_
} else {_x000D_
    test1.addClass('failure');_x000D_
}_x000D_
_x000D_
if(test2.children().length > 0) {_x000D_
    test2.addClass('success');_x000D_
} else {_x000D_
    test2.addClass('failure');_x000D_
}
_x000D_
.success {_x000D_
    background: #9f9;_x000D_
}_x000D_
_x000D_
.failure {_x000D_
    background: #f99;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>_x000D_
<div id="test">_x000D_
   <span>Children</span>_x000D_
</div>_x000D_
<div id="test2">_x000D_
   No children_x000D_
</div>
_x000D_
_x000D_
_x000D_


The vanilla JS way

If you don't want to use jQuery, you can use document.getElementById('id').children.length > 0 to test if an element has children.

Demo

_x000D_
_x000D_
var test1 = document.getElementById('test');_x000D_
var test2 = document.getElementById('test2');_x000D_
_x000D_
if(test1.children.length > 0) {_x000D_
    test1.classList.add('success');_x000D_
} else {_x000D_
    test1.classList.add('failure');_x000D_
}_x000D_
_x000D_
if(test2.children.length > 0) {_x000D_
    test2.classList.add('success');_x000D_
} else {_x000D_
    test2.classList.add('failure');_x000D_
}
_x000D_
.success {_x000D_
    background: #9f9;_x000D_
}_x000D_
_x000D_
.failure {_x000D_
    background: #f99;_x000D_
}
_x000D_
<div id="test">_x000D_
   <span>Children</span>_x000D_
</div>_x000D_
<div id="test2">_x000D_
   No children_x000D_
</div>
_x000D_
_x000D_
_x000D_

Reset auto increment counter in postgres

Note that if you have table name with '_', it is removed in sequence name.

For example, table name: user_tokens column: id Sequence name: usertokens_id_seq

Why use Ruby's attr_accessor, attr_reader and attr_writer?

It is important to understand that accessors restrict access to variable, but not their content. In ruby, like in some other OO languages, every variable is a pointer to an instance. So if you have an attribute to an Hash, for example, and you set it to be "read only" you always could change its content, but not the content of pointer. Look at this:

irb(main):024:0> class A
irb(main):025:1> attr_reader :a
irb(main):026:1> def initialize
irb(main):027:2> @a = {a:1, b:2}
irb(main):028:2> end
irb(main):029:1> end
=> :initialize
irb(main):030:0> a = A.new
=> #<A:0x007ffc5a10fe88 @a={:a=>1, :b=>2}>
irb(main):031:0> a.a
=> {:a=>1, :b=>2}
irb(main):032:0> a.a.delete(:b)
=> 2
irb(main):033:0> a.a
=> {:a=>1}
irb(main):034:0> a.a = {}
NoMethodError: undefined method `a=' for #<A:0x007ffc5a10fe88 @a={:a=>1}>
        from (irb):34
        from /usr/local/bin/irb:11:in `<main>'

As you can see is possible delete a key/value pair from the Hash @a, as add new keys, change values, eccetera. But you can't point to a new object because is a read only instance variable.

How to run a stored procedure in oracle sql developer?

-- If no parameters need to be passed to a procedure, simply:

BEGIN
   MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;

How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

Remove an element from a Bash array

Using unset

To remove an element at particular index, we can use unset and then do copy to another array. Only just unset is not required in this case. Because unset does not remove the element it just sets null string to the particular index in array.

declare -a arr=('aa' 'bb' 'cc' 'dd' 'ee')
unset 'arr[1]'
declare -a arr2=()
i=0
for element in "${arr[@]}"
do
    arr2[$i]=$element
    ((++i))
done
echo "${arr[@]}"
echo "1st val is ${arr[1]}, 2nd val is ${arr[2]}"
echo "${arr2[@]}"
echo "1st val is ${arr2[1]}, 2nd val is ${arr2[2]}"

Output is

aa cc dd ee
1st val is , 2nd val is cc
aa cc dd ee
1st val is cc, 2nd val is dd

Using :<idx>

We can remove some set of elements using :<idx> also. For example if we want to remove 1st element we can use :1 as mentioned below.

declare -a arr=('aa' 'bb' 'cc' 'dd' 'ee')
arr2=("${arr[@]:1}")
echo "${arr2[@]}"
echo "1st val is ${arr2[1]}, 2nd val is ${arr2[2]}"

Output is

bb cc dd ee
1st val is cc, 2nd val is dd

jQuery Datepicker localization

In case you are looking for datepicker in spanish (datepicker en español)

<script type="text/javascript">
    $.datepicker.regional['es'] = {
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        dayNames: ['Domingo', 'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado'],
        dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'],
        dayNamesMin: ['Do', 'Lu', 'Ma', 'Mc', 'Ju', 'Vi', 'Sa']
    }

    $.datepicker.setDefaults($.datepicker.regional['es']);

</script>

What is better, adjacency lists or adjacency matrices for graph problems in C++?

Depending on the Adjacency Matrix implementation the 'n' of the graph should be known earlier for an efficient implementation. If the graph is too dynamic and requires expansion of the matrix every now and then that can also be counted as a downside?

Check whether specific radio button is checked

I think you're using the wrong approach. You should set the value attribute of your input elements. Check the docs for .val() for examples of setting and returning the .val() of input elements.

ie.

<input type="radio" runat="server" name="testGroup" value="test2" />

return $('input:radio[name=testGroup]:checked').val() == 'test2';

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

return collection.All(i => i == collection.First())) 
    ? collection.First() : otherValue;.

Or if you're worried about executing First() for each element (which could be a valid performance concern):

var first = collection.First();
return collection.All(i => i == first) ? first : otherValue;

How to get the full path of running process?

I guess you already have the process object of the running process (e.g. by GetProcessesByName()). You can then get the executable file name by using

Process p;
string filename = p.MainModule.FileName;

Get only part of an Array in Java?

Yes, you can use Arrays.copyOfRange

It does about the same thing (note there is a copy : you don't change the initial array).

SQL Query - Concatenating Results into One String

Here is another real life example that works fine at least with 2008 release (and later).

This is the original query which uses simple max() to get at least one of the values:

SELECT option_name, Field_M3_name, max(Option_value) AS "Option value", max(Sorting) AS "Sorted"
FROM Value_list group by Option_name, Field_M3_name
ORDER BY option_name, Field_M3_name

Improved version, where the main improvement is that we show all values comma separated:

SELECT from1.keys, from1.option_name, from1.Field_M3_name,

 Stuff((SELECT DISTINCT ', ' + [Option_value] FROM Value_list from2
  WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
  .value('text()[1]','nvarchar(max)'),1,2,N'') AS "Option values",

 Stuff((SELECT DISTINCT ', ' + CAST([Sorting] AS VARCHAR) FROM Value_list from2
  WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
  .value('text()[1]','nvarchar(max)'),1,2,N'') AS "Sorting"

FROM ((SELECT DISTINCT COALESCE(Option_name,'') + '|' + COALESCE(Field_M3_name,'') AS keys, Option_name, Field_M3_name FROM Value_list)
-- WHERE
) from1
ORDER BY keys

Note that we have solved all possible NULL case issues that I can think of and also we fixed an error that we got for numeric values (field Sorting).

pip install gives error: Unable to find vcvarsall.bat

You need to have Visual Studio's bin dir in your path. Pip install is trying to compile some C code.

Python Accessing Nested JSON Data

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

print j['state']
print j['places'][1]['post code']

android get all contacts

//GET CONTACTLIST WITH ALL FIELD...       

public ArrayList < ContactItem > getReadContacts() {
         ArrayList < ContactItem > contactList = new ArrayList < > ();
         ContentResolver cr = getContentResolver();
         Cursor mainCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
         if (mainCursor != null) {
          while (mainCursor.moveToNext()) {
           ContactItem contactItem = new ContactItem();
           String id = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts._ID));
           String displayName = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

           Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
           Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);

           //ADD NAME AND CONTACT PHOTO DATA...
           contactItem.setDisplayName(displayName);
           contactItem.setPhotoUrl(displayPhotoUri.toString());

           if (Integer.parseInt(mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
            //ADD PHONE DATA...
            ArrayList < PhoneContact > arrayListPhone = new ArrayList < > ();
            Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (phoneCursor != null) {
             while (phoneCursor.moveToNext()) {
              PhoneContact phoneContact = new PhoneContact();
              String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              phoneContact.setPhone(phone);
              arrayListPhone.add(phoneContact);
             }
            }
            if (phoneCursor != null) {
             phoneCursor.close();
            }
            contactItem.setArrayListPhone(arrayListPhone);


            //ADD E-MAIL DATA...
            ArrayList < EmailContact > arrayListEmail = new ArrayList < > ();
            Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (emailCursor != null) {
             while (emailCursor.moveToNext()) {
              EmailContact emailContact = new EmailContact();
              String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
              emailContact.setEmail(email);
              arrayListEmail.add(emailContact);
             }
            }
            if (emailCursor != null) {
             emailCursor.close();
            }
            contactItem.setArrayListEmail(arrayListEmail);

            //ADD ADDRESS DATA...
            ArrayList < PostalAddress > arrayListAddress = new ArrayList < > ();
            Cursor addrCursor = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (addrCursor != null) {
             while (addrCursor.moveToNext()) {
              PostalAddress postalAddress = new PostalAddress();
              String city = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
              String state = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
              String country = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
              postalAddress.setCity(city);
              postalAddress.setState(state);
              postalAddress.setCountry(country);
              arrayListAddress.add(postalAddress);
             }
            }
            if (addrCursor != null) {
             addrCursor.close();
            }
            contactItem.setArrayListAddress(arrayListAddress);
           }
           contactList.add(contactItem);
          }
         }
         if (mainCursor != null) {
          mainCursor.close();
         }
         return contactList;
        }



    //MODEL...
        public class ContactItem {

            private String displayName;
            private String photoUrl;
            private ArrayList<PhoneContact> arrayListPhone = new ArrayList<>();
            private ArrayList<EmailContact> arrayListEmail = new ArrayList<>();
            private ArrayList<PostalAddress> arrayListAddress = new ArrayList<>();


            public String getDisplayName() {
                return displayName;
            }

            public void setDisplayName(String displayName) {
                this.displayName = displayName;
            }

            public String getPhotoUrl() {
                return photoUrl;
            }

            public void setPhotoUrl(String photoUrl) {
                this.photoUrl = photoUrl;
            }

            public ArrayList<PhoneContact> getArrayListPhone() {
                return arrayListPhone;
            }

            public void setArrayListPhone(ArrayList<PhoneContact> arrayListPhone) {
                this.arrayListPhone = arrayListPhone;
            }

            public ArrayList<EmailContact> getArrayListEmail() {
                return arrayListEmail;
            }

            public void setArrayListEmail(ArrayList<EmailContact> arrayListEmail) {
                this.arrayListEmail = arrayListEmail;
            }

            public ArrayList<PostalAddress> getArrayListAddress() {
                return arrayListAddress;
            }

            public void setArrayListAddress(ArrayList<PostalAddress> arrayListAddress) {
                this.arrayListAddress = arrayListAddress;
            }
        }

        public class EmailContact
        {
            private String email = "";

            public String getEmail() {
                return email;
            }

            public void setEmail(String email) {
                this.email = email;
            }
        }

        public class PhoneContact
        {
            private String phone="";

            public String getPhone()
            {
                return phone;
            }

            public void setPhone(String phone) {
                this.phone = phone;
            }
        }


        public class PostalAddress
        {
            private String city="";
            private String state="";
            private String country="";

            public String getCity() {
                return city;
            }

            public void setCity(String city) {
                this.city = city;
            }

            public String getState() {
                return state;
            }

            public void setState(String state) {
                this.state = state;
            }

            public String getCountry() {
                return country;
            }

            public void setCountry(String country) {
                this.country = country;
            }
        }

Create Django model or update if exists

This should be the answer you are looking for

EmployeeInfo.objects.update_or_create(
    #id or any primary key:value to search for
    identifier=your_id, 
    #if found update with the following or save/create if not found
    defaults={'name':'your_name'}
)

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

How can I show an element that has display: none in a CSS rule?

try setting the display to block in your javascript instead of a blank value.

How to turn off word wrapping in HTML?

If you want a HTML only solution, we can just use the pre tag. It defines "preformatted text" which means that it does not format word-wrapping. Here is a quick example to explain:

_x000D_
_x000D_
div {
    width: 200px;
    height: 200px;
    padding: 20px;
    background: #adf;
}
pre {
    width: 200px;
    height: 200px;
    padding: 20px;
    font: inherit;
    background: #fda;
}
_x000D_
<div>Look at this, this text is very neat, isn't it? But it's not quite what we want, though, is it? This text shouldn't be here! It should be all the way over there! What can we do?</div>
<pre>The pre tag has come to the rescue! Yay! However, we apologise in advance for any horizontal scrollbars that may be caused. If you need support, please raise a support ticket.</pre>
_x000D_
_x000D_
_x000D_

How to generate entire DDL of an Oracle schema (scriptable)?

You can spool the schema out to a file via SQL*Plus and dbms_metadata package. Then replace the schema name with another one via sed. This works for Oracle 10 and higher.

sqlplus<<EOF
set long 100000
set head off
set echo off
set pagesize 0
set verify off
set feedback off
spool schema.out

select dbms_metadata.get_ddl(object_type, object_name, owner)
from
(
    --Convert DBA_OBJECTS.OBJECT_TYPE to DBMS_METADATA object type:
    select
        owner,
        --Java object names may need to be converted with DBMS_JAVA.LONGNAME.
        --That code is not included since many database don't have Java installed.
        object_name,
        decode(object_type,
            'DATABASE LINK',      'DB_LINK',
            'JOB',                'PROCOBJ',
            'RULE SET',           'PROCOBJ',
            'RULE',               'PROCOBJ',
            'EVALUATION CONTEXT', 'PROCOBJ',
            'CREDENTIAL',         'PROCOBJ',
            'CHAIN',              'PROCOBJ',
            'PROGRAM',            'PROCOBJ',
            'PACKAGE',            'PACKAGE_SPEC',
            'PACKAGE BODY',       'PACKAGE_BODY',
            'TYPE',               'TYPE_SPEC',
            'TYPE BODY',          'TYPE_BODY',
            'MATERIALIZED VIEW',  'MATERIALIZED_VIEW',
            'QUEUE',              'AQ_QUEUE',
            'JAVA CLASS',         'JAVA_CLASS',
            'JAVA TYPE',          'JAVA_TYPE',
            'JAVA SOURCE',        'JAVA_SOURCE',
            'JAVA RESOURCE',      'JAVA_RESOURCE',
            'XML SCHEMA',         'XMLSCHEMA',
            object_type
        ) object_type
    from dba_objects 
    where owner in ('OWNER1')
        --These objects are included with other object types.
        and object_type not in ('INDEX PARTITION','INDEX SUBPARTITION',
           'LOB','LOB PARTITION','TABLE PARTITION','TABLE SUBPARTITION')
        --Ignore system-generated types that support collection processing.
        and not (object_type = 'TYPE' and object_name like 'SYS_PLSQL_%')
        --Exclude nested tables, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_nested_tables)
        --Exclude overflow segments, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_tables where iot_type = 'IOT_OVERFLOW')
)
order by owner, object_type, object_name;

spool off
quit
EOF

cat schema.out|sed 's/OWNER1/MYOWNER/g'>schema.out.change.sql

Put everything in a script and run it via cron (scheduler). Exporting objects can be tricky when advanced features are used. Don't be surprised if you need to add some more exceptions to the above code.

Where does PostgreSQL store the database?

picmate's answer is right. on windows the main DB folder location is (at least on my installation)

C:\PostgreSQL\9.2\data\base\

and not in program files.

his 2 scripts, will give you the exact directory/file(s) you need:

SELECT oid from pg_database WHERE datname = <database_name>;
SELECT relname, relfilenode FROM pg_class WHERE relname = <table_name>; 

mine is in datname 16393 and relfilenode 41603

database files in postgresql

HTML Button Close Window

When in the onclick attribute you do not need to specify that it is Javascript.

<button type="button" 
        onclick="window.open('', '_self', ''); window.close();">Discard</button>

This should do it. In order to close it your page needs to be opened by the script, hence the window.open. Here is an article explaining this in detail:

Click Here

If all else fails, you should also add a message asking the user to manually close the window, as there is no cross-browser solution for this, especially with older browsers such as IE 8.

How to create an empty file with Ansible?

Turns out I don't have enough reputation to put this as a comment, which would be a more appropriate place for this:

Re. AllBlackt's answer, if you prefer Ansible's multiline format you need to adjust the quoting for state (I spent a few minutes working this out, so hopefully this speeds someone else up),

- stat:
    path: "/etc/nologin"
  register: p

- name: create fake 'nologin' shell
  file:
    path: "/etc/nologin"
    owner: root
    group: sys
    mode: 0555
    state: '{{ "file" if  p.stat.exists else "touch" }}'

Is it possible to get an Excel document's row count without loading the entire document into memory?

The solution suggested in this answer has been deprecated, and might no longer work.


Taking a look at the source code of OpenPyXL (IterableWorksheet) I've figured out how to get the column and row count from an iterator worksheet:

wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]

row_count = sheet.get_highest_row() - 1
column_count = letter_to_index(sheet.get_highest_column()) + 1

IterableWorksheet.get_highest_column returns a string with the column letter that you can see in Excel, e.g. "A", "B", "C" etc. Therefore I've also written a function to translate the column letter to a zero based index:

def letter_to_index(letter):
    """Converts a column letter, e.g. "A", "B", "AA", "BC" etc. to a zero based
    column index.

    A becomes 0, B becomes 1, Z becomes 25, AA becomes 26 etc.

    Args:
        letter (str): The column index letter.
    Returns:
        The column index as an integer.
    """
    letter = letter.upper()
    result = 0

    for index, char in enumerate(reversed(letter)):
        # Get the ASCII number of the letter and subtract 64 so that A
        # corresponds to 1.
        num = ord(char) - 64

        # Multiply the number with 26 to the power of `index` to get the correct
        # value of the letter based on it's index in the string.
        final_num = (26 ** index) * num

        result += final_num

    # Subtract 1 from the result to make it zero-based before returning.
    return result - 1

I still haven't figured out how to get the column sizes though, so I've decided to use a fixed-width font and automatically scaled columns in my application.

How to use phpexcel to read data and insert into database?

Using the PHPExcel library, the following code will do.

require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';    
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true); //optional

$objPHPExcel = $objReader->load(__DIR__.'/YourExcelFile.xlsx');
$objWorksheet = $objPHPExcel->getActiveSheet();

$i=1;
foreach ($objWorksheet->getRowIterator() as $row) {

    $column_A_Value = $objPHPExcel->getActiveSheet()->getCell("A$i")->getValue();//column A
    //you can add your own columns B, C, D etc.

    //inset $column_A_Value value in DB query here

    $i++;
}

How to add multiple files to Git at the same time

As some have mentioned a possible way is using git interactive staging. This is great when you have files with different extensions

$ git add -i
           staged     unstaged path
  1:    unchanged        +0/-1 TODO
  2:    unchanged        +1/-1 index.html
  3:    unchanged        +5/-1 lib/simplegit.rb

*** Commands ***
  1: status     2: update      3: revert     4: add untracked
  5: patch      6: diff        7: quit       8: help
What now>

If you press 2 then enter you will get a list of available files to be added:

What now> 2
           staged     unstaged path
  1:    unchanged        +0/-1 TODO
  2:    unchanged        +1/-1 index.html
  3:    unchanged        +5/-1 lib/simplegit.rb
Update>>

Now you just have to insert the number of the files you want to add, so if we wanted to add TODO and index.html we would type 1,2

Update>> 1,2
           staged     unstaged path
* 1:    unchanged        +0/-1 TODO
* 2:    unchanged        +1/-1 index.html
  3:    unchanged        +5/-1 lib/simplegit.rb
Update>>

You see the * before the number? that means that the file was added.

Now imagine that you have 7 files and you want to add them all except the 7th? Sure we could type 1,2,3,4,5,6 but imagine instead of 7 we have 16, that would be quite cumbersome, the good thing we don't need to type them all because we can use ranges,by typing 1-6

Update>> 1-6
           staged     unstaged path
* 1:    unchanged        +0/-1 TODO
* 2:    unchanged        +1/-1 index.html
* 3:    unchanged        +5/-1 lib/simplegit.rb
* 4:    unchanged        +5/-1 file4.html
* 5:    unchanged        +5/-1 file5.html
* 6:    unchanged        +5/-1 file6.html
  7:    unchanged        +5/-1 file7.html
Update>>

We can even use multiple ranges, so if we want from 1 to 3 and from 5 to 7 we type 1-3, 5-7:

Update>> 1-3, 5-7
           staged     unstaged path
* 1:    unchanged        +0/-1 TODO
* 2:    unchanged        +1/-1 index.html
* 3:    unchanged        +5/-1 lib/simplegit.rb
  4:    unchanged        +5/-1 file4.html
* 5:    unchanged        +5/-1 file5.html
* 6:    unchanged        +5/-1 file6.html
* 7:    unchanged        +5/-1 file7.html
Update>>

We can also use this to unstage files, if we type -number, so if we wanted to unstage file number 1 we would type -1:

Update>> -1
           staged     unstaged path
  1:    unchanged        +0/-1 TODO
* 2:    unchanged        +1/-1 index.html
* 3:    unchanged        +5/-1 lib/simplegit.rb
  4:    unchanged        +5/-1 file4.html
* 5:    unchanged        +5/-1 file5.html
* 6:    unchanged        +5/-1 file6.html
* 7:    unchanged        +5/-1 file7.html
Update>>

And as you can imagine we can also unstage a range of files, so if we type -range all the files on that range would be unstaged. If we wanted to unstage all the files from 5 to 7 we would type -5-7:

Update>> -5-7
           staged     unstaged path
  1:    unchanged        +0/-1 TODO
* 2:    unchanged        +1/-1 index.html
* 3:    unchanged        +5/-1 lib/simplegit.rb
  4:    unchanged        +5/-1 file4.html
  5:    unchanged        +5/-1 file5.html
  6:    unchanged        +5/-1 file6.html
  7:    unchanged        +5/-1 file7.html
Update>>

Posting parameters to a url using the POST method without using a form

it can be done with CURL or AJAX. The response is equally cryptic as the answer.

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:

main.xml

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

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE" android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
    </LinearLayout>

</RelativeLayout>

Your activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            ImageView img = (ImageView) findViewById( R.id.img1 );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img2 );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img3 );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img4 );
            moveViewToScreenCenter( img );
        }
    });
}

private void moveViewToScreenCenter( View view )
{
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setDuration(1000);
    anim.setFillAfter( true );
    view.startAnimation(anim);
}

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type np.dot(X, T) to float32 like this:

z=np.array(np.dot(X, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

CSS3 selector :first-of-type with class name?

This is an old thread, but I'm responding because it still appears high in the list of search results. Now that the future has arrived, you can use the :nth-child pseudo-selector.

p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }

The :nth-child pseudo-selector is powerful - the parentheses accept formulas as well as numbers.

More here: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

static files with express.js

If you have a complicated folder structure, such as

- Your application
     - assets
         - images
             - profile.jpg
     - web
     - server
        - index.js

If you want to serve assets/images from index.js

app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))

To view from your browser

http://localhost:4000/images/profile.jpg

If you need more clarification comment, I'll elaborate.

Sort a list alphabetically

Another way

_details.Sort((s1, s2) => s1.CompareTo(s2)); 

Cannot find pkg-config error

For Ubuntu/Debian OS,

apt-get install -y pkg-config

For Redhat/Yum OS,

yum install -y pkgconfig

For Archlinux OS,

pacman -S pkgconf

How to get logged-in user's name in Access vba?

Public Declare Function GetUserName Lib "advapi32.dll" 
    Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

....

Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String

strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))

Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?

Fix height of a table row in HTML Table

the bottom cell will grow as you enter more text ... setting the table width will help too

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

There are 3 things I can think of off the top of my head:

  1. Just used named urls, it's more robust and maintainable anyway
  2. Try using django.core.urlresolvers.reverse at the command line for a (possibly) better error

    >>> from django.core.urlresolvers import reverse
    >>> reverse('products.views.filter_by_led')
    
  3. Check to see if you have more than one url that points to that view

Set height of <div> = to height of another <div> through .css

You would certainly benefit from using a responsive framework for your project. It would save you a good amount of headaches. However, seeing the structure of your HTML I would do the following:

Please check the example: http://jsfiddle.net/xLA4q/

HTML:

<div class="nav-content-wrapper">
 <div class="left-nav">asdasdasd ads asd ads asd ad asdasd ad ad a ad</div>
 <div class="content">asd as dad ads ads ads ad ads das ad sad</div>
</div>

CSS:

.nav-content-wrapper{position:relative; overflow:auto; display:block;height:300px;}
.left-nav{float:left;width:30%;height:inherit;}
.content{float:left;width:70%;height:inherit;}

How to resolve TypeError: Cannot convert undefined or null to object

If you're using Laravel, my problem was in the name of my Route. Instead:

Route::put('/reason/update', 'REASONController@update');

I wrote:

Route::put('/reason/update', 'RESONController@update');

and when I fixed the controller name, the code worked!

How to group by month from Date field using sql

You can do this by using Year(), Month() Day() and datepart().

In you example this would be:

select  Closing_Date, Category,  COUNT(Status)TotalCount from  MyTable
where Closing_Date >= '2012-02-01' and Closing_Date <= '2012-12-31' 
and Defect_Status1 is not null 
group by Year(Closing_Date), Month(Closing_Date), Category

Send data from javascript to a mysql database

You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

If the error is

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

Step1: stop the server

Step2: run commands are npm uninstall node-sass

Step3: check node-sass in package.json if node-sass is available in the file then again run Step2.

Step4: npm install [email protected] <=== run command

Step5: wait until the command successfully runs.

Step6: start-server using npm start

Looping through GridView rows and Checking Checkbox Control

Loop like

foreach (GridViewRow row in grid.Rows)
{
   if (((CheckBox)row.FindControl("chkboxid")).Checked)
   {
    //read the label            
   }            
}

'if' in prolog?

Prolog program actually is big condition for "if" with "then" which prints "Goal is reached" and "else" which prints "No sloutions was found". A, Bmeans "A is true and B is true", most of prolog systems will not try to satisfy "B" if "A" is not reachable (i.e. X=3, write('X is 3'),nl will print 'X is 3' when X=3, and will do nothing if X=2).

printf \t option

That's something controlled by your terminal, not by printf.

printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

REST API Authentication

  1. Use HTTP Basic Auth to authenticate clients, but treat username/password only as temporary session token.

    The session token is just a header attached to every HTTP request, eg: Authorization: Basic Ym9ic2Vzc2lvbjE6czNjcmV0

    The string Ym9ic2Vzc2lvbjE6czNjcmV0 above is just the string "bobsession1:s3cret" (which is a username/password) encoded in Base64.

  2. To obtain the temporary session token above, provide an API function (eg: http://mycompany.com/apiv1/login) which takes master-username and master-password as an input, creates a temporary HTTP Basic Auth username / password on the server side, and returns the token (eg: Ym9ic2Vzc2lvbjE6czNjcmV0). This username / password should be temporary, it should expire after 20min or so.

  3. For added security ensure your REST service are served over HTTPS so that information are not transferred plaintext

If you're on Java, Spring Security library provides good support to implement above method

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

Counter increment in Bash loop not working

Source script has some problem with subshell. First example, you probably do not need subshell. But We don't know what is hidden under "Some more action". The most popular answer has hidden bug, that will increase I/O, and won't work with subshell, because it restores couter inside loop.

Do not fortot add '\' sign, it will inform bash interpreter about line continuation. I hope it will help you or anybody. But in my opinion this script should be fully converted to AWK script, or else rewritten to python using regexp, or perl, but perl popularity over years is degraded. Better do it with python.

Corrected Version without subshell:

#!/bin/bash
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' |\
awk -F ', ' '{print $2,$4,$0}' |\
awk '{print "http://example.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' |\
awk -F '&end=1' '{print $1"&end=1"}' |\
#(  #unneeded bracket
while read WFY_URL
do
    echo $WFY_URL #Some more action
    COUNTER=$((COUNTER+1))
done
# ) unneeded bracket

echo $COUNTER # output = 0

Version with subshell if it is really needed

#!/bin/bash

TEMPFILE=/tmp/$$.tmp  #I've got it from the most popular answer
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' |\
awk -F ', ' '{print $2,$4,$0}' |\
awk '{print "http://example.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' |\
awk -F '&end=1' '{print $1"&end=1"}' |\
(
while read WFY_URL
do
    echo $WFY_URL #Some more action
    COUNTER=$((COUNTER+1))
done
echo $COUNTER > $TEMPFILE  #store counter only once, do it after loop, you will save I/O
)

COUNTER=$(cat $TEMPFILE)  #restore counter
unlink $TEMPFILE
echo $COUNTER # output = 0

Inline labels in Matplotlib

Update: User cphyc has kindly created a Github repository for the code in this answer (see here), and bundled the code into a package which may be installed using pip install matplotlib-label-lines.


Pretty Picture:

semi-automatic plot-labeling

In matplotlib it's pretty easy to label contour plots (either automatically or by manually placing labels with mouse clicks). There does not (yet) appear to be any equivalent capability to label data series in this fashion! There may be some semantic reason for not including this feature which I am missing.

Regardless, I have written the following module which takes any allows for semi-automatic plot labelling. It requires only numpy and a couple of functions from the standard math library.

Description

The default behaviour of the labelLines function is to space the labels evenly along the x axis (automatically placing at the correct y-value of course). If you want you can just pass an array of the x co-ordinates of each of the labels. You can even tweak the location of one label (as shown in the bottom right plot) and space the rest evenly if you like.

In addition, the label_lines function does not account for the lines which have not had a label assigned in the plot command (or more accurately if the label contains '_line').

Keyword arguments passed to labelLines or labelLine are passed on to the text function call (some keyword arguments are set if the calling code chooses not to specify).

Issues

  • Annotation bounding boxes sometimes interfere undesirably with other curves. As shown by the 1 and 10 annotations in the top left plot. I'm not even sure this can be avoided.
  • It would be nice to specify a y position instead sometimes.
  • It's still an iterative process to get annotations in the right location
  • It only works when the x-axis values are floats

Gotchas

  • By default, the labelLines function assumes that all data series span the range specified by the axis limits. Take a look at the blue curve in the top left plot of the pretty picture. If there were only data available for the x range 0.5-1 then then we couldn't possibly place a label at the desired location (which is a little less than 0.2). See this question for a particularly nasty example. Right now, the code does not intelligently identify this scenario and re-arrange the labels, however there is a reasonable workaround. The labelLines function takes the xvals argument; a list of x-values specified by the user instead of the default linear distribution across the width. So the user can decide which x-values to use for the label placement of each data series.

Also, I believe this is the first answer to complete the bonus objective of aligning the labels with the curve they're on. :)

label_lines.py:

from math import atan2,degrees
import numpy as np

#Label line with line2D label data
def labelLine(line,x,label=None,align=True,**kwargs):

    ax = line.axes
    xdata = line.get_xdata()
    ydata = line.get_ydata()

    if (x < xdata[0]) or (x > xdata[-1]):
        print('x label location is outside data range!')
        return

    #Find corresponding y co-ordinate and angle of the line
    ip = 1
    for i in range(len(xdata)):
        if x < xdata[i]:
            ip = i
            break

    y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])

    if not label:
        label = line.get_label()

    if align:
        #Compute the slope
        dx = xdata[ip] - xdata[ip-1]
        dy = ydata[ip] - ydata[ip-1]
        ang = degrees(atan2(dy,dx))

        #Transform to screen co-ordinates
        pt = np.array([x,y]).reshape((1,2))
        trans_angle = ax.transData.transform_angles(np.array((ang,)),pt)[0]

    else:
        trans_angle = 0

    #Set a bunch of keyword arguments
    if 'color' not in kwargs:
        kwargs['color'] = line.get_color()

    if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
        kwargs['ha'] = 'center'

    if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
        kwargs['va'] = 'center'

    if 'backgroundcolor' not in kwargs:
        kwargs['backgroundcolor'] = ax.get_facecolor()

    if 'clip_on' not in kwargs:
        kwargs['clip_on'] = True

    if 'zorder' not in kwargs:
        kwargs['zorder'] = 2.5

    ax.text(x,y,label,rotation=trans_angle,**kwargs)

def labelLines(lines,align=True,xvals=None,**kwargs):

    ax = lines[0].axes
    labLines = []
    labels = []

    #Take only the lines which have labels other than the default ones
    for line in lines:
        label = line.get_label()
        if "_line" not in label:
            labLines.append(line)
            labels.append(label)

    if xvals is None:
        xmin,xmax = ax.get_xlim()
        xvals = np.linspace(xmin,xmax,len(labLines)+2)[1:-1]

    for line,x,label in zip(labLines,xvals,labels):
        labelLine(line,x,label,align,**kwargs)

Test code to generate the pretty picture above:

from matplotlib import pyplot as plt
from scipy.stats import loglaplace,chi2

from labellines import *

X = np.linspace(0,1,500)
A = [1,2,5,10,20]
funcs = [np.arctan,np.sin,loglaplace(4).pdf,chi2(5).pdf]

plt.subplot(221)
for a in A:
    plt.plot(X,np.arctan(a*X),label=str(a))

labelLines(plt.gca().get_lines(),zorder=2.5)

plt.subplot(222)
for a in A:
    plt.plot(X,np.sin(a*X),label=str(a))

labelLines(plt.gca().get_lines(),align=False,fontsize=14)

plt.subplot(223)
for a in A:
    plt.plot(X,loglaplace(4).pdf(a*X),label=str(a))

xvals = [0.8,0.55,0.22,0.104,0.045]
labelLines(plt.gca().get_lines(),align=False,xvals=xvals,color='k')

plt.subplot(224)
for a in A:
    plt.plot(X,chi2(5).pdf(a*X),label=str(a))

lines = plt.gca().get_lines()
l1=lines[-1]
labelLine(l1,0.6,label=r'$Re=${}'.format(l1.get_label()),ha='left',va='bottom',align = False)
labelLines(lines[:-1],align=False)

plt.show()

slashes in url variables

You need to escape those but don't just replace it by %2F manually. You can use URLEncoder for this.

Eg URLEncoder.encode(url, "UTF-8")

Then you can say

yourUrl = "www.musicExplained/index.cfm/artist/" + URLEncoder.encode(VariableName, "UTF-8")

Eclipse Workspaces: What for and why?

Basically the scope of workspace(s) is divided in two points.

First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.

And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.

Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!

Find duplicate records in a table using SQL Server

Try this

with T1 AS
(
SELECT LASTNAME, COUNT(1) AS 'COUNT' FROM Employees GROUP BY LastName HAVING  COUNT(1) > 1
)
SELECT E.*,T1.[COUNT] FROM Employees E INNER JOIN T1 ON T1.LastName = E.LastName

Does my application "contain encryption"?

If you're not explicitly using an encryption library, or rolling your own encryption code, then I think the answer is "no"

don't fail jenkins build if execute shell fails

If there is nothing to push git returns exit status 1. Execute shell build step is marked as failed respectively. You can use OR statement || (double pipe).

git commit -m 'some messasge' || echo 'Commit failed. There is probably nothing to commit.'

That means, execute second argument if first failed (returned exit status > 0). Second command always returns 0. When there is nothing to push (exit status 1 -> execute second command) echo will return 0 and build step continues.

To mark build as unstable you can use post-build step Jenkins Text Finder. It can go through console output, match pattern (your echo) and mark build as unstable.

How to loop backwards in python?

To reverse a string without using reversed or [::-1], try something like:

def reverse(text):
    # Container for reversed string
    txet=""

    # store the length of the string to be reversed
    # account for indexes starting at 0
    length = len(text)-1

    # loop through the string in reverse and append each character
    # deprecate the length index
    while length>=0:
        txet += "%s"%text[length]
        length-=1
    return txet

What does the C++ standard state the size of int, long type to be?

As mentioned the size should reflect the current architecture. You could take a peak around in limits.h if you want to see how your current compiler is handling things.

How big can a MySQL database get before performance starts to degrade

The physical database size doesn't matter. The number of records don't matter.

In my experience the biggest problem that you are going to run in to is not size, but the number of queries you can handle at a time. Most likely you are going to have to move to a master/slave configuration so that the read queries can run against the slaves and the write queries run against the master. However if you are not ready for this yet, you can always tweak your indexes for the queries you are running to speed up the response times. Also there is a lot of tweaking you can do to the network stack and kernel in Linux that will help.

I have had mine get up to 10GB, with only a moderate number of connections and it handled the requests just fine.

I would focus first on your indexes, then have a server admin look at your OS, and if all that doesn't help it might be time to implement a master/slave configuration.

What is a singleton in C#?

I use it for lookup data. Load once from DB.

public sealed class APILookup
    {
        private static readonly APILookup _instance = new APILookup();
        private Dictionary<string, int> _lookup;

        private APILookup()
        {
            try
            {
                _lookup = Utility.GetLookup();
            }
            catch { }
        }

        static APILookup()
        {            
        }

        public static APILookup Instance
        {
            get
            {
                return _instance;
            }
        }
        public Dictionary<string, int> GetLookup()
        {
            return _lookup;
        }

    }

What algorithms compute directions from point A to point B on a map?

I see what's up with the maps in the OP:

Look at the route with the intermediate point specified: The route goes slightly backwards due to that road that isn't straight.

If their algorithm won't backtrack it won't see the shorter route.

Executing Javascript code "on the spot" in Chrome?

If you mean you want to execute the function inputted, yes, that is simple:

Use this JS code:

eval(document.getElementById( -- el ID -- ).value);

How can I get a first element from a sorted list?

You have to access lists a little differently than arrays in Java. See the javadocs for the List interface for more information.

playersList.get(0)

However if you want to find the smallest element in playersList, you shouldn't sort it and then get the first element. This runs very slowly compared to just searching once through the list to find the smallest element.

For example:

int smallestIndex = 0;
for (int i = 1; i < playersList.size(); i++) {
    if (playersList.get(i) < playersList.get(smallestIndex))
        smallestIndex = i;
}

playersList.get(smallestIndex);

The above code will find the smallest element in O(n) instead of O(n log n) time.

SQL Server Script to create a new user

Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.

Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:

CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO

Here is how you create a User with db_owner privileges using the Login you just declared:

Use YourDatabase;
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
    CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
    EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO

Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).

However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.

UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.

Add number of days to a date

Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.

Here's a little php function which takes care of that:

function add_days($date, $days) {
    $timeStamp = strtotime(date('Y-m-d',$date));
    $timeStamp+= 24 * 60 * 60 * $days;

    // ...clock change....
    if (date("I",$timeStamp) != date("I",$date)) {
        if (date("I",$date)=="1") { 
            // summer to winter, add an hour
            $timeStamp+= 60 * 60; 
        } else {
            // summer to winter, deduct an hour
            $timeStamp-= 60 * 60;           
        } // if
    } // if
    $cur_dat = mktime(0, 0, 0, 
                      date("n", $timeStamp), 
                      date("j", $timeStamp), 
                      date("Y", $timeStamp)
                     ); 
    return $cur_dat;
}

How to get the current loop index when using Iterator?

Use your own variable and increment it in the loop.

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Mutable changes the meaning of const from bitwise const to logical const for the class.

This means that classes with mutable members are longer be bitwise const and will no longer appear in read-only sections of the executable.

Furthermore, it modifies type-checking by allowing const member functions to change mutable members without using const_cast.

class Logical {
    mutable int var;

public:
    Logical(): var(0) {}
    void set(int x) const { var = x; }
};

class Bitwise {
    int var;

public:
    Bitwise(): var(0) {}
    void set(int x) const {
        const_cast<Bitwise*>(this)->var = x;
    }
};

const Logical logical; // Not put in read-only.
const Bitwise bitwise; // Likely put in read-only.

int main(void)
{
    logical.set(5); // Well defined.
    bitwise.set(5); // Undefined.
}

See the other answers for more details but I wanted to highlight that it isn't merely for type-saftey and that it affects the compiled result.

How to Populate a DataTable from a Stored Procedure

You can use a SqlDataAdapter:

    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);
    cmd.CommandType = CommandType.StoredProcedure;
    adapter.SelectCommand = cmd;
    DataTable dt = new DataTable();
    adapter.Fill(dt);

How to format x-axis time scale values in Chart.js v2

You could format the dates before you add them to your array. That is how I did. I used AngularJS

//convert the date to a standard format

var dt = new Date(date);

//take only the date and month and push them to your label array

$rootScope.charts.mainChart.labels.push(dt.getDate() + "-" + (dt.getMonth() + 1));

Use this array in your chart presentation

How we can bold only the name in table td tag not the value

Surround what you want to be bold with:

<span style="font-weight:bold">Your bold text</span>

This would go inside your <td> tag.

JavaScript - document.getElementByID with onClick

Perhaps you might want to use "addEventListener"

document.getElementById("test").addEventListener('click',function ()
{
    foo2();
   }  ); 

Hope it's still useful for you

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Ternary operators in JavaScript without an "else"

First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

Common Header / Footer with static HTML

The simplest way to do that is using plain HTML.

You can use one of these ways:

<embed type="text/html" src="header.html">

or:

<object name="foo" type="text/html" data="header.html"></object>

Change button text from Xcode?

Swift 5 Use button.setTitle()

  1. If using storyboards, make a IBOutlet reference.

@IBOutlet weak var button: UIButton!

  1. Call setTitle on the button followed by the text and the state.

button.setTitle("Button text here", forState: .normal)

Gradle version 2.2 is required. Current version is 2.10

I Had similar issue. Every project has his own gradle folder, check if in your project root there's another gradle folder:

/my_projects_root_folder/project/gradle
/my_projects_root_folder/gradle

If so, in every folder you'll find /gradle/wrapper/gradle-wrapper.properties.

Check if in /my_projects_root_folder/gradle/gradle-wrapper.properties gradle version at least match /my_projects_root_folder/ project/ gradle/ gradle-wrapper.properties gradle version

Or just delete/rename your /my_projects_root_folder/gradle and restart android studio and let Gradle sync work and download required gradle.

Is it possible to set ENV variables for rails development environment in my code?

Script for loading of custom .env file: Add the following lines to /config/environment.rb, between the require line, and the Application.initialize line:

# Load the app's custom environment variables here, so that they are loaded before environments/*.rb

app_environment_variables = File.join(Rails.root, 'config', 'local_environment.env')
if File.exists?(app_environment_variables)
  lines = File.readlines(app_environment_variables)
  lines.each do |line|
    line.chomp!
    next if line.empty? or line[0] == '#'
    parts = line.partition '='
    raise "Wrong line: #{line} in #{app_environment_variables}" if parts.last.empty?
    ENV[parts.first] = parts.last
  end
end

And config/local_environment.env (you will want to .gitignore it) will look like:

# This is ignored comment
DATABASE_URL=mysql2://user:[email protected]:3307/database
RACK_ENV=development

(Based on solution of @user664833)

How to check if X server is running?

$DISPLAY is the standard way. That's how users communicate with programs about which X server to use, if any.

Flatten nested dictionaries, compressing keys

def flatten(unflattened_dict, separator='_'):
    flattened_dict = {}

    for k, v in unflattened_dict.items():
        if isinstance(v, dict):
            sub_flattened_dict = flatten(v, separator)
            for k2, v2 in sub_flattened_dict.items():
                flattened_dict[k + separator + k2] = v2
        else:
            flattened_dict[k] = v

    return flattened_dict

ListAGG in SQLSERVER

In SQL Server 2017 STRING_AGG is added:

SELECT t.name,STRING_AGG (c.name, ',') AS csv
FROM sys.tables t
JOIN sys.columns c on t.object_id = c.object_id
GROUP BY t.name
ORDER BY 1

Also, STRING_SPLIT is usefull for the opposite case and available in SQL Server 2016

How do I pipe a subprocess call to a text file?

You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:

$ /path/to/the/script.py > output.txt

This will overwrite the file. You can use >> to append to it.

If you want errors to be logged in the file as well, use &>> or &>.

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

Monitor network activity in Android Phones

TCPDUMP is one of my favourite tools for analyzing network, but if you find difficult to cross-compile tcpdump for android, I'd recomend you to use some applications from the market.

These are the applications I was talking about:

  • Shark: Is small version of wireshark for Android phones). This program will create a *.pcap and you can read the file on PC with wireshark.
  • Shark Reader : This program allows you to read the *.pcap directly in your Android phone.

Shark app works with rooted devices, so if you want to install it, be sure that you have your device already rooted.

Good luck ;)

Xcode 8 shows error that provisioning profile doesn't include signing certificate

For those who still struggle with this problem in Xcode8. For me was a duplicate Certificate problem, this is how I solved it:

I read the answer of Nick and then I began my investigation. I checked all the keys and Certificates in my particular case (inside ~/Library/Keychains/System.keychain).

When I opened the file, I found that I had two iPhone Distribution Certificates (that was the certificate that Xcode was requesting me), one with the iOS Distribution private key that I have been using since the beginning, and another iPhone Distribution Certificate which its private Key had a name (iOS Distribution:NAME) that wasn´t familiar for me. I deleted this last certificate, started Xcode again and the problem was gone. xCode wasn´t able to resolve that conflict and that´s why it was giving signing certificate error all the time.

Check your keychains, maybe you have a duplicate certificate.

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

jdk7 32 bit windows version to download

As detailed in the Oracle Java SE Support Roadmap

After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive

Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe (64-bit is named jdk-7u80-windows-x64.exe.

Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget to grab the file without signing in.

wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"

What does "export default" do in JSX?

In Simple Words -

The export statement is used when creating JavaScript modules to export functions, objects, or primitive values from the module so they can be used by other programs with the import statement.

Here is a link to get clear understanding : MDN Web Docs

PDOException SQLSTATE[HY000] [2002] No such file or directory

If you are using Laravel Homestead, here is settings

(include Vagrant-Virtual Machine)

.bash-profile

alias vm="ssh [email protected] -p 2222"

database.php

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', '127.0.0.1'),
        'database'  => env('DB_DATABASE', 'homestead'),
        'username'  => env('DB_USERNAME', 'homestead'),
        'password'  => env('DB_PASSWORD', 'secret'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

Terminal

vm

vagrant@homestead:~/Code/projectFolder  php artisan migrate:install

Installing NumPy via Anaconda in Windows

Anaconda folder basically resides in C:\Users\\Anaconda. Try setting the PATH to this folder.

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

How do I use the JAVA_OPTS environment variable?

Just figured it out in Oracle Java the environmental variable is called: JAVA_TOOL_OPTIONS rather than JAVA_OPTS

Merge Two Lists in R

Here's some code that I ended up writing, based upon @Andrei's answer but without the elegancy/simplicity. The advantage is that it allows a more complex recursive merge and also differs between elements that should be connected with rbind and those that are just connected with c:

# Decided to move this outside the mapply, not sure this is 
# that important for speed but I imagine redefining the function
# might be somewhat time-consuming
mergeLists_internal <- function(o_element, n_element){
  if (is.list(n_element)){
    # Fill in non-existant element with NA elements
    if (length(n_element) != length(o_element)){
      n_unique <- names(n_element)[! names(n_element) %in% names(o_element)]
      if (length(n_unique) > 0){
        for (n in n_unique){
          if (is.matrix(n_element[[n]])){
            o_element[[n]] <- matrix(NA, 
                                     nrow=nrow(n_element[[n]]), 
                                     ncol=ncol(n_element[[n]]))
          }else{
            o_element[[n]] <- rep(NA, 
                                  times=length(n_element[[n]]))
          }
        }
      }

      o_unique <- names(o_element)[! names(o_element) %in% names(n_element)]
      if (length(o_unique) > 0){
        for (n in o_unique){
          if (is.matrix(n_element[[n]])){
            n_element[[n]] <- matrix(NA, 
                                     nrow=nrow(o_element[[n]]), 
                                     ncol=ncol(o_element[[n]]))
          }else{
            n_element[[n]] <- rep(NA, 
                                  times=length(o_element[[n]]))
          }
        }
      }
    }  

    # Now merge the two lists
    return(mergeLists(o_element, 
                      n_element))

  }
  if(length(n_element)>1){
    new_cols <- ifelse(is.matrix(n_element), ncol(n_element), length(n_element))
    old_cols <- ifelse(is.matrix(o_element), ncol(o_element), length(o_element))
    if (new_cols != old_cols)
      stop("Your length doesn't match on the elements,",
           " new element (", new_cols , ") !=",
           " old element (", old_cols , ")")
  }

  return(rbind(o_element, 
               n_element, 
               deparse.level=0))
  return(c(o_element, 
           n_element))
}
mergeLists <- function(old, new){
  if (is.null(old))
    return (new)

  m <- mapply(mergeLists_internal, old, new, SIMPLIFY=FALSE)
  return(m)
}

Here's my example:

v1 <- list("a"=c(1,2), b="test 1", sublist=list(one=20:21, two=21:22))
v2 <- list("a"=c(3,4), b="test 2", sublist=list(one=10:11, two=11:12, three=1:2))
mergeLists(v1, v2)

This results in:

$a
     [,1] [,2]
[1,]    1    2
[2,]    3    4

$b
[1] "test 1" "test 2"

$sublist
$sublist$one
     [,1] [,2]
[1,]   20   21
[2,]   10   11

$sublist$two
     [,1] [,2]
[1,]   21   22
[2,]   11   12

$sublist$three
     [,1] [,2]
[1,]   NA   NA
[2,]    1    2

Yeah, I know - perhaps not the most logical merge but I have a complex parallel loop that I had to generate a more customized .combine function for, and therefore I wrote this monster :-)

How to use multiple databases in Laravel

Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file

return [
    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
'mysqlOne' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST_ONE', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_ONE', 'forge'),
            'username' => env('DB_USERNAME_ONE', 'forge'),
            'password' => env('DB_PASSWORD_ONE', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
];

Once you have this you can create two base model class for each connection and define the connection name in those models

//BaseModel.php
protected $connection = 'mysql';

//BaseModelOne.php
protected $connection = 'mysqlOne';

You can extend these models to create more models for tables in each DB.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Create table variable in MySQL

If you don't want to store table in database then @Evan Todd already has been provided temporary table solution.

But if you need that table for other users and want to store in db then you can use below procedure.

Create below ‘stored procedure’:

————————————

DELIMITER $$

USE `test`$$

DROP PROCEDURE IF EXISTS `sp_variable_table`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_variable_table`()
BEGIN

SELECT CONCAT(‘zafar_’,REPLACE(TIME(NOW()),’:',’_')) INTO @tbl;

SET @str=CONCAT(“create table “,@tbl,” (pbirfnum BIGINT(20) NOT NULL DEFAULT ’0', paymentModes TEXT ,paymentmodeDetails TEXT ,shippingCharges TEXT ,shippingDetails TEXT ,hypenedSkuCodes TEXT ,skuCodes TEXT ,itemDetails TEXT ,colorDesc TEXT ,size TEXT ,atmDesc TEXT ,promotional TEXT ,productSeqNumber VARCHAR(16) DEFAULT NULL,entity TEXT ,entityDetails TEXT ,kmtnmt TEXT ,rating BIGINT(1) DEFAULT NULL,discount DECIMAL(15,0) DEFAULT NULL,itemStockDetails VARCHAR(38) NOT NULL DEFAULT ”) ENGINE=INNODB DEFAULT CHARSET=utf8");
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT ‘Table has been created’;
END$$

DELIMITER ;

———————————————–

Now you can execute this procedure to create a variable name table as per below-

call sp_variable_table();

You can check new table after executing below command-

use test;show tables like ‘%zafar%’; — test is here ‘database’ name.

You can also check more details at below path-

http://mydbsolutions.in/how-can-create-a-table-with-variable-name/

How to plot ROC curve in Python

When you need the probabilities as well... The following gets the AUC value and plots it all in one shot.

from sklearn.metrics import plot_roc_curve

plot_roc_curve(m,xs,y)

When you have the probabilities... you can't get the auc value and plots in one shot. Do the following:

from sklearn.metrics import roc_curve

fpr,tpr,_ = roc_curve(y,y_probas)
plt.plot(fpr,tpr, label='AUC = ' + str(round(roc_auc_score(y,m.oob_decision_function_[:,1]), 2)))
plt.legend(loc='lower right')

How to trigger click event on href element

Just want to let you guys know, the accepted answer doesn't always work.

Here's an example it will fail.

if <href='/list'>

href = $('css_selector').attr('href')
"/list"
href = document.querySelector('css_selector').href
"http://localhost/list"

or you could append the href you got from jQuery to this

href = document.URL +$('css_selector').attr('href');

or jQuery way

href = $('css_selector').prop('href')

Finally, invoke it to change the browser current page's url

window.location.href = href

or pop it out using window.open(url)

Here's an example in JSFiddle.

How to add a hook to the application context initialization event?

Create your annotation

  @Retention(RetentionPolicy.RUNTIME)
    public @interface AfterSpringLoadComplete {
    }

Create class

    public class PostProxyInvokerContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    ConfigurableListableBeanFactory factory;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            try {
                BeanDefinition definition = factory.getBeanDefinition(name);
                String originalClassName = definition.getBeanClassName();
                Class<?> originalClass = Class.forName(originalClassName);
                Method[] methods = originalClass.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AfterSpringLoadComplete.class)){
                        Object bean = context.getBean(name);
                        Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
                        currentMethod.invoke(bean);
                    }
                }
            } catch (Exception ignored) {
            }
        }
    }
}

Register this class by @Component annotation or in xml

<bean class="ua.adeptius.PostProxyInvokerContextListener"/>

and use annotation where you wan on any method that you want to run after context initialized, like:

   @AfterSpringLoadComplete
    public void init() {}

How do I request and receive user input in a .bat and use it to run a certain program?

I don't know the platform you're doing this on but I assume Windows due to the .bat extension.

Also I don't have a way to check this but this seems like the batch processor skips the If lines due to some errors and then executes the one with -dev.

You could try this by chaning the two jump targets (:yes and :no) along with the code. If then the line without -dev is executed you know your If lines are erroneous.

If so, please check if == is really the right way to do a comparison in .bat files.

Also, judging from the way bash does this stuff, %foo=="y" might evaluate to true only if %foo includes the quotes. So maybe "%foo"=="y" is the way to go.

Using Sockets to send and receive data

I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream:

Client:

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

Server:

Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());

boolean done = false;
while(!done) {
  byte messageType = dIn.readByte();

  switch(messageType)
  {
  case 1: // Type A
    System.out.println("Message A: " + dIn.readUTF());
    break;
  case 2: // Type B
    System.out.println("Message B: " + dIn.readUTF());
    break;
  case 3: // Type C
    System.out.println("Message C [1]: " + dIn.readUTF());
    System.out.println("Message C [2]: " + dIn.readUTF());
    break;
  default:
    done = true;
  }
}

dIn.close();

Obviously, you can send all kinds of data, not just bytes and strings (UTF).

Note that writeUTF writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535 bytes to send. This makes it possible for readUTF to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.

mysqldump exports only one table

In case you encounter an error like this

mysqldump: 1044 Access denied when using LOCK TABLES

A quick workaround is to pass the –-single-transaction option to mysqldump.

So your command will be like this.

mysqldump --single-transaction -u user -p DBNAME > backup.sql

Understanding INADDR_ANY for socket programming

INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")

What is the meaning of {...this.props} in Reactjs

It is ES-6 feature. It means you extract all the properties of props in div.{... }

operator is used to extract properties of an object.

How to create a project from existing source in Eclipse and then find it?

Easiest Method:

  1. Put all source files into one directory named after your project. i.e. "ProjectName" You can keep this directory in your workspace or it can be somewhere else.
  2. Start a new project in eclipse and name it using that same project name.
  3. Uncheck the "use default location" box and find the directory where your project is unless your project is already in the workspace - then you must not uncheck the "use default location" box
  4. Click 'next'.

Eclipse should be smart enough to figure out what's going on. After clicking next, it will show you all of the files it found in that directory. It will just automatically add those files to your project. Voilà!

Set HTML element's style property in javascript

You can try grabbing the cssText and className.

var css1 = table.rows[1].style.cssText;
var css2 = table.rows[2].style.cssText;
var class1 = table.rows[1].className;
var class2 = table.rows[2].className;

// sort

// loop
    if (i%2==0) {
        table.rows[i].style.cssText = css1;
        table.rows[i].className = class1;
    } else {
        table.rows[i].style.cssText = css2;
        table.rows[i].className = class2;
    }

Not entirely sure about browser compatibility with cssText, though.

How can I rollback a git repository to a specific commit?

Most suggestions are assuming that you need to somehow destroy the last 20 commits, which is why it means "rewriting history", but you don't have to.

Just create a new branch from the commit #80 and work on that branch going forward. The other 20 commits will stay on the old orphaned branch.

If you absolutely want your new branch to have the same name, remember that branch are basically just labels. Just rename your old branch to something else, then create the new branch at commit #80 with the name you want.

Getting rid of bullet points from <ul>

I had an identical problem.

The solution was that the bullet was added via a background image, NOT via list-style-type. A quick 'background: none' and Bob's your uncle!

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

Excel plot time series frequency with continuous xaxis

I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog

Non-uniformly distributed data can be plotted in excel in

  • X Y (Scatter Plots)
  • Linear plots with Date axis
    • These don't take time into account, only days.
    • This method is quite cumbersome as it requires translating your time units to days, months, or years.. then change the axis labels... Not Recommended

Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.

1- Add the center point to your data series

+---------------+-------+------+
|    Time       | Time  | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 |  12  |
| 09:00 - 10:00 | 09:30 |  13  |
| 10:00 - 11:00 | 10:30 |  10  |
| 13:00 - 14:00 | 13:30 |   5  |
| 14:00 - 15:00 | 14:30 |  14  |
+---------------+-------+------+

2- Create a Scatter Plot

3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:

  • Minimum : Fix : 0.33333
  • Maximum : Fix : 0.625
  • Major unit : Fix : 0.041667

Line Scatter Plot


Alternative Display:

Make the points turn into columns:

To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.

1- You're going to need to add several rows where we draw the line and disjoint the data

+-------+------+
| Time  | Freq |
+-------+------+
| 08:30 |   0  |
| 08:30 |  12  |
|       |      |
| 09:30 |   0  |
| 09:30 |  13  |
|       |      |
| 10:30 |   0  |
| 10:30 |  10  |
|       |      |
| 13:30 |   0  |
| 13:30 |   5  |
|       |      |
| 14:30 |   0  |
| 14:30 |  14  |
+-------+------+

2- Plot an X Y (Scatter) Chart with Lines.

3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.

Bar-Line Scatter Plot

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

I disabled all installed extensions in Chrome - works for me. I have now clear console without errors.

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What do numbers using 0x notation mean?

The numbers starting with 0x are hexadecimal (base 16).0x6400 represents 25600.

To convert,

  • multiply the last digit times 1
  • add second-last digit times 16 (16^1)
  • add third-last digit times 256 (16^2)
  • add fourth-last digit times 4096 (16^3)
  • ...and so on

The factors 1, 16, 256, etc. are the increasing powers of 16.

0x6400 = (0*1) + (0*16^1) + (4*16^2) + (6*16^3) = 25600 

or

0x6400 = (0*1) + (0*16) + (4*256) + (6*4096) = 25600 

Python script to copy text to clipboard

Use Tkinter:

https://stackoverflow.com/a/4203897/2804197

try:
    from Tkinter import Tk
except ImportError:
    from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

(Original author: https://stackoverflow.com/users/449571/atomizer)

Iterate over a Javascript associative array in sorted order

You can use the keys function from the underscore.js library to get the keys, then the sort() array method to sort them:

var sortedKeys = _.keys(dict).sort();

The keys function in the underscore's source code:

// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    return keys;
};    

// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
    return hasOwnProperty.call(obj, key);
};

Display unescaped HTML in Vue.js

Before using v-html, you have to make sure that the element which you escape is sanitized in case you allow user input, otherwise you expose your app to xss vulnerabilities.

More info here: https://vuejs.org/v2/guide/security.html

I highly encourage you that instead of using v-html to use this npm package

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

Refresh Part of Page (div)

You need to do that on the client side for instance with jQuery.

Let's say you want to retrieve HTML into div with ID mydiv:

<h1>My page</h1>
<div id="mydiv">
    <h2>This div is updated</h2>
</div>

You can update this part of the page with jQuery as follows:

$.get('/api/mydiv', function(data) {
  $('#mydiv').html(data);
});

In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.

See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/

html <input type="text" /> onchange event not working

use following events instead of "onchange"

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

How to make a button redirect to another page using jQuery or just Javascript

And in Rails 3 with CoffeeScript using unobtrusive JavaScript (UJS):

Add to assets/javascripts/my_controller.js.coffee:

$ ->
  $('#field_name').click ->
    window.location.href = 'new_url'

which reads: when the document.ready event has fired, add an onclick event to a DOM object whose ID is field_name which executes the javascript window.location.href='new_url';

Cannot read configuration file due to insufficient permissions

Changing the Process Model Identity to LocalSystem fixed this issue for me. You can find this setting if you right click on the application pool and chose "Advanced Settings". I'm running IIS 7.5.

Save classifier to disk in scikit-learn

Classifiers are just objects that can be pickled and dumped like any other. To continue your example:

import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
    cPickle.dump(gnb, fid)    

# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
    gnb_loaded = cPickle.load(fid)

Edit: if you are using a sklearn Pipeline in which you have custom transformers that cannot be serialized by pickle (nor by joblib), then using Neuraxle's custom ML Pipeline saving is a solution where you can define your own custom step savers on a per-step basis. The savers are called for each step if defined upon saving, and otherwise joblib is used as default for steps without a saver.

Days between two dates?

Referencing my comments on other answers. This is how I would work out the difference in days based on 24 hours and calender days. the days attribute works well for 24 hours and the function works best for calendar checks.

from datetime import timedelta, datetime

def cal_days_diff(a,b):

    A = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    B = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    return (A - B).days

if __name__ == '__main__':

    x = datetime(2013, 06, 18, 16, 00)
    y = datetime(2013, 06, 19, 2, 00)

    print (y - x).days          # 0
    print cal_days_diff(y, x)   # 1 

    z = datetime(2013, 06, 20, 2, 00)

    print (z - x).days          # 1
    print cal_days_diff(z, x)   # 2 

JavaFX: How to get stage from controller during initialization?

I know it's not the answer you want, but IMO the proposed solutions are not good (and your own way is). Why? Because they depend on the application state. In JavaFX, a control, a scene and a stage do not depend on each other. This means a control can live without being added to a scene and a scene can exist without being attached to a stage. And then, at a time instant t1, control can get attached to a scene and at instant t2, that scene can be added to a stage (and that explains why they are observable properties of each other).

So the approach that suggests getting the controller reference and invoking a method, passing the stage to it adds a state to your application. This means you need to invoke that method at the right moment, just after the stage is created. In other words, you need to follow an order now: 1- Create the stage 2- Pass this created stage to the controller via a method.

You cannot (or should not) change this order in this approach. So you lost statelessness. And in software, generally, state is evil. Ideally, methods should not require any call order.

So what is the right solution? There are two alternatives:

1- Your approach, in the controller listening properties to get the stage. I think this is the right approach. Like this:

pane.sceneProperty().addListener((observableScene, oldScene, newScene) -> {
    if (oldScene == null && newScene != null) {
        // scene is set for the first time. Now its the time to listen stage changes.
        newScene.windowProperty().addListener((observableWindow, oldWindow, newWindow) -> {
            if (oldWindow == null && newWindow != null) {
                // stage is set. now is the right time to do whatever we need to the stage in the controller.
                ((Stage) newWindow).maximizedProperty().addListener((a, b, c) -> {
                    if (c) {
                        System.out.println("I am maximized!");
                    }
                });
            }
        });
    }
});

2- You do what you need to do where you create the Stage (and that's not what you want):

Stage stage = new Stage();
stage.maximizedProperty().addListener((a, b, c) -> {
            if (c) {
                System.out.println("I am maximized!");
            }
        });
stage.setScene(someScene);
...

Length of string in bash

To get the length of a string stored in a variable, say:

myvar="some string"
size=${#myvar} 

To confirm it was properly saved, echo it:

$ echo "$size"
11

tsc is not recognized as internal or external command

In the VSCode file tasks.json, the "command": "tsc" will try to find the tsc windows command script in some folder that it deems to be your modules folder.

If you know where the command npm install -g typescript or npm install typescript is saving to, I would recommend replacing:

"command": "tsc"

with

"command": "D:\\Projects\\TS\\Tutorial\\node_modules\\.bin\\tsc"

where D:\\...\\bin is the folder that contains my tsc windows executable

Will determine where my vscode is natively pointing to right now to find the tsc and fix it I guess.

Get css top value as number not as string?

A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")

Android Stop Emulator from Command Line

List of devices attached emulator-5584 host emulator-5580 host emulator-5576 host emulator-5572 host emulator-5568 host emulator-5564 host emulator-5560 host

C:\Users\Administrator>adb -s emulator-5584 emu kill error: could not connect to TCP port 5584: cannot connect to 127.0.0.1:5584: No connection could be made because the target machine actively refused it. (10061)

NOTE: gui of emulator is not running but still it's showing

SOLUTION:

adb kill-server

start emulator using:

emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_19

I hope this will help you!

How to remove old Docker containers

I wanted to add this simple answer as I didn't see it, and the question is specifically "old" not "all".

sudo docker container prune --filter "until=24h"

Adjust the 24h for whatever time span you want to remove containers that are older than.

How to redirect docker container logs to a single file?

The easiest way that I use is this command on terminal:

docker logs elk > /home/Desktop/output.log

structure is:

docker logs <Container Name> > path/filename.log

How can I account for period (AM/PM) using strftime?

format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.

Access Database opens as read only

In my case it was because it was being backed up my a background process which started before I opened Access. It isn't normally a problem if it have the database open when the backup starts.

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

C# removing items from listbox

You can't modify the references in an enumerator whilst you enumerate over it; you must keep track of the ones to remove then remove them.

This is an example of the work around:

List<string> listbox = new List<string>();
List<object> toRemove = new List<object>();

foreach (string item in listbox)
{
    string removelistitem = "OBJECT";
    if (item.Contains(removelistitem))
    {
        toRemove.Add(item);
    }
}

foreach (string item in toRemove)
{
    listbox.Remove(item);
}

But if you're using c#3.5, you could say something like this.

listbox.Items = listbox.Items.Select(n => !n.Contains("OBJECT"));

Android: How to bind spinner to custom object list?

By far the simplest way that I've found:

@Override
public String toString() {
    return this.label;           
}

Now you can stick any object in your spinner, and it will display the specified label.

Check if property has attribute

To update and/or enhance the answer by @Hans Passant I would separate the retrieval of the property into an extension method. This has the added benefit of removing the nasty magic string in the method GetProperty()

public static class PropertyHelper<T>
{
    public static PropertyInfo GetProperty<TValue>(
        Expression<Func<T, TValue>> selector)
    {
        Expression body = selector;
        if (body is LambdaExpression)
        {
            body = ((LambdaExpression)body).Body;
        }
        switch (body.NodeType)
        {
            case ExpressionType.MemberAccess:
                return (PropertyInfo)((MemberExpression)body).Member;
            default:
                throw new InvalidOperationException();
        }
    }
}

Your test is then reduced to two lines

var property = PropertyHelper<MyClass>.GetProperty(x => x.MyProperty);
Attribute.IsDefined(property, typeof(MyPropertyAttribute));

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

i followed all the suggested steps, in particular the ones provided from ios_dev but my iPhone was not recognized from Xcode and i was not able to debug over WiFi. Right click on the left panel over my iDevice in "Devices and Simulators" window, then "Connect via IP Address...", inserted the iPhone IP and now it correctly works

How to download image using requests

Following code snippet downloads a file.

The file is saved with its filename as in specified url.

import requests

url = "http://example.com/image.jpg"
filename = url.split("/")[-1]
r = requests.get(url, timeout=0.5)

if r.status_code == 200:
    with open(filename, 'wb') as f:
        f.write(r.content)

Can I grep only the first n lines of a file?

For folks who find this on Google, I needed to search the first n lines of multiple files, but to only print the matching filenames. I used

 gawk 'FNR>10 {nextfile} /pattern/ { print FILENAME ; nextfile }' filenames

The FNR..nextfile stops processing a file once 10 lines have been seen. The //..{} prints the filename and moves on whenever the first match in a given file shows up. To quote the filenames for the benefit of other programs, use

 gawk 'FNR>10 {nextfile} /pattern/ { print "\"" FILENAME "\"" ; nextfile }' filenames

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

As others have stated, regular (traditional) functions use this from the object that called the function, (e.g. a button that was clicked). Instead, arrow functions use this from the object that defines the function.

Consider two almost identical functions:

regular = function() {
  ' Identical Part Here;
}


arrow = () => {
  ' Identical Part Here;
}

The snippet below demonstrates the fundamental difference between what this represents for each function. The regular function outputs [object HTMLButtonElement] whereas the arrow function outputs [object Window].

_x000D_
_x000D_
<html>_x000D_
 <button id="btn1">Regular: `this` comes from "this button"</button>_x000D_
 <br><br>_x000D_
 <button id="btn2">Arrow: `this` comes from object that defines the function</button>_x000D_
 <p id="res"/>_x000D_
_x000D_
 <script>_x000D_
  regular = function() {_x000D_
    document.getElementById("res").innerHTML = this;_x000D_
  }_x000D_
_x000D_
  arrow = () => {_x000D_
    document.getElementById("res").innerHTML = this;_x000D_
  }_x000D_
_x000D_
  document.getElementById("btn1").addEventListener("click", regular);_x000D_
  document.getElementById("btn2").addEventListener("click", arrow);_x000D_
 </script>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Determine if map contains a value for a key?

Check the return value of find against end.

map<int, Bar>::iterator it = m.find('2');
if ( m.end() != it ) { 
  // contains
  ...
}

Android BroadcastReceiver within Activity

Extends the ToastDisplay class with BroadcastReceiver and register the receiver in the manifest file,and dont register your broadcast receiver in onResume() .

<application
  ....
  <receiver android:name=".ToastDisplay">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

if you want to register in activity then register in the onCreate() method e.g:

onCreate(){

    sentSmsBroadcastCome = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "SMS SENT!!", Toast.LENGTH_SHORT).show();
        }
    };
    IntentFilter filterSend = new IntentFilter();
    filterSend.addAction("m.sent");
    registerReceiver(sentSmsBroadcastCome, filterSend);
}

Angular 2 two way binding using ngModel is not working

For newer versions of Angular:

  1. -write it as [(ngModel)] = yourSearch

  2. declare a empty variable(property) named as yourSearch in .ts file

  3. add FormsModule in app.module.ts file from - @angular/forms;

  4. if your application is running, then restart it as you made changes in its module.ts file

Select all from table with Laravel and Eloquent

There are 3 ways that one can do that.

1.

$entireTable = TableModelName::all();

eg,

$posts = Posts::get(); 
  1. put this line before the class in the controller

    use Illuminate\Support\Facades\DB; // this will import the DB facade into your controller class

Now in the class

$posts = DB::table('posts')->get(); // it will get the entire table
  1. put this line before the class in the controller

    Same import the DB facade like method 2

Now in the controller

$posts = DB::select('SELECT * FROM posts');

How do I call a specific Java method on a click/submit event of a specific button in JSP?

You can try adding action="#{yourBean.function1}" on each button (changing of course the method function2, function3, or whatever you need). If that does not work, you can try the same with the onclick event.

Anyway, it would be easier to help you if you tell us what kind of buttons are you trying to use, a4j:commandButton or whatever you are using.

How can I get selector from jQuery object

http://www.selectorgadget.com/ is a bookmarklet designed explicitly for this use case.

That said, I agree with most other people in that you should just learn CSS selectors yourself, trying to generate them with code is not sustainable. :)

Which characters make a URL invalid?

All valid characters that can be used in a URI (a URL is a type of URI) are defined in RFC 3986.

All other characters can be used in a URL provided that they are "URL Encoded" first. This involves changing the invalid character for specific "codes" (usually in the form of the percent symbol (%) followed by a hexadecimal number).

This link, HTML URL Encoding Reference, contains a list of the encodings for invalid characters.

How to SELECT the last 10 rows of an SQL table which has no ID field?

You can use the "ORDER BY DESC" option, then put it back in the original order:

(SELECT * FROM tablename ORDER BY id DESC LIMIT 10) ORDER BY id;

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

How to get a cross-origin resource sharing (CORS) post request working

If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…

For example in one <VirtualHost> that uses SSL add the two following directives:

SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth

Make sure the following apache modules are loaded (load them using a2enmod):

  • proxy
  • proxy_connect
  • proxy_http

Obviously you'll have to change your AJAX requests url in order to use the apache proxy…

Increment counter with loop

what led me to this page is that I set within a page then the inside of an included page I did the increment

and here is the problem

so to solve such a problem, simply use scope="request" when you declare the variable or the increment

//when you set the variale add scope="request"
<c:set var="nFilters" value="${0}" scope="request"/>
//the increment, it can be happened inside an included page
<c:set var="nFilters" value="${nFilters + 1}"  scope="request" />

hope this saves your time

Flutter: Setting the height of the AppBar

You can use the toolbarHeight property of Appbar, it does exactly what you want.

Accurate way to measure execution times of php scripts

Here is my script to measure average time

<?php

$times = [];
$nbrOfLoops = 4;
for ($i = 0; $i < $nbrOfLoops; ++$i) {
    $start = microtime(true);
    sleep(1);
    $times[] = microtime(true) - $start;
}

echo 'Average: ' . (array_sum($times) / count($times)) . 'seconds';

PostgreSQL: insert from another table

For referential integtity :

insert into  main_tbl (col1, ref1, ref2, createdby)
values ('col1_val',
        (select ref1 from ref1_tbl where lookup_val = 'lookup1'),
        (select ref2 from ref2_tbl where lookup_val = 'lookup2'),
        'init-load'
       );

How can I initialize base class member variables in derived class constructor?

Leaving aside the fact that they are private, since a and b are members of A, they are meant to be initialized by A's constructors, not by some other class's constructors (derived or not).

Try:

class A
{
    int a, b;

protected: // or public:
    A(int a, int b): a(a), b(b) {}
};

class B : public A
{
    B() : A(0, 0) {}
};

How to declare an ArrayList with values?

You can do like this :

List<String> temp = new ArrayList<String>(Arrays.asList("1", "12"));

How to take input in an array + PYTHON?

arr = []
elem = int(raw_input("insert how many elements you want:"))
for i in range(0, elem):
    arr.append(int(raw_input("Enter next no :")))
print arr

What does -z mean in Bash?

test -z returns true if the parameter is empty (see man sh or man test).

json parsing error syntax error unexpected end of input

Don't Return Empty Json

In My Case I was returning Empty Json String in .Net Core Web API Project.

So I Changed My Code

From

 return Ok();

To

 return Ok("Done");

It seems you have to return some string or object.

Hope this helps.

Convert float to std::string in C++

If you're worried about performance, check out the Boost::lexical_cast library.

DateTime to javascript date

This method is working for me:

   public sCdateToJsDate(cSDate: any): Date {
        // cSDate is '2017-01-24T14:14:55.807'
        var datestr = cSDate.toString();
        var dateAr = datestr.split('-');
        var year = parseInt(dateAr[0]);
        var month = parseInt(dateAr[1])-1;
        var day = parseInt(dateAr[2].substring(0, dateAr[2].indexOf("T")));
        var timestring = dateAr[2].substring(dateAr[2].indexOf("T") + 1);
        var timeAr = timestring.split(":");
        var hour = parseInt(timeAr[0]);
        var min = parseInt(timeAr[1]);
        var sek = parseInt(timeAr[2]);
        var date = new Date(year, month, day, hour, min, sek, 0);
        return date;
    }

Jquery resizing image

$(document).ready(function(){
    $('img').each(function(){
        var maxWidth = 660;
        var ratio = 0;
        var img = $(this);

        if(img.width() > maxWidth){
            ratio = img.height() / img.width();
            img.attr('width', maxWidth);
            img.attr('height', (maxWidth*ratio));   
        }
    });
});

that will do the magic trick for everyone using latest jquery. Be sure you set your selector right (I used $('img') but that can be different in your case). This only works for landscape mode. But if you look at it, only a few things have to be done to set it to portrait, aka, if img.height() > maxHeight) stuff

LINQ to SQL - How to select specific columns and return strongly typed list

The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

About the differences, there is an important one in the results between querySelectorAll and getElementsByClassName: the return value is different. querySelectorAll will return a static collection, while getElementsByClassName returns a live collection. This could lead to confusion if you store the results in a variable for later use:

  • A variable generated with querySelectorAll will contain the elements that fulfilled the selector at the moment the method was called.
  • A variable generated with getElementsByClassName will contain the elements that fulfilled the selector when it is used (that may be different from the moment the method was called).

For example, notice how even if you haven't reassigned the variables aux1 and aux2, they contain different values after updating the classes:

_x000D_
_x000D_
// storing all the elements with class "blue" using the two methods_x000D_
var aux1 = document.querySelectorAll(".blue");_x000D_
var aux2 = document.getElementsByClassName("blue");_x000D_
_x000D_
// write the number of elements in each array (values match)_x000D_
console.log("Number of elements with querySelectorAll = " + aux1.length);_x000D_
console.log("Number of elements with getElementsByClassName = " + aux2.length);_x000D_
_x000D_
// change one element's class to "blue"_x000D_
document.getElementById("div1").className = "blue";_x000D_
_x000D_
// write the number of elements in each array (values differ)_x000D_
console.log("Number of elements with querySelectorAll = " + aux1.length);_x000D_
console.log("Number of elements with getElementsByClassName = " + aux2.length);
_x000D_
.red { color:red; }_x000D_
.green { color:green; }_x000D_
.blue { color:blue; }
_x000D_
<div id="div0" class="blue">Blue</div>_x000D_
<div id="div1" class="red">Red</div>_x000D_
<div id="div2" class="green">Green</div>
_x000D_
_x000D_
_x000D_

Can I have multiple background images using CSS?

If you want multiple background images but don't want them to overlap, you can use this CSS:

body {
  font-size: 13px;
  font-family:Century Gothic, Helvetica, sans-serif;
  color: #333;
  text-align: center;
  margin:0px;
  padding: 25px;
}

#topshadow {
  height: 62px
  width:1030px;
  margin: -62px
  background-image: url(images/top-shadow.png);
}

#pageborders {
width:1030px;
min-height:100%;
margin:auto;        
    background:url(images/mid-shadow.png);
}

#bottomshadow {
    margin:0px;
height:66px;
width:1030px;
background:url(images/bottom-shadow.png);
}

#page {
  text-align: left;
  margin:62px, 0px, 20px;
  background-color: white;
  margin:auto;
  padding:0px;
  width:1000px;
}

with this HTML structure:

<body 

<?php body_class(); ?>>

  <div id="topshadow">
  </div>

  <div id="pageborders">

    <div id="page">
    </div>
  </div>
</body>

Pausing a batch file for amount of time

ping -n 11 -w 1000 127.0.0.1 > nul

Update

Beginner's mistake. Ping doesn't wait 1000 ms before or after an request, but inbetween requests. So to wait 10 seconds, you'll have to do 11 pings to have 10 'gaps' of a second inbetween.

Wrap text in <td> tag

This worked for me with some css frameworks (material design lite [MDL]).

table {
  table-layout: fixed;
  white-space: normal!important;
}

td {
  word-wrap: break-word;
}

How do I draw a circle in iOS Swift?

I find Core Graphics to be pretty simple for Swift 3:

if let cgcontext = UIGraphicsGetCurrentContext() {
    cgcontext.strokeEllipse(in: CGRect(x: center.x-diameter/2, y: center.y-diameter/2, width: diameter, height: diameter))
}

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How do I Validate the File Type of a File Upload?

Avoid the standard Asp.Net control and use the NeadUpload component from Brettle Development: http://www.brettle.com/neatupload

Faster, easier to use, no worrying about the maxRequestLength parameter in config files and very easy to integrate.

Changing password with Oracle SQL Developer

Depending on the admin settings, you may have to specify your old password using the REPLACE option

alter user <username> identified by <newpassword> replace <oldpassword> 

Set default host and port for ng serve in config file

You can save these in a file, but you have to to put it in .ember-cli (at the moment, at least); see https://github.com/angular/angular-cli/issues/1156#issuecomment-227412924

{
"port": 4201,
"liveReload": true,
"host": "dev.domain.org",
"live-reload-port": 49153
}

edit: you can now set these in angular-cli.json as of commit https://github.com/angular/angular-cli/commit/da255b0808dcbe2f9da62086baec98dacc4b7ec9, which is in build 1.0.0-beta.30

Convert a secure string to plain text

In PS 7, you can use ConvertFrom-SecureString and -AsPlainText:

 $UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/ConvertFrom-SecureString?view=powershell-7#parameters

ConvertFrom-SecureString
           [-SecureString] <SecureString>
           [-AsPlainText]
           [<CommonParameters>]

Excel formula to reference 'CELL TO THE LEFT'

When creating your conditional formatting, set the range to which it applies to what you want (the whole sheet), then enter a relative formula (remove the $ signs) as if you were only formatting the upper-left corner.

Excel will properly apply the formatting to the rest of the cells accordingly.

In this example, starting in B1, the left cell would be A1. Just use that--no advanced formula required.


If you're looking for something more advanced, you can play around with column(), row(), and indirect(...).

Is there a way to get the XPath in Google Chrome?

You can try using Chrome Web Extension TruePath which dynamically generates the relative XPath on right click on the web page and display all the XPath as menu items.

How to check if a variable exists in a FreeMarker template?

For versions previous to FreeMarker 2.3.7

You can not use ?? to handle missing values, the old syntax is:

<#if userName?exists>
   Hi ${userName}, How are you?
</#if>

Adding a parameter to the URL with JavaScript

Vianney Bajart's answer is correct; however, URL will only work if you have the complete URL with port, host, path and query:

new URL('http://server/myapp.php?id=10&enabled=true')

And URLSearchParams will only work if you pass only the query string:

new URLSearchParams('?id=10&enabled=true')

If you have an incomplete or relative URL and don't care for the base URL, you can just split by ? to get the query string and join later like this:

function setUrlParams(url, key, value) {
  url = url.split('?');
  usp = new URLSearchParams(url[1]);
  usp.set(key, value);
  url[1] = usp.toString();
  return url.join('?');
}

let url = 'myapp.php?id=10';
url = setUrlParams(url, 'enabled', true);  // url = 'myapp.php?id=10&enabled=true'
url = setUrlParams(url, 'id', 11);         // url = 'myapp.php?id=11&enabled=true'

Not compatible with Internet Explorer.

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

Spark - SELECT WHERE or filtering?

According to spark documentation "where() is an alias for filter()"

filter(condition) Filters rows using the given condition. where() is an alias for filter().

Parameters: condition – a Column of types.BooleanType or a string of SQL expression.

>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]

>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]

Cannot find "Package Explorer" view in Eclipse

You might be in debug mode. If this is the problem, you can simply click on the "Java" button (next to the "Debug" button) in the upper-right hand corner, or click on "Open Perspective" and then select "Java (default)" from the "Open Perspective" window.

Retrieving Android API version programmatically

Build.VERSION.RELEASE;

That will give you the actual numbers of your version; aka 2.3.3 or 2.2. The problem with using Build.VERSION.SDK_INT is if you have a rooted phone or custom rom, you could have a non standard OS (aka my android is running 2.3.5) and that will return a null when using Build.VERSION.SDK_INT so Build.VERSION.RELEASE will work no matter using standard Android version or not !

To use it, you could just do this;

String androidOS = Build.VERSION.RELEASE;

gdb: "No symbol table is loaded"

First of all, what you have is a fully compiled program, not an object file, so drop the .o extension. Now, pay attention to what the error message says, it tells you exactly how to fix your problem: "No symbol table is loaded. Use the "file" command."

(gdb) exec-file test
(gdb) b 2
No symbol table is loaded.  Use the "file" command.
(gdb) file test
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Or just pass the program on the command line.

$ gdb test
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Angular JS break ForEach

There's no way to do this. See https://github.com/angular/angular.js/issues/263. Depending on what you're doing you can use a boolean to just not going into the body of the loop. Something like:

var keepGoing = true;
angular.forEach([0,1,2], function(count){
  if(keepGoing) {
    if(count == 1){
      keepGoing = false;
    }
  }
});