Programs & Examples On #Smarty

Smarty is a templating engine for PHP. It allows for easy separation of application logic and display code, as well as simplifying reuse of templates.

How to Debug Variables in Smarty like in PHP var_dump()

In smarty there is built in modifier you could use that by using | (single pipeline operator). Like this {$varname|@print_r} will print value as print_r($php_variable)

What are .tpl files? PHP, web design

Number 3 hit on Google for "tpl file" (even though it's one of those annoying "Fix TPL errors now", "Scan TPL files with our virus scanner", sell-you-everything-under-the-sun-with-flashy-ugly-ads-when-all-you-wanted-was-the-file-description sites) is:

Used by PHP web development and PHP web applications as a template file. Mostly used by Smarty template engine. Template is a common text file (like .html file) and contains user defined variables that are replaced by user defined output content when PHP web application parsing a template file.

JavaScript - get the first day of the week from current date

An example of the mathematically only calculation, without any Date functions.

_x000D_
_x000D_
const date = new Date();_x000D_
const ts = +date;_x000D_
_x000D_
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);_x000D_
_x000D_
const monday = new Date(mondayTS);_x000D_
console.log(monday.toISOString(), 'Day:', monday.getDay());
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
const formatTS = v => new Date(v).toISOString();_x000D_
const adjust = (v, d = 1) => v - v % (d * 1000);_x000D_
_x000D_
const d = new Date('2020-04-22T21:48:17.468Z');_x000D_
const ts = +d; // 1587592097468_x000D_
_x000D_
const test = v => console.log(formatTS(adjust(ts, v)));_x000D_
_x000D_
test();                     // 2020-04-22T21:48:17.000Z_x000D_
test(60);                   // 2020-04-22T21:48:00.000Z_x000D_
test(60 * 60);              // 2020-04-22T21:00:00.000Z_x000D_
test(60 * 60 * 24);         // 2020-04-22T00:00:00.000Z_x000D_
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday_x000D_
_x000D_
// So, what does `(7-4)` mean?_x000D_
// 7 - days number in the week_x000D_
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second._x000D_
//     new Date(0)          ---> 1970-01-01T00:00:00.000Z_x000D_
//     new Date(0).getDay() ---> 4
_x000D_
_x000D_
_x000D_

Does Java have an exponential operator?

There is no operator, but there is a method.

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.

How to show full object in Chrome console?

I wrote a function to conveniently print things to the console.

// function for debugging stuff
function print(...x) {
    console.log(JSON.stringify(x,null,4));
}

// how to call it
let obj = { a: 1, b: [2,3] };
print('hello',123,obj);

will output in console:

[
    "hello",
    123,
    {
        "a": 1,
        "b": [
            2,
            3
        ]
    }
]

Scrolling to element using webdriver?

You can scroll to the element by using javascript through the execute_javascript method. For example here is how I do it using SeleniumLibrary on Robot Framework:

web_element = self.selib.find_element(locator)
self.selib.execute_javascript(
    "ARGUMENTS",
    web_element,
    "JAVASCRIPT",
    'arguments[0].scrollIntoView({behavior: "instant", block: "start", inline: "start"});'
)

What is the difference between parseInt(string) and Number(string) in JavaScript?

parseInt("123qwe")

returns 123

Number("123qwe")

returns NaN

In other words parseInt() parses up to the first non-digit and returns whatever it had parsed. Number() wants to convert the entire string into a number, which can also be a float BTW.


EDIT #1: Lucero commented about the radix that can be used along with parseInt(). As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).


EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number() in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat() aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui") also returns NaN). And the biggest difference is the use of radix that Number() doesn't know of and parseInt() may indirectly guess from the given string (that can cause weird results sometimes).

How to create a custom-shaped bitmap marker with Android map API v2

From lambda answer, I have made something closer to the requirements.

boolean imageCreated = false;

Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
    if (!imageCreated) {
        imageCreated = true;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        bmp = Bitmap.createBitmap(400, 400, conf);
        Canvas canvas1 = new Canvas(bmp);

        Paint color = new Paint();
        color.setTextSize(30);
        color.setColor(Color.WHITE);

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inMutable = true;

        Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
                R.drawable.messi,opt);
        Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
        canvas1.drawBitmap(resized, 40, 40, color);

        canvas1.drawText("Le Messi", 30, 40, color);

        currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
                .icon(BitmapDescriptorFactory.fromBitmap(bmp))
                // Specifies the anchor to be at a particular point in the marker image.
                .anchor(0.5f, 1));
    } else {
        currentLocationMarker.setPosition(currentLocation);
    }

}

Causes of getting a java.lang.VerifyError

Another reason for this error can be the combination of AspectJ <= 1.6.11 with JRE > 6.

See Eclipse Bug 353467 and Kieker ticket 307 for details.

This is especially true when everything works fine on JRE 6 and moving to JRE7 breaks things.

How to get primary key of table?

SELECT kcu.column_name, kcu.ordinal_position
FROM   information_schema.table_constraints tc
INNER JOIN information_schema.key_column_usage kcu
ON     tc.CONSTRAINT_CATALOG = kcu.CONSTRAINT_CATALOG
AND    tc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA
AND    tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
WHERE  tc.table_schema = schema()             -- only look in the current schema
AND    tc.constraint_type = 'PRIMARY KEY'
AND    tc.table_name = '<your-table-name>'    -- specify your table.
ORDER BY kcu.ordinal_position

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.

First, run following code in the console:

chcp 65001
set PYTHONIOENCODING=utf-8

Then, start python do anything you want.

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

None of the above worked for me but I came up with this and it worked:

function toggleChevron(el) {
  if ($(el).find('i').hasClass('icon-chevron-left'))
      $(el).find('.icon-chevron-left').removeClass("icon-chevron-left").addClass("icon-chevron-down");
  else 
      $(el).find('.icon-chevron-down').removeClass("icon-chevron-down").addClass("icon-chevron-left");
}

HTML implementation:

<div class="accordion" id="accordion-send">
  <div class="accordion-group">
    <div class="accordion-heading" onClick="toggleChevron(this)">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion-send" href="#collapse-refund">
        <i class="icon icon-chevron-right"></i> Send notice
      </a>
      ...

foreach with index

I keep this extension method around for this:

public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action)
{
    var i = 0;
    foreach (var e in ie) action(e, i++);
}

And use it like so:

var strings = new List<string>();
strings.Each((str, n) =>
{
    // hooray
});

Or to allow for break-like behaviour:

public static bool Each<T>(this IEnumerable<T> ie, Func<T, int, bool> action)
{
    int i = 0;
    foreach (T e in ie) if (!action(e, i++)) return false;
    return true;
}

var strings = new List<string>() { "a", "b", "c" };

bool iteratedAll = strings.Each ((str, n)) =>
{
    if (str == "b") return false;
    return true;
});

perform an action on checkbox checked or unchecked event on html form

Given you use JQuery, you can do something like below :

HTML

<form id="myform">
    syn<input type="checkbox" name="checkfield" id="g01-01"  onclick="doalert()"/>
</form>

JS

function doalert() {
  if ($("#g01-01").is(":checked")) {
    alert ("hi");
  } else {
    alert ("bye");
  }
}

alert a variable value

Note, while the above answers are correct, if you want, you can do something like:

alert("The variable named x1 has value:  " + x1);

Excel formula to display ONLY month and year?

There are a number of ways to go about this. One way would be to enter the date 8/1/2013 manually in the first cell (say A1 for example's sake) and then in B1 type the following formula (and then drag it across):

=DATE(YEAR(A1),MONTH(A1)+1,1)

Since you only want to see month and year, you can format accordingly using the different custom date formats available.

The format you're looking for is YY-Mmm.

Format number as percent in MS SQL Server

Using FORMAT function in new versions of SQL Server is much simpler and allows much more control:

FORMAT(yournumber, '#,##0.0%')

Benefit of this is you can control additional things like thousand separators and you don't get that space between the number and '%'.

How do you list all triggers in a MySQL database?

I hope following code will give you more information.

select * from information_schema.triggers where 
information_schema.triggers.trigger_schema like '%your_db_name%'

This will give you total 22 Columns in MySQL version: 5.5.27 and Above

TRIGGER_CATALOG 
TRIGGER_SCHEMA
TRIGGER_NAME
EVENT_MANIPULATION
EVENT_OBJECT_CATALOG
EVENT_OBJECT_SCHEMA 
EVENT_OBJECT_TABLE
ACTION_ORDER
ACTION_CONDITION
ACTION_STATEMENT
ACTION_ORIENTATION
ACTION_TIMING
ACTION_REFERENCE_OLD_TABLE
ACTION_REFERENCE_NEW_TABLE
ACTION_REFERENCE_OLD_ROW
ACTION_REFERENCE_NEW_ROW
CREATED 
SQL_MODE
DEFINER 
CHARACTER_SET_CLIENT
COLLATION_CONNECTION
DATABASE_COLLATION

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

Gmail: 530 5.5.1 Authentication Required. Learn more at

You need to go here https://security.google.com/settings/security/apppasswords

then select Gmail and then select device. then click on Generate. Simply Copy & Paste password which is generated by Google.

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

Display a view from another controller in ASP.NET MVC

You can also call any controller from JavaScript/jQuery. Say you have a controller returning 404 or some other usercontrol/page. Then, on some action, from your client code, you can call some address that will fire your controller and return the result in HTML format your client code can take this returned result and put it wherever you want in you your page...

Add new row to excel Table (VBA)

I had the same problem before and i fixed it by creating the same table in a new sheet and deleting all the name ranges associated to the table, i believe whene you're using listobjects you're not alowed to have name ranges contained within your table hope that helps thanks

Add Auto-Increment ID to existing table?

This SQL request works for me :

ALTER TABLE users
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;

How do I query for all dates greater than a certain date in SQL Server?

DateTime start1 = DateTime.Parse(txtDate.Text);

SELECT * 
FROM dbo.March2010 A
WHERE A.Date >= start1;

First convert TexBox into the Datetime then....use that variable into the Query

How can I use different certificates on specific connections?

I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).

This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.

So this is in our LocalSSLSocketFactory:

static {
    try {
        SSL_CONTEXT = SSLContext.getInstance("SSL");
        SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    } catch (KeyManagementException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });

    return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}

Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

Big-O summary for Java Collections Framework implementations?

The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).

List implementations:

                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)

Set implementations:

                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)

Map implementations:

                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table capacity 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table capacity 
ConcurrentSkipListMap O(log n) O(log n)    O(1)

Queue implementations:

                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

The bottom of the javadoc for the java.util package contains some good links:

How to remove unused imports from Eclipse

Not to reorganize imports (not to unfold .* and not to reorder lines) to have least VCS changeset
you can use custom eclipse clenup as this answer suggests

How can I check if a Perl module is installed on my system from the command line?

You can check for a module's installation path by:

perldoc -l XML::Simple

The problem with your one-liner is that, it is not recursively traversing directories/sub-directories. Hence, you get only pragmatic module names as output.

How to connect wireless network adapter to VMWare workstation?

Since there is only one WiFi hardware on the computer its not possible to connect one WiFi hardware to multiple WiFi networks, if you want to that I think you have to map WiFi hardware to guest OS and how host you'll have to use some other hardware (may be Ethernet) but I'm sure that it will work in that way as no VM software allow us to allocate Hardware to Guest except for USB, you can also get USB WiFI and allocate that to VM only.

How do I use a custom Serializer with Jackson?

These are behavior patterns I have noticed while trying to understand Jackson serialization.

1) Assume there is an object Classroom and a class Student. I've made everything public and final for ease.

public class Classroom {
    public final double double1 = 1234.5678;
    public final Double Double1 = 91011.1213;
    public final Student student1 = new Student();
}

public class Student {
    public final double double2 = 1920.2122;
    public final Double Double2 = 2324.2526;
}

2) Assume that these are the serializers we use for serializing the objects into JSON. The writeObjectField uses the object's own serializer if it is registered with the object mapper; if not, then it serializes it as a POJO. The writeNumberField exclusively only accepts primitives as arguments.

public class ClassroomSerializer extends StdSerializer<Classroom> {
    public ClassroomSerializer(Class<Classroom> t) {
        super(t);
    }

    @Override
    public void serialize(Classroom value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeStartObject();
        jgen.writeObjectField("double1-Object", value.double1);
        jgen.writeNumberField("double1-Number", value.double1);
        jgen.writeObjectField("Double1-Object", value.Double1);
        jgen.writeNumberField("Double1-Number", value.Double1);
        jgen.writeObjectField("student1", value.student1);
        jgen.writeEndObject();
    }
}

public class StudentSerializer extends StdSerializer<Student> {
    public StudentSerializer(Class<Student> t) {
        super(t);
    }

    @Override
    public void serialize(Student value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeStartObject();
        jgen.writeObjectField("double2-Object", value.double2);
        jgen.writeNumberField("double2-Number", value.double2);
        jgen.writeObjectField("Double2-Object", value.Double2);
        jgen.writeNumberField("Double2-Number", value.Double2);
        jgen.writeEndObject();
    }
}

3) Register only a DoubleSerializer with DecimalFormat output pattern ###,##0.000, in SimpleModule and the output is:

{
  "double1" : 1234.5678,
  "Double1" : {
    "value" : "91,011.121"
  },
  "student1" : {
    "double2" : 1920.2122,
    "Double2" : {
      "value" : "2,324.253"
    }
  }
}

You can see that the POJO serialization differentiates between double and Double, using the DoubleSerialzer for Doubles and using a regular String format for doubles.

4) Register DoubleSerializer and ClassroomSerializer, without the StudentSerializer. We expect that the output is such that if we write a double as an object, it behaves like a Double, and if we write a Double as a number, it behaves like a double. The Student instance variable should be written as a POJO and follow the pattern above since it does not register.

{
  "double1-Object" : {
    "value" : "1,234.568"
  },
  "double1-Number" : 1234.5678,
  "Double1-Object" : {
    "value" : "91,011.121"
  },
  "Double1-Number" : 91011.1213,
  "student1" : {
    "double2" : 1920.2122,
    "Double2" : {
      "value" : "2,324.253"
    }
  }
}

5) Register all serializers. The output is:

{
  "double1-Object" : {
    "value" : "1,234.568"
  },
  "double1-Number" : 1234.5678,
  "Double1-Object" : {
    "value" : "91,011.121"
  },
  "Double1-Number" : 91011.1213,
  "student1" : {
    "double2-Object" : {
      "value" : "1,920.212"
    },
    "double2-Number" : 1920.2122,
    "Double2-Object" : {
      "value" : "2,324.253"
    },
    "Double2-Number" : 2324.2526
  }
}

exactly as expected.

Another important note: If you have multiple serializers for the same class registered with the same Module, then the Module will select the serializer for that class that is most recently added to the list. This should not be used - it's confusing and I am not sure how consistent this is

Moral: if you want to customize serialization of primitives in your object, you must write your own serializer for the object. You cannot rely on the POJO Jackson serialization.

Removing body margin in CSS

You've still got a margin on your h1 tag

So you need to remove that like this:

h1 {
 margin-top:0;
}

How to serialize an object to XML without getting xmlns="..."?

If you are unable to get rid of extra xmlns attributes for each element, when serializing to xml from generated classes (e.g.: when xsd.exe was used), so you have something like:

<manyElementWith xmlns="urn:names:specification:schema:xsd:one" />

then i would share with you what worked for me (a mix of previous answers and what i found here)

explicitly set all your different xmlns as follows:

Dim xmlns = New XmlSerializerNamespaces()
xmlns.Add("one", "urn:names:specification:schema:xsd:one")
xmlns.Add("two",  "urn:names:specification:schema:xsd:two")
xmlns.Add("three",  "urn:names:specification:schema:xsd:three")

then pass it to the serialize

serializer.Serialize(writer, object, xmlns);

you will have the three namespaces declared in the root element and no more needed to be generated in the other elements which will be prefixed accordingly

<root xmlns:one="urn:names:specification:schema:xsd:one" ... />
   <one:Element />
   <two:ElementFromAnotherNameSpace /> ...

AngularJS - How to use $routeParams in generating the templateUrl?

I couldn't find a way to inject and use the $routeParams service (which I would assume would be a better solution) I tried this thinking it might work:

angular.module('myApp', []).
    config(function ($routeProvider, $routeParams) {
        $routeProvider.when('/:primaryNav/:secondaryNav', {
            templateUrl: 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html'
        });
    });

Which yielded this error:

Unknown provider: $routeParams from myApp

If something like that isn't possible you can change your templateUrl to point to a partial HTML file that just has ng-include and then set the URL in your controller using $routeParams like this:

angular.module('myApp', []).
    config(function ($routeProvider) {
        $routeProvider.when('/:primaryNav/:secondaryNav', {
            templateUrl: 'resources/angular/templates/nav/urlRouter.html',
            controller: 'RouteController'
        });
    });

function RouteController($scope, $routeParams) {
        $scope.templateUrl = 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html';
    }

With this as your urlRouter.html

<div ng-include src="templateUrl"></div>

How do I use TensorFlow GPU?

Uninstall tensorflow and install only tensorflow-gpu; this should be sufficient. By default, this should run on the GPU and not the CPU. However, further you can do the following to specify which GPU you want it to run on.

If you have an nvidia GPU, find out your GPU id using the command nvidia-smi on the terminal. After that, add these lines in your script:

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = #GPU_ID from earlier

config = tf.ConfigProto()
sess = tf.Session(config=config)

For the functions where you wish to use GPUs, write something like the following:

with tf.device(tf.DeviceSpec(device_type="GPU", device_index=gpu_id)):

How do I vertically align text in a div?

Using flex, be careful with differences in browsers' rendering.

This works well both for Chrome and Internet Explorer:

_x000D_
_x000D_
.outer {_x000D_
    display: flex;_x000D_
    width: 200px;_x000D_
    height: 200px;_x000D_
    background-color: #ffc;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
    display: flex;_x000D_
    width: 50%;_x000D_
    height: 50%;_x000D_
    margin: auto;_x000D_
    text-align: center;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
    background-color: #fcc;_x000D_
}
_x000D_
<div class="outer"><div class="inner">Active Tasks</div></div>
_x000D_
_x000D_
_x000D_

Compare with this one that works only with Chrome:

_x000D_
_x000D_
.outer {_x000D_
    display: flex;_x000D_
    width: 200px;_x000D_
    height: 200px;_x000D_
    background-color: #ffc;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
    display: flex;_x000D_
    width: 50%;_x000D_
    height: 50%;_x000D_
    margin: auto;_x000D_
    background-color: #fcc;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="inner"><span style=" margin: auto;">Active Tasks</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Bootstrap 4 dropdown with search

dropdown with search using bootstrap 4.4.0 version

_x000D_
_x000D_
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div
    = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i <
    a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
}
_x000D_
#myInput {
  box-sizing: border-box;
  background-image: url('searchicon.png');
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  border-bottom: 1px solid #ddd;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: 1px solid #ddd;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    <a href="#about">home</a>
    <a href="#base">contact</a>

  </div>
</div>
_x000D_
_x000D_
_x000D_

Imported a csv-dataset to R but the values becomes factors

Both the data import function (here: read.csv()) as well as a global option offer you to say stringsAsFactors=FALSE which should fix this.

Print the address or pointer for value in C

I have been in this position, especially with new hardware. I suggest you write a little hex dump routine of your own. You will be able to see the data, and the addresses they are at, shown all together. It's good practice and a confidence builder.

gcc warning" 'will be initialized after'

Make sure the members appear in the initializer list in the same order as they appear in the class

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

or you can turn -Wno-reorder

Date Format in Swift

Another interessant possibility of format date. This screenshot belongs to Apple's App "News".

App screenshot

Here is the code:

let dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "EEEE"
let stringDay = dateFormat1.string(from: Date())

let dateFormat2 = DateFormatter()
dateFormat2.dateFormat = "MMMM"
let stringMonth = dateFormat2.string(from: Date())

let dateFormat3 = DateFormatter()
dateFormat3.dateFormat = "dd"
let numDay = dateFormat3.string(from: Date())

let stringDate = String(format: "%@\n%@ %@", stringDay.uppercased(), stringMonth.uppercased(), numDay)

Nothing to add to alternative proposed by lorenzoliveto. It's just perfect.

let dateFormat = DateFormatter()
dateFormat.dateFormat = "EEEE\nMMMM dd"
let stringDate = dateFormat.string(from: Date()).uppercased()

How to check if a view controller is presented modally or pushed on a navigation stack?

if let navigationController = self.navigationController, navigationController.isBeingPresented {
    // being presented
}else{
    // being pushed
}

JQuery How to extract value from href tag?

I see two options here

var link = $('a').attr('href');
var equalPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(equalPosition + 1); //Split the string and get the number.

I dont know if you're gonna use it for paging and have the text in the <a>-tag as you have it, but if you should you can also do

var number = $('a').text();

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

Because it's not actually a dictionary; it's another mapping type that looks like a dictionary. Use type() to verify. Pass it to dict() to get a real dictionary from it.

How to use executables from a package installed locally in node_modules?

Include coffee-script in package.json with the specific version required in each project, typically like this:

"dependencies":{
  "coffee-script": ">= 1.2.0"

Then run npm install to install dependencies in each project. This will install the specified version of coffee-script which will be accessible locally to each project.

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Do aman 2 sendfile. You only need to open the source file on the client and destination file on the server, then call sendfile and the kernel will chop and move the data.

How to redirect user's browser URL to a different page in Nodejs?

If you are using Express, the cleanest complete answer is this

const express = require('express')
const app     = express()

app.get('*', (req, res) => {
  // REDIRECT goes here
  res.redirect('https://www.YOUR_URL.com/')
})

app.set('port', (process.env.PORT || 3000))
const server = app.listen(app.get('port'), () => {})

Is it possible to use if...else... statement in React render function?

I used ternary operator and it's working fine for me.

> {item.lotNum == null ? ('PDF'):(item.lotNum)}

Proper way to initialize C++ structs

Since it's a POD struct, you could always memset it to 0 - this might be the easiest way to get the fields initialized (assuming that is appropriate).

Rename multiple files by replacing a particular pattern in the filenames using a shell script

You can try this:

for file in *.jpg;
do
  mv $file $somestring_${file:((-7))}
done

You can see "parameter expansion" in man bash to understand the above better.

Where can I download Eclipse Android bundle?

Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

Error: java.lang.NoSuchMethodError: javax.persistence.JoinTable.indexes()[Ljavax/persistence/Index;

The only thing that solved my problem was removing the following dependency in pom.xml: <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency>

And replace it for:

<dependency>
  <groupId>javax.persistence</groupId>
  <artifactId>persistence-api</artifactId>
  <version>1.0.2</version>
</dependency>

Hope it helps someone.

How to find the type of an object in Go?

I would stay away from the reflect. package. Instead use %T

package main

import (
    "fmt"
)

func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}

    fmt.Printf("%T\n", b)
    fmt.Printf("%T\n", s)
    fmt.Printf("%T\n", n)
    fmt.Printf("%T\n", f)
    fmt.Printf("%T\n", a)
 }

Truststore and Keystore Definitions

A keystore contains private keys, and the certificates with their corresponding public keys.

A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.

Rolling or sliding window iterator?

def rolling_window(list, degree):
    for i in range(len(list)-degree+1):
        yield [list[i+o] for o in range(degree)]

Made this for a rolling average function

Why isn't Python very good for functional programming?

Let me demonstrate with a piece of code taken from an answer to a "functional" Python question on SO

Python:

def grandKids(generation, kidsFunc, val):
  layer = [val]
  for i in xrange(generation):
    layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer))
  return layer

Haskell:

grandKids generation kidsFunc val =
  iterate (concatMap kidsFunc) [val] !! generation

The main difference here is that Haskell's standard library has useful functions for functional programming: in this case iterate, concat, and (!!)

How to print pthread_t

Just a supplement to the first post: use a user defined union type to store the pthread_t:

union tid {
    pthread_t pthread_id;
    unsigned long converted_id;
};

Whenever you want to print pthread_t, create a tid and assign tid.pthread_id = ..., then print tid.converted_id.

How to use icons and symbols from "Font Awesome" on Native Android Application

Maybe too late but I had the same need so I've published this https://github.com/liltof/font-awsome-for-android It's an android ready xml version of font awesome usable just like Keith Corwin said

Hope it will help others.

Adding an HTTP Header to the request in a servlet filter

You'll have to use an HttpServletRequestWrapper:

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
        @Override
        public String getHeader(String name) {
            final String value = request.getParameter(name);
            if (value != null) {
                return value;
            }
            return super.getHeader(name);
        }
    };
    chain.doFilter(wrapper, response);
}

Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

move this line: ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Before this line: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

Original post: KB4344167 security update breaks TLS Code

Reading value from console, interactively

I had to write a "tic-tac-toe" game in Node that took input from the command line, and wrote this basic async/await block of code that did the trick.

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

async function getAnswer (prompt) {
  const answer = await new Promise((resolve, reject) =>{
    rl.question(`${prompt}\n`, (answer) => {
      resolve(answer)
    });
  })
  return answer
}

let done = false
const playGame = async () => {
  let i = 1
  let prompt = `Question #${i}, enter "q" to quit`
  while (!done) {
    i += 1
    const answer = await getAnswer(prompt)
    console.log(`${answer}`)
    prompt = processAnswer(answer, i)
  }
  rl.close()
}

const processAnswer = (answer, i) => {
  // this will be set depending on the answer
  let prompt = `Question #${i}, enter "q" to quit`
  // if answer === 'q', then quit
  if (answer === 'q') {
    console.log('User entered q to quit')
    done = true
    return
  }
  // parse answer

  // if answer is invalid, return new prompt to reenter

  // if answer is valid, process next move

  // create next prompt
  return prompt
}

playGame()

How do I free my port 80 on localhost Windows?

That agony has been solved for me. I found out that what was taking over port 80 is http api service. I wrote in cmd:

net stop http

Asked me "The following services will be stopped, do you want to continue?" Pressed y

It stopped a number of services actually.

Then wrote localhost and wallah, Apache is up and running on port 80.
Hope this helps

Important: Skype uses port 80 by default, you can change this in skype options > advanced > connection - and uncheck "use port 80"

Access host database from a docker container

From the 18.03 docs:

I want to connect from a container to a service on the host

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

The gateway is also reachable as gateway.docker.internal.

EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:

mysql://host.docker.internal:3306/my_awesome_database

Laravel 5: Display HTML with Blade

I have been there and it was my fault. And very stupid one.

if you forget .blade extension in the file name, that file doesn't understand blade but runs php code. You should use

/resources/views/filename.blade.php

instead of

/resources/views/filename.php

hope this helps some one

sqlite database default time value 'now'

according to dr. hipp in a recent list post:

CREATE TABLE whatever(
     ....
     timestamp DATE DEFAULT (datetime('now','localtime')),
     ...
);

How do I find my host and username on mysql?

You should be able to access the local database by using the name localhost. There is also a way to determine the hostname of the computer you're running on, but it doesn't sound like you need that. As for the username, you can either (1) give permissions to the account that PHP runs under to access the database without a password, or (2) store the username and password that you need to connect with (hard-coded or stored in a config file), and pass those as arguments to mysql_connect. See http://php.net/manual/en/function.mysql-connect.php.

How do I write a "tab" in Python?

This is the code:

f = open(filename, 'w')
f.write("hello\talex")

The \t inside the string is the escape sequence for the horizontal tabulation.

Opening a new tab to read a PDF file

Try this, it worked for me.

<td><a href="Docs/Chapter 1_ORG.pdf" target="pdf-frame">Chapter-1 Organizational</a></td>

This app won't run unless you update Google Play Services (via Bazaar)

This app won't run unless you update Google Play Services. I have tried it for such a long much time, but still I didn't get the map... Only a blank screen is appearing, even if I modified my Google Play Service given by the below comment..


Check your play services manifest file and check the version code for the APK file com.google.android.gms. In the below, it is "3136110". Download these APK files and install from a DOS prompt, but before installation run your target emulator.

package="com.google.android.gms"
android:versionCode="3136110"
android:versionName="3.1.36 (673201-10)

I got these APK files from this link.

How do I filter ForeignKey choices in a Django ModelForm?

A more public way is by calling get_form in Admin classes. It also works for non-database fields too. For example here i have a field called '_terminal_list' on the form that can be used in special cases for choosing several terminal items from get_list(request), then filtering based on request.user:

class ChangeKeyValueForm(forms.ModelForm):  
    _terminal_list = forms.ModelMultipleChoiceField( 
queryset=Terminal.objects.all() )

    class Meta:
        model = ChangeKeyValue
        fields = ['_terminal_list', 'param_path', 'param_value', 'scheduled_time',  ] 

class ChangeKeyValueAdmin(admin.ModelAdmin):
    form = ChangeKeyValueForm
    list_display = ('terminal','task_list', 'plugin','last_update_time')
    list_per_page =16

    def get_form(self, request, obj = None, **kwargs):
        form = super(ChangeKeyValueAdmin, self).get_form(request, **kwargs)
        qs, filterargs = Terminal.get_list(request)
        form.base_fields['_terminal_list'].queryset = qs
        return form

Eclipse C++: Symbol 'std' could not be resolved

Try out this step: https://www.eclipse.org/forums/index.php/t/636348/

Go to

Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros, etc. -> Providers

  • Activate CDT GCC Built-in Compiler Settings
  • Deactivate Use global provider shared between projects
  • Add the command line argument -std=c++11.

example

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

Simple Pivot Table to Count Unique Values

You can make an additional column to store the uniqueness, then sum that up in your pivot table.

What I mean is, cell C1 should always be 1. Cell C2 should contain the formula =IF(COUNTIF($A$1:$A1,$A2)*COUNTIF($B$1:$B1,$B2)>0,0,1). Copy this formula down so cell C3 would contain =IF(COUNTIF($A$1:$A2,$A3)*COUNTIF($B$1:$B2,$B3)>0,0,1) and so on.

If you have a header cell, you'll want to move these all down a row and your C3 formula should be =IF(COUNTIF($A$2:$A2,$A3)*COUNTIF($B$2:$B2,$B3)>0,0,1).

UPDATE multiple tables in MySQL using LEFT JOIN

The same can be applied to a scenario where the data has been normalized, but now you want a table to have values found in a third table. The following will allow you to update a table with information from a third table that is liked by a second table.

UPDATE t1
LEFT JOIN
 t2
ON 
 t2.some_id = t1.some_id
LEFT JOIN
 t3 
ON
 t2.t3_id = t3.id
SET 
 t1.new_column = t3.column;

This would be useful in a case where you had users and groups, and you wanted a user to be able to add their own variation of the group name, so originally you would want to import the existing group names into the field where the user is going to be able to modify it.

How to run specific test cases in GoogleTest

You could use advanced options to run Google tests.

To run only some unit tests you could use --gtest_filter=Test_Cases1* command line option with value that accepts the * and ? wildcards for matching with multiple tests. I think it will solve your problem.

UPD:

Well, the question was how to run specific test cases. Integration of gtest with your GUI is another thing, which I can't really comment, because you didn't provide details of your approach. However I believe the following approach might be a good start:

  1. Get all testcases by running tests with --gtest_list_tests
  2. Parse this data into your GUI
  3. Select test cases you want ro run
  4. Run test executable with option --gtest_filter

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

If you have not ejected from CRA yet, you can't easily modify your webpack config. The config file is hidden in node_modules/react_scripts/config/webpackDevServer.config.js. You are discouraged to change that config.

Instead, you can just set the environment variable DANGEROUSLY_DISABLE_HOST_CHECK to true to disable the host check:

DANGEROUSLY_DISABLE_HOST_CHECK=true yarn start  
# or the equivalent npm command

How to use cURL to get jSON data and decode the data?

You can Use this for Curl:

function fakeip()  
{  
    return long2ip( mt_rand(0, 65537) * mt_rand(0, 65535) );   
}  

function getdata($url,$args=false) 
{ 
    global $session; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".fakeip(),"X-Client-IP: ".fakeip(),"Client-IP: ".fakeip(),"HTTP_X_FORWARDED_FOR: ".fakeip(),"X-Forwarded-For: ".fakeip())); 
    if($args) 
    { 
        curl_setopt($ch, CURLOPT_POST, 1); 
        curl_setopt($ch, CURLOPT_POSTFIELDS,$args); 
    } 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888"); 
    $result = curl_exec ($ch); 
    curl_close ($ch); 
    return $result; 
} 

Then To Read Json:

$result=getdata("https://example.com");

Then :

///Deocde Json
$data = json_decode($result,true);
///Count
             $total=count($data);
             $Str='<h1>Total : '.$total.'';
             echo $Str;
//You Can Also Make In Table:
             foreach ($data as $key => $value)
              {
          echo '  <td><font  face="calibri"color="red">'.$value[type].'   </font></td><td><font  face="calibri"color="blue">'.$value[category].'   </font></td><td><font  face="calibri"color="green">'.$value[amount].'   </font></tr><tr>';

           }
           echo "</tr></table>";
           }

You Can Also Use This:

echo '<p>Name : '.$data['result']['name'].'</p>
      <img src="'.$data['result']['pic'].'"><br>';

Hope this helped.

What is the difference between .text, .value, and .value2?

Regarding conventions in C#. Let's say you're reading a cell that contains a date, e.g. 2014-10-22.

When using:

.Text, you'll get the formatted representation of the date, as seen in the workbook on-screen:
2014-10-22. This property's type is always string but may not always return a satisfactory result.

.Value, the compiler attempts to convert the date into a DateTime object: {2014-10-22 00:00:00} Most probably only useful when reading dates.

.Value2, gives you the real, underlying value of the cell. In the case for dates, it's a date serial: 41934. This property can have a different type depending on the contents of the cell. For date serials though, the type is double.

So you can retrieve and store the value of a cell in either dynamic, var or object but note that the value will always have some sort of innate type that you will have to act upon.

dynamic x = ws.get_Range("A1").Value2;
object  y = ws.get_Range("A1").Value2;
var     z = ws.get_Range("A1").Value2;
double  d = ws.get_Range("A1").Value2;      // Value of a serial is always a double

How do I add 1 day to an NSDate?

iOS 8+, OSX 10.9+, Objective-C

NSCalendar *cal = [NSCalendar currentCalendar];    
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay 
                                   value:1 
                                  toDate:[NSDate date] 
                                 options:0];

How do I autoindent in Netbeans?

for Java NetBeans 7.1 and later, even in NetBeans 8.0 (That i´m currently using) and later, the shortcut is:

Alt+Shift+F

if you look into the KeyMap accessing from the menu: Tools -> Options -> Keymap, the "action" is Format defined with the Shortcut : Alt+Shift+F

How to give a Blob uploaded as FormData a file name?

That name looks derived from an object URL GUID. Do the following to get the object URL that the name was derived from.

var URL = self.URL || self.webkitURL || self;
var object_url = URL.createObjectURL(blob);
URL.revokeObjectURL(object_url);

object_url will be formatted as blob:{origin}{GUID} in Google Chrome and moz-filedata:{GUID} in Firefox. An origin is the protocol+host+non-standard port for the protocol. For example, blob:http://stackoverflow.com/e7bc644d-d174-4d5e-b85d-beeb89c17743 or blob:http://[::1]:123/15111656-e46c-411d-a697-a09d23ec9a99. You probably want to extract the GUID and strip any dashes.

Difference between java.lang.RuntimeException and java.lang.Exception

In Java, there are two types of exceptions: checked exceptions and un-checked exceptions. A checked exception must be handled explicitly by the code, whereas, an un-checked exception does not need to be explicitly handled.

For checked exceptions, you either have to put a try/catch block around the code that could potentially throw the exception, or add a "throws" clause to the method, to indicate that the method might throw this type of exception (which must be handled in the calling class or above).

Any exception that derives from "Exception" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.

Replace all non-alphanumeric characters in a string

Use \W which is equivalent to [^a-zA-Z0-9_]. Check the documentation, https://docs.python.org/2/library/re.html

Import re
s =  'h^&ell`.,|o w]{+orld'
replaced_string = re.sub(r'\W+', '*', s)
output: 'h*ell*o*w*orld'

update: This solution will exclude underscore as well. If you want only alphabets and numbers to be excluded, then solution by nneonneo is more appropriate.

IndentationError: unindent does not match any outer indentation level

For example:

1. def convert_distance(miles):
2.   km = miles * 1.6
3.   return km

In this code same situation occurred for me. Just delete the previous indent spaces of line 2 and 3, and then either use tab or space. Never use both. Give proper indentation while writing code in python. For Spyder goto Source > Fix Indentation. Same goes to VC Code and sublime text or any other editor. Fix the indentation.

How do you get a directory listing in C?

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

https://github.com/cxong/tinydir

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

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

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

    tinydir_next(&dir);
}

tinydir_close(&dir);

How to parse string into date?

CONVERT(datetime, '24.04.2012', 104)

Should do the trick. See here for more info: CAST and CONVERT (Transact-SQL)

Waiting for Target Device to Come Online

Did not read all the answers. Anyway Accepted one didn't work for me. What did was upgrading the android studio to last stable version and then created a new virtual device. I guess my nexus 5p virtual device got out of sync with the android studio environment.

PHP multiline string with PHP

The internal set of single quotes in your code is killing the string. Whenever you hit a single quote it ends the string and continues processing. You'll want something like:

$thisstring = 'this string is long \' in needs escaped single quotes or nothing will run';

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

We also encountered similar problems. However, setting the charset as noted in the previous comment did not help. Our application was making an AJAX request every 60 seconds and our webserver, nginx, was sending Keep-Alive timeout at 60 seconds.

We fixed the problem by setting the keep-alive timeout value to 75 seconds.

This is what we believe was happening:

  1. IE makes an AJAX request every 60 seconds, setting Keep-Alive in the request.
  2. At the same time, nginx knows that the Keep-Alive timeout value is ignored by IE, so it starts the TCP connection close process (in the case of FF/Chrome this is started by the client)
  3. IE receives the close connection request for the previously sent request. Since this is not expected by IE, it throws an error and aborts.
  4. nginx still seems to be responding to the request even though the connection is closed.

A Wireshark TCP dump would provide more clarity, our problem is fixed and we do not wish to spend more time on it.

How can I wait for a thread to finish with .NET?

Here's a simple example that waits for a tread to finish, within the same class. It also makes a call to another class in the same namespace. I included the "using" statements so it can execute as a Windows Forms form as long as you create button1.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace ClassCrossCall
{

    public partial class Form1 : Form
    {
        int number = 0; // This is an intentional problem, included
                        // for demonstration purposes
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1.Text = "Initialized";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = "Clicked";
            button1.Refresh();
            Thread.Sleep(400);
            List<Task> taskList = new List<Task>();
            taskList.Add(Task.Factory.StartNew(() => update_thread(2000)));
            taskList.Add(Task.Factory.StartNew(() => update_thread(4000)));
            Task.WaitAll(taskList.ToArray());
            worker.update_button(this, number);
        }

        public void update_thread(int ms)
        {
            // It's important to check the scope of all variables
            number = ms; // This could be either 2000 or 4000. Race condition.
            Thread.Sleep(ms);
        }
    }

    class worker
    {
        public static void update_button(Form1 form, int number)
        {
            form.button1.Text = $"{number}";
        }
    }
}

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

IIS was the main offender for me. My IIS was running and it restrains any new socket connections from opening. The problem resolved for me by stopping IIS by running the command "iisreset -stop"

Remove x-axis label/text in chart.js

Inspired by christutty's answer, here is a solution that modifies the source but has not been tested thoroughly. I haven't had any issues yet though.

In the defaults section, add this line around line 71:

// Boolean - Omit x-axis labels
omitXLabels: true,

Then around line 2215, add this in the buildScale method:

//if omitting x labels, replace labels with empty strings           
if(Chart.defaults.global.omitXLabels){
    var newLabels=[];
    for(var i=0;i<labels.length;i++){
        newLabels.push('');
    }
    labels=newLabels;
}

This preserves the tool tips also.

LIKE operator in LINQ

Well... sometimes it may be uncomfortable to use Contains, StartsWith or EndsWith especially when searching value determine LIKE statment e.g. passed 'value%' require from developer to use StartsWith function in expression. So I decided to write extension for IQueryable objects.

Usage

// numbers: 11-000-00, 00-111-00, 00-000-11

var data1 = parts.Like(p => p.Number, "%11%");
// result: 11-000-00, 00-111-00, 00-000-11

var data2 = parts.Like(p => p.Number, "11%");
// result: 11-000-00

var data3 = parts.Like(p => p.Number, "%11");
// result: 00-000-11

Code

public static class LinqEx
{
    private static readonly MethodInfo ContainsMethod = typeof(string).GetMethod("Contains");
    private static readonly MethodInfo StartsWithMethod = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
    private static readonly MethodInfo EndsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });

    public static Expression<Func<TSource, bool>> LikeExpression<TSource, TMember>(Expression<Func<TSource, TMember>> property, string value)
    {
        var param = Expression.Parameter(typeof(TSource), "t");
        var propertyInfo = GetPropertyInfo(property);
        var member = Expression.Property(param, propertyInfo.Name);

        var startWith = value.StartsWith("%");
        var endsWith = value.EndsWith("%");

        if (startWith)
            value = value.Remove(0, 1);

        if (endsWith)
            value = value.Remove(value.Length - 1, 1);

        var constant = Expression.Constant(value);
        Expression exp;

        if (endsWith && startWith)
        {
            exp = Expression.Call(member, ContainsMethod, constant);
        }
        else if (startWith) 
        {
            exp = Expression.Call(member, EndsWithMethod, constant);
        }
        else if (endsWith)
        {
            exp = Expression.Call(member, StartsWithMethod, constant);
        }
        else
        {
            exp = Expression.Equal(member, constant);
        }

        return Expression.Lambda<Func<TSource, bool>>(exp, param);
    }

    public static IQueryable<TSource> Like<TSource, TMember>(this IQueryable<TSource> source, Expression<Func<TSource, TMember>> parameter, string value)
    {
        return source.Where(LikeExpression(parameter, value));
    }

    private static PropertyInfo GetPropertyInfo(Expression expression)
    {
        var lambda = expression as LambdaExpression;
        if (lambda == null)
            throw new ArgumentNullException("expression");

        MemberExpression memberExpr = null;

        switch (lambda.Body.NodeType)
        {
            case ExpressionType.Convert:
                memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
                break;
            case ExpressionType.MemberAccess:
                memberExpr = lambda.Body as MemberExpression;
                break;
        }

        if (memberExpr == null)
            throw new InvalidOperationException("Specified expression is invalid. Unable to determine property info from expression.");


        var output = memberExpr.Member as PropertyInfo;

        if (output == null)
            throw new InvalidOperationException("Specified expression is invalid. Unable to determine property info from expression.");

        return output;
    }
}

Getting an attribute value in xml element

Below is the code to do it in vtd-xml. It basically queries the XML with the XPath of "/xml/item/@name."

import com.ximpleware.*;

public class getAttrs{

   public static void main(String[] s) throws VTDException{
         VTDGen vg = new VTDGen();
         if (!vg.parseFile("input.xml",false)) // turn off namespace
              return;
         VTDNav vn = vg.getNav();
         AutoPilot ap =  new AutoPilot(vn);
         ap.selectXPath("/xml/item/@name");
         int i=0;
         while( (i=ap.evalXPath())!=-1){
              System.out.println(" item name is ===>"+vn.toString(i+1)); 
         }
   }
}

Simple linked list in C++

This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.

#include <iostream>
using namespace std;

class LinkedList{
    // Struct inside the class LinkedList
    // This is one node which is not needed by the caller. It is just
    // for internal work.
    struct Node {
        int x;
        Node *next;
    };

// public member
public:
    // constructor
    LinkedList(){
        head = NULL; // set head to NULL
    }

    // destructor
    ~LinkedList(){
        Node *next = head;
        
        while(next) {              // iterate over all elements
            Node *deleteMe = next;
            next = next->next;     // save pointer to the next element
            delete deleteMe;       // delete the current entry
        }
    }
    
    // This prepends a new value at the beginning of the list
    void addValue(int val){
        Node *n = new Node();   // create new Node
        n->x = val;             // set value
        n->next = head;         // make the node point to the next node.
                                //  If the list is empty, this is NULL, so the end of the list --> OK
        head = n;               // last but not least, make the head point at the new node.
    }

    // returns the first element in the list and deletes the Node.
    // caution, no error-checking here!
    int popValue(){
        Node *n = head;
        int ret = n->x;

        head = head->next;
        delete n;
        return ret;
    }

// private member
private:
    Node *head; // this is the private member variable. It is just a pointer to the first Node
};

int main() {
    LinkedList list;

    list.addValue(5);
    list.addValue(10);
    list.addValue(20);

    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    // because there is no error checking in popValue(), the following
    // is undefined behavior. Probably the program will crash, because
    // there are no more values in the list.
    // cout << list.popValue() << endl;
    return 0;
}

I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this: http://www.galileocomputing.de/1278?GPP=opoo

EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)

python: how to get information about a function?

Try

help(my_list)

to get built-in help messages.

How to get all keys with their values in redis

I have written a small code for this particular requirement using hiredis , please find the code with a working example at http://rachitjain1.blogspot.in/2013/10/how-to-get-all-keyvalue-in-redis-db.html

Here is the code that I have written,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hiredis.h"

int main(void)
{
        unsigned int i,j=0;char **str1;
        redisContext *c; char *t;
        redisReply *reply, *rep;

        struct timeval timeout = { 1, 500000 }; // 1.5 seconds
        c = redisConnectWithTimeout((char*)"127.0.0.2", 6903, timeout);
        if (c->err) {
                printf("Connection error: %s\n", c->errstr);
                exit(1);
        }

        reply = redisCommand(c,"keys *");
        printf("KEY\t\tVALUE\n");
        printf("------------------------\n");
        while ( reply->element[j]->str != NULL)
        {
                rep = redisCommand(c,"GET  %s", reply->element[j]->str);
                if (strstr(rep->str,"ERR Operation against a key holding"))
                {
                        printf("%s\t\t%s\n",  reply->element[j]->str,rep->str);
                        break;
                }
                printf("%s\t\t%s\n",  reply->element[j]->str,rep->str);
                j++;
                freeReplyObject(rep);
        }
}

How can I get a JavaScript stack trace when I throw an exception?

function:

function print_call_stack(err) {
    var stack = err.stack;
    console.error(stack);
}

use case:

     try{
         aaa.bbb;//error throw here
     }
     catch (err){
         print_call_stack(err); 
     }

What is the difference between require_relative and require in Ruby?

require_relative is a convenient subset of require

require_relative('path')

equals:

require(File.expand_path('path', File.dirname(__FILE__)))

if __FILE__ is defined, or it raises LoadError otherwise.

This implies that:

  • require_relative 'a' and require_relative './a' require relative to the current file (__FILE__).

    This is what you want to use when requiring inside your library, since you don't want the result to depend on the current directory of the caller.

  • eval('require_relative("a.rb")') raises LoadError because __FILE__ is not defined inside eval.

    This is why you can't use require_relative in RSpec tests, which get evaled.

The following operations are only possible with require:

  • require './a.rb' requires relative to the current directory

  • require 'a.rb' uses the search path ($LOAD_PATH) to require. It does not find files relative to current directory or path.

    This is not possible with require_relative because the docs say that path search only happens when "the filename does not resolve to an absolute path" (i.e. starts with / or ./ or ../), which is always the case for File.expand_path.

The following operation is possible with both, but you will want to use require as it is shorter and more efficient:

  • require '/a.rb' and require_relative '/a.rb' both require the absolute path.

Reading the source

When the docs are not clear, I recommend that you take a look at the sources (toggle source in the docs). In some cases, it helps to understand what is going on.

require:

VALUE rb_f_require(VALUE obj, VALUE fname) {
  return rb_require_safe(fname, rb_safe_level());
}

require_relative:

VALUE rb_f_require_relative(VALUE obj, VALUE fname) {
    VALUE base = rb_current_realfilepath();
    if (NIL_P(base)) {
        rb_loaderror("cannot infer basepath");
    }
    base = rb_file_dirname(base);
    return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
}

This allows us to conclude that

require_relative('path')

is the same as:

require(File.expand_path('path', File.dirname(__FILE__)))

because:

rb_file_absolute_path   =~ File.expand_path
rb_file_dirname1        =~ File.dirname
rb_current_realfilepath =~ __FILE__

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

Python send POST with header

To make POST request instead of GET request using urllib2, you need to specify empty data, for example:

import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)

SQLite UPSERT / UPDATE OR INSERT

Here's an approach that doesn't require the brute-force 'ignore' which would only work if there was a key violation. This way works based on any conditions you specify in the update.

Try this...

-- Try to update any existing row
UPDATE players
SET age=32
WHERE user_name='steven';

-- If no update happened (i.e. the row didn't exist) then insert one
INSERT INTO players (user_name, age)
SELECT 'steven', 32
WHERE (Select Changes() = 0);

How It Works

The 'magic sauce' here is using Changes() in the Where clause. Changes() represents the number of rows affected by the last operation, which in this case is the update.

In the above example, if there are no changes from the update (i.e. the record doesn't exist) then Changes() = 0 so the Where clause in the Insert statement evaluates to true and a new row is inserted with the specified data.

If the Update did update an existing row, then Changes() = 1 (or more accurately, not zero if more than one row was updated), so the 'Where' clause in the Insert now evaluates to false and thus no insert will take place.

The beauty of this is there's no brute-force needed, nor unnecessarily deleting, then re-inserting data which may result in messing up downstream keys in foreign-key relationships.

Additionally, since it's just a standard Where clause, it can be based on anything you define, not just key violations. Likewise, you can use Changes() in combination with anything else you want/need anywhere expressions are allowed.

Getting request payload from POST request in Java servlet

Using Java 8 try with resources:

    StringBuilder stringBuilder = new StringBuilder();
    try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
        char[] charBuffer = new char[1024];
        int bytesRead;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
            stringBuilder.append(charBuffer, 0, bytesRead);
        }
    }

Are arrays passed by value or passed by reference in Java?

Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:

// assuming you allocated the list
public void addItem(Integer[] list, int item) {
    list[1] = item;
}

You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:

// assuming you allocated the list
public void changeArray(Integer[] list) {
    list = null;
}

If you pass a non-null list, it won't be null by the time the method returns.

Safe navigation operator (?.) or (!.) and null property paths

Update:

Planned in the scope of 3.7 release
https://github.com/microsoft/TypeScript/issues/33352


You can try to write a custom function like that.

The main advantage of the approach is a type-checking and partial intellisense.

export function nullSafe<T, 
    K0 extends keyof T, 
    K1 extends keyof T[K0],
    K2 extends keyof T[K0][K1],
    K3 extends keyof T[K0][K1][K2],
    K4 extends keyof T[K0][K1][K2][K3],
    K5 extends keyof T[K0][K1][K2][K3][K4]>
    (obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
    let result: any = obj;

    const keysCount = arguments.length - 1;
    for (var i = 1; i <= keysCount; i++) {
        if (result === null || result === undefined) return result;
        result = result[arguments[i]];
    }

    return result;
}

And usage (supports up to 5 parameters and can be extended):

nullSafe(a, 'b', 'c');

Example on playground.

UTL_FILE.FOPEN() procedure not accepting path for directory?

Since Oracle 9i there are two ways or declaring a directory for use with UTL_FILE.

The older way is to set the INIT.ORA parameter UTL_FILE_DIR. We have to restart the database for a change to take affect. The value can like any other PATH variable; it accepts wildcards. Using this approach means passing the directory path...

UTL_FILE.FOPEN('c:\temp', 'vineet.txt', 'W');

The alternative approach is to declare a directory object.

create or replace directory temp_dir as 'C:\temp'
/

grant read, write on directory temp_dir to vineet
/

Directory objects require the exact file path, and don't accept wildcards. In this approach we pass the directory object name...

UTL_FILE.FOPEN('TEMP_DIR', 'vineet.txt', 'W');

The UTL_FILE_DIR is deprecated because it is inherently insecure - all users have access to all the OS directories specified in the path, whereas read and write privileges can de granted discretely to individual users. Also, with Directory objects we can be add, remove or change directories without bouncing the database.

In either case, the oracle OS user must have read and/or write privileges on the OS directory. In case it isn't obvious, this means the directory must be visible from the database server. So we cannot use either approach to expose a directory on our local PC to a process running on a remote database server. Files must be uploaded to the database server, or a shared network drive.


If the oracle OS user does not have the appropriate privileges on the OS directory, or if the path specified in the database does not match to an actual path, the program will hurl this exception:

ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 7

The OERR text for this error is pretty clear:

29283 -  "invalid file operation"
*Cause:    An attempt was made to read from a file or directory that does
           not exist, or file or directory access was denied by the
           operating system.
*Action:   Verify file and directory access privileges on the file system,
           and if reading, verify that the file exists.

Check if number is decimal

I was passed a string, and wanted to know if it was a decimal or not. I ended up with this:

function isDecimal($value) 
{
     return ((float) $value !== floor($value));
}

I ran a bunch of test including decimals and non-decimals on both sides of zero, and it seemed to work.

How to get request URI without context path?

May be you can just use the split method to eliminate the '/myapp' for example:

string[] uris=request.getRequestURI().split("/");
string uri="/"+uri[1]+"/"+uris[2];

Laravel 5 call a model function in a blade view

Related to the question in your answer:

You have multiple options to achieve this that are way better:

Let's assume you have a model which you pass to the view:

$model = Model::find(1);
View::make('view')->withModel($model);

Now in your Model you could have a function:

public function someFunction() {
    // do something
}

In your view you could call that function directly:

{{$model->someFunction()}}

This is nice if you want to do something with the model (the dataset).

If not you can still make a static function in the model:

public static function someStaticFunction($var1, $var2) {
    // do something
}

And then:

{{App\Model::someStaticFunction($yourVar1,$yourVar2)}}

Hope it helps.

New to unit testing, how to write great tests?

It's worth noting that retro-fitting unit tests into existing code is far more difficult than driving the creation of that code with tests in the first place. That's one of the big questions in dealing with legacy applications... how to unit test? This has been asked many times before (so you may be closed as a dupe question), and people usually end up here:

Moving existing code to Test Driven Development

I second the accepted answer's book recommendation, but beyond that there's more information linked in the answers there.

SQL Server Installation - What is the Installation Media Folder?

For me the Issue was I didn't run the setup as Administrator, after running the setup as administrator the message go away and I was prompted to install and continue process.

Delete multiple rows by selecting checkboxes using PHP

Something that sometimes crops up you may/maynot be aware of

Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE

As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?

If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?

Measuring code execution time

Stopwatch measures time elapsed.

// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing
stopwatch.Start();

Threading.Thread.Sleep(500)

// Stop timing
stopwatch.Stop();

Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

Here is a DEMO.

Android Studio doesn't start, fails saying components not installed

One possible solution is to open Android SDK Manager from

C:\Users\%user%\AppData\Local\Android\sdk

Check Android SDK build tool 21.1.1 download and install. Restart Android Studio

Get the current file name in gulp.src()

You can use the gulp-filenames module to get the array of paths. You can even group them by namespaces:

var filenames = require("gulp-filenames");

gulp.src("./src/*.coffee")
    .pipe(filenames("coffeescript"))
    .pipe(gulp.dest("./dist"));

gulp.src("./src/*.js")
  .pipe(filenames("javascript"))
  .pipe(gulp.dest("./dist"));

filenames.get("coffeescript") // ["a.coffee","b.coffee"]  
                              // Do Something With it 

How do I simulate a hover with a touch in touch enabled browsers?

The mouse hover effect cannot be implemented in touch device . When I'm appeared with same situation in safari ios I used :active in css to make effect.

ie.

p:active {
  color:red;
}

In my case its working .May be this is also the case that can be used with out using javascript. Just give a try.

How to increase time in web.config for executing sql query

I think you can't increase the time for query execution, but you need to increase the timeout for the request.

Execution Timeout Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. (Default time is 110 seconds.)

For Details, please have a look at https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.100%29.aspx

You can do in the web.config. e.g

<httpRuntime maxRequestLength="2097152" executionTimeout="600" />

How to use localization in C#

  • Add a Resource file to your project (you can call it "strings.resx") by doing the following:
    Right-click Properties in the project, select Add -> New Item... in the context menu, then in the list of Visual C# Items pick "Resources file" and name it strings.resx.
  • Add a string resouce in the resx file and give it a good name (example: name it "Hello" with and give it the value "Hello")
  • Save the resource file (note: this will be the default resource file, since it does not have a two-letter language code)
  • Add references to your program: System.Threading and System.Globalization

Run this code:

Console.WriteLine(Properties.strings.Hello);

It should print "Hello".

Now, add a new resource file, named "strings.fr.resx" (note the "fr" part; this one will contain resources in French). Add a string resource with the same name as in strings.resx, but with the value in French (Name="Hello", Value="Salut"). Now, if you run the following code, it should print Salut:

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
Console.WriteLine(Properties.strings.Hello);

What happens is that the system will look for a resource for "fr-FR". It will not find one (since we specified "fr" in your file"). It will then fall back to checking for "fr", which it finds (and uses).

The following code, will print "Hello":

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(Properties.strings.Hello);

That is because it does not find any "en-US" resource, and also no "en" resource, so it will fall back to the default, which is the one that we added from the start.

You can create files with more specific resources if needed (for instance strings.fr-FR.resx and strings.fr-CA.resx for French in France and Canada respectively). In each such file you will need to add the resources for those strings that differ from the resource that it would fall back to. So if a text is the same in France and Canada, you can put it in strings.fr.resx, while strings that are different in Canadian french could go into strings.fr-CA.resx.

Creating .pem file for APNS?

I would suggest a much more simple solution. Just use Certifire.
Certifire is a macOS application that generates Apple Push Notification Certificates with just one click in a couple of seconds.

Here are the steps:
1. Download the app.
2. Log in using your Apple Developer Account credentials.
3. Choose the App-ID
4. Click "Generate" button
5. You're done!

You will get APN certificates in .pem format as well as in .p12 format. Even more, you will get also combined .pem and .p12 too (key+cert)!
Much more, you will get no-passphrase versions of all these certificates also!

enter image description here

enter image description here

CSS background opacity with rgba not working in IE 8

The best solution I found so far is the one proposed by David J Marland in his blog, to support opacity in old browsers (IE 6+):

.alpha30{
    background:rgb(255,0,0); /* Fallback for web browsers that don't support RGBa nor filter */ 
    background: transparent\9; /* backslash 9 hack to prevent IE 8 from falling into the fallback */
    background:rgba(255,0,0,0.3); /* RGBa declaration for browsers that support it */
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4cFF0000,endColorstr=#4cFF0000); /* needed for IE 6-8 */
    zoom: 1; /* needed for IE 6-8 */
}

/* 
 * CSS3 selector (not supported by IE 6 to IE 8),
 * to avoid IE more recent versions to apply opacity twice
 * (once with rgba and once with filter)
 */
.alpha30:nth-child(n) {
    filter: none;
}

Color picker utility (color pipette) in Ubuntu

You can install the package gcolor2 for this:

sudo apt-get install gcolor2

Then:

Applications -> Graphics -> GColor2

Change the Blank Cells to "NA"

As of (dplyr 1.0.0) we can use across()

For all columns:

dat <- dat %>%
   mutate(across(everything(), ~ifelse(.=="", NA, as.character(.))))

For individual columns:

dat <- dat %>%
   mutate(across(c("Age","Gender"), ~ifelse(.=="", NA, as.character(.))))

As of (dplyr 0.8.0 above) the way this should be written has changed. Before it was, funs() in .funs (funs(name = f(.)). Instead of funs, now we use list (list(name = ~f(.)))

Note that there is also a much simpler way to list the column names ! (both the name of the column and column index work)

dat <- dat %>%
mutate_at(.vars = c("Age","Gender"),
    .funs = list(~ifelse(.=="", NA, as.character(.))))

Original Answer:

You can also use mutate_at in dplyr

dat <- dat %>%
mutate_at(vars(colnames(.)),
        .funs = funs(ifelse(.=="", NA, as.character(.))))

Select individual columns to change:

dat <- dat %>%
mutate_at(vars(colnames(.)[names(.) %in% c("Age","Gender")]),
        .funs = funs(ifelse(.=="", NA, as.character(.))))

window.onload vs $(document).ready()

Document.ready (a jQuery event) will fire when all the elements are in place, and they can be referenced in the JavaScript code, but the content is not necessarily loaded. Document.ready executes when the HTML document is loaded.

$(document).ready(function() {

    // Code to be executed
    alert("Document is ready");
});

The window.load however will wait for the page to be fully loaded. This includes inner frames, images, etc.

$(window).load(function() {

    //Fires when the page is loaded completely
    alert("window is loaded");
});

Turn a number into star rating display using jQuery and CSS

Here's a solution for you, using only one very tiny and simple image and one automatically generated span element:

CSS

span.stars, span.stars span {
    display: block;
    background: url(stars.png) 0 -16px repeat-x;
    width: 80px;
    height: 16px;
}

span.stars span {
    background-position: 0 0;
}

Image

alt text
(source: ulmanen.fi)

Note: do NOT hotlink to the above image! Copy the file to your own server and use it from there.

jQuery

$.fn.stars = function() {
    return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range, multiply to get width
        var size = Math.max(0, (Math.min(5, val))) * 16;
        // Create stars holder
        var $span = $('<span />').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}

If you want to restrict the stars to only half or quarter star sizes, add one of these rows before the var size row:

val = Math.round(val * 4) / 4; /* To round to nearest quarter */
val = Math.round(val * 2) / 2; /* To round to nearest half */

HTML

<span class="stars">4.8618164</span>
<span class="stars">2.6545344</span>
<span class="stars">0.5355</span>
<span class="stars">8</span>

Usage

$(function() {
    $('span.stars').stars();
});

Output

Image from fugue icon set (www.pinvoke.com)
(source: ulmanen.fi)

Demo

http://www.ulmanen.fi/stuff/stars.php

This will probably suit your needs. With this method you don't have to calculate any three quarter or whatnot star widths, just give it a float and it'll give you your stars.


A small explanation on how the stars are presented might be in order.

The script creates two block level span elements. Both of the spans initally get a size of 80px * 16px and a background image stars.png. The spans are nested, so that the structure of the spans looks like this:

<span class="stars">
    <span></span>
</span>

The outer span gets a background-position of 0 -16px. That makes the gray stars in the outer span visible. As the outer span has height of 16px and repeat-x, it will only show 5 gray stars.

The inner span on the other hand has a background-position of 0 0 which makes only the yellow stars visible.

This would of course work with two separate imagefiles, star_yellow.png and star_gray.png. But as the stars have a fixed height, we can easily combine them into one image. This utilizes the CSS sprite technique.

Now, as the spans are nested, they are automatically overlayed over each other. In the default case, when the width of both spans is 80px, the yellow stars completely obscure the grey stars.

But when we adjust the width of the inner span, the width of the yellow stars decreases, revealing the gray stars.

Accessibility-wise, it would have been wiser to leave the float number inside the inner span and hide it with text-indent: -9999px, so that people with CSS turned off would at least see the floating point number instead of the stars.

Hopefully that made some sense.


Updated 2010/10/22

Now even more compact and harder to understand! Can also be squeezed down to a one liner:

$.fn.stars = function() {
    return $(this).each(function() {
        $(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
    });
}

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

SQL multiple column ordering

Multiple column ordering depends on both column's corresponding values: Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.

enter image description here

Now I perform Order By in these two columns by executing below command:

enter image description here

Now again I insert new values in these two columns, where Alphabet value in ASC order:

enter image description here

and the columns in Example table look like this. Now again perform the same operation:

enter image description here

You can see the values in the first column are in desc order but second column is not in ASC order.

#ifdef replacement in the Swift language

There is no Swift preprocessor. (For one thing, arbitrary code substitution breaks type- and memory-safety.)

Swift does include build-time configuration options, though, so you can conditionally include code for certain platforms or build styles or in response to flags you define with -D compiler args. Unlike with C, though, a conditionally compiled section of your code must be syntactically complete. There's a section about this in Using Swift With Cocoa and Objective-C.

For example:

#if os(iOS)
    let color = UIColor.redColor()
#else
    let color = NSColor.redColor()
#endif

jquery validate check at least one checkbox

 if ($('input:checkbox').filter(':checked').length < 1){
        alert("Check at least one!");
 return false;
 }

Docker Error bind: address already in use

On my machine a PID was not being shown from this command netstat -tulpn for the in-use port (8080), so i could not kill it, killing the containers and restarting the computer did not work. So service docker restart command restarted docker for me (ubuntu) and the port was no longer in use and i am a happy chap and off to lunch.

How to hide collapsible Bootstrap 4 navbar on click

This code simulates a click on the burguer button to close the navbar by clicking on a link in the menu, keeping the fade out effect. Solution with typescript for angular 7. Avoid routerLink problems.

ToggleNavBar () {
    let element: HTMLElement = document.getElementsByClassName( 'navbar-toggler' )[ 0 ] as HTMLElement;
    if ( element.getAttribute( 'aria-expanded' ) == 'true' ) {
        element.click();
    }
}

<li class="nav-item" [routerLinkActive]="['active']">
    <a class="nav-link" [routerLink]="['link1']" title="link1" (click)="ToggleNavBar()">link1</a>
</li>

Is it possible to use argsort in descending order?

You could create a copy of the array and then multiply each element with -1.
As an effect the before largest elements would become the smallest.
The indeces of the n smallest elements in the copy are the n greatest elements in the original.

How to remove the focus from a TextBox in WinForms?

If all you want is the optical effect that the textbox has no blue selection all over its contents, just select no text:

textBox_Log.SelectionStart = 0;
textBox_Log.SelectionLength = 0;
textBox_Log.Select();

After this, when adding content with .Text += "...", no blue selection will be shown.

How can I refresh or reload the JFrame?

Here's a short code that might help.

    <yourJFrameName> main = new <yourJFrameName>();    

    main.setVisible(true);
    this.dispose();

where...

main.setVisible(true);

will run the JFrame again.

this.dispose();

will terminate the running window.

Convert Numeric value to Varchar

i think it should be

select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212

or

select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212

How do you replace all the occurrences of a certain character in a string?

I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.

def remove_chars(line):
    line7=line[7].translate(None,'abcd')
    return line[:7]+[line7]+line[8:]

line= ['ad','da','sdf','asd',
        '3424','342sfas','asdfaf','sdfa',
        'afase']
print line[7]
line = remove_chars(line)
print line[7]

Creating a list of pairs in java

Similar to what Mark E has proposed, but no need to recreate the wheel, if you don't mind relying on 3rd party libs.

Apache Commons has tuples already defined:

org.apache.commons.lang3.tuple.Pair<L,R>

Apache Commons is so pervasive, I typically already have it in my projects, anyway. https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

How to put text in the upper right, or lower right corner of a "box" using css

You need to put "here" into a <div> or <span> with style="float: right".

Refresh an asp.net page on button click

  • Create a class for maintain hit counters

    public static class Counter
    {
           private static long hit;
    
           public static void HitCounter()
           {
              hit++;
           }
    
           public static long GetCounter()
           {
              return hit;
           }
    }
    
  • Increment the value of counter at page load event

    protected void Page_Load(object sender, EventArgs e)
    {
        Counter.HitCounter(); // call static function of static class Counter to increment the counter value
    }
    
  • Redirect the page on itself and display the counter value on button click

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(Request.RawUrl.ToString()); // redirect on itself
        Response.Write("<br /> Counter =" + Counter.GetCounter() ); // display counter value
    }
    

Bash Templating: How to build configuration files from templates with Bash?

Instead of reinventing the wheel go with envsubst Can be used in almost any scenario, for instance building configuration files from environment variables in docker containers.

If on mac make sure you have homebrew then link it from gettext:

brew install gettext
brew link --force gettext

./template.cfg

# We put env variables into placeholders here
this_variable_1 = ${SOME_VARIABLE_1}
this_variable_2 = ${SOME_VARIABLE_2}

./.env:

SOME_VARIABLE_1=value_1
SOME_VARIABLE_2=value_2

./configure.sh

#!/bin/bash
cat template.cfg | envsubst > whatever.cfg

Now just use it:

# make script executable
chmod +x ./configure.sh
# source your variables
. .env
# export your variables
# In practice you may not have to manually export variables 
# if your solution depends on tools that utilise .env file 
# automatically like pipenv etc. 
export SOME_VARIABLE_1 SOME_VARIABLE_2
# Create your config file
./configure.sh

Round number to nearest integer

Your solution is calling round without specifying the second argument (number of decimal places)

>>> round(0.44)
0
>>> round(0.64)
1

which is a much better result than

>>> int(round(0.44, 2))
0
>>> int(round(0.64, 2))
0

From the Python documentation at https://docs.python.org/3/library/functions.html#round

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

SQL/mysql - Select distinct/UNIQUE but return all columns?

select min(table.id), table.column1
from table 
group by table.column1

How to skip the first n rows in sql query

This works with all DBRM/SQL, it is standard ANSI:

SELECT *
  FROM owner.tablename A
 WHERE condition
  AND  n+1 <= (
         SELECT COUNT(DISTINCT b.column_order)
           FROM owner.tablename B
          WHERE condition
            AND b.column_order>a.column_order
          )
ORDER BY a.column_order DESC

How do I install Python libraries in wheel format?

i have write the answer here How to add/use libraries in Python (3.5.1) but no problem will rewrite it again

if u have or you can create a file requirements.txt which contains the libraries that you want to install for ex:

numpy==1.14.2
Pillow==5.1.0

You gonna situate in your folder which contains that requirements.txt in my case the path to my project is

C:\Users\LE\Desktop\Projet2_Sig_Exo3\exo 3\k-means

now just type

python -m pip install -r ./requirements.txt

and all the libararies that you want gonna install

C:\Users\LE\Desktop\Projet2_Sig_Exo3\exo 3\k-means>python -m pip install -r ./requirements.txt

How to implement LIMIT with SQL Server?

This is almost a duplicate of a question I asked in October: Emulate MySQL LIMIT clause in Microsoft SQL Server 2000

If you're using Microsoft SQL Server 2000, there is no good solution. Most people have to resort to capturing the result of the query in a temporary table with a IDENTITY primary key. Then query against the primary key column using a BETWEEN condition.

If you're using Microsoft SQL Server 2005 or later, you have a ROW_NUMBER() function, so you can get the same result but avoid the temporary table.

SELECT t1.*
FROM (
    SELECT ROW_NUMBER OVER(ORDER BY id) AS row, t1.*
    FROM ( ...original SQL query... ) t1
) t2
WHERE t2.row BETWEEN @offset+1 AND @offset+@count;

You can also write this as a common table expression as shown in @Leon Tayson's answer.

How to create hyperlink to call phone number on mobile devices?

Dashes (-) have no significance other than making the number more readable, so you might as well include them.

Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the + sign is always necessary. The + sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.

Using your example number, when calling from China, people would need to dial:

00-1-555-555-1212

And from Russia, they would dial

810-1-555-555-1212

The + sign solves this issue by allowing you to omit the international dialing prefix.

After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.

Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:

<a href="tel:+1-555-555-1212">+1-555-555-1212</a>

Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0), you need to omit it because the number must be in international format.

How can strings be concatenated?

you can also do this:

section = "C_type"
new_section = "Sec_%s" % section

This allows you not only append, but also insert wherever in the string:

section = "C_type"
new_section = "Sec_%s_blah" % section

Netbeans how to set command line arguments in Java

I am guessing that you are running the file using Run | Run File (or shift-F6) rather than Run | Run Main Project. The NetBeans 7.1 help file (F1 is your friend!) states for the Arguments parameter:

Add arguments to pass to the main class during application execution. Note that arguments cannot be passed to individual files.

I verified this with a little snippet of code:

public class Junk
{
    public static void main(String[] args)
    {
        for (String s : args)
            System.out.println("arg -> " + s);
    }
}

I set Run -> Arguments to x y z. When I ran the file by itself I got no output. When I ran the project the output was:

arg -> x
arg -> y
arg -> z

Activate tabpage of TabControl

Use SelectTab like this:

TabPage t = tabControl1.TabPages[2];
tabControl1.SelectTab(t); //go to tab

Use SelectedTab like this:

TabPage t = tabControl1.TabPages[2];
tabControl1.SelectedTab = t; //go to tab

How do I get video durations with YouTube API version 3?

I got it!

$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vId&key=dldfsd981asGhkxHxFf6JqyNrTqIeJ9sjMKFcX4");

$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
    $vTime= $vidTime['contentDetails']['duration'];
}

There it returns the time for YouTube API version 3 (the key is made up by the way ;). I used $vId that I had gotten off of the returned list of the videos from the channel I am showing the videos from...

It works. Google REALLY needs to include the duration in the snippet so you can get it all with one call instead of two... it's on their 'wontfix' list.

Make TextBox uneditable

If you want your TextBox uneditable you should make it ReadOnly.

Convert String (UTF-16) to UTF-8 in C#

Check the Jon Skeet answer to this other question: UTF-16 to UTF-8 conversion (for scripting in Windows)

It contains the source code that you need.

Hope it helps.

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

The easiest way for me to convert a date was to stringify it then slice it.

var event = new Date("Fri Apr 05 2019 16:59:00 GMT-0700 (Pacific Daylight Time)");

let date = JSON.stringify(event)
date = date.slice(1,11)

// console.log(date) = '2019-04-05'

What data is stored in Ephemeral Storage of Amazon EC2 instance?

ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store

So Everything will be stored on ephemeral.

if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

This worked for me.

You need to run it twice once for globals followed by locals

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

for name in dir():
    if not name.startswith('_'):
        del locals()[name]

PHP: How to get referrer URL?

If $_SERVER['HTTP_REFERER'] variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.

What is the difference between window, screen, and document in Javascript?

Well, the window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

What about the document object then? The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.

dom

That seems simple enough. But what happens once an IFRAME is introduced?

iframe

How to align the text middle of BUTTON

You can use text-align: center; line-height: 65px;

Demo

CSS

.loginBtn {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    text-align: center;  <--------- Here
    line-height: 65px;   <--------- Here
}

How can I determine whether a 2D Point is within a Polygon?

If you're using Google Map SDK and want to check if a point is inside a polygon, you can try to use GMSGeometryContainsLocation. It works great!! Here is how that works,

if GMSGeometryContainsLocation(point, polygon, true) {
    print("Inside this polygon.")
} else {
    print("outside this polygon")
}

Here is the reference: https://developers.google.com/maps/documentation/ios-sdk/reference/group___geometry_utils#gaba958d3776d49213404af249419d0ffd

BAT file to open CMD in current directory

You could add a context menu entry through the registry:

  1. Navigate in your Registry to HKEY_LOCAL_MACHINE/Software/Classes/Folder/Shell and create a key called "Command Prompt" without the quotes.

  2. Set the default string to whatever text you want to appear in the right-click menu.

  3. Create a new key within your newly created command prompt named "command," and set the default string to

    cmd.exe /k pushd %1
    

You may need to add %SystemRoot%\system32\ before the cmd.exe if the executable can't be found.

  1. The changes should take place immediately. Right click a folder and your new menu item should appear.

Also see http://www.petri.co.il/add_command_prompt_here_shortcut_to_windows_explorer.htm

How do I set the colour of a label (coloured text) in Java?

JLabel label = new JLabel ("Text Color: Red");
label.setForeground (Color.red);

this should work

How to delete zero components in a vector in Matlab?

You could use sparse(a), which would return

(1,2) 1

(1,4) 3

This allows you to keep the information about where your non-zero entries used to be.

IOException: The process cannot access the file 'file path' because it is being used by another process

Using FileShare fixed my issue of opening file even if it is opened by another process.

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}

Differences between C++ string == and compare()?

Suppose consider two string s and t.
Give them some values.
When you compare them using (s==t) it returns a boolean value(true or false , 1 or 0).
But when you compare using s.compare(t) ,the expression returns a value
(i) 0 - if s and t are equal
(ii) <0 - either if the value of the first unmatched character in s is less than that of t or the length of s is less than that of t.
(iii) >0 - either if the value of the first unmatched character in t is less than that of s or the length of t is less than that of s.

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

How do I pass named parameters with Invoke-Command?

I suspect its a new feature since this post was created - pass parameters to the script block using $Using:var. Then its a simple mater to pass parameters provided the script is already on the machine or in a known network location relative to the machine

Taking the main example it would be:

icm -cn $Env:ComputerName { 
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -one "uno" -two "dos" -Debug -Clear $Using:Clear
}

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

Can I append an array to 'formdata' in javascript?

Writing as

var formData = new FormData;
var array = ['1', '2'];
for (var i = 0; i < array.length; i++) {
    formData.append('array_php_side[]', array[i]);
}

you can receive just as normal array post/get by php.

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

How to use HTTP_X_FORWARDED_FOR properly?

You can use this function to get proper client IP:

public function getClientIP(){       
     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)){
            return  $_SERVER["HTTP_X_FORWARDED_FOR"];  
     }else if (array_key_exists('REMOTE_ADDR', $_SERVER)) { 
            return $_SERVER["REMOTE_ADDR"]; 
     }else if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
            return $_SERVER["HTTP_CLIENT_IP"]; 
     } 

     return '';
}

Read and write a String from text file

Earlier solutions answers question, but in my case deleting old content of file while writing was a problem.

So, I created piece of code for writing to file in documents directory without deleting previous content. You probably need better error handling, but I believe it's good starting point. Swift 4. Usuage:

    let filename = "test.txt"
    createOrOverwriteEmptyFileInDocuments(filename: filename)
    if let handle = getHandleForFileInDocuments(filename: filename) {
        writeString(string: "aaa", fileHandle: handle)
        writeString(string: "bbb", fileHandle: handle)
        writeString(string: "\n", fileHandle: handle)
        writeString(string: "ccc", fileHandle: handle)
    }

Helper methods:

func createOrOverwriteEmptyFileInDocuments(filename: String){
    guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        debugPrint("ERROR IN createOrOverwriteEmptyFileInDocuments")
        return
    }
    let fileURL = dir.appendingPathComponent(filename)
    do {
        try "".write(to: fileURL, atomically: true, encoding: .utf8)
    }
    catch {
        debugPrint("ERROR WRITING STRING: " + error.localizedDescription)
    }
    debugPrint("FILE CREATED: " + fileURL.absoluteString)
}

private func writeString(string: String, fileHandle: FileHandle){
    let data = string.data(using: String.Encoding.utf8)
    guard let dataU = data else {
        debugPrint("ERROR WRITING STRING: " + string)
        return
    }
    fileHandle.seekToEndOfFile()
    fileHandle.write(dataU)
}

private func getHandleForFileInDocuments(filename: String)->FileHandle?{
    guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        debugPrint("ERROR OPENING FILE")
        return nil
    }
    let fileURL = dir.appendingPathComponent(filename)
    do {
        let fileHandle: FileHandle? = try FileHandle(forWritingTo: fileURL)
        return fileHandle
    }
    catch {
        debugPrint("ERROR OPENING FILE: " + error.localizedDescription)
        return nil
    }
}

How do I add a reference to the MySQL connector for .NET?

This is an older question, but I found it yesterday while struggling with getting the MySQL Connector reference working properly on examples I'd found on the web. I'm working with VS 2010 on Win7 64 bit but have to work with .NET 3.5.

As others have stated, you need to download the .Net & Mono versions (I don't know why this is true, but it's what I've found works). The link to the connectors is given above in the earlier answers.

  • Extract the connectors somewhere convenient.
  • Open the project in Visual Studio, then on the menu bar navigate to Solution Explorer (View > Solution Explorer), and choose Properties (first box on the far left of the toolbar. The Solution Explorer shows up in the top right pane for me, but YMMV).
  • In Properties, select References & locate the instance for mysql.data. It's likely to have a yellow bang on it (Yellow triangle with exclamation point in it). Remove it.
  • Then on the menu bar, navigate to Project > Add Reference... > Browse > point to where you downloaded the connectors. I have only been able to get the V2 version to work, but that may be a factor of my platform, not sure.
  • Clean & build your application. You should now be able to use the MySQL connectors to talk to your database.
  • You can also now downgrade your .NET instance if you need to (we're constrained to .NET 3.5, but mysql.data.dll wants 4.0 at the time of my writing this). On the menu bar, navigate to the properties of your project (Project > Properties). Choose the Application tab > Target framework > Choose which .NET framework you want to use. You have to build the application at least once before you can change the .NET framework. Once you built once the connector will no longer complain about the lower version of .NET.

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

Travel/Hotel API's?

I've used the TripAdvisor API before and its suited me well. It returns, per destination, a list of top-rated hotels, along with options to retrieve reviews, photos, nearby restaurants and a couple other useful things.

http://www.tripadvisor.com/help/what_type_of_tripadvisor_content_is_available

From the API page (available API content) :

* Hotel, attraction and restaurant ratings and reviews
* Top 10 lists of hotels, attractions and restaurants in a destination
* Traveler photos of a destination
* Travelers' Choice award badges for hotels and destinations

To expand upon @nstehr's answer, you could also use Yahoo Pipes to facilitate a more granular local search. Go to pipes.yahoo.com and do a search for existing hotel pipes and you'll get the idea..

How to find if div with specific id exists in jQuery?

Here is the jQuery function I use:

function isExists(var elemId){
    return jQuery('#'+elemId).length > 0;
}

This will return a boolean value. If element exists, it returns true. If you want to select element by class name, just replace # with .

How to get form input array into PHP array

However, VolkerK's solution is the best to avoid miss couple between email and username. So you have to generate HTML code with PHP like this:

<? foreach ($i = 0; $i < $total_data; $i++) : ?>
    <input type="text" name="name[<?= $i ?>]" />
    <input type="text" name="email[<?= $i ?>]" />
<? endforeach; ?>

Change $total_data to suit your needs. To show it, just like this:

$output = array_map(create_function('$name, $email', 'return "The name is $name and email is $email, thank you.";'), $_POST['name'], $_POST['email']);
echo implode('<br>', $output);

Assuming the data was sent using POST method.

Find and replace string values in list

Beside list comprehension, you can try map

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Recommendation for compressing JPG files with ImageMagick

Did some experimenting myself here and boy does that Gaussian blur make a nice different. The final command I used was:

mogrify * -sampling-factor 4:2:0 -strip -quality 88 -interlace Plane -define jpeg:dct-method=float -colorspace RGB -gaussian-blur 0.05 

Without the Gaussian blur at 0.05 it was around 261kb, with it it was around 171KB for the image I was testing on. The visual difference on a 1440p monitor with a large complex image is not noticeable until you zoom way way in.

How to make HTTP Post request with JSON body in Swift

HTTP Post in Swift capturing the errors

let json = [ Activity.KEY_IDSUBJECT : activity.idSubject, Activity.KEY_RECORDMODE : "3", Activity.KEY_LOCATION_LONGITUDE : "0",Activity.KEY_LOCATION_LATITUDE : "0", Activity.KEY_CHECKIN : String(activity.dateCheckIn), Activity.KEY_CHECKOUT : String(activity.dateCheckOut) ]

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)

    // create post request
    let url = NSURL(string: "https://...appspot.com/_ah/api/activityendpoint/v1/activity")!
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"

    // insert json data to the request
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.HTTPBody = jsonData


    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
        if error != nil{
            print("Error -> \(error)")
            return
        }

        do {
            let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

            print("Result -> \(result)")

        } catch {
            print("Error -> \(error)")
        }
    }

    task.resume()
    return task
} catch {
    print(error)
}

Python json.loads shows ValueError: Extra data

This may also happen if your JSON file is not just 1 JSON record. A JSON record looks like this:

[{"some data": value, "next key": "another value"}]

It opens and closes with a bracket [ ], within the brackets are the braces { }. There can be many pairs of braces, but it all ends with a close bracket ]. If your json file contains more than one of those:

[{"some data": value, "next key": "another value"}]
[{"2nd record data": value, "2nd record key": "another value"}]

then loads() will fail.

I verified this with my own file that was failing.

import json

guestFile = open("1_guests.json",'r')
guestData = guestFile.read()
guestFile.close()
gdfJson = json.loads(guestData)

This works because 1_guests.json has one record []. The original file I was using all_guests.json had 6 records separated by newline. I deleted 5 records, (which I already checked to be bookended by brackets) and saved the file under a new name. Then the loads statement worked.

Error was

   raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 10 column 1 (char 261900 - 6964758)

PS. I use the word record, but that's not the official name. Also, if your file has newline characters like mine, you can loop through it to loads() one record at a time into a json variable.

How can I reference a commit in an issue comment on GitHub?

To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.

See also:

How can I develop for iPhone using a Windows development machine?

Develop iOS Apps on Windows With Cross-Platform Tools

Cross-platform tools are awesome: you code your app once, and export it to iOS and Android. That could potentially cut your app development time and cost in half. Several cross-platform tools allow you to develop iOS apps on a Windows PC, or allow you to compile the app if there’s a Mac in your local network.

Well, not so fast…

The cross-platform tool ecosystem is very large. On the one side you have complete Integrated Development Environments (IDEs) like Xamarin, that allow you to build cross-platform apps with C#.

The middle ground is covered by tools like PhoneGap, Cordova, Ionic and Appcelerator, that let you build native apps with HTML5 components. The far end includes smaller platforms like React Native that allow you to write native apps with a JavaScript wrapper.

The one thing that stands out for all cross-platform tools is this: they’re not beginner friendly! It’s much easier to get access to a Mac, learn Swift, and build a simple app, than it is to get started with Xamarin.

Most of the cross-platform tools require you to have a basic understanding of programming, compilation options, and the iOS and Android ecosystems. That’s something you don’t really have as a beginner developer!

Having said that, let’s look at a couple of options:

If you’re familiar with Windows-based development tools and IDEs, and if you already know how to code, it’s worthwhile to check out Xamarin. With Xamarin you code apps in C#, for multiple platforms, using the Mono and MonoTouch frameworks. If you’re familiar with web-based development, check out PhoneGap or Ionic. You’ll feel right at home with HTML 5, CSS and JavaScript. Don’t forget: a native app works different than a website… If you’re familiar with JavaScript, or if you’d rather learn to code JavaScript than Swift, check out React Native. With React Native you can code native apps for iOS and Android using a “wrapper”. Always deliberately choose for cross-platform tools because it’s a smart option, not because you think a native platform language is bad. The fact that one option isn’t right, doesn’t immediately make another option smarter!

If you don’t want to join the proprietary closed Apple universe, don’t forget that many cross-platform tools are operated by equally evil companies like Google, Facebook, Microsoft, Adobe and Amazon.

An often heard argument against cross-platform tools is that they offer limited access to and support for smartphone hardware, and are less “snappy” than their native counterparts. Keep in mind that any cross-platform tool will require you to write platform-specific code at one point, especially if you want to code custom features.

How do I size a UITextView to its content?

I found out a way to resize the height of a text field according to the text inside it and also arrange a label below it based on the height of the text field! Here is the code.

UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];
NSString *str = @"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.";
_textView.text = str;

[self.view addSubview:_textView];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];
lbl.text = @"Hello!";
[self.view addSubview:lbl];

Class has no objects member

You can change the linter for Python extension for Visual Studio Code.

In VS open the Command Palette Ctrl+Shift+P and type in one of the following commands:

Python: Select Linter

when you select a linter it will be installed. I tried flake8 and it seems issue resolved for me.

Bootstrap collapse animation not smooth

Adding to @CR Rollyson answer,

In case if you have a collapsible div which has a min-height attribute, it will also cause the jerking. Try removing that attribute from directly collapsible div. Use it in the child div of the collapsible div.

<div class="form-group">
    <a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">+ Not Jerky</a>
    <div class="collapse" id="collapseOne" style="padding: 0;">
        <textarea class="form-control" rows="4" style="padding: 20px;">No padding on animated element. Padding on child.</textarea>
    </div>
</div>

Fiddle

how to add picasso library in android studio

Dependency

dependencies {

   implementation 'com.squareup.picasso:picasso:2.71828'

}

//Java Code for Image Loading into imageView

Picasso.get().load(werURL).into(imageView);

Convert string in base64 to image and save on filesystem in Python

You can use Pillow.

pip install Pillow



image = base64.b64decode(str(base64String))       
fileName = 'test.jpeg'

imagePath = FILE_UPLOAD_DIR + fileName

img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
return fileName

reference for complete source code: https://abhisheksharma.online/convert-base64-blob-to-image-file-in-python/

Redirect output of mongo query to a csv file

I know this question is old but I spend an hour trying to export a complex query to csv and I wanted to share my thoughts. First I couldn't get any of the json to csv converters to work (although this one looked promising). What I ended up doing was manually writing the csv file in my mongo script.

This is a simple version but essentially what I did:

print("name,id,email");
db.User.find().forEach(function(user){
  print(user.name+","+user._id.valueOf()+","+user.email);
});

This I just piped the query to stdout

mongo test export.js > out.csv

where test is the name of the database I use.

Get last 3 characters of string

Many ways this can be achieved.

Simple approach should be taking Substring of an input string.

var result = input.Substring(input.Length - 3);

Another approach using Regular Expression to extract last 3 characters.

var result = Regex.Match(input,@"(.{3})\s*$");

Working Demo

Different ways of loading a file as an InputStream

After trying some ways to load the file with no success, I remembered I could use FileInputStream, which worked perfectly.

InputStream is = new FileInputStream("file.txt");

This is another way to read a file into an InputStream, it reads the file from the currently running folder.

javascript - Create Simple Dynamic Array

If you are asking whether there is a built in Pythonic range-like function, there isn't. You have to do it the brute force way. Maybe rangy would be of interest to you.

How can I hide a checkbox in html?

This two classes are borrowed from the HTML Boilerplate main.css. Although the invisible checkbox will be focused and not the label.

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

Using LINQ to concatenate strings

Here it is using pure LINQ as a single expression:

static string StringJoin(string sep, IEnumerable<string> strings) {
  return strings
    .Skip(1)
    .Aggregate(
       new StringBuilder().Append(strings.FirstOrDefault() ?? ""), 
       (sb, x) => sb.Append(sep).Append(x));
}

And its pretty damn fast!

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

Error : Index was outside the bounds of the array.

You have declared an array that can store 8 elements not 9.

this.posStatus = new int[8]; 

It means postStatus will contain 8 elements from index 0 to 7.

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Doesn't matter if Connection is poolable or not. Even poolable connection has to clean before returning to the pool.

"Clean" usually means closing resultsets & rolling back any pending transactions but not closing the connection. Otherwise pooling looses its sense.

Show how many characters remaining in a HTML text box using JavaScript

I needed something like that and the solution I gave with the help of jquery is this:

<textarea class="textlimited" data-textcounterid="counter1" maxlength="30">text</textarea>
<span class='textcounter' id="counter1"></span>

With this script:

// the selector below will catch the keyup events of elements decorated with class textlimited and have a maxlength
$('.textlimited[maxlength]').keyup(function(){
     //get the fields limit
    var maxLength = $(this).attr("maxlength");

    // check if the limit is passed
    if(this.value.length > maxLength){
        return false;
    }

    // find the counter element by the id specified in the source input element
    var counterElement = $(".textcounter#" + $(this).data("textcounterid"));
    // update counter 's text
    counterElement.html((maxLength - this.value.length) + " chars left");
});

? live demo Here