Programs & Examples On #Bsod

The Blue Screen of Death (also called BSoD, Blue Screen, or bluescreen) is the error screen displayed by the Microsoft Windows family of operating systems upon encountering a critical error, of a non-recoverable nature.

How to serialize object to CSV file?

For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.

EDIT

According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !

By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.

I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):

You called the draw() method with the wrong type of data rather than a DataTable or DataView.

The solution would be: replace jsapi and just use loader.js with:

google.charts.load('current', {packages: ['corechart']}) and 
google.charts.setOnLoadCallback 

-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

How to log a method's execution time exactly in milliseconds?

NSDate *methodStart = [NSDate date];

/* ... Do whatever you need to do ... */

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

Swift:

let methodStart = NSDate()

/* ... Do whatever you need to do ... */

let methodFinish = NSDate()
let executionTime = methodFinish.timeIntervalSinceDate(methodStart)
print("Execution time: \(executionTime)")

Swift3:

let methodStart = Date()

/* ... Do whatever you need to do ... */

let methodFinish = Date()
let executionTime = methodFinish.timeIntervalSince(methodStart)
print("Execution time: \(executionTime)")

Easy to use and has sub-millisecond precision.

How to increase the clickable area of a <a> tag button?

If you're using HTML 5, i.e. the doctype

<!doctype html>

then you can just use block-level links.

<a href="google.com">
  <div class="hello">
    ..
  </div>
</a>

Call a child class method from a parent class object

One possible solution can be

class Survey{
  void renderSurvey(Question q) {
  /*
      Depending on the type of question (choice, dropdwn or other, I have to render
      the question on the UI. The class that calls this doesnt have compile time 
      knowledge of the type of question that is going to be rendered. Each question 
      type has its own rendering function. If this is for choice , I need to access 
      its functions using q. 
  */
  if(q.getOption() instanceof ChoiceQuestionOption)
  {
    ChoiceQuestionOption choiceQuestion = (ChoiceQuestionOption)q.getOption();
    boolean result = choiceQuestion.getMultiple();
    //do something with result......
  }
 }
}

DataTables: Cannot read property style of undefined

POSSIBLE CAUSES

  • Number of th elements in the table header or footer differs from number of columns in the table body or defined using columns option.
  • Attribute colspan is used for th element in the table header.
  • Incorrect column index specified in columnDefs.targets option.

SOLUTIONS

  • Make sure that number of th elements in the table header or footer matches number of columns defined in the columns option.
  • If you use colspan attribute in the table header, make sure you have at least two header rows and one unique th element for each column. See Complex header for more information.
  • If you use columnDefs.targets option, make sure that zero-based column index refers to existing columns.

LINKS

See jQuery DataTables: Common JavaScript console errors - TypeError: Cannot read property ‘style’ of undefined for more information.

Where to find Java JDK Source Code?

I had this problem with my Ubuntu.

All I needed to do to get sources for my java insallation was:

sudo apt-get install sun-java6-source 

Mockito match any class argument

the solution from millhouse is not working anymore with recent version of mockito

This solution work with java 8 and mockito 2.2.9

where ArgumentMatcher is an instanceof org.mockito.ArgumentMatcher

public class ClassOrSubclassMatcher<T> implements ArgumentMatcher<Class<T>> {

   private final Class<T> targetClass;

    public ClassOrSubclassMatcher(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public boolean matches(Class<T> obj) {
        if (obj != null) {
            if (obj instanceof Class) {
                return targetClass.isAssignableFrom( obj);
            }
        }
        return false;
    }
}

And the use

when(a.method(ArgumentMatchers.argThat(new ClassOrSubclassMatcher<>(A.class)))).thenReturn(b);

How to execute a shell script on a remote server using Ansible?

You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

C++ callback using class member

What you want to do is to make an interface which handles this code and all your classes implement the interface.

class IEventListener{
public:
   void OnEvent(int x) = 0;  // renamed Callback to OnEvent removed the instance, you can add it back if you want.
};


class MyClass :public IEventListener
{
    ...
    void OnEvent(int x); //typically such a function is NOT static. This wont work if it is static.
};

class YourClass :public IEventListener
{

Note that for this to work the "Callback" function is non static which i believe is an improvement. If you want it to be static, you need to do it as JaredC suggests with templates.

How can I use pickle to save a dict?

In general, pickling a dict will fail unless you have only simple objects in it, like strings and integers.

Python 2.7.9 (default, Dec 11 2014, 01:21:43) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import *
>>> type(globals())     
<type 'dict'>
>>> import pickle
>>> pik = pickle.dumps(globals())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
    Pickler(file, protocol).dump(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle module objects
>>> 

Even a really simple dict will often fail. It just depends on the contents.

>>> d = {'x': lambda x:x}
>>> pik = pickle.dumps(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
    Pickler(file, protocol).dump(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems
    save(v)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 748, in save_global
    (obj, module, name))
pickle.PicklingError: Can't pickle <function <lambda> at 0x102178668>: it's not found as __main__.<lambda>

However, if you use a better serializer like dill or cloudpickle, then most dictionaries can be pickled:

>>> import dill
>>> pik = dill.dumps(d)

Or if you want to save your dict to a file...

>>> with open('save.pik', 'w') as f:
...   dill.dump(globals(), f)
... 

The latter example is identical to any of the other good answers posted here (which aside from neglecting the picklability of the contents of the dict are good).

Equivalent of Oracle's RowID in SQL Server

Several of the answers above will work around the lack of a direct reference to a specific row, but will not work if changes occur to the other rows in a table. That is my criteria for which answers fall technically short.

A common use of Oracle's ROWID is to provide a (somewhat) stable method of selecting rows and later returning to the row to process it (e.g., to UPDATE it). The method of finding a row (complex joins, full-text searching, or browsing row-by-row and applying procedural tests against the data) may not be easily or safely re-used to qualify the UPDATE statement.

The SQL Server RID seems to provide the same functionality, but does not provide the same performance. That is the only issue I see, and unfortunately the purpose of retaining a ROWID is to avoid repeating an expensive operation to find the row in, say, a very large table. Nonetheless, performance for many cases is acceptable. If Microsoft adjusts the optimizer in a future release, the performance issue could be addressed.

It is also possible to simply use FOR UPDATE and keep the CURSOR open in a procedural program. However, this could prove expensive in large or complex batch processing.

Caveat: Even Oracle's ROWID would not be stable if the DBA, between the SELECT and the UPDATE, for example, were to rebuild the database, because it is the physical row identifier. So the ROWID device should only be used within a well-scoped task.

How do I set up NSZombieEnabled in Xcode 4?

In Xcode 4.2

  • Project Name/Edit Scheme/Diagnostics/
  • Enable Zombie Objects check box
  • You're done

Is there any boolean type in Oracle databases?

No, there isn't a boolean type in Oracle Database, but you can do this way:

You can put a check constraint on a column.

If your table hasn't a check column, you can add it:

ALTER TABLE table_name
ADD column_name_check char(1) DEFAULT '1';

When you add a register, by default this column get 1.

Here you put a check that limit the column value, just only put 1 or 0

ALTER TABLE table_name ADD
CONSTRAINT name_constraint 
column_name_check (ONOFF in ( '1', '0' ));

jQuery to retrieve and set selected option value of html select element

to get/set the actual selectedIndex property of the select element use:

$("#select-id").prop("selectedIndex");

$("#select-id").prop("selectedIndex",1);

How to start MySQL with --skip-grant-tables?

On the Linux system you can do following (Should be similar for other OS)

Check if mysql process is running:

sudo service mysql status

If runnning then stop the process: (Make sure you close all mysql tool)

sudo service mysql stop

If you have issue stopping then do following

Search for process: ps aux | grep mysqld Kill the process: kill -9 process_id

Now start mysql in safe mode with skip grant

sudo mysqld_safe --skip-grant-tables &

Normalizing images in OpenCV

When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.

casting Object array to Integer array error

When casting is done in Java, Java compiler as well as Java run-time check whether the casting is possible or not and throws errors in case not.

When casting of Object types is involved, the instanceof test should pass in order for the assignment to go through. In your example it results
Object[] a = new Object[1]; boolean isIntegerArr = a instanceof Integer[]
If you do a sysout of the above line, it would return false;
So trying an instance of check before casting would help. So, to fix the error, you can either add 'instanceof' check
OR
use following line of code:
(Arrays.asList(a)).toArray(c);

Please do note that the above code would fail, if the Object array contains any entry that is other than Integer.

prevent property from being serialized in web API

I will show you 2 ways to accomplish what you want:

First way: Decorate your field with JsonProperty attribute in order to skip the serialization of that field if it is null.

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<Something> Somethings { get; set; }
}

Second way: If you are negotiation with some complex scenarios then you could use the Web Api convention ("ShouldSerialize") in order to skip serialization of that field depending of some specific logic.

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    public List<Something> Somethings { get; set; }

    public bool ShouldSerializeSomethings() {
         var resultOfSomeLogic = false;
         return resultOfSomeLogic; 
    }
}

WebApi uses JSON.Net and it use reflection to serialization so when it has detected (for instance) the ShouldSerializeFieldX() method the field with name FieldX will not be serialized.

Connection refused to MongoDB errno 111

In my case previous version was 3.2. I have upgraded to 3.6 but data files was not compatible to new version so I removed all data files as it was not usable for me and its works.

You can check logs using /var/log/mongodb

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

How to hide a div from code (c#)

one fast and simple way is to make the div as

<div runat="server" id="MyDiv"></div>

and on code behind you set MyDiv.Visible=false

Get characters after last / in url

array_pop(explode("/", "http://vimeo.com/1234567")); will return the last element of the example url

C# 4.0: Convert pdf to byte[] and vice versa

Easiest way:

byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
   buffer = new byte[stream.Length - 1];
   stream.Read(buffer, 0, buffer.Length);
}

using (Stream stream = new IO.FileStream("newFile.pdf"))
{
   stream.Write(buffer, 0, buffer.Length);
}

Or something along these lines...

possible EventEmitter memory leak detected

Replace .on() with once(). Using once() removes event listeners when the event is handled by the same function.

If this doesn't fix it, then reinstall restler with this in your package.json "restler": "git://github.com/danwrong/restler.git#9d455ff14c57ddbe263dbbcd0289d76413bfe07d"

This has to do with restler 0.10 misbehaving with node. you can see the issue closed on git here: https://github.com/danwrong/restler/issues/112 However, npm has yet to update this, so that is why you have to refer to the git head.

How to get the date from jQuery UI datepicker

Try this, works like charm, gives the date you have selected. onsubmit form try to get this value:-

var date = $("#scheduleDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();

Reference here

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

How to convert a byte array to a hex string in Java?

My solution is based on maybeWeCouldStealAVan's solution, but does not rely on any additionaly allocated lookup tables. It does not uses any 'int-to-char' casts hacks (actually, Character.forDigit() does it, performing some comparison to check what the digit truly is) and thus might be a bit slower. Please feel free to use it wherever you want. Cheers.

public static String bytesToHex(final byte[] bytes)
{
    final int numBytes = bytes.length;
    final char[] container = new char[numBytes * 2];

    for (int i = 0; i < numBytes; i++)
    {
        final int b = bytes[i] & 0xFF;

        container[i * 2] = Character.forDigit(b >>> 4, 0x10);
        container[i * 2 + 1] = Character.forDigit(b & 0xF, 0x10);
    }

    return new String(container);
}

JPA CascadeType.ALL does not delete orphans

I was using one to one mapping , but child was not getting deleted JPA was giving foreign key violation

After using orphanRemoval = true , issue got resolved

Disabled form fields not submitting data

add CSS or class to the input element which works in select and text tags like

style="pointer-events: none;background-color:#E9ECEF"

Serving favicon.ico in ASP.NET MVC

Placing favicon.ico in the root of your domain only really affects IE5, IIRC. For more modern browsers you should be able to include a link tag to point to another directory:

<link rel="SHORTCUT ICON" href="http://www.mydomain.com/content/favicon.ico"/>

You can also use non-ico files for browsers other than IE, for which I'd maybe use the following conditional statement to serve a PNG to FF,etc, and an ICO to IE:

<link rel="icon" type="image/png" href="http://www.mydomain.com/content/favicon.png" />
<!--[if IE]>
<link rel="shortcut icon" href="http://www.mydomain.com/content/favicon.ico" type="image/vnd.microsoft.icon" />
<![endif]-->

Java, How to get number of messages in a topic in apache kafka

In most recent versions of Kafka Manager, there is a column titled Summed Recent Offsets.

enter image description here

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

JAD Decomplier plug-in for Eclipse version 3.x and 4.x.

update site: http://feeling.sourceforge.net/update

Steps:

  1. Open Eclipse IDE.
  2. Click Help->Install New software
  3. Paste above URL and give name as JAD.
  4. Select the Eclipse Class Decompiler
  5. Click on Next and accept agreements
  6. Install it.
  7. Restart Eclipse and check now.

How can I select from list of values in Oracle

You can do this:

create type number_tab is table of number;

select * from table (number_tab(1,2,3,4,5,6));

The column is given the name COLUMN_VALUE by Oracle, so this works too:

select column_value from table (number_tab(1,2,3,4,5,6));

How to change the color of the axis, ticks and labels for a plot in matplotlib

As a quick example (using a slightly cleaner method than the potentially duplicate question):

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')

plt.show()

alt text

Alternatively

[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]

Can CSS detect the number of children an element has?

If you are going to do it in pure CSS (using scss) but you have different elements/classes inside the same parent class you can use this version!!

  &:first-of-type:nth-last-of-type(1) {
    max-width: 100%;
  }

  @for $i from 2 through 10 {
    &:first-of-type:nth-last-of-type(#{$i}),
    &:first-of-type:nth-last-of-type(#{$i}) ~ & {
      max-width: (100% / #{$i});
    }
  }

TypeError: $(...).modal is not a function with bootstrap Modal

I had the same issue. Changing

$.ajax(...)

to

jQuery.ajax(...)

did not work. But then I found that jQuery was included twice and removing one of them fixed the problem.

Opacity of div's background without affecting contained element in IE 8?

it's simple only you have do is to give

background: rgba(0,0,0,0.3)

& for IE use this filter

background: transparent;
zoom: 1;    
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000,endColorstr=#4C000000); /* IE 6 & 7 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000,endColorstr=#4C000000)"; /* IE8 */

you can generate your rgba filter from here http://kimili.com/journal/rgba-hsla-css-generator-for-internet-explorer/

Objective-C Static Class Level variables

u can rename the class as classA.mm and add C++ features in it.

Horizontal Scroll Table in Bootstrap/CSS

@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:

css:

.scrollme {
    overflow-x: auto;
}

html:

<div class="scrollme">                        
  <table class="table table-responsive"> ...
  </table>
</div>

Edit: changing scroll-y to scroll-x

Spring: @Component versus @Bean

@Component and @Bean do two quite different things, and shouldn't be confused.

@Component (and @Service and @Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.

@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.

To answer your question...

would it have been possible to re-use the @Component annotation instead of introducing @Bean annotation?

Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.

Global keyboard capture in C# application

Stephen Toub wrote a great article on implementing global keyboard hooks in C#:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main()
    {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}

Reading output of a command into an array in Bash

You can use

my_array=( $(<command>) )

to store the output of command <command> into the array my_array.

You can access the length of that array using

my_array_length=${#my_array[@]}

Now the length is stored in my_array_length.

how to remove multiple columns in r dataframe?

x <-dplyr::select(dataset_df, -c('coloumn1', 'column2'))

This works for me.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24' - it is a performance killer:

  • it will calculate DATE() for all rows, including those, that don't match
  • it will make it impossible to use an index for the query

It is much faster to use

SELECT * FROM tablename 
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'

as this will allow index use without calculation.

EDIT

As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read

SELECT * FROM tablename 
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'

The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.

How do I print the full value of a long string in gdb?

As long as your program's in a sane state, you can also call (void)puts(your_string) to print it to stdout. Same principle applies to all functions available to the debugger, actually.

How can I use MS Visual Studio for Android Development?

I suppose you can open Java files in Visual Studio and just use the command line tools directly. I don't think you'd get syntax highlighting or autocompletion though.

Eclipse is really not all that different from Visual Studio, and there are a lot of tools that are designed to make Android development more comfortable that work from within Eclipse.

Locking pattern for proper use of .NET MemoryCache

I assume this code has concurrency issues:

Actually, it's quite possibly fine, though with a possible improvement.

Now, in general the pattern where we have multiple threads setting a shared value on first use, to not lock on the value being obtained and set can be:

  1. Disastrous - other code will assume only one instance exists.
  2. Disastrous - the code that obtains the instance is not can only tolerate one (or perhaps a certain small number) concurrent operations.
  3. Disastrous - the means of storage is not thread-safe (e.g. have two threads adding to a dictionary and you can get all sorts of nasty errors).
  4. Sub-optimal - the overall performance is worse than if locking had ensured only one thread did the work of obtaining the value.
  5. Optimal - the cost of having multiple threads do redundant work is less than the cost of preventing it, especially since that can only happen during a relatively brief period.

However, considering here that MemoryCache may evict entries then:

  1. If it's disastrous to have more than one instance then MemoryCache is the wrong approach.
  2. If you must prevent simultaneous creation, you should do so at the point of creation.
  3. MemoryCache is thread-safe in terms of access to that object, so that is not a concern here.

Both of these possibilities have to be thought about of course, though the only time having two instances of the same string existing can be a problem is if you're doing very particular optimisations that don't apply here*.

So, we're left with the possibilities:

  1. It is cheaper to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().
  2. It is cheaper not to avoid the cost of duplicate calls to SomeHeavyAndExpensiveCalculation().

And working that out can be difficult (indeed, the sort of thing where it's worth profiling rather than assuming you can work it out). It's worth considering here though that most obvious ways of locking on insert will prevent all additions to the cache, including those that are unrelated.

This means that if we had 50 threads trying to set 50 different values, then we'll have to make all 50 threads wait on each other, even though they weren't even going to do the same calculation.

As such, you're probably better off with the code you have, than with code that avoids the race-condition, and if the race-condition is a problem, you quite likely either need to handle that somewhere else, or need a different caching strategy than one that expels old entries†.

The one thing I would change is I'd replace the call to Set() with one to AddOrGetExisting(). From the above it should be clear that it probably isn't necessary, but it would allow the newly obtained item to be collected, reducing overall memory use and allowing a higher ratio of low generation to high generation collections.

So yeah, you could use double-locking to prevent concurrency, but either the concurrency isn't actually a problem, or your storing the values in the wrong way, or double-locking on the store would not be the best way to solve it.

*If you know only one each of a set of strings exists, you can optimise equality comparisons, which is about the only time having two copies of a string can be incorrect rather than just sub-optimal, but you'd want to be doing very different types of caching for that to make sense. E.g. the sort XmlReader does internally.

†Quite likely either one that stores indefinitely, or one that makes use of weak references so it will only expel entries if there are no existing uses.

Using jQuery to center a DIV on the screen

I like adding functions to jQuery so this function would help:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}

Now we can just write:

$(element).center();

Demo: Fiddle (with added parameter)

Go build: "Cannot find package" (even though GOPATH is set)

If you have a valid $GOROOT and $GOPATH but are developing outside of them, you might get this error if the package (yours or someone else's) hasn't been downloaded.

If that's the case, try go get -d (-d flag prevents installation) to ensure the package is downloaded before you run, build or install.

Add comma to numbers every three digits

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

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

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

How to remove illegal characters from path and filenames?

I think the question already not full answered... The answers only describe clean filename OR path... not both. Here is my solution:

private static string CleanPath(string path)
{
    string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
    Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
    List<string> split = path.Split('\\').ToList();
    string returnValue = split.Aggregate(string.Empty, (current, s) => current + (r.Replace(s, "") + @"\"));
    returnValue = returnValue.TrimEnd('\\');
    return returnValue;
}

Using CookieContainer with WebClient class

The HttpWebRequest modifies the CookieContainer assigned to it. There is no need to process returned cookies. Simply assign your cookie container to every web request.

public class CookieAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; set; } = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest request = base.GetWebRequest(uri);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = CookieContainer;
        }
        return request;
    }
}

Move / Copy File Operations in Java

Not yet, but the New NIO (JSR 203) will have support for these common operations.

In the meantime, there are a few things to keep in mind.

File.renameTo generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.

When a rename doesn't work you will need to actually copy the file (deleting the original with File.delete if it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferTo or FileChannel.transferFrom methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.

Python dict how to create key or append an element to key?

Use dict.setdefault():

dic.setdefault(key,[]).append(value)

help(dict.setdefault):

    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

copy db file with adb pull results in 'permission denied' error

The pull command is:

adb pull source dest

When you write:

adb pull /data/data/path.to.package/databases/data /sdcard/test

It means that you'll pull from /data/data/path.to.package/databases/data and you'll copy it to /sdcard/test, but the destination MUST be a local directory. You may write C:\Users\YourName\temp instead.

For example:

adb pull /data/data/path.to.package/databases/data c:\Users\YourName\temp

Using Excel OleDb to get sheet names IN SHEET ORDER

Can you not just loop through the sheets from 0 to Count of names -1? that way you should get them in the correct order.

Edit

I noticed through the comments that there are a lot of concerns about using the Interop classes to retrieve the sheet names. Therefore here is an example using OLEDB to retrieve them:

/// <summary>
/// This method retrieves the excel sheet names from 
/// an excel workbook.
/// </summary>
/// <param name="excelFile">The excel file.</param>
/// <returns>String[]</returns>
private String[] GetExcelSheetNames(string excelFile)
{
    OleDbConnection objConn = null;
    System.Data.DataTable dt = null;

    try
    {
        // Connection String. Change the excel file to the file you
        // will search.
        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
          "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
        // Create connection object by using the preceding connection string.
        objConn = new OleDbConnection(connString);
        // Open connection with the database.
        objConn.Open();
        // Get the data table containg the schema guid.
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        if(dt == null)
        {
           return null;
        }

        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        // Add the sheet name to the string array.
        foreach(DataRow row in dt.Rows)
        {
           excelSheets[i] = row["TABLE_NAME"].ToString();
           i++;
        }

        // Loop through all of the sheets if you want too...
        for(int j=0; j < excelSheets.Length; j++)
        {
            // Query each excel sheet.
        }

        return excelSheets;
   }
   catch(Exception ex)
   {
       return null;
   }
   finally
   {
      // Clean up.
      if(objConn != null)
      {
          objConn.Close();
          objConn.Dispose();
      }
      if(dt != null)
      {
          dt.Dispose();
      }
   }
}

Extracted from Article on the CodeProject.

Sorting a list with stream.sorted() in Java

It seems to be working fine:

List<BigDecimal> list = Arrays.asList(new BigDecimal("24.455"), new BigDecimal("23.455"), new BigDecimal("28.455"), new BigDecimal("20.455"));
System.out.println("Unsorted list: " + list);
final List<BigDecimal> sortedList = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
System.out.println("Sorted list: " + sortedList);

Example Input/Output

Unsorted list: [24.455, 23.455, 28.455, 20.455]
Sorted list: [20.455, 23.455, 24.455, 28.455]

Are you sure you are not verifying list instead of sortedList [in above example] i.e. you are storing the result of stream() in a new List object and verifying that object?

How to split a string of space separated numbers into integers?

text = "42 0"
nums = [int(n) for n in text.split()]

Why can a function modify some arguments as perceived by the caller, but not others?

I had modified my answer tons of times and realized i don't have to say anything, python had explained itself already.

a = 'string'
a.replace('t', '_')
print(a)
>>> 'string'

a = a.replace('t', '_')
print(a)
>>> 's_ring'

b = 100
b + 1
print(b)
>>> 100

b = b + 1
print(b)
>>> 101

def test_id(arg):
    c = id(arg)
    arg = 123
    d = id(arg)
    return

a = 'test ids'
b = id(a)
test_id(a)
e = id(a)

# b = c  = e != d
# this function do change original value
del change_like_mutable(arg):
    arg.append(1)
    arg.insert(0, 9)
    arg.remove(2)
    return

test_1 = [1, 2, 3]
change_like_mutable(test_1)



# this function doesn't 
def wont_change_like_str(arg):
     arg = [1, 2, 3]
     return


test_2 = [1, 1, 1]
wont_change_like_str(test_2)
print("Doesn't change like a imutable", test_2)

This devil is not the reference / value / mutable or not / instance, name space or variable / list or str, IT IS THE SYNTAX, EQUAL SIGN.

Vue 'export default' vs 'new Vue'

Whenever you use

export someobject

and someobject is

{
 "prop1":"Property1",
 "prop2":"Property2",
}

the above you can import anywhere using import or module.js and there you can use someobject. This is not a restriction that someobject will be an object only it can be a function too, a class or an object.

When you say

new Object()

like you said

new Vue({
  el: '#app',
  data: []
)}

Here you are initiating an object of class Vue.

I hope my answer explains your query in general and more explicitly.

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

How to add subject alernative name to ssl certs?

Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS entries for a host name and IP entries for IP addresses).

To quote myself:

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1

Note that you only need Java 7's keytool to use this command. Once you've prepared your keystore, it should work with previous versions of Java.

(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)

How do I get the current date and current time only respectively in Django?

Another way to get datetime UTC with milliseconds.

from datetime import datetime

datetime.utcnow().isoformat(sep='T', timespec='milliseconds') + 'Z'

2020-10-29T14:46:37.655Z

What is the difference between a 'closure' and a 'lambda'?

There is a lot of confusion around lambdas and closures, even in the answers to this StackOverflow question here. Instead of asking random programmers who learned about closures from practice with certain programming languages or other clueless programmers, take a journey to the source (where it all began). And since lambdas and closures come from Lambda Calculus invented by Alonzo Church back in the '30s before first electronic computers even existed, this is the source I'm talking about.

Lambda Calculus is the simplest programming language in the world. The only things you can do in it:?

  • APPLICATION: Applying one expression to another, denoted f x.
    (Think of it as a function call, where f is the function and x is its only parameter)
  • ABSTRACTION: Binds a symbol occurring in an expression to mark that this symbol is just a "slot", a blank box waiting to be filled with value, a "variable" as it were. It is done by prepending a Greek letter ? (lambda), then the symbolic name (e.g. x), then a dot . before the expression. This then converts the expression into a function expecting one parameter.
    For example: ?x.x+2 takes the expression x+2 and tells that the symbol x in this expression is a bound variable – it can be substituted with a value you supply as a parameter.
    Note that the function defined this way is anonymous – it doesn't have a name, so you can't refer to it yet, but you can immediately call it (remember application?) by supplying it the parameter it is waiting for, like this: (?x.x+2) 7. Then the expression (in this case a literal value) 7 is substituted as x in the subexpression x+2 of the applied lambda, so you get 7+2, which then reduces to 9 by common arithmetics rules.

So we've solved one of the mysteries:
lambda is the anonymous function from the example above, ?x.x+2.


In different programming languages, the syntax for functional abstraction (lambda) may differ. For example, in JavaScript it looks like this:

function(x) { return x+2; }

and you can immediately apply it to some parameter like this:

(function(x) { return x+2; })(7)

or you can store this anonymous function (lambda) into some variable:

var f = function(x) { return x+2; }

which effectively gives it a name f, allowing you to refer to it and call it multiple times later, e.g.:

alert(  f(7) + f(10)  );   // should print 21 in the message box

But you didn't have to name it. You could call it immediately:

alert(  function(x) { return x+2; } (7)  );  // should print 9 in the message box

In LISP, lambdas are made like this:

(lambda (x) (+ x 2))

and you can call such a lambda by applying it immediately to a parameter:

(  (lambda (x) (+ x 2))  7  )


OK, now it's time to solve the other mystery: what is a closure. In order to do that, let's talk about symbols (variables) in lambda expressions.

As I said, what the lambda abstraction does is binding a symbol in its subexpression, so that it becomes a substitutible parameter. Such a symbol is called bound. But what if there are other symbols in the expression? For example: ?x.x/y+2. In this expression, the symbol x is bound by the lambda abstraction ?x. preceding it. But the other symbol, y, is not bound – it is free. We don't know what it is and where it comes from, so we don't know what it means and what value it represents, and therefore we cannot evaluate that expression until we figure out what y means.

In fact, the same goes with the other two symbols, 2 and +. It's just that we are so familiar with these two symbols that we usually forget that the computer doesn't know them and we need to tell it what they mean by defining them somewhere, e.g. in a library or the language itself.

You can think of the free symbols as defined somewhere else, outside the expression, in its "surrounding context", which is called its environment. The environment might be a bigger expression that this expression is a part of (as Qui-Gon Jinn said: "There's always a bigger fish" ;) ), or in some library, or in the language itself (as a primitive).

This lets us divide lambda expressions into two categories:

  • CLOSED expressions: every symbol that occurs in these expressions is bound by some lambda abstraction. In other words, they are self-contained; they don't require any surrounding context to be evaluated. They are also called combinators.
  • OPEN expressions: some symbols in these expressions are not bound – that is, some of the symbols occurring in them are free and they require some external information, and thus they cannot be evaluated until you supply the definitions of these symbols.

You can CLOSE an open lambda expression by supplying the environment, which defines all these free symbols by binding them to some values (which may be numbers, strings, anonymous functions aka lambdas, whatever…).

And here comes the closure part:
The closure of a lambda expression is this particular set of symbols defined in the outer context (environment) that give values to the free symbols in this expression, making them non-free anymore. It turns an open lambda expression, which still contains some "undefined" free symbols, into a closed one, which doesn't have any free symbols anymore.

For example, if you have the following lambda expression: ?x.x/y+2, the symbol x is bound, while the symbol y is free, therefore the expression is open and cannot be evaluated unless you say what y means (and the same with + and 2, which are also free). But suppose that you also have an environment like this:

{  y: 3,
+: [built-in addition],
2: [built-in number],
q: 42,
w: 5  }

This environment supplies definitions for all the "undefined" (free) symbols from our lambda expression (y, +, 2), and several extra symbols (q, w). The symbols that we need to be defined are this subset of the environment:

{  y: 3,
+: [built-in addition],
2: [built-in number]  }

and this is precisely the closure of our lambda expression :>

In other words, it closes an open lambda expression. This is where the name closure came from in the first place, and this is why so many people's answers in this thread are not quite correct :P


So why are they mistaken? Why do so many of them say that closures are some data structures in memory, or some features of the languages they use, or why do they confuse closures with lambdas? :P

Well, the corporate marketoids of Sun/Oracle, Microsoft, Google etc. are to blame, because that's what they called these constructs in their languages (Java, C#, Go etc.). They often call "closures" what are supposed to be just lambdas. Or they call "closures" a particular technique they used to implement lexical scoping, that is, the fact that a function can access the variables that were defined in its outer scope at the time of its definition. They often say that the function "encloses" these variables, that is, captures them into some data structure to save them from being destroyed after the outer function finishes executing. But this is just made-up post factum "folklore etymology" and marketing, which only makes things more confusing, because every language vendor uses its own terminology.

And it's even worse because of the fact that there's always a bit of truth in what they say, which does not allow you to easily dismiss it as false :P Let me explain:

If you want to implement a language that uses lambdas as first-class citizens, you need to allow them to use symbols defined in their surrounding context (that is, to use free variables in your lambdas). And these symbols must be there even when the surrounding function returns. The problem is that these symbols are bound to some local storage of the function (usually on the call stack), which won't be there anymore when the function returns. Therefore, in order for a lambda to work the way you expect, you need to somehow "capture" all these free variables from its outer context and save them for later, even when the outer context will be gone. That is, you need to find the closure of your lambda (all these external variables it uses) and store it somewhere else (either by making a copy, or by preparing space for them upfront, somewhere else than on the stack). The actual method you use to achieve this goal is an "implementation detail" of your language. What's important here is the closure, which is the set of free variables from the environment of your lambda that need to be saved somewhere.

It didn't took too long for people to start calling the actual data structure they use in their language's implementations to implement closure as the "closure" itself. The structure usually looks something like this:

Closure {
   [pointer to the lambda function's machine code],
   [pointer to the lambda function's environment]
}

and these data structures are being passed around as parameters to other functions, returned from functions, and stored in variables, to represent lambdas, and allowing them to access their enclosing environment as well as the machine code to run in that context. But it's just a way (one of many) to implement closure, not the closure itself.

As I explained above, the closure of a lambda expression is the subset of definitions in its environment that give values to the free variables contained in that lambda expression, effectively closing the expression (turning an open lambda expression, which cannot be evaluated yet, into a closed lambda expression, which can then be evaluated, since all the symbols contained in it are now defined).

Anything else is just a "cargo cult" and "voo-doo magic" of programmers and language vendors unaware of the real roots of these notions.

I hope that answers your questions. But if you had any follow-up questions, feel free to ask them in the comments, and I'll try to explain it better.

How to automatically generate getters and setters in Android Studio

You can use AndroidAccessors Plugin of Android Studio to generate getter and setter without m as prefix to methods

Ex: mId; Will generate getId() and setId() instead of getmId() and setmId()

plugin screenshot

How can I color a UIImage in Swift?

First you have to change the rendering property of the image to "Template Image" in the .xcassets folder. You can then just change the tint color property of the instance of your UIImageView like so:

imageView.tintColor = UIColor.whiteColor()

enter image description here

How do you make a HTTP request with C++?

Here is some (relatively) simple C++11 code that uses libCURL to download a URL's content into a std::vector<char>:

http_download.hh

# pragma once

#include <string>
#include <vector>

std::vector<char> download(std::string url, long* responseCode = nullptr);

http_download.cc

#include "http_download.hh"

#include <curl/curl.h>
#include <sstream>
#include <stdexcept>

using namespace std;

size_t callback(void* contents, size_t size, size_t nmemb, void* user)
{
  auto chunk = reinterpret_cast<char*>(contents);
  auto buffer = reinterpret_cast<vector<char>*>(user);

  size_t priorSize = buffer->size();
  size_t sizeIncrease = size * nmemb;

  buffer->resize(priorSize + sizeIncrease);
  std::copy(chunk, chunk + sizeIncrease, buffer->data() + priorSize);

  return sizeIncrease;
}

vector<char> download(string url, long* responseCode)
{
  vector<char> data;

  curl_global_init(CURL_GLOBAL_ALL);
  CURL* handle = curl_easy_init();
  curl_easy_setopt(handle, CURLOPT_URL, url.c_str());
  curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, callback);
  curl_easy_setopt(handle, CURLOPT_WRITEDATA, &data);
  curl_easy_setopt(handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
  CURLcode result = curl_easy_perform(handle);
  if (responseCode != nullptr)
    curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, responseCode);
  curl_easy_cleanup(handle);
  curl_global_cleanup();

  if (result != CURLE_OK)
  {
    stringstream err;
    err << "Error downloading from URL \"" << url << "\": " << curl_easy_strerror(result);
    throw runtime_error(err.str());
  }

  return data;
}

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

I recently had to change the ownership of all objects in a database. Although tables, views, triggers and sequences were somewhat easily changed the above approach failed for functions as the signature is part of the function name. Granted, I have a MySQL background and am not that familiar with Postgres.

However, pg_dump allows you to dump just the schema and this contains the ALTER xxx OWNER TO yyy; statements you need. Here is my bit of shell magic on the topic

pg_dump -s YOUR_DB | grep -i 'owner to' | sed -e 's/OWNER TO .*;/OWNER TO NEW_OWNER;/i' | psqL YOUR_DB

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

Can I access variables from another file?

As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared. You could also use a property of window or (in the global scope) this to get the same effect.

// first.js
var colorCodes = {

  back  : "#fff",
  front : "#888",
  side  : "#369"

};

... in another file ...

// second.js
alert (colorCodes.back); // alerts `#fff`

... in your html file ...

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

Git Clone - Repository not found

For me it worked by removing the credential.helper config and cloning the repository again

git config --global --unset credential.helper
git clone https://<repository>

document.getelementbyId will return null if element is not defined?

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');

How to assign an exec result to a sql variable?

declare @EventId int

CREATE TABLE #EventId (EventId int)

insert into #EventId exec rptInputEventId

set @EventId = (select * from #EventId)

drop table #EventId 

android on Text Change Listener

Another solution that may help someone. There are 2 EditText which change instead of each other after editing. By default, it led to cyclicity.

use variable:

Boolean uahEdited = false;
Boolean usdEdited = false;

add TextWatcher

uahEdit = findViewById(R.id.uahEdit);
usdEdit = findViewById(R.id.usdEdit);

uahEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!usdEdited) {
                uahEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = uahEdit.getText().toString();

            if(!tmp.isEmpty() && uahEdited) {
                uah = Double.valueOf(tmp);
                usd = uah / 27;
                usdEdit.setText(String.valueOf(usd));
            } else if (tmp.isEmpty()) {
                usdEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            uahEdited = false;
        }
    });

usdEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!uahEdited) {
                usdEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = usdEdit.getText().toString();

            if (!tmp.isEmpty() && usdEdited) {
                usd = Double.valueOf(tmp);
                uah = usd * 27;
                uahEdit.setText(String.valueOf(uah));
            } else if (tmp.isEmpty()) {
                uahEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            usdEdited = false;
        }
    });

Don't criticize too much. I am a novice developer

How can I record a Video in my Android App.?

For the benefit of searchers, this example will give you an active preview, with a start/stop button for recording. It was modified from this android blog and seems fairly reliable.

java class (VideoWithSurfaceVw)

package <<your packagename here>>;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

public class VideoWithSurfaceVw extends Activity{

    // Adapted from http://sandyandroidtutorials.blogspot.co.uk/2013/05/android-video-capture-tutorial.html


    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;

    Button myButton;
    SurfaceHolder surfaceHolder;
    boolean recording;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recording = false;

        setContentView(R.layout.activity_video_with_surface_vw);

        //Get Camera for preview
        myCamera = getCameraInstance();
        if(myCamera == null){
            Toast.makeText(VideoWithSurfaceVw.this,
                    "Fail to get Camera",
                    Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
        myCameraPreview.addView(myCameraSurfaceView);

        myButton = (Button)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
    }

    Button.OnClickListener myButtonOnClickListener
            = new Button.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            try{
                if(recording){
                    // stop recording and release camera
                    mediaRecorder.stop();  // stop the recording
                    releaseMediaRecorder(); // release the MediaRecorder object

                    //Exit after saved
                    //finish();
                    myButton.setText("REC");
                    recording = false;
                }else{

                    //Release Camera before MediaRecorder start
                    releaseCamera();

                    if(!prepareMediaRecorder()){
                        Toast.makeText(VideoWithSurfaceVw.this,
                                "Fail in prepareMediaRecorder()!\n - Ended -",
                                Toast.LENGTH_LONG).show();
                        finish();
                    }

                    mediaRecorder.start();
                    recording = true;
                    myButton.setText("STOP");
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }};

    private Camera getCameraInstance(){
        // TODO Auto-generated method stub
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    private String getFileName_CustomFormat() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    }


    private boolean prepareMediaRecorder(){
        myCamera = getCameraInstance();
        mediaRecorder = new MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));



        mediaRecorder.setOutputFile("/sdcard/" + getFileName_CustomFormat() + ".mp4");
        //mediaRecorder.setOutputFile("/sdcard/myvideo1.mp4");
        mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
        mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M

        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder(){
        if (mediaRecorder != null) {
            mediaRecorder.reset();   // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = new MediaRecorder();
            myCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();        // release the camera for other applications
            myCamera = null;
        }
    }

    public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

        private SurfaceHolder mHolder;
        private Camera mCamera;

        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;

            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                                   int height) {
            // If your preview can change or rotate, take care of those events here.
            // Make sure to stop the preview before resizing or reformatting it.

            if (mHolder.getSurface() == null){
                // preview surface does not exist
                return;
            }

            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e){
                // ignore: tried to stop a non-existent preview
            }

            // make any resize, rotate or reformatting changes here

            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            // The Surface has been created, now tell the camera where to draw the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub

        }
    }
}

activity (activity_video_with_surface_vw)

<RelativeLayout android:id="@+id/surface_camera"     
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:layout_weight="1"
>

<RelativeLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <FrameLayout
        android:id="@+id/videoview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
    <Button
        android:id="@+id/mybutton"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:text="REC"
        android:textSize="12dp"/>
</RelativeLayout>

</RelativeLayout>

How to check if text fields are empty on form submit using jQuery?

you should try with jquery validate plugin :

$('form').validate({
   rules:{
       email:{
          required:true,
          email:true
       }
   },
   messages:{
       email:{
          required:"Email is required",
          email:"Please type a valid email"
        }
   }
})

Conditional Replace Pandas

The reason your original dataframe does not update is because chained indexing may cause you to modify a copy rather than a view of your dataframe. The docs give this advice:

When setting values in a pandas object, care must be taken to avoid what is called chained indexing.

You have a few alternatives:-

loc + Boolean indexing

loc may be used for setting values and supports Boolean masks:

df.loc[df['my_channel'] > 20000, 'my_channel'] = 0

mask + Boolean indexing

You can assign to your series:

df['my_channel'] = df['my_channel'].mask(df['my_channel'] > 20000, 0)

Or you can update your series in place:

df['my_channel'].mask(df['my_channel'] > 20000, 0, inplace=True)

np.where + Boolean indexing

You can use NumPy by assigning your original series when your condition is not satisfied; however, the first two solutions are cleaner since they explicitly change only specified values.

df['my_channel'] = np.where(df['my_channel'] > 20000, 0, df['my_channel'])

Android Google Maps v2 - set zoom level for myLocation

You can use

    CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);

How to install trusted CA certificate on Android device?

The guide linked here will probably answer the original question without the need for programming a custom SSL connector.

Found a very detailed how-to guide on importing root certificates that actually steps you through installing trusted CA certificates on different versions of Android devices (among other devices).

Basically you'll need to:

  1. Download: the cacerts.bks file from your phone.

    adb pull /system/etc/security/cacerts.bks cacerts.bks

  2. Download the .crt file from the certifying authority you want to allow.

  3. Modify the cacerts.bks file on your computer using the BouncyCastle Provider

  4. Upload the cacerts.bks file back to your phone and reboot.

Here is a more detailed step by step to update earlier android phones: How to update HTTPS security certificate authority keystore on pre-android-4.0 device

How can I set the Secure flag on an ASP.NET Session Cookie?

secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text.

Gridview row editing - dynamic binding to a DropDownList

 <asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
            AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
            BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
            OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowDeleting="GridView1_RowDeleting">
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <RowStyle BackColor="White" ForeColor="#330099" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <Columns>
            <asp:TemplateField HeaderText="SerialNo">
            <ItemTemplate>
            <%# Container .DataItemIndex+1 %>.&nbsp
            </ItemTemplate>
            </asp:TemplateField>
                <asp:TemplateField HeaderText="RollNo">
                    <ItemTemplate>
                        <%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
                        <asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="SName">
                    <ItemTemplate>
                    <%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
                        <asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="C">
                    <ItemTemplate>
                    <%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
                        <asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cpp">
                    <ItemTemplate>
                    <%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
                       <asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Java">
                    <ItemTemplate>
                       <%--  <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
                        <asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit" ShowHeader="False">
                    <EditItemTemplate>
                        <asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
                            CommandName="Update"></asp:LinkButton>
                        <asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
                            CommandName="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
                            Text="Edit"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
                <asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
            </Columns>
        </asp:GridView>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
                    <asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
                    <asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
                    <asp:TextBox ID="txtc" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
                    <asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
                    <asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
                    <asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
                </td>
            </tr>
        </table>

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

Android ImageView Fixing Image Size

I had the same issue and this helped me.

<ImageView
    android:id="@+id/image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitXY"
    />

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

Escape text for HTML

Didn't see this here

System.Web.HttpUtility.JavaScriptStringEncode("Hello, this is Satan's Site")

it was the only thing that worked (asp 4.0+) when dealing with html like this. The&apos; gets rendered as ' (using htmldecode) in the html, causing it to fail:

<a href="article.aspx?id=268" onclick="tabs.open('modules/xxx/id/268', 'It&apos;s Allstars'); return false;">It's Allstars</a>

How to remove unused dependencies from composer?

Just run composer install - it will make your vendor directory reflect dependencies in composer.lock file.

In other words - it will delete any vendor which is missing in composer.lock.

Please update the composer itself before running this.

Change private static final field using Java reflection

I also integrated it with joor library

Just use

      Reflect.on(yourObject).set("finalFieldName", finalFieldValue);

Also I fixed an issue with override which the previous solutions seem to miss. However use this very carefully, only when there's no other good solution.

Replace last occurrence of character in string

Reverse the string, replace the char, reverse the string.

Here is a post for reversing a string in javascript: How do you reverse a string in place in JavaScript?

jQuery toggle animation

onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');" 

onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"

Just put two stops -- one onmouseover and one onmouseout.

How do I free my port 80 on localhost Windows?

I had this problem previously,

if you see the Task manager(after enabling the view for PID), you will find PID=4 is "port 80 in use by NT Kernel & System; "

Just go to

  1. Control Panel
  2. Programs
  3. Turn Windows features on/off
  4. check if the World wide web services under IIS is checked

If so, Uncheck and netstat(or TCPVIEW) again to see if 80 is free.

How to label scatterplot points by name?

Well I did not think this was possible until I went and checked. In some previous version of Excel I could not do this. I am currently using Excel 2013.

This is what you want to do in a scatter plot:

  1. right click on your data point

  2. select "Format Data Labels" (note you may have to add data labels first)

  3. put a check mark in "Values from Cells"
  4. click on "select range" and select your range of labels you want on the points

Example Graph

UPDATE: Colouring Individual Labels

In order to colour the labels individually use the following steps:

  1. select a label. When you first select, all labels for the series should get a box around them like the graph above.
  2. Select the individual label you are interested in editing. Only the label you have selected should have a box around it like the graph below.
  3. On the right hand side, as shown below, Select "TEXT OPTIONS".
  4. Expand the "TEXT FILL" category if required.
  5. Second from the bottom of the category list is "COLOR", select the colour you want from the pallet.

If you have the entire series selected instead of the individual label, text formatting changes should apply to all labels instead of just one.

Colouring

How do I find the stack trace in Visual Studio?

Using the Call Stack Window

To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, double click the first column of the row.

http://msdn.microsoft.com/en-us/library/windows/hardware/hh439516(v=vs.85).aspx

"Faceted Project Problem (Java Version Mismatch)" error message

In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.

Thanks & Regards Vengat Maran

How to install OpenSSL in windows 10?

Either set the openssl present in Git as your default openssl and include that into your path in environmental variables (quick way)

OR

  1. Install the system-specific openssl from this link.
  2. set the following variable : set OPENSSL_CONF=LOCATION_OF_SSL_INSTALL\bin\openssl.cfg
  3. Update the path : set Path=...Other Values here...;LOCATION_OF_SSL_INSTALL\bin

What are the benefits to marking a field as `readonly` in C#?

Keep in mind that readonly only applies to the value itself, so if you're using a reference type readonly only protects the reference from being change. The state of the instance is not protected by readonly.

How to return a value from a Form in C#?

I just put into constructor something by reference, so the subform can change its value and main form can get new or modified object from subform.

Multipart File upload Spring Boot

You can simply use a controller method like this:

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
    @RequestParam("file") MultipartFile file) {

  try {
    // Handle the received file here
    // ...
  }
  catch (Exception e) {
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  }

  return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

Without any additional configurations for Spring Boot.

Using the following html form client side:

<html>
<body>
  <form action="/uploadFile" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload"> 
  </form>
</body>
</html>

If you want to set limits on files size you can do it in the application.properties:

# File size limit
multipart.maxFileSize = 3Mb

# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb

Moreover to send the file with Ajax take a look here: http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/

Styling Password Fields in CSS

The problem is that (as of 2016), for the password field, Firefox and Internet Explorer use the character "Black Circle" (?), which uses the Unicode code point 25CF, but Chrome uses the character "Bullet" (•), which uses the Unicode code point 2022.

As you can see, even in the StackOverflow font the two characters have different sizes.

The font you're using, "Lucida Sans Unicode", has an even greater disparity between the sizes of these two characters, leading to you noticing the difference.

The simple solution is to use a font in which both characters have similar sizes.

The fix could thus be to use a default font of the browser, which should render the characters in the password field just fine:

input[type="password"] {
    font-family: caption;
}

Case vs If Else If: Which is more efficient?

Wikipedia's Switch statement entry is pretty big and actually pretty good. Interesting points:

  • Switches are not inherently fast. It depends on the language, compiler, and specific use.
  • A compiler may optimize switches using jump tables or indexed function pointers.
  • The statement was inspired by some interesting math from Stephen Kleene (and others).

For a strange and interesting optimization using a C switch see Duff's Device.

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

Make sure that destination object is not empty ( null or undefined ).

You can initialize destination object with empty object like below:

var destinationObj = {};

Object.assign(destinationObj, sourceObj);

Make Iframe to fit 100% of container's remaining height

It's right, you are showing an iframe with 100% height respect to its container: the body.

Try this:

<body>
  <div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
  <div style="width:100%; height:90%; background-color:transparent;">
    <iframe src="http: //www.google.com.tw" style="width:100%; height:100%;">
    </iframe> 
  </div>
</body>

Of course, change the height of the second div to the height you want.

Make git automatically remove trailing whitespace before committing

To delete trailing whitespace at end of line in a file portably, use ed:

test -s file &&
   printf '%s\n' H ',g/[[:space:]]*$/s///' 'wq' | ed -s file

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Configuring Log4j Loggers Programmatically

It sounds like you're trying to use log4j from "both ends" (the consumer end and the configuration end).

If you want to code against the slf4j api but determine ahead of time (and programmatically) the configuration of the log4j Loggers that the classpath will return, you absolutely have to have some sort of logging adaptation which makes use of lazy construction.

public class YourLoggingWrapper {
    private static boolean loggingIsInitialized = false;

    public YourLoggingWrapper() {
        // ...blah
    }

    public static void debug(String debugMsg) {
        log(LogLevel.Debug, debugMsg);
    }

    // Same for all other log levels your want to handle.
    // You mentioned TRACE and ERROR.

    private static void log(LogLevel level, String logMsg) {
        if(!loggingIsInitialized)
            initLogging();

        org.slf4j.Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger("DebugLogger");

        switch(level) {
        case: Debug:
            logger.debug(logMsg);
            break;
        default:
            // whatever
        }
    }

    // log4j logging is lazily constructed; it gets initialized
    // the first time the invoking app calls a log method
    private static void initLogging() {
        loggingIsInitialized = true;

        org.apache.log4j.Logger debugLogger = org.apache.log4j.LoggerFactory.getLogger("DebugLogger");

        // Now all the same configuration code that @oers suggested applies...
        // configure the logger, configure and add its appenders, etc.
        debugLogger.addAppender(someConfiguredFileAppender);
    }

With this approach, you don't need to worry about where/when your log4j loggers get configured. The first time the classpath asks for them, they get lazily constructed, passed back and made available via slf4j. Hope this helped!

Bootstrap css hides portion of container below navbar navbar-fixed-top

It happens because with navbar-fixed-top class the navbar gets the position:fixed. This in turns take the navbar out of the document flow leaving the body to take up the space behind the navbar.

You need to apply padding-top or margin-top to your container, based on your requirements with values >= 50px. (or play around with different values)

The basic bootstrap navbar takes height around 40px. So if you give a padding-top or margin-top of 50px or more, you will always have that breathing space between your container and the navbar.

What is the meaning of prepended double colon "::"?

(This answer is mostly for googlers, because OP has solved his problem already.) The meaning of prepended :: - scope resulution operator - has been described in other answers, but I'd like to add why people are using it.

The meaning is "take name from global namespace, not anything else". But why would this need to be spelled explicitly?

Use case - namespace clash

When you have the same name in global namespace and in local/nested namespace, the local one will be used. So if you want the global one, prepend it with ::. This case was described in @Wyatt Anderson's answer, plese see his example.

Use case - emphasise non-member function

When you are writing a member function (a method), calls to other member function and calls to non-member (free) functions look alike:

class A {
   void DoSomething() {
      m_counter=0;
      ...
      Twist(data); 
      ...
      Bend(data);
      ...
      if(m_counter>0) exit(0);
   }
   int m_couner;
   ...
}

But it might happen that Twist is a sister member function of class A, and Bend is a free function. That is, Twist can use and modify m_couner and Bend cannot. So if you want to ensure that m_counter remains 0, you have to check Twist, but you don't need to check Bend.

So to make this stand out more clearly, one can either write this->Twist to show the reader that Twist is a member function or write ::Bend to show that Bend is free. Or both. This is very useful when you are doing or planning a refactoring.

How to disable auto-play for local video in iframe

Replace the iframe for this:

<video class="video-fluid z-depth-1" loop controls muted>
  <source src="videos/example.mp4" type="video/mp4" />
</video>

CSS - Make divs align horizontally

you can use the clip property:

#container {
  position: absolute;
  clip: rect(0px,200px,100px,0px);
  overflow: hidden;
  background: red;
}

note the position: absolute and overflow: hidden needed in order to get clip to work.

JavaScript pattern for multiple constructors

How do you find this one?

function Foobar(foobar) {
    this.foobar = foobar;
}

Foobar.prototype = {
    foobar: null
};

Foobar.fromComponents = function(foo, bar) {
    var foobar = foo + bar;
    return new Foobar(foobar);
};

//usage: the following two lines give the same result
var x = Foobar.fromComponents('Abc', 'Cde');
var y = new Foobar('AbcDef')

how to pass command line arguments to main method dynamically

go to Run Configuration and in argument tab you can write your argument

Difference between @Mock and @InjectMocks

In your test class, the tested class should be annotated with @InjectMocks. This tells Mockito which class to inject mocks into:

@InjectMocks
private SomeManager someManager;

From then on, we can specify which specific methods or objects inside the class, in this case, SomeManager, will be substituted with mocks:

@Mock
private SomeDependency someDependency;

In this example, SomeDependency inside the SomeManager class will be mocked.

Is it possible to reference one CSS rule within another?

No, you cannot reference one rule-set from another.

You can, however, reuse selectors on multiple rule-sets within a stylesheet and use multiple selectors on a single rule-set (by separating them with a comma).

.opacity, .someDiv {
    filter:alpha(opacity=60);
    -moz-opacity:0.6;
    -khtml-opacity: 0.6;
    opacity: 0.6; 
}
.radius, .someDiv {
    border-top-left-radius: 15px;
    border-top-right-radius: 5px;
    -moz-border-radius-topleft: 10px;
    -moz-border-radius-topright: 10px;    
}

You can also apply multiple classes to a single HTML element (the class attribute takes a space separated list).

<div class="opacity radius">

Either of those approaches should solve your problem.

It would probably help if you used class names that described why an element should be styled instead of how it should be styled. Leave the how in the stylesheet.

How to Read from a Text File, Character by Character in C++

You could try something like:

char ch;
fstream fin("file", fstream::in);
while (fin >> noskipws >> ch) {
    cout << ch; // Or whatever
}

How to automatically update your docker containers, if base-images are updated

You can use Watchtower to watch for updates to the image a container is instantiated from and automatically pull the update and restart the container using the updated image. However, that doesn't solve the problem of rebuilding your own custom images when there's a change to the upstream image it's based on. You could view this as a two-part problem: (1) knowing when an upstream image has been updated, and (2) doing the actual image rebuild. (1) can be solved fairly easily, but (2) depends a lot on your local build environment/practices, so it's probably much harder to create a generalized solution for that.

If you're able to use Docker Hub's automated builds, the whole problem can be solved relatively cleanly using the repository links feature, which lets you trigger a rebuild automatically when a linked repository (probably an upstream one) is updated. You can also configure a webhook to notify you when an automated build occurs. If you want an email or SMS notification, you could connect the webhook to IFTTT Maker. I found the IFTTT user interface to be kind of confusing, but you would configure the Docker webhook to post to https://maker.ifttt.com/trigger/`docker_xyz_image_built`/with/key/`your_key`.

If you need to build locally, you can at least solve the problem of getting notifications when an upstream image is updated by creating a dummy repo in Docker Hub linked to your repo(s) of interest. The sole purpose of the dummy repo would be to trigger a webhook when it gets rebuilt (which implies one of its linked repos was updated). If you're able to receive this webhook, you could even use that to trigger a rebuild on your side.

How to print an unsigned char in C?

The range of char is 127 to -128. If you assign 212, ch stores -44 (212-128-128) not 212.So if you try to print a negative number as unsigned you get (MAX value of unsigned int)-abs(number) which in this case is 4294967252

So if you want to store 212 as it is in ch the only thing you can do is declare ch as

unsigned char ch;

now the range of ch is 0 to 255.

How to flip background image using CSS?

You can flip both vertical and horizontal at the same time

    -moz-transform: scaleX(-1) scaleY(-1);
    -o-transform: scaleX(-1) scaleY(-1);
    -webkit-transform: scaleX(-1) scaleY(-1);
    transform: scaleX(-1) scaleY(-1);

And with the transition property you can get a cool flip

    -webkit-transition: transform .4s ease-out 0ms;
    -moz-transition: transform .4s ease-out 0ms;
    -o-transition: transform .4s ease-out 0ms;
    transition: transform .4s ease-out 0ms;
    transition-property: transform;
    transition-duration: .4s;
    transition-timing-function: ease-out;
    transition-delay: 0ms;

Actually it flips the whole element, not just the background-image

SNIPPET

_x000D_
_x000D_
function flip(){_x000D_
 var myDiv = document.getElementById('myDiv');_x000D_
 if (myDiv.className == 'myFlipedDiv'){_x000D_
  myDiv.className = '';_x000D_
 }else{_x000D_
  myDiv.className = 'myFlipedDiv';_x000D_
 }_x000D_
}
_x000D_
#myDiv{_x000D_
  display:inline-block;_x000D_
  width:200px;_x000D_
  height:20px;_x000D_
  padding:90px;_x000D_
  background-color:red;_x000D_
  text-align:center;_x000D_
  -webkit-transition:transform .4s ease-out 0ms;_x000D_
  -moz-transition:transform .4s ease-out 0ms;_x000D_
  -o-transition:transform .4s ease-out 0ms;_x000D_
  transition:transform .4s ease-out 0ms;_x000D_
  transition-property:transform;_x000D_
  transition-duration:.4s;_x000D_
  transition-timing-function:ease-out;_x000D_
  transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
  -moz-transform:scaleX(-1) scaleY(-1);_x000D_
  -o-transform:scaleX(-1) scaleY(-1);_x000D_
  -webkit-transform:scaleX(-1) scaleY(-1);_x000D_
  transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
_x000D_
_x000D_

how to call an ASP.NET c# method using javascript

The Jayrock RPC library is a great tool for doing this in a nice familliar way for C# developers. It allows you to create a .NET class with the methods you require, and add this class as a script (in a roundabout way) to your page. You can then create a js object of your type and call methods as you would any other object.

It essentially hides away ajax implementation and presents RPC in a familliar format. Mind you the best option really is to use ASP.NET MVC and use jQuery ajax calls to action methods - much more concise and less messing about!

close vs shutdown socket?

"shutdown() doesn't actually close the file descriptor—it just changes its usability. To free a socket descriptor, you need to use close()."1

Java - How to find the redirected url of a url?

You need to cast the URLConnection to HttpURLConnection and instruct it to not follow the redirects by setting HttpURLConnection#setInstanceFollowRedirects() to false. You can also set it globally by HttpURLConnection#setFollowRedirects().

You only need to handle redirects yourself then. Check the response code by HttpURLConnection#getResponseCode(), grab the Location header by URLConnection#getHeaderField() and then fire a new HTTP request on it.

Escape a string for a sed replace pattern

It's a bit late to respond... but there IS a much simpler way to do this. Just change the delimiter (i.e., the character that separates fields). So, instead of s/foo/bar/ you write s|bar|foo.

And, here's the easy way to do this:

sed 's|/\*!50017 DEFINER=`snafu`@`localhost`\*/||g'

The resulting output is devoid of that nasty DEFINER clause.

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

With Swift 3 and Swift 4, String has a method called data(using:allowLossyConversion:). data(using:allowLossyConversion:) has the following declaration:

func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?

Returns a Data containing a representation of the String encoded using a given encoding.

With Swift 4, String's data(using:allowLossyConversion:) can be used in conjunction with JSONDecoder's decode(_:from:) in order to deserialize a JSON string into a dictionary.

Furthermore, with Swift 3 and Swift 4, String's data(using:allowLossyConversion:) can also be used in conjunction with JSONSerialization's json?Object(with:?options:?) in order to deserialize a JSON string into a dictionary.


#1. Swift 4 solution

With Swift 4, JSONDecoder has a method called decode(_:from:). decode(_:from:) has the following declaration:

func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable

Decodes a top-level value of the given type from the given JSON representation.

The Playground code below shows how to use data(using:allowLossyConversion:) and decode(_:from:) in order to get a Dictionary from a JSON formatted String:

let jsonString = """
{"password" : "1234",  "user" : "andreas"}
"""

if let data = jsonString.data(using: String.Encoding.utf8) {
    do {
        let decoder = JSONDecoder()
        let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
        print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
    } catch {
        // Handle error
        print(error)
    }
}

#2. Swift 3 and Swift 4 solution

With Swift 3 and Swift 4, JSONSerialization has a method called json?Object(with:?options:?). json?Object(with:?options:?) has the following declaration:

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any

Returns a Foundation object from given JSON data.

The Playground code below shows how to use data(using:allowLossyConversion:) and json?Object(with:?options:?) in order to get a Dictionary from a JSON formatted String:

import Foundation

let jsonString = "{\"password\" : \"1234\",  \"user\" : \"andreas\"}"

if let data = jsonString.data(using: String.Encoding.utf8) {
    do {
        let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
        print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
    } catch {
        // Handle error
        print(error)
    }
}

How do I toggle an element's class in pure JavaScript?

2014 answer: classList.toggle() is the standard and supported by most browsers.

Older browsers can use use classlist.js for classList.toggle():

var menu = document.querySelector('.menu') // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');

As an aside, you shouldn't be using IDs (they leak globals into the JS window object).

Cast int to varchar

You will need to cast or convert as a CHAR datatype, there is no varchar datatype that you can cast/convert data to:

select CAST(id as CHAR(50)) as col1 
from t9;

select CONVERT(id, CHAR(50)) as colI1 
from t9;

See the following SQL — in action — over at SQL Fiddle:

/*! Build Schema */
create table t9 (id INT, name VARCHAR(55));
insert into t9 (id, name) values (2, 'bob');

/*! SQL Queries */
select CAST(id as CHAR(50)) as col1 from t9;
select CONVERT(id, CHAR(50)) as colI1 from t9;

Besides the fact that you were trying to convert to an incorrect datatype, the syntax that you were using for convert was incorrect. The convert function uses the following where expr is your column or value:

 CONVERT(expr,type)

or

 CONVERT(expr USING transcoding_name)

Your original query had the syntax backwards.

Are there any log file about Windows Services Status?

The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.

What is so bad about singletons?

Singletons are bad from a purist point of view.

From a pratical point of view, a singleton is a trade-off developing time vs complexity.

If you know your application won't change that much they are pretty OK to go with. Just know that you may need to refactor things up if your requirements change in an unexpected way (which is pretty OK in most cases).

Singletons sometimes also complicate unit testing.

How to remove a directory from git repository?

To add new directory:

mkdir <YOUR-DIRECTORY>

But now Git is not aware by this new directory, because Git keep tracks of file not directories DIRECTORY

git status

Git won't be aware with the change we've made, so we add hidden .keep file to make Git aware by this new change.

touch /YOUR-directory/.keep

Now, if you hit git status Git will be aware with the changes.

And If you want to delete the directory, you should use this command.

rm -r <YOUR-DIRECTORY>

And If you checked by using git status, you will see the directory has been removed.

java.io.FileNotFoundException: the system cannot find the file specified

Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:

import java.io.File;
import java.util.*;

public class Hangman1 {

    public static void main(String[] args) throws Exception {
        File myFile = new File("word.txt");
        System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());

        Scanner input = new Scanner(myFile);
        String in = "";
        in = input.nextLine();
    }

}

This code should print the folder where it is looking for. Place the file there and you'll be good to go.

How to resolve ambiguous column names when retrieving results?

If you don't feel like aliassing you can also just prefix the tablenames.

This way you can better automate generation of your queries. Also, it's a best-practice to not use select * (it is obviously slower than just selecting the fields you need Furthermore, only explicitly name the fields you want to have.

SELECT
    news.id, news.title, news.author, news.posted, 
    users.id, users.name, users.registered 
FROM 
    news 
LEFT JOIN 
    users 
ON 
    news.user = user.id

Sum rows in data.frame or matrix

The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:

data$new <- rowSums( data[,43:167] )

If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.

How can I bind a background color in WPF/XAML?

Important:

Make sure you're using System.Windows.Media.Brush and not System.Drawing.Brush

They're not compatible and you'll get binding errors.

The color enumeration you need to use is also different

System.Windows.Media.Colors.Aquamarine (class name is Colors) <--- use this one System.Drawing.Color.Aquamarine (class name is Color)

If in doubt use Snoop and inspect the element's background property to look for binding errors - or just look in your debug log.

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

How to force NSLocalizedString to use a specific language

For Swift you can override the main.swift file and set the UserDefaults string there before you app runs. This way you do not have to restart the App to see the desired effect.

import Foundation
import UIKit

// Your initialisation code here
let langCultureCode: String = "LANGUAGE_CODE"

UserDefaults.standard.set([langCultureCode], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()

UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))

paired together with the removal of @UIApplicationMain in your AppDelegate.swift file.

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

Install Android App Bundle on device

Use (on Linux): cd android ./gradlew assemblyRelease|assemblyDebug

An unsigned APK is generated for each case (for debug or testing)

NOTE: On Windows, replace gradle executable for gradlew.bat

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

If you use angular remove the ng-storage profile from your browser console. It is not a general solution bit It worked in my case.

In Chrome F12->Resources->Local Storage

How to fix git error: RPC failed; curl 56 GnuTLS

I got this error while i tried to push a new branch upstream

git push --set-upstream origin xyz

I tried almost all of the git config edits suggested above including a system reboot. Nothing worked.

So I went back to master and did a pull, went back to my xyz branch, did a merge with master and was able to push.

* currently on branch xyz
git checkout master
git pull
git checkout xyz
git merge master
git push --set-upstream origin xyz

I have to say nothing in master conflicted with any of my changes in my new branch "xyx". Only a couple of new commits from master were merged to my "xyz" branch. This shouldn't have been a problem on normal days.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Size-limited queue that holds last N elements in Java

Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.

I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):

public LimitedSizeQueue implements Queue
{
  private int maxSize;
  private LinkedList storageArea;

  public LimitedSizeQueue(final int maxSize)
  {
    this.maxSize = maxSize;
    storageArea = new LinkedList();
  }

  public boolean offer(ElementType element)
  {
    if (storageArea.size() < maxSize)
    {
      storageArea.addFirst(element);
    }
    else
    {
      ... remove last element;
      storageArea.addFirst(element);
    }
  }

  ... the rest of this class

A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:

public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
    private int maxSize;
    private CircularFifoBuffer storageArea;

    public LimitedSizeQueue(final int maxSize)
    {
        if (maxSize > 0)
        {
            this.maxSize = maxSize;
            storateArea = new CircularFifoBuffer(maxSize);
        }
        else
        {
            throw new IllegalArgumentException("blah blah blah");
        }
    }

    ... implement the Queue interface using the CircularFifoBuffer class
}

php mail setup in xampp

Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.

In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.

You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.

How to position two elements side by side using CSS

Put the iframe inside the <p> and make the iframe CSS

float:left;

display:inline-block;

Application_Start not firing?

Had the same problem in a Project we had taken over after another vendor built it. The problem was that while there were a number of commands written by the previous vendor in Global.asax.cs, which might lead you to believe it was in use, it was actually being ignored entirely. Global.asax wasn't inheriting from it, and it's easy to never see this file if the .cs file is present - you have to right-click Global.asax and click View Markup to actually see it.

Global.asax:

<%@ Application Language="C#" %>

Needed to be changed to:

<%@ Application Codebehind="Global.asax.cs" Inherits="ProjectNamespace.MvcApplication" Language="C#" %>

Where ProjectNamespace is whatever the namespace is of your Global.asax.cs class (usually the name of your Project).

In our case the file contained a bunch of inline code, some of which was copy-pasted from the .cs file, some not. We just dumped the inline code over to the .cs file and gradually merged our changes back in.

Spring MVC Controller redirect using URL parameters instead of in response

@RequestMapping(path="/apps/add", method=RequestMethod.POST)
public String addApps(String appUrl, Model model, final RedirectAttributes redirectAttrs) {
    if (!validate(appUrl)) {
       redirectAttrs.addFlashAttribute("error", "Validation failed");
    }
    return "redirect:/apps/add"
} 

@RequestMapping(path="/apps/add", method=RequestMethod.GET)
public String addAppss(Model model) {
    String error = model.asMap().get("error");
}

How to check for changes on remote (origin) Git repository

One potential solution

Thanks to Alan Haggai Alavi's solution I came up with the following potential workflow:

Step 1:

git fetch origin

Step 2:

git checkout -b localTempOfOriginMaster origin/master
git difftool HEAD~3 HEAD~2
git difftool HEAD~2 HEAD~1
git difftool HEAD~1 HEAD~0

Step 3:

git checkout master
git branch -D localTempOfOriginMaster
git merge origin/master

HTML text input field with currency symbol

If you only need to support Safari, you can do it like this:

input.currency:before {
  content: attr(data-symbol);
  float: left;
  color: #aaa;
}

and an input field like

<input class="currency" data-symbol="€" type="number" value="12.9">

This way you don't need an extra tag and keep the symbol information in the markup.

How to find the php.ini file used by the command line?

On OSX Mavericks, running:

$ php -i | grep 'Configuration File'

Returned:

Configuration File (php.ini) Path => /etc
Loaded Configuration File:         (none)

In the /etc/ directory was:

php.ini.default

(as well as php-fpm.conf.default)

I was able to copy php.ini.default to php.ini, add date.timezone = "US/Central" to the top (right below [php]), and the problem is solved.

(At least the error message is gone.)

Show/hide image with JavaScript

You can do this with jquery just visit http://jquery.com/ to get the link then do something like this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').show('slow');
      });
   });
</script>

or if you would like the link to turn the image on and off do this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none;" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').toggle();
      });
   });
</script>

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

What is the difference between compileSdkVersion and targetSdkVersion?

As a oneliner guide:

minSdkVersion <= targetSdkVersion <= compileSdkVersion

Ideally:

minSdkVersion (lowest possible) <= targetSdkVersion == compileSdkVersion (latest SDK)

Read more from this great post by Ian Lake

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

Bad Request - Invalid Hostname IIS7

Make sure IIS is listening to your port.

In my case this was the issue. So I had to change my port to something else like 8083 and it solved this issue.

Is it possible to use global variables in Rust?

You can use static variables fairly easily as long as they are thread-local.

The downside is that the object will not be visible to other threads your program might spawn. The upside is that unlike truly global state, it is entirely safe and is not a pain to use - true global state is a massive pain in any language. Here's an example:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<sqlite::database::Database> = RefCell::new(sqlite::open("test.db"));

fn main() {
    ODB.with(|odb_cell| {
        let odb = odb_cell.borrow_mut();
        // code that uses odb goes here
    });
}

Here we create a thread-local static variable and then use it in a function. Note that it is static and immutable; this means that the address at which it resides is immutable, but thanks to RefCell the value itself will be mutable.

Unlike regular static, in thread-local!(static ...) you can create pretty much arbitrary objects, including those that require heap allocations for initialization such as Vec, HashMap and others.

If you cannot initialize the value right away, e.g. it depends on user input, you may also have to throw Option in there, in which case accessing it gets a bit unwieldy:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<Option<sqlite::database::Database>> = RefCell::New(None));

fn main() {
    ODB.with(|odb_cell| {
        // assumes the value has already been initialized, panics otherwise
        let odb = odb_cell.borrow_mut().as_mut().unwrap();
        // code that uses odb goes here
    });
}

How do I add a simple onClick event handler to a canvas element?

I recommand the following article : Hit Region Detection For HTML5 Canvas And How To Listen To Click Events On Canvas Shapes which goes through various situations.

However, it does not cover the addHitRegion API, which must be the best way (using math functions and/or comparisons is quite error prone). This approach is detailed on developer.mozilla

TypeError: 'dict' object is not callable

A more functional approach would be by using dict.get

input_nums = [int(in_str) for in_str in input_str.split())
strikes = list(map(number_map.get, input_nums.split()))

One can observe that the conversion is a little clumsy, better would be to use the abstraction of function composition:

def compose2(f, g):
    return lambda x: f(g(x))

strikes = list(map(compose2(number_map.get, int), input_str.split()))

Example:

list(map(compose2(number_map.get, int), ["1", "2", "7"]))
Out[29]: [-3, -2, None]

Obviously in Python 3 you would avoid the explicit conversion to a list. A more general approach for function composition in Python can be found here.

(Remark: I came here from the Design of Computer Programs Udacity class, to write:)

def word_score(word):
    "The sum of the individual letter point scores for this word."
    return sum(map(POINTS.get, word))

Generate Json schema from XML schema (XSD)

Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.

Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.

Let's take the Purchase Order schema for example. Here's a fragment:

  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>

  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>

You can compile this schema using the provided command-line tool:

java -jar jsonix-schema-compiler-full.jar
    -generateJsonSchema
    -p PO
    schemas/purchaseorder.xsd

The compiler generates Jsonix mappings as well the matching JSON Schema.

Here's what the result looks like (edited for brevity):

{
    "id":"PurchaseOrder.jsonschema#",
    "definitions":{
        "PurchaseOrderType":{
            "type":"object",
            "title":"PurchaseOrderType",
            "properties":{
                "shipTo":{
                    "title":"shipTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                },
                "billTo":{
                    "title":"billTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                }, ...
            }
        },
        "USAddress":{ ... }, ...
    },
    "anyOf":[
        {
            "type":"object",
            "properties":{
                "name":{
                    "$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
                },
                "value":{
                    "$ref":"#/definitions/PurchaseOrderType"
                }
            },
            "elementName":{
                "localPart":"purchaseOrder",
                "namespaceURI":""
            }
        }
    ]
}

Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.

The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).

Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.

Links:

How to read an http input stream

It looks like the documentation is just using readStream() to mean:

Ok, we've shown you how to get the InputStream, now your code goes in readStream()

So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.

Named capturing groups in JavaScript regex?

Update: It finally made it into JavaScript (ECMAScript 2018)!


Named capturing groups could make it into JavaScript very soon.
The proposal for it is at stage 3 already.

A capture group can be given a name inside angular brackets using the (?<name>...) syntax, for any identifier name. The regular expression for a date then can be written as /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u. Each name should be unique and follow the grammar for ECMAScript IdentifierName.

Named groups can be accessed from properties of a groups property of the regular expression result. Numbered references to the groups are also created, just as for non-named groups. For example:

let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = re.exec('2015-01-02');
// result.groups.year === '2015';
// result.groups.month === '01';
// result.groups.day === '02';

// result[0] === '2015-01-02';
// result[1] === '2015';
// result[2] === '01';
// result[3] === '02';

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

Bash command line and input limit

The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX and on POSIX conformant systems you can query it with

$ getconf ARG_MAX    # Get argument limit in bytes

E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.

If you need to process a list of files exceeding this limit, you might want to look at the xargs utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX.

To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".

Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX. The restriction also does not apply to shell-builtins.

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

DataGridView checkbox column - value and functionality

if u make this column in sql database (bit) as a data type u should edit this code

DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
dataGridView1.Columns.Insert(0, doWork);

with this

DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "False";
doWork.TrueValue = "True";
dataGridView1.Columns.Insert(0, doWork);

How can I check if a string represents an int, without using try/except?

Use a regular expression:

import re
def RepresentsInt(s):
    return re.match(r"[-+]?\d+$", s) is not None

If you must accept decimal fractions also:

def RepresentsInt(s):
    return re.match(r"[-+]?\d+(\.0*)?$", s) is not None

For improved performance if you're doing this often, compile the regular expression only once using re.compile().

How to convert milliseconds to seconds with precision

Why don't you simply try

System.out.println(1500/1000.0);
System.out.println(500/1000.0);

Subtract two dates in SQL and get days of the result

SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between
FROM dual
/

Passing parameters in rails redirect_to

Just append them to the options:

redirect_to controller: 'thing', action: 'edit', id: 3, something: 'else'

Would yield /thing/3/edit?something=else

SQL query for finding records where count > 1

Use the HAVING clause and GROUP By the fields that make the row unique

The below will find

all users that have more than one payment per day with the same account number

SELECT 
 user_id ,
 COUNT(*) count
FROM 
 PAYMENT
GROUP BY
 account,
 user_id ,
 date
HAVING
COUNT(*) > 1

Update If you want to only include those that have a distinct ZIP you can get a distinct set first and then perform you HAVING/GROUP BY

 SELECT 
    user_id,
    account_no , 
    date,
        COUNT(*)
 FROM
    (SELECT DISTINCT
            user_id,
            account_no , 
            zip, 
            date
         FROM
            payment 
    
        ) 
        payment
 GROUP BY
    
    user_id,
    account_no , 
    
    date
HAVING COUNT(*) > 1

Javascript - validation, numbers only

If you are using React, just do:

<input
  value={this.state.input}
  placeholder="Enter a number"
  onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>

_x000D_
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>_x000D_
<script type="text/babel">_x000D_
class Demo extends React.Component {_x000D_
    state = {_x000D_
      input: '',_x000D_
    }_x000D_
    _x000D_
    onChange = e => {_x000D_
      let input = e.target.value.replace(/[^0-9]/g, '');_x000D_
      this.setState({ input });_x000D_
    }_x000D_
    _x000D_
    render() {_x000D_
        return (_x000D_
          <div>_x000D_
            <input_x000D_
              value={this.state.input}_x000D_
              placeholder="Enter a number"_x000D_
              onChange={this.onChange}_x000D_
            />_x000D_
            <br />_x000D_
            <h1>{this.state.input}</h1>_x000D_
           </div>_x000D_
        );_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Demo />, document.getElementById('root'));_x000D_
</script>
_x000D_
_x000D_
_x000D_

Nested attributes unpermitted parameters

Today I came across this same issue, whilst working on rails 4, I was able to get it working by structuring my fields_for as:

<%= f.select :tag_ids, Tag.all.collect {|t| [t.name, t.id]}, {}, :multiple => true %>

Then in my controller I have my strong params as:

private
def post_params
    params.require(:post).permit(:id, :title, :content, :publish, tag_ids: [])
end

All works!

Ignore .classpath and .project from Git

If the .project and .classpath are already committed, then they need to be removed from the index (but not the disk)

git rm --cached .project
git rm --cached .classpath

Then the .gitignore would work (and that file can be added and shared through clones).
For instance, this gitignore.io/api/eclipse file will then work, which does include:

# Eclipse Core      
.project

# JDT-specific (Eclipse Java Development Tools)     
.classpath

Note that you could use a "Template Directory" when cloning (make sure your users have an environment variable $GIT_TEMPLATE_DIR set to a shared folder accessible by all).
That template folder can contain an info/exclude file, with ignore rules that you want enforced for all repos, including the new ones (git init) that any user would use.


As commented by Abdollah

When you change the index, you need to commit the change and push it.
Then the file is removed from the repository. So the newbies cannot checkout the files .classpath and .project from the repo.

Datanode process not running in Hadoop

Instead of deleting everything under the "hadoop tmp dir", you can set another one. For example, if your core-site.xml has this property:

<property>
  <name>hadoop.tmp.dir</name>
  <value>/home/hduser/data/tmp</value>
</property>

You can change this to:

<property>
  <name>hadoop.tmp.dir</name>
  <value>/home/hduser/data/tmp2</value>
</property>

and then scp core-site.xml to each node, and then "hadoop namenode -format", and then restart hadoop.

Use images instead of radio buttons

Here is very simple example

_x000D_
_x000D_
input[type="radio"]{_x000D_
   display:none;_x000D_
}_x000D_
_x000D_
input[type="radio"] + label_x000D_
{_x000D_
    background-image:url(http://www.clker.com/cliparts/c/q/l/t/l/B/radiobutton-unchecked-sm-md.png);_x000D_
    background-size: 100px 100px;_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    display:inline-block;_x000D_
    padding: 0 0 0 0px;_x000D_
    cursor:pointer;_x000D_
}_x000D_
_x000D_
input[type="radio"]:checked + label_x000D_
{_x000D_
    background-image:url(http://www.clker.com/cliparts/M/2/V/6/F/u/radiobutton-checked-sm-md.png);_x000D_
}
_x000D_
<div>_x000D_
  <input type="radio" id="shipadd1" value=1 name="address" />_x000D_
  <label for="shipadd1"></label>_x000D_
  value 1_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <input type="radio" id="shipadd2" value=2 name="address" />_x000D_
  <label for="shipadd2"></label>_x000D_
  value 2_x000D_
</div>
_x000D_
_x000D_
_x000D_

Demo: http://jsfiddle.net/La8wQ/2471/

This example based on this trick: https://css-tricks.com/the-checkbox-hack/

I tested it on: chrome, firefox, safari

C# Numeric Only TextBox Control

TRY THIS CODE

// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;
    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if (e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (nonNumberEntered == true)
    {
       MessageBox.Show("Please enter number only..."); 
       e.Handled = true;
    }
}


Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx

Ruby/Rails: converting a Date to a UNIX timestamp

Solution for Ruby 1.8 when you have an arbitrary DateTime object:

1.8.7-p374 :001 > require 'date'
 => true 
1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
 => "1326585600"

The operation cannot be completed because the DbContext has been disposed error

You need to remember that IQueryable queries are not actually executed against the data store until you enumerate them.

using (var dataContext = new dataContext())
{

This line of code doesn't actually do anything other than build the SQL statement

    users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);

.Any() is an operation that enumerates the IQueryable, so the SQL is sent to the data source (through dataContext), and then the .Any() operations is executed against it

    if(users.Any() == false)
    {
        return null;
    }
}

Your "problem" line is reusing the sql built above, and then doing an additional operation (.Select()), which just adds to the query. If you left it here, no exception, except your problem line

return users.Select(x => x.ToInfo()).ToList(); // this line is the problem

calls .ToList(), which enumerates the IQueryable, which causes the SQL to be sent to the datasource through the dataContext that was used in the original LINQ query. Since this dataContext has been disposed, it is no longer valid, and .ToList() throws an exception.

That is the "why it doesn't work". The fix is to move this line of code inside the scope of your dataContext.

How to use it properly is another question with a few arguably correct answers that depend on your application (Forms vs. ASP.net vs. MVC, etc.). The pattern that this implements is the Unit of Work pattern. There is almost no cost to creating a new context object, so the general rule is to create one, do your work, and then dispose of it. In web apps, some people will create a Context per request.

How to find row number of a value in R code

I would be tempted to use grepl, which should give all the lines with matches and can be generalised for arbitrary strings.

mydata_2 <- read.table(textConnection("
sex age height_seca1 height_chad1 height_DL weight_alog1
1 F 19 1800 1797 180 70.0
2 F 19 1682 1670 167 69.0
3 F 21 1765 1765 178 80.0
4 F 21 1829 1833 181 74.0
5 F 21 1706 1705 170 103.0
6 F 18 1607 1606 160 76.0
7 F 19 1578 1576 156 50.0
8 F 19 1577 1575 156 61.0
9 F 21 1666 1665 166 52.0
10 F 17 1710 1716 172 65.0
11 F 28 1616 1619 161 65.5
12 F 22 1648 1644 165 57.5
13 F 19 1569 1570 155 55.0
14 F 19 1779 1777 177 55.0
15 M 18 1773 1772 179 70.0
16 M 18 1816 1809 181 81.0
17 M 19 1766 1765 178 77.0
18 M 19 1745 1741 174 76.0
19 M 18 1716 1714 170 71.0
20 M 21 1785 1783 179 64.0
21 M 19 1850 1854 185 71.0
22 M 31 1875 1880 188 95.0
23 M 26 1877 1877 186 105.5
24 M 19 1836 1837 185 100.0
25 M 18 1825 1823 182 85.0
26 M 19 1755 1754 174 79.0
27 M 26 1658 1658 165 69.0
28 M 20 1816 1818 183 84.0
29 M 18 1755 1755 175 67.0"),
                       sep = " ", header = TRUE)

which(grepl(1578, mydata_2$height_seca1))

The output is:

> which(grepl(1578, mydata_2$height_seca1))
[1] 7
> 

[Edit] However, as pointed out in the comments, this will capture much more than the string 1578 (e.g. it also matches for 21578 etc) and thus should be used only if you are certain that you the length of the values you are searching will not be larger than the four characters or digits shown here.

And subsetting as per the other answer also works fine:

mydata_2[mydata_2$height_seca1 == 1578, ]
  sex age height_seca1 height_chad1 height_DL weight_alog1
7   F  19         1578         1576       156           50
> 

If you're looking for several different values, you could put them in a vector and then use the %in% operator:

look.for <- c(1578, 1658, 1616)
> mydata_2[mydata_2$height_seca1 %in% look.for, ]
   sex age height_seca1 height_chad1 height_DL weight_alog1
7    F  19         1578         1576       156         50.0
11   F  28         1616         1619       161         65.5
27   M  26         1658         1658       165         69.0
> 

move column in pandas dataframe

You can also do this as a one-liner:

df.drop(columns=['b', 'x']).assign(b=df['b'], x=df['x'])

How to print the array?

If you want to print the array like you print a 2D list in Python:

#include <stdio.h>

int main()
{
  int i, j;
  int my_array[3][3] = {{10, 23, 42}, {1, 654, 0}, {40652, 22, 0}};
  for(i = 0; i < 3; i++)
  {
      if (i == 0) {
          printf("[");
      }
      printf("[");
      for(j = 0; j < 3; j++)
      {
         printf("%d", my_array[i][j]);
         if (j < 2) {
             printf(", ");
         }
      }
    printf("]");
    if (i == 2) {
        printf("]");
    }

    if (i < 2) {
        printf(", ");
    }
  }
  return 0;
}

Output will be:

[[10, 23, 42], [1, 654, 0], [40652, 22, 0]]

LINQ order by null column where order is ascending and nulls should be last

Here is another way:

//Acsending
case "SUP_APPROVED_IND": qry =
                            qry.OrderBy(r => r.SUP_APPROVED_IND.Trim() == null).
                                    ThenBy(r => r.SUP_APPROVED_IND);

                            break;
//….
//Descending
case "SUP_APPROVED_IND": qry =
                            qry.OrderBy(r => r.SUP_APPROVED_IND.Trim() == null).
                                    ThenByDescending(r => r.SUP_APPROVED_IND); 

                            break;

SUP_APPROVED_IND is char(1) in Oracle db.

Note that r.SUP_APPROVED_IND.Trim() == null is treated as trim(SUP_APPROVED_IND) is null in Oracle db.

See this for details: How can i query for null values in entity framework?

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

Why isn't textarea an input[type="textarea"]?

So that its value can easily contain quotes and <> characters and respect whitespace and newlines.

The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Yes I can</title>
</head>
<body>
    <textarea name="test">
        I can put < and > and & signs in 
        my textarea without any problems.
    </textarea>
</body>
</html>

How to start new activity on button click

Although proper answers have been already provided but I am here for searching the answer in language Kotlin. This Question is not about language specific so I am adding the code to accomplish this task in Kotlin language.

Here is how you do this in Kotlin for andorid

testActivityBtn1.setOnClickListener{
      val intent = Intent(applicationContext,MainActivity::class.java)
      startActivity(intent)

 }

Adding the "Clear" Button to an iPhone UITextField

Swift 4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

or even shorter:

textField.clearButtonMode = .whileEditing

How can I remove specific rules from iptables?

Use -D command, this is how man page explains it:

-D, --delete chain rule-specification
-D, --delete chain rulenum
    Delete  one  or more rules from the selected chain.  
    There are two versions of this command: 
    the rule can be specified as a number in the chain (starting at 1 for the first rule) or a rule to match.

Do realize this command, like all other command(-A, -I) works on certain table. If you'are not working on the default table(filter table), use -t TABLENAME to specify that target table.

Delete a rule to match

iptables -D INPUT -i eth0 -p tcp --dport 443 -j ACCEPT

Note: This only deletes the first rule matched. If you have many rules matched(this can happen in iptables), run this several times.

Delete a rule specified as a number

iptables -D INPUT 2

Other than counting the number you can list the line-number with --line-number parameter, for example:

iptables -t nat -nL --line-number

java.net.SocketException: Connection reset by peer: socket write error When serving a file

It is possible for the TCP socket to be "closing" and your code to not have yet been notified.

Here is a animation for the life cycle. http://tcp.cs.st-andrews.ac.uk/index.shtml?page=connection_lifecycle

Basically, the connection was closed by the client. You already have throws IOException and SocketException extends IOException. This is working just fine. You just need to properly handle IOException because it is a normal part of the api.

EDIT: The RST packet occurs when a packet is received on a socket which does not exist or was closed. There is no difference to your application. Depending on the implementation the reset state may stick and closed will never officially occur.

fail to change placeholder color with Bootstrap 3

The others did not work in my case (Bootstrap 4). Here is the solution I used.

html .form-control::-webkit-input-placeholder { color:white; }
html .form-control:-moz-placeholder { color:white; }
html .form-control::-moz-placeholder { color:white; }
html .form-control:-ms-input-placeholder { color:white; }

If we use a stronger selector (html first), we don't need to use the hacky value !important.

This overrides bootstraps CSS as we use a higher level of specificity to target .form-control elements (html first instead of .form-control first).

Writing a new line to file in PHP (line feed)

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);

current/duration time of html5 video?

This page might help you out. Everything you need to know about HTML5 video and audio

var video = document.createElement('video');
var curtime = video.currentTime;

If you already have the video element, .currentTime should work. If you need more details, that webpage should be able to help.

Setting public class variables

Inside class Testclass:

public function __construct($new_value)
{
    $this->testvar = $new_value;
}

How do you set the max number of characters for an EditText in Android?

I always set the max like this:

    <EditText
        android:id="@+id/edit_blaze_it
        android:layout_width="0dp"
        android:layout_height="@dimen/too_high"

    <!-- This is the line you need to write to set the max-->
        android:maxLength="420"
        />

Redirect using AngularJS

Don't forget to inject $location into controller.

C# send a simple SSH command

SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\"");
cSSH.Disconnect();
cSSH.Dispose();

//using SSH.Net