Programs & Examples On #Mirror

How to run html file on localhost?

On macOS:

Open Terminal (or iTerm) install Homebrew then run brew install live-server and run live-server.

You also can install Python 3 and run python3 -m http.server PORT.

On Windows:

If you have VS Code installed open it and install extension liveserver, then click Go Live in the bottom right corner.

Alternatively you can install WSL2 and follow the macOS steps via apt (sudo apt-get).

On Linux:

Open your favorite terminal emulator and follow the macOS steps via apt (sudo apt-get).

Question mark characters displaying within text, why is this?

I usually curse MS word and then run the following Wscript.

// replace with path to a file that needs cleaning
PATH = "test.html"

var go=WScript.CreateObject("Scripting.FileSystemObject");
var content=go.GetFile(PATH).OpenAsTextStream().ReadAll();
var out=go.CreateTextFile("clean-"+PATH, true);

// symbols
content=content.replace(/“/g,'"');
content=content.replace(/”/g,'"');
content=content.replace(/’/g,"'");
content=content.replace(/–/g,"-");
content=content.replace(/©/g,"©");
content=content.replace(/®/g,"®");
content=content.replace(/°/g,"°");
content=content.replace(/¶/g,"<p>");
content=content.replace(/¿/g,"&iquest;");
content=content.replace(/¡/g,'&iexcl;');
content=content.replace(/¢/g,'&cent;');
content=content.replace(/£/g,'&pound;');
content=content.replace(/¥/g,'&yen;');

out.Write(content);

How to update a git clone --mirror?

This is the command that you need to execute on the mirror:

git remote update

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

Remove the parentheses:

List<string> nameslist = new List<string> {"one", "two", "three"};

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.

As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.

Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.

As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).

Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.

The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.

Convert json to a C# array?

using Newtonsoft.Json;

Install this class in package console This class works fine in all .NET Versions, for example in my project: I have DNX 4.5.1 and DNX CORE 5.0 and everything works.

Firstly before JSON deserialization, you need to declare a class to read normally and store some data somewhere This is my class:

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

In HttpContent section where you requesting data by GET request for example:

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

Storing JSON in database vs. having a new column for each key

some time joins on the table will be an overhead. lets say for OLAP. if i have two tables one is ORDERS table and other one is ORDER_DETAILS. For getting all the order details we have to join two tables this will make the query slower when no of rows in the tables increase lets say in millions or so.. left/right join is too slower than inner join. I Think if we add JSON string/Object in the respective ORDERS entry JOIN will be avoided. add report generation will be faster...

Where to place the 'assets' folder in Android Studio?

Click over main ? new -> directory ? and type as name "assets"

or... main -> new -> folder -> assets folder (see image)

enter image description here

Convert float to double without losing precision

For information this comes under Item 48 - Avoid float and double when exact values are required, of Effective Java 2nd edition by Joshua Bloch. This book is jam packed with good stuff and definitely worth a look.

How to initialize an array of custom objects

Use a "Here-String" and cast to XML.

[xml]$myxml = @"
<stuff>
 <item name="Joe" age="32">
  <info>something about him</info>
 </item>
 <item name="Sue" age="29">
  <info>something about her</info>
 </item>
 <item name="Cat" age="12">
  <info>something else</info>
 </item>
</stuff>
"@

[array]$myitems = $myxml.stuff.Item

$myitems

Convert a SQL Server datetime to a shorter date format

The original DateTime field : [_Date_Time]

The converted to Shortdate : 'Short_Date'

CONVERT(date, [_Date_Time]) AS 'Short_Date'

Validation error: "No validator could be found for type: java.lang.Integer"

As per the javadoc of NotEmpty, Integer is not a valid type for it to check. It's for Strings and collections. If you just want to make sure an Integer has some value, javax.validation.constraints.NotNull is all you need.

public @interface NotEmpty

Asserts that the annotated string, collection, map or array is not null or empty.

How to get files in a relative path in C#

string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");

The first parameter is the path. The second is the search pattern you want to use.

Logout button php

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

session_destroy();

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

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

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

Edit:

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

exit;

Call a VBA Function into a Sub Procedure

To Add a Function To a new Button on your Form: (and avoid using macro to call function)

After you created your Function (Function MyFunctionName()) and you are in form design view:

  1. Add a new button (I don't think you can reassign an old button - not sure though).

  2. When the button Wizard window opens up click Cancel.

  3. Go to the Button properties Event Tab - On Click - field.

  4. At that fields drop down menu select: Event Procedure.

  5. Now click on button beside drop down menu that has ... in it and you will be taken to a new Private Sub in the forms Visual Basic window.

  6. In that Private Sub type: Call MyFunctionName
    It should look something like this:

    Private Sub Command23_Click()
    
        Call MyFunctionName
    
    End Sub
    
  7. Then just save it.

Fill Combobox from database

void Fillcombobox()
{

    con.Open();
    cmd = new SqlCommand("select ID From Employees",con);
    Sdr = cmd.ExecuteReader();
    while (Sdr.Read())
    {
        for (int i = 0; i < Sdr.FieldCount; i++)
        {
           comboID.Items.Add( Sdr.GetString(i));

        }
    }
    Sdr.Close();
    con.Close();

}

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

Creating email templates with Django

There is an error in the example.... if you use it as written, the following error occurs:

< type 'exceptions.Exception' >: 'dict' object has no attribute 'render_context'

You will need to add the following import:

from django.template import Context

and change the dictionary to be:

d = Context({ 'username': username })

See http://docs.djangoproject.com/en/1.2/ref/templates/api/#rendering-a-context

How to change DatePicker dialog color for Android 5.0

Kotlin, 2021

// set date as button text if pressed
btnDate.setOnClickListener(View.OnClickListener {

    val dpd = DatePickerDialog(
        this,
        { view, year, monthOfYear, dayOfMonth ->
            val selectDate = Calendar.getInstance()
            selectDate.set(Calendar.YEAR, year)
            selectDate.set(Calendar.MONTH, monthOfYear)
            selectDate.set(Calendar.DAY_OF_MONTH, dayOfMonth)

            var formatDate = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
            val date = formatDate.format(selectDate.time)
            Toast.makeText(this, date, Toast.LENGTH_SHORT).show()
            btnDate.text = date
        }, 1990, 6, 6
    )

    val calendar = Calendar.getInstance()
    val year = calendar[Calendar.YEAR]
    val month = calendar[Calendar.MONTH]
    val day = calendar[Calendar.DAY_OF_MONTH]
    dpd.datePicker.minDate = GregorianCalendar(year - 90, month, day, 0, 0).timeInMillis
    dpd.datePicker.maxDate = GregorianCalendar(year - 10, month, day, 0, 0).timeInMillis
    dpd.show()
})

Styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- This is main Theme Style for your application! -->
    <item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.DatePicker">
    <item name="android:headerBackground">#A500FF</item>
</style>

enter image description here

How to create a new instance from a class object in Python

If you have a module with a class you want to import, you can do it like this.

module = __import__(filename)
instance = module.MyClass()

If you do not know what the class is named, you can iterate through the classes available from a module.

import inspect
module = __import__(filename)
for c in module.__dict__.values():
    if inspect.isclass(c):
        # You may need do some additional checking to ensure 
        # it's the class you want
        instance = c()

Dynamically adding HTML form field using jQuery

This will insert a new element after the input field with id "password".

$(document).ready(function(){
  var newInput = $("<input name='new_field' type='text'>");
  $('input#password').after(newInput);
});

Not sure if this answers your question.

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

The private key password defined in your app/config is incorrect. First try verifying the the private key password by changing to another one as follows:

keytool -keypasswd -new changeit -keystore cacerts -storepass changeit -alias someapp -keypass password

The above example changes the password from password to changeit. This command will succeed if the private key password was password.

How to unload a package without restarting R

I tried what kohske wrote as an answer and I got error again, so I did some search and found this which worked for me (R 3.0.2):

require(splines) # package
detach(package:splines)

or also

library(splines)
pkg <- "package:splines"
detach(pkg, character.only = TRUE)

SQL UPDATE all values in a field with appended string CONCAT not working

That's pretty much all you need:

mysql> select * from t;
+------+-------+
| id   | data  |
+------+-------+
|    1 | max   |
|    2 | linda |
|    3 | sam   |
|    4 | henry |
+------+-------+
4 rows in set (0.02 sec)

mysql> update t set data=concat(data, 'a');
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4  Changed: 4  Warnings: 0

mysql> select * from t;
+------+--------+
| id   | data   |
+------+--------+
|    1 | maxa   |
|    2 | lindaa |
|    3 | sama   |
|    4 | henrya |
+------+--------+
4 rows in set (0.00 sec)

Not sure why you'd be having trouble, though I am testing this on 5.1.41

Using Mockito with multiple calls to the same method with the same arguments

You can use a LinkedList and an Answer. Eg

MyService mock = mock(MyService.class);
LinkedList<String> results = new LinkedList<>(List.of("A", "B", "C"));
when(mock.doSomething(any())).thenAnswer(invocation -> results.removeFirst());

How to change lowercase chars to uppercase using the 'keyup' event?

This worked for me

jQuery(document).ready(function(){ 
        jQuery('input').keyup(function() {
            this.value = this.value.toLocaleUpperCase();
        });
        jQuery('textarea').keyup(function() {
            this.value = this.value.toLocaleUpperCase();
        });
 });

How to select the first element with a specific attribute using XPath

Use the index to get desired node if xpath is complicated or more than one node present with same xpath.

Ex :

(//bookstore[@location = 'US'])[index]

You can give the number which node you want.

Darkening an image with CSS (In any shape)

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!

style

.wrapper{background-image:url(silhouette.png);} 
.original{opacity:0.7:}
.original:hover{opacity:1}

<div class="wrapper">
  <div class="img">
    <img src="original.png">
  </div>
</div>

What is the difference between dim and set in vba

According to VBA help on SET statement it sets a reference to an object.so if you change a property the actual object will also changes.

Dim newObj as Object
Set var1=Object1(same type as Object)
Set var2=Object1(same type as Object)
Set var3=Object1(same type as Object)
Set var4=Object1(same type as Object)
Var1.property1=NewPropertyValue

the other Vars properties also changes,so:

Var1.property1=Var2.property1=Var3.property1=Var4.property1=Object1.Property1=NewpropertyValue`

actualy all vars are the same!

Run function in script from command line (Node JS)

If you turn db.js into a module you can require it from db_init.js and just: node db_init.js.

db.js:

module.exports = {
  method1: function () { ... },
  method2: function () { ... }
}

db_init.js:

var db = require('./db');

db.method1();
db.method2();

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

struct in class

Your E class doesn't have a member of type struct X, you've just defined a nested struct X in there (i.e. you've defined a new type).

Try:

#include <iostream>

class E
{
    public: 
    struct X { int v; };
    X x; // an instance of `struct X`
};

int main(){

    E object;
    object.x.v = 1;

    return 0;
}

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

eval() can not handle the list object

tf.reset_default_graph()

a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
    z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])

init = tf.global_variables_initializer()

with tf.Session() as sess:
    init.run()
    print("z:", z.eval())
    print("grad", grad.eval())

but Session.run() can

print("grad", sess.run(grad))

correct me if I am wrong

Windows Scheduled task succeeds but returns result 0x1

Just had the same problem here. In my case, the bat files had space " " After getting rid of spaces from filename and change into underscore, bat file worked

sample before it wont start

"x:\Update & pull.bat"

after rename

"x:\Update_and_pull.bat"

How to set initial value and auto increment in MySQL?

SET GLOBAL auto_increment_offset=1;

SET GLOBAL auto_increment_increment=5;

auto_increment_offset: interval between successive column values

auto_increment_offset: determines the starting point for the AUTO_INCREMENT column value. The default value is 1.

read more here

How to determine the number of days in a month in SQL Server?

SELECT DAY(SUBDATE(ADDDATE(CONCAT(YEAR(NOW()), '-', MONTH(NOW()), '-1'), INTERVAL 1 MONTH), INTERVAL 1 DAY))

Nice 'n' Simple and does not require creating any functions

Which comes first in a 2D array, rows or columns?

In Java, there are no multi-dimension arrays. There are arrays of arrays. So:

int[][] array = new int[2][3];

It actually consists of two arrays, each has three elements.

Running npm command within Visual Studio Code

To install npm on VS Code:

  1. Click Ctrl+P
  2. Write ext install npm script runner
  3. On the results list look for npm 'npm commands for VS Code'. This npm manages commands. Click Install, then Reload VS Code to save changes
  4. Restart VS Code
  5. On the Integrated Terminal, Run 'npm install'

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

If you're dealing with a response from an AJAX (or XMLHttpRequest) call, what worked for me is to check the response content type and parse or not the content accordingly.

Can you nest html forms?

Before I knew I wasn't supposed to do this I had nested forms for the purpose of having multiple submit buttons. Ran that way for 18 months, thousands of signup transactions, no one called us about any difficulties.

Nested forms gave me an ID to parse for the correct action to take. Didn't break 'til I tried to attach a field to one of the buttons and Validate complained. Wasn't a big deal to untangle it--I used an explicit stringify on the outer form so it didn't matter the submit and form didn't match. Yeah, yeah, should've taken the buttons from a submit to an onclick.

Point is there are circumstances where it's not entirely broken. But "not entirely broken" is perhaps too low a standard to shoot for :-)

ORA-01653: unable to extend table by in tablespace ORA-06512

Just add a new datafile for the existing tablespace

ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;

To find out the location and size of your data files:

SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';

How to iterate through LinkedHashMap with lists as values

for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    // now work with key and value...
}

By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.

PHP - add 1 day to date format mm-dd-yyyy

there you go

$date = "04-15-2013";
$date1 = str_replace('-', '/', $date);
$tomorrow = date('m-d-Y',strtotime($date1 . "+1 days"));

echo $tomorrow;

this will output

04-16-2013

Documentation for both function
date
strtotime

Install tkinter for Python

If you're using Python 3 then you must install as follows:

sudo apt-get update
sudo apt-get install python3-tk

Tkinter for Python 2 (python-tk) is different from Python 3's (python3-tk).

'App not Installed' Error on Android

In case, you have your app's older version installed from Google Play and you want to test the newer release version of your app:

  1. Open Google Play Console

  2. Upload the newer release version of your app to Alpha / Beta, but do not release it yet!

enter image description here

  1. You can now download the derived apk:
    enter image description here

Install the downloaded derived apk on your phone now. The derived apk is re-signed by Google Play with a different key from the release app Android Studio generates.

How do I activate C++ 11 in CMake?

I think just these two lines are enough.

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

Remove the last line from a file in Bash

Here is a solution using sponge (from the moreutils package):

head -n -1 foo.txt | sponge foo.txt

Summary of solutions:

  1. If you want a fast solution for large files, use the efficient tail or dd approach.

  2. If you want something easy to extend/tweak and portable, use the redirect and move approach.

  3. If you want something easy to extend/tweak, the file is not too large, portability (i.e., depending on moreutils package) is not an issue, and you are a fan of square pants, consider the sponge approach.

A nice benefit of the sponge approach, compared to "redirect and move" approaches, is that sponge preserves file permissions.

Sponge uses considerably more RAM compared to the "redirect and move" approach. This gains a bit of speed (only about 20%), but if you're interested in speed the "efficient tail" and dd approaches are the way to go.

Disallow Twitter Bootstrap modal window from closing

To Update the backdrop state in Bootstrap 4.1.3 after the modal have been Display, We used the following line from Bootstrap-Modal-Wrapper plugin. Plugin Repository code reference.

$("#yourModalElement").data('bs.modal')._config.backdrop = (true : "static");

SQL Server CASE .. WHEN .. IN statement

Thanks for the Answer I have modified the statements to look like below

SELECT
     AlarmEventTransactionTable.TxnID,
     CASE 
    WHEN DeviceID IN('7', '10', '62', '58', '60',
            '46', '48', '50', '137', '139',
             '141', '145', '164') THEN '01'
    WHEN DeviceID IN('8', '9', '63', '59', '61',
            '47', '49', '51', '138', '140',
            '142', '146', '165') THEN '02'
             ELSE 'NA' END AS clocking,
     AlarmEventTransactionTable.DateTimeOfTxn
FROM
     multiMAXTxn.dbo.AlarmEventTransactionTable

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

Why Java Calendar set(int year, int month, int date) not returning correct date?

Selected date at the example is interesting. Example code block is:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

Unrecognized escape sequence for path string containing backslashes

If your string is a file path, as in your example, you can also use Unix style file paths:

string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";

But the other answers have the more general solutions to string escaping in C#.

What is the common header format of Python files?

I strongly favour minimal file headers, by which I mean just:

  • The hashbang (#! line) if this is an executable script
  • Module docstring
  • Imports, grouped in the standard way, eg:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  from mypackage import (  # local source
      mymodule,
      myothermodule,
  )

ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.

Everything else is a waste of time, visual space, and is actively misleading.

If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE file, not random source code.

Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.

I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.

Compiling C++ on remote Linux machine - "clock skew detected" warning

That message is usually an indication that some of your files have modification times later than the current system time. Since make decides which files to compile when performing an incremental build by checking if a source files has been modified more recently than its object file, this situation can cause unnecessary files to be built, or worse, necessary files to not be built.

However, if you are building from scratch (not doing an incremental build) you can likely ignore this warning without consequence.

Android: ScrollView force to bottom

One possible reason of why scroll.fullScroll(View.FOCUS_DOWN) might not work even wrapped in .post() is that the view is not laid out. In this case View.doOnLayout() could be a better option:

scroll.doOnLayout(){
    scroll.fullScroll(View.FOCUS_DOWN)
}

Or, something more elaborated for the brave souls: https://chris.banes.dev/2019/12/03/suspending-views/

Reading binary file and looping over each byte

To sum up all the brilliant points of chrispy, Skurmedel, Ben Hoyt and Peter Hansen, this would be the optimal solution for processing a binary file one byte at a time:

with open("myfile", "rb") as f:
    while True:
        byte = f.read(1)
        if not byte:
            break
        do_stuff_with(ord(byte))

For python versions 2.6 and above, because:

  • python buffers internally - no need to read chunks
  • DRY principle - do not repeat the read line
  • with statement ensures a clean file close
  • 'byte' evaluates to false when there are no more bytes (not when a byte is zero)

Or use J. F. Sebastians solution for improved speed

from functools import partial

with open(filename, 'rb') as file:
    for byte in iter(partial(file.read, 1), b''):
        # Do stuff with byte

Or if you want it as a generator function like demonstrated by codeape:

def bytes_from_file(filename):
    with open(filename, "rb") as f:
        while True:
            byte = f.read(1)
            if not byte:
                break
            yield(ord(byte))

# example:
for b in bytes_from_file('filename'):
    do_stuff_with(b)

How to upload & Save Files with Desired name

use this for target path for uploading

<?php
$file_name = $_FILES["csvFile"]["name"];
$target_path = $dir = plugin_dir_path( __FILE__ )."\\upload\\". $file_name;
echo $target_path;
move_uploaded_file($_FILES["csvFile"]["tmp_name"],$target_path. $file_name);
?>

How to make a link open multiple pages when clicked

If you prefer to inform the visitor which links will be opened, you can use a JS function reading links from an html element. You can even let the visitor write/modify the links as seen below:

<script type="text/javascript"> 
    function open_all_links() {
        var x = document.getElementById('my_urls').value.split('\n');
        for (var i = 0; i < x.length; i++)
            if (x[i].indexOf('.') > 0)
            if (x[i].indexOf('://') < 0)
                window.open('http://' + x[i]);
            else
                window.open(x[i]);
    }
</script>



<form method="post" name="input" action=""> 
    <textarea id="my_urls" rows="4" placeholder="enter links in each row..."></textarea>
    <input value="open all now" type="button" onclick="open_all_links();">
</form>

How to get first and last element in an array in java?

I think there is only one intuitive solution and it is:

int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);

Output:

First: 1
Last: 5

How to change a field name in JSON using Jackson

Jackson

If you are using Jackson, then you can use the @JsonProperty annotation to customize the name of a given JSON property.

Therefore, you just have to annotate the entity fields with the @JsonProperty annotation and provide a custom JSON property name, like this:

@Entity
public class City {

   @Id
   @JsonProperty("value")
   private Long id;

   @JsonProperty("label")
   private String name;

   //Getters and setters omitted for brevity
}

JavaEE or JakartaEE JSON-B

JSON-B is the standard binding layer for converting Java objects to and from JSON. If you are using JSON-B, then you can override the JSON property name via the @JsonbProperty annotation:

@Entity
public class City {

   @Id
   @JsonbProperty("value")
   private Long id;

   @JsonbProperty("label")
   private String name;

   //Getters and setters omitted for brevity
}

Display string as html in asp.net mvc view

You are close you want to use @Html.Raw(str)

@Html.Encode takes strings and ensures that all the special characters are handled properly. These include characters like spaces.

How to install mcrypt extension in xampp

Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

http://php.net/manual/en/mcrypt.requirements.php

But if you really want to download it, just go to the mcrypt sourceforge page

http://sourceforge.net/projects/mcrypt/files/?source=navbar

Deleting all records in a database table

If you mean delete every instance of all models, I would use

ActiveRecord::Base.connection.tables.map(&:classify)
  .map{|name| name.constantize if Object.const_defined?(name)}
  .compact.each(&:delete_all)

Getting attributes of a class

This can be done without inspect, I guess.

Take the following class:

 class Test:
   a = 1
   b = 2

   def __init__(self):
     self.c = 42

   @staticmethod
   def toto():
     return "toto"

   def test(self):
     return "test"

Looking at the members along with their types:

t = Test()
l = [ (x, eval('type(x.%s).__name__' % x)) for x in dir(a) ]

... gives:

[('__doc__', 'NoneType'),
 ('__init__', 'instancemethod'),
 ('__module__', 'str'),
 ('a', 'int'),
 ('b', 'int'),
 ('c', 'int'),
 ('test', 'instancemethod'),
 ('toto', 'function')]

So to output only the variables, you just have to filter the results by type, and names not starting with '__'. E.g.

filter(lambda x: x[1] not in ['instancemethod', 'function'] and not x[0].startswith('__'), l)

[('a', 'int'), ('b', 'int'), ('c', 'int')] # actual result

That's it.

Note: if you're using Python 3, convert the iterators to lists.

If you want a more robust way to do it, use inspect.

How do I delete files programmatically on Android?

Try this one. It is working for me.

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Set up the projection (we only need the ID)
        String[] projection = { MediaStore.Images.Media._ID };

        // Match on the file path
        String selection = MediaStore.Images.Media.DATA + " = ?";
        String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };

        // Query for the ID of the media matching the file path
        Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver = getActivity().getContentResolver();
        Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);

        if (c != null) {
            if (c.moveToFirst()) {
                // We found the ID. Deleting the item via the content provider will also remove the file
                long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
                contentResolver.delete(deleteUri, null, null);
            } else {
                // File not found in media store DB
            }
            c.close();
        }
    }
}, 5000);

In Chart.js set chart title, name of x axis and y axis?

If you have already set labels for your axis like how @andyhasit and @Marcus mentioned, and would like to change it at a later time, then you can try this:

chart.options.scales.yAxes[ 0 ].scaleLabel.labelString = "New Label";

Full config for reference:

var chartConfig = {
    type: 'line',
    data: {
      datasets: [ {
        label: 'DefaultLabel',
        backgroundColor: '#ff0000',
        borderColor: '#ff0000',
        fill: false,
        data: [],
      } ]
    },
    options: {
      responsive: true,
      scales: {
        xAxes: [ {
          type: 'time',
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Date'
          },
          ticks: {
            major: {
              fontStyle: 'bold',
              fontColor: '#FF0000'
            }
          }
        } ],
        yAxes: [ {
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'value'
          }
        } ]
      }
    }
  };

post checkbox value

in normal time, checkboxes return an on/off value.

you can verify it with this code:

<form action method="POST">
      <input type="checkbox" name="hello"/>
</form>

<?php
if(isset($_POST['hello'])) echo('<p>'.$_POST['hello'].'</p>');
?>

this will return

<p>off</p>

or

<p>on</p>

How do I list the symbols in a .so file

You can use the nm -g tool from the binutils toolchain. However, their source is not always readily available. and I'm not actually even sure that this information can always be retrieved. Perhaps objcopy reveals further information.

/EDIT: The tool's name is of course nm. The flag -g is used to show only exported symbols.

IDENTITY_INSERT is set to OFF - How to turn it ON?

I believe it needs to be done in a single query batch. Basically, the GO statements are breaking your commands into multiple batches and that is causing the issue. Change it to this:

SET IDENTITY_INSERT tbl_content ON
/* GO */

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO

Java: Insert multiple rows into MySQL with PreparedStatement

we can be submit multiple updates together in JDBC to submit batch updates.

we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit

addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate

here addBatch() method adds a set of statements or parameters to the current batch.

When restoring a backup, how do I disconnect all active connections?

I ran across this problem while automating a restore proccess in SQL Server 2008. My (successfull) approach was a mix of two of the answers provided.

First, I run across all the connections of said database, and kill them.

DECLARE @SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While @spid Is Not Null
Begin
        Execute ('Kill ' + @spid)
        Select @spid = top 1 spid from master.dbo.sysprocesses
        where dbid = db_id('dbName')
End

Then, I set the database to a single_user mode

ALTER DATABASE dbName SET SINGLE_USER

Then, I run the restore...

RESTORE DATABASE and whatnot

Kill the connections again

(same query as above)

And set the database back to multi_user.

ALTER DATABASE dbName SET MULTI_USER

This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.

How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

    public interface IFileProxy {
        void Delete(string path);
    }

    public class FileProxy : IFileProxy {
        public void Delete(string path) {
            System.IO.File.Delete(path);
        }
    }

    public class MyClass {

        private IFileProxy _fileProxy;

        public MyClass(IFileProxy fileProxy) {
            _fileProxy = fileProxy;
        }

        public void DoSomethingAndDeleteFile(string path) {
            // Do Something with file
            // ...
            // Delete
            System.IO.File.Delete(path);
        }

        public void DoSomethingAndDeleteFileUsingProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            _fileProxy.Delete(path);

        }
    }

The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

   public static class FileServices {

        static FileServices() {
            Reset();
        }

        internal static IFileProxy FileProxy { private get; set; }

        public static void Reset(){
           FileProxy = new FileProxy();
        }

        public static void Delete(string path) {
            FileProxy.Delete(path);
        }

    }

Our method now becomes

    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            FileServices.Delete(path);

    }

For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

How can I replace a regex substring match in Javascript?

I think the simplest way to achieve your goal is this:

var str   = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);

jQuery: Scroll down page a set increment (in pixels) on click?

var y = $(window).scrollTop();  //your current y position on the page
$(window).scrollTop(y+150);

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

Wildcard string comparison in Javascript

This function convert wildcard to regexp and make test (it supports . and * wildcharts)

function wildTest(wildcard, str) {
  let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape 
  const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
  return re.test(str); // remove last 'i' above to have case sensitive
}

_x000D_
_x000D_
function wildTest(wildcard, str) {_x000D_
  let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape _x000D_
  const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');_x000D_
  return re.test(str); // remove last 'i' above to have case sensitive_x000D_
}_x000D_
_x000D_
_x000D_
// Example usage_x000D_
_x000D_
let arr = ["birdBlue", "birdRed", "pig1z", "pig2z", "elephantBlua" ];_x000D_
_x000D_
let resultA = arr.filter( x => wildTest('biRd*', x) );_x000D_
let resultB = arr.filter( x => wildTest('p?g?z', x) );_x000D_
let resultC = arr.filter( x => wildTest('*Blu?', x) );_x000D_
_x000D_
console.log('biRd*',resultA);_x000D_
console.log('p?g?z',resultB);_x000D_
console.log('*Blu?',resultC);
_x000D_
_x000D_
_x000D_

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

Use CSS to make a span not clickable

Yes you can.... you can place something on top of the link element.

<!DOCTYPE html>
<html>
<head>
    <title>Yes you CAN</title>
    <style type="text/css">
        ul{
            width: 500px;
            border: 5px solid black; 
        }
        .product-type-simple {
            position: relative;
            height: 150px;
            width: 150px;
        }
        .product-type-simple:before{
            position: absolute;
            height: 100% ;
            width: 100% ;
            content: '';
            background: green;//for debugging purposes , remove this if you want to see whats behind
            z-index: 999999999999;
        }
    </style>
</head>
<body>
<ul>
    <li class='product-type-simple'>
        <a href="/link1">
            <img src="http://placehold.it/150x150">
        </a>
    </li>
    <li class='product-type-simple'>
        <a href="/link2">
            <img src="http://placehold.it/150x150">
        </a>
    </li>
</ul>
</body>
</html>

the magic sauce happens at product-type-simple:before class Whats happening here is that for each element that has class of product-type-simple you create something that has the width and height equal to that of the product-type-simple , then you increase its z-index to make sure it will place it self on top of the content of product-type-simple. You can toggle the background color if you want to see whats going on.

here is an example of the code https://jsfiddle.net/92qky63j/

I need to learn Web Services in Java. What are the different types in it?

  1. SOAP Web Services are standard-based and supported by almost every software platform: They rely heavily in XML and have support for transactions, security, asynchronous messages and many other issues. It’s a pretty big and complicated standard, but covers almost every messaging situation. On the other side, RESTful services relies of HTTP protocol and verbs (GET, POST, PUT, DELETE) to interchange messages in any format, preferable JSON and XML. It’s a pretty simple and elegant architectural approach.
  2. As in every topic in the Java World, there are several libraries to build/consume Web Services. In the SOAP Side you have the JAX-WS standard and Apache Axis, and in REST you can use Restlets or Spring REST Facilities among other libraries.

With question 3, this article states that RESTful Services are appropiate in this scenarios:

  • If you have limited bandwidth
  • If your operations are stateless: No information is preserved from one invocation to the next one, and each request is treated independently.
  • If your clients require caching.

While SOAP is the way to go when:

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are stateful: For example, you store information/data on a request and use that stored data on the next one.

Copying a HashMap in Java

Since Java 10 it is possible to use

Map.copyOf

for creating a shallow copy, which is also immutable. (Here is its Javadoc). For a deep copy, as mentioned in this answer you, need some kind of value mapper to make a safe copy of values. You don't need to copy keys though, since they must be immutable.

Request format is unrecognized for URL unexpectedly ending in

In my case the error happened when i move from my local PC Windows 10 to a dedicated server with Windows 2012. The solution for was to add to the web.config the following lines

<webServices>
        <protocols>
               <add name="Documentation"/>
        </protocols>
</webServices>

Creating Unicode character from its number

(ANSWER IS IN DOT NET 4.5 and in java, there must be a similar approach exist)

I am from West Bengal in INDIA. As I understand your problem is ... You want to produce similar to ' ? ' (It is a letter in Bengali language) which has Unicode HEX : 0X0985.

Now if you know this value in respect of your language then how will you produce that language specific Unicode symbol right ?

In Dot Net it is as simple as this :

int c = 0X0985;
string x = Char.ConvertFromUtf32(c);

Now x is your answer. But this is HEX by HEX convert and sentence to sentence conversion is a work for researchers :P

Taking multiple inputs from user in python

In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way. I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.

items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]

print items

CURL Command Line URL Parameters

Felipsmartins is correct.

It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.

Which means you can do this:

curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'

Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.

I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.

curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros

This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)

Hope it helps.

Add leading zeroes/0's to existing Excel values to certain length

I know this was answered a while ago but just chiming with a simple solution here that I am surprised wasn't mentioned.

=RIGHT("0000" & A1, 4)

Whenever I need to pad I use something like the above. Personally I find it the simplest solution and easier to read.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

You may use any standard encoding of your specific usage and input.

utf-8 is the default.

iso8859-1 is also popular for Western Europe.

e.g: bytes_obj.decode('iso8859-1')

see: docs

How do I convert Long to byte[] and back in java

 public static long bytesToLong(byte[] bytes) {
        if (bytes.length > 8) {
            throw new IllegalMethodParameterException("byte should not be more than 8 bytes");

        }
        long r = 0;
        for (int i = 0; i < bytes.length; i++) {
            r = r << 8;
            r += bytes[i];
        }

        return r;
    }



public static byte[] longToBytes(long l) {
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        while (l != 0) {
            bytes.add((byte) (l % (0xff + 1)));
            l = l >> 8;
        }
        byte[] bytesp = new byte[bytes.size()];
        for (int i = bytes.size() - 1, j = 0; i >= 0; i--, j++) {
            bytesp[j] = bytes.get(i);
        }
        return bytesp;
    }

Increase JVM max heap size for Eclipse

--launcher.XXMaxPermSize

256m

Try to bump that value up!

What do we mean by Byte array?

I assume you know what a byte is. A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

Just as bytes can encode different types and ranges of data (numbers from 0 to 255, numbers from -128 to 127, single characters using ASCII e.g. 'a' or '%', CPU op-codes), each byte in a byte array may be any of these things, or contribute to some multi-byte values such as numbers with larger range (e.g. 16-bit unsigned int from 0..65535), international character sets, textual strings ("hello"), or part/all of a compiled computer programs.

The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit. The bad thing is the computer just treats every entry as an independent 8-bit number - which may be what your program is dealing with, or you may prefer some powerful data-type such as a string that keeps track of its own length and grows as necessary, or a floating point number that lets you store say 3.14 without thinking about the bit-wise representation. As a data type, it is inefficient to insert or remove data near the start of a long array, as all the subsequent elements need to be shuffled to make or fill the gap created/required.

Delete all files in directory (but not directory) - one liner solution

Peter Lawrey's answer is great because it is simple and not depending on anything special, and it's the way you should do it. If you need something that removes subdirectories and their contents as well, use recursion:

void purgeDirectory(File dir) {
    for (File file: dir.listFiles()) {
        if (file.isDirectory())
            purgeDirectory(file);
        file.delete();
    }
}

To spare subdirectories and their contents (part of your question), modify as follows:

void purgeDirectoryButKeepSubDirectories(File dir) {
    for (File file: dir.listFiles()) {
        if (!file.isDirectory())
            file.delete();
    }
}

Or, since you wanted a one-line solution:

for (File file: dir.listFiles())
    if (!file.isDirectory())
        file.delete();

Using an external library for such a trivial task is not a good idea unless you need this library for something else anyway, in which case it is preferrable to use existing code. You appear to be using the Apache library anyway so use its FileUtils.cleanDirectory() method.

How to check cordova android version of a cordova/phonegap project?

Run

cordova -v 

to see the currently running version. Run the npm info command

npm info cordova

for a longer listing that includes the current version along with other available version numbers

how to write value into cell with vba code without auto type conversion?

Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:

Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"

Knockout validation

Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.

Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.

Python and SQLite: insert into table

Adapted from http://docs.python.org/library/sqlite3.html:

# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
    c.execute('insert into stocks values (?,?,?,?,?)', t)

Tesseract OCR simple example

Try updating the line to:

ocr.Init(@"C:\", "eng", false); // the path here should be the parent folder of tessdata

How to execute a raw update sql with dynamic binding in rails

I needed to use raw sql because I failed at getting composite_primary_keys to function with activerecord 2.3.8. So in order to access the sqlserver 2000 table with a composite primary key, raw sql was required.

sql = "update [db].[dbo].[#{Contacts.table_name}] " +
      "set [COLUMN] = 0 " +
      "where [CLIENT_ID] = '#{contact.CLIENT_ID}' and CONTACT_ID = '#{contact.CONTACT_ID}'"
st = ActiveRecord::Base.connection.raw_connection.prepare(sql)
st.execute

If a better solution is available, please share.

C# - Making a Process.Start wait until the process has start-up

Are you sure the Start method returns before the child process starts? I was always under the impression that Start starts the child process synchronously.

If you want to wait until your child process finishes some sort of initialization then you need inter-process communication - see Interprocess communication for Windows in C# (.NET 2.0).

How to write text in ipython notebook?

Change the cell type to Markdown in the menu bar, from Code to Markdown. Currently in Notebook 4.x, the keyboard shortcut for such an action is: Esc (for command mode), then m (for markdown).

Attempt to set a non-property-list object as an NSUserDefaults

Swift 5: The Codable protocol can be used instead of NSKeyedArchiever.

struct User: Codable {
    let id: String
    let mail: String
    let fullName: String
}

The Pref struct is custom wrapper around the UserDefaults standard object.

struct Pref {
    static let keyUser = "Pref.User"
    static var user: User? {
        get {
            if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
                do {
                    return try JSONDecoder().decode(User.self, from: data)
                } catch {
                    print("Error while decoding user data")
                }
            }
            return nil
        }
        set {
            if let newValue = newValue {
                do {
                    let data = try JSONEncoder().encode(newValue)
                    UserDefaults.standard.set(data, forKey: keyUser)
                } catch {
                    print("Error while encoding user data")
                }
            } else {
                UserDefaults.standard.removeObject(forKey: keyUser)
            }
        }
    }
}

So you can use it this way:

Pref.user?.name = "John"

if let user = Pref.user {...

First Or Create

firstOrCreate() checks for all the arguments to be present before it finds a match.

If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'abcd',
    'lastName' => 'efgh',
    'veristyName'=>'xyz',
]);

Then it check only the email

SSIS Connection not found in package

In my case i found out that the problem was a Log Provider previously configured point to an old connection not used anymore. To solve the problem click the Package Explorer Tab then click Log Providers and delete the outdated Log Provider. I hope this helps someone.

Fragment onResume() & onPause() is not called on backstack

The fragments onResume() or onPause() will be called only when the Activities onResume() or onPause() is called. They are tightly coupled to the Activity.

Read the Handling the Fragment Lifecycle section of this article.

HTML img onclick Javascript

use this simple cod:

    <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}

#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation */
.modal-content, #caption {  
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {-webkit-transform:scale(0)} 
  to {-webkit-transform:scale(1)}
}

@keyframes zoom {
  from {transform:scale(0)} 
  to {transform:scale(1)}
}

/* The Close Button */
.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
  .modal-content {
    width: 100%;
  }
}
</style>
</head>
<body>

<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>

<img id="myImg" src="img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

<script>
// Get the modal
var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("modal")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
  modal.style.display = "none";
}
</script>

</body>
</html>

this code open and close your photo.

How to send FormData objects with Ajax-requests in jQuery?

If you want to submit files using ajax use "jquery.form.js" This submits all form elements easily.

Samples http://jquery.malsup.com/form/#ajaxSubmit

rough view :

<form id='AddPhotoForm' method='post' action='../photo/admin_save_photo.php' enctype='multipart/form-data'>


<script type="text/javascript">
function showResponseAfterAddPhoto(responseText, statusText)
{ 
    information= responseText;
    callAjaxtolist();
    $("#AddPhotoForm").resetForm();
    $("#photo_msg").html('<div class="album_msg">Photo uploaded Successfully...</div>');        
};

$(document).ready(function(){
    $('.add_new_photo_div').live('click',function(){
            var options = {success:showResponseAfterAddPhoto};  
            $("#AddPhotoForm").ajaxSubmit(options);
        });
});
</script>

How create table only using <div> tag and Css

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key to getting empty cells and cells in general to be the right size, is Box-Sizing and Padding. Border will do the same thing as well, but creates a line in the row. Padding doesn't. And, while I haven't tried it, I think Margin will act the same way as Padding, in forcing and empty cell to be rendered properly.

ng-mouseover and leave to toggle item using mouse in angularjs

A little late here, but I've found this to be a common problem worth a custom directive to handle. Here's how that might look:

  .directive('toggleOnHover', function(){
    return {
      restrict: 'A',
      link: link
    };

    function link(scope, elem, attrs){
      elem.on('mouseenter', applyToggleExp);
      elem.on('mouseleave', applyToggleExp);

      function applyToggleExp(){
        scope.$apply(attrs.toggleOnHover);
      }
    }

  });

You can use it like this:

<li toggle-on-hover="editableProp = !editableProp">edit</li> 

How to edit default.aspx on SharePoint site without SharePoint Designer

I was able to accomplish editing the default.aspx page by:

  • Opening the site in SharePoint Designer 2013
  • Then clicking 'All Files' to view all of the files,
  • Then right-click -> Edit file in Advanced Mode.

By doing that I was able to remove the tagprefix causing a problem on my page.

SyntaxError: non-default argument follows default argument

You can't have a non-keyword argument after a keyword argument.

Make sure you re-arrange your function arguments like so:

def a(len1,til,hgt=len1,col=0):
    system('mode con cols='+len1,'lines='+hgt)
    system('title',til)
    system('color',col)

a(64,"hi",25,"0b")

Installing SetupTools on 64-bit Windows

Get the file register.py from this gist. Save it on your C drive or D drive, go to CMD to run it with:

'python register.py'

Then you will be able to install it.

Efficiently getting all divisors of a given number

for (int i = 1; i*i <= num; ++i)
{
    if (num % i == 0)
    cout << i << endl;
    if (num/i!=i)
    cout << num/i << endl;
}

Django download a file

You can add "download" attribute inside your tag to download files.

<a  href="/project/download" download> Download Document </a>

https://www.w3schools.com/tags/att_a_download.asp

How do I store an array in localStorage?

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');

How to get a value from a cell of a dataframe?

These are fast access for scalars

In [15]: df = pandas.DataFrame(numpy.random.randn(5,3),columns=list('ABC'))

In [16]: df
Out[16]: 
          A         B         C
0 -0.074172 -0.090626  0.038272
1 -0.128545  0.762088 -0.714816
2  0.201498 -0.734963  0.558397
3  1.563307 -1.186415  0.848246
4  0.205171  0.962514  0.037709

In [17]: df.iat[0,0]
Out[17]: -0.074171888537611502

In [18]: df.at[0,'A']
Out[18]: -0.074171888537611502

Correct way to delete cookies server-side

At the time of my writing this answer, the accepted answer to this question appears to state that browsers are not required to delete a cookie when receiving a replacement cookie whose Expires value is in the past. That claim is false. Setting Expires to be in the past is the standard, spec-compliant way of deleting a cookie, and user agents are required by spec to respect it.

Using an Expires attribute in the past to delete a cookie is correct and is the way to remove cookies dictated by the spec. The examples section of RFC 6255 states:

Finally, to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created.

The User Agent Requirements section includes the following requirements, which together have the effect that a cookie must be immediately expunged if the user agent receives a new cookie with the same name whose expiry date is in the past

  1. If [when receiving a new cookie] the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:

    1. ...
    2. ...
    3. Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
    4. Remove the old-cookie from the cookie store.
  2. Insert the newly created cookie into the cookie store.

A cookie is "expired" if the cookie has an expiry date in the past.

The user agent MUST evict all expired cookies from the cookie store if, at any time, an expired cookie exists in the cookie store.

Points 11-3, 11-4, and 12 above together mean that when a new cookie is received with the same name, domain, and path, the old cookie must be expunged and replaced with the new cookie. Finally, the point below about expired cookies further dictates that after that is done, the new cookie must also be immediately evicted. The spec offers no wiggle room to browsers on this point; if a browser were to offer the user the option to disable cookie expiration, as the accepted answer suggests some browsers do, then it would be in violation of the spec. (Such a feature would also have little use, and as far as I know it does not exist in any browser.)

Why, then, did the OP of this question observe this approach failing? Though I have not dusted off a copy of Internet Explorer to check its behaviour, I suspect it was because the OP's Expires value was malformed! They used this value:

expires=Thu, Jan 01 1970 00:00:00 UTC;

However, this is syntactically invalid in two ways.

The syntax section of the spec dictates that the value of the Expires attribute must be a

rfc1123-date, defined in [RFC2616], Section 3.3.1

Following the second link above, we find this given as an example of the format:

Sun, 06 Nov 1994 08:49:37 GMT

and find that the syntax definition...

  1. requires that dates be written in day month year format, not month day year format as used by the question asker.

    Specifically, it defines rfc1123-date as follows:

    rfc1123-date = wkday "," SP date1 SP time SP "GMT"
    

    and defines date1 like this:

    date1        = 2DIGIT SP month SP 4DIGIT
                 ; day month year (e.g., 02 Jun 1982)
    

and

  1. doesn't permit UTC as a timezone.

    The spec contains the following statement about what timezone offsets are acceptable in this format:

    All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception.

    What's more if we dig deeper into the original spec of this datetime format, we find that in its initial spec in https://tools.ietf.org/html/rfc822, the Syntax section lists "UT" (meaning "universal time") as a possible value, but does not list not UTC (Coordinated Universal Time) as valid. As far as I know, using "UTC" in this date format has never been valid; it wasn't a valid value when the format was first specified in 1982, and the HTTP spec has adopted a strictly more restrictive version of the format by banning the use of all "zone" values other than "GMT".

If the question asker here had instead used an Expires attribute like this, then:

expires=Thu, 01 Jan 1970 00:00:00 GMT;

then it would presumably have worked.

Create Map in Java

Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
hm.put(1, new Point2D.Double(50, 50));

Writing sqlplus output to a file

You may use the SPOOL command to write the information to a file.

Before executing any command type the following:

SPOOL <output file path>

All commands output following will be written to the output file.

To stop command output writing type

SPOOL OFF

Android java.exe finished with non-zero exit value 1

Well there can be many problems associated with it. First of all check whether you messed up with some file placements. for example what I did is I placed non xml file in anim folder, which isn't allowed. So check whether such things happened to you as well.

endforeach in loops?

It's the end statement for the alternative syntax:

foreach ($foo as $bar) :
    ...
endforeach;

Useful to make code more readable if you're breaking out of PHP:

<?php foreach ($foo as $bar) : ?>
    <div ...>
        ...
    </div>
<?php endforeach; ?>

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

This usually happen when you upgrade mysql. The installed mysql2 gem which was built on the old mysql libs cannot work with new libs. Just need to reinstall it.

Uninstall mysql2 with gem uninstall mysql2. Then install it with gem install mysql2

What, exactly, is needed for "margin: 0 auto;" to work?

For anybody just now hitting this question, and not being able to fix margin: 0 auto, here's something I discovered you may find useful: a table element with no specified width must have display: table and not display: block in order for margin: auto to do work. This may be obvious to some, as the combination of display: block and the default width value will give a table which expands to fill its container, but if you want the table to take it's "natural" width and be centered, you need display: table

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

Favicon dimensions?

No, you can't use a non-standard size or dimension, as it'd wreak havoc on peoples' browsers wherever the icons are displayed. You could make it 12x16 (with four pixels of white/transparent padding on the 12 pixel side) to preserve your aspect ratio, but you can't go bigger (well, you can, but the browser'll shrink it).

Where is adb.exe in windows 10 located?

It is located in the AppData hidden folder

C:\Users\[user]\AppData\Local\Android\sdk\platform-tools

From l33t's comment below you may use the following shortcut:

%LOCALAPPDATA%\Android\sdk\platform-tools

Insert some string into given string at given index in Python

Answer for Insert characters of string in other string al located positions

str1 = "ibuprofen"
str2 = "MEDICAL"
final_string=""
Value = 2
list2=[]
result=[str1[i:i+Value] for i in range(0, len(str1), Value)]
count = 0

for letter in result:
    if count < len(result)-1:
        final_string = letter + str2[count]
        list2.append(final_string)
    elif ((len(result)-1)==count):
        list2.append(letter + str2[count:len(str2)])
        break
    count += 1

print(''.join(list2))

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

How to make a edittext box in a dialog

Simplified version

final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Add a new task")
        .setMessage("What do you want to do next?")
        .setView(taskEditText)
        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String task = String.valueOf(taskEditText.getText());
                SQLiteDatabase db = mHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
                        null,
                        values,
                        SQLiteDatabase.CONFLICT_REPLACE);
                db.close();
                updateUI();
            }
        })
        .setNegativeButton("Cancel", null)
        .create();
dialog.show();
return true;

I have filtered my Excel data and now I want to number the rows. How do I do that?

I had the same need to fill up a column with a sequence series for each value on another column. I tried all the answers above and could not fix the problem. I solved it with a simple VBA macro.

My data have the same structure (but with 3000 rows):

  • N2 is the column on which the table is filtered;
  • N3 is the column where I wanted to fill a series;

A | B

N2 | N3

1 | 1

2 | 1

3 | 1

1 | 2

6 | 1

4 | 1

2 | 2

1 | 3

5 | 1

Here below the code:

> Sub Seq_N3() ' ' Seq_N3 Macro ' Sequence numbering of N3 based on N2 value
> do N2 
>     Dim N2 As Integer
>     Dim seq As Integer
> 
>         With ActiveSheet
>             
>             For N2 = 1 To 7 Step 1
>             seq = 1                 ' 
>             .Range("B2").Select     ' 
>             
>                 Do While ActiveCell.Offset(0, -1).Value2 <> 0
>                     
>                     If ActiveCell.Offset(0, -1).Value2 = N2 Then        
>                         ActiveCell.Value2 = seq                         
>                         seq = seq + 1                                   
>                         ActiveCell.Offset(1, 0).Select
>                     Else
>                         ActiveCell.Offset(1, 0).Select                  
>                     End If
>                     
>                 Loop
>                 
>             Next N2
>                    
>         End With End Sub

Hope it helps!

Make file echo displaying "$PATH" string

In the manual for GNU make, they talk about this specific example when describing the value function:

The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.

The syntax of the value function is:

 $(value variable)

Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)

The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:

 FOO = $PATH

 all:
         @echo $(FOO)
         @echo $(value FOO)

The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.

Spring-Security-Oauth2: Full authentication is required to access this resource

The client_id and client_secret, by default, should go in the Authorization header, not the form-urlencoded body.

  1. Concatenate your client_id and client_secret, with a colon between them: [email protected]:12345678.
  2. Base 64 encode the result: YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==
  3. Set the Authorization header: Authorization: Basic YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==

Determining if an Object is of primitive type

I'm late to the show, but if you're testing a field, you can use getGenericType:

import static org.junit.Assert.*;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

import org.junit.Test;

public class PrimitiveVsObjectTest {

    private static final Collection<String> PRIMITIVE_TYPES = 
            new HashSet<>(Arrays.asList("byte", "short", "int", "long", "float", "double", "boolean", "char"));

    private static boolean isPrimitive(Type type) {
        return PRIMITIVE_TYPES.contains(type.getTypeName());
    }

    public int i1 = 34;
    public Integer i2 = 34;

    @Test
    public void primitive_type() throws NoSuchFieldException, SecurityException {
        Field i1Field = PrimitiveVsObjectTest.class.getField("i1");
        Type genericType1 = i1Field.getGenericType();
        assertEquals("int", genericType1.getTypeName());
        assertNotEquals("java.lang.Integer", genericType1.getTypeName());
        assertTrue(isPrimitive(genericType1));
    }

    @Test
    public void object_type() throws NoSuchFieldException, SecurityException {
        Field i2Field = PrimitiveVsObjectTest.class.getField("i2");
        Type genericType2 = i2Field.getGenericType();
        assertEquals("java.lang.Integer", genericType2.getTypeName());
        assertNotEquals("int", genericType2.getTypeName());
        assertFalse(isPrimitive(genericType2));
    }
}

The Oracle docs list the 8 primitive types.

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Get a resource using getResource()

TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
  • leading slash to denote the root of the classpath
  • slashes instead of dots in the path
  • you can call getResource() directly on the class.

How to fix corrupt HDFS FIles

the solution here worked for me : https://community.hortonworks.com/articles/4427/fix-under-replicated-blocks-in-hdfs-manually.html

su - <$hdfs_user>

bash-4.1$ hdfs fsck / | grep 'Under replicated' | awk -F':' '{print $1}' >> /tmp/under_replicated_files 

-bash-4.1$ for hdfsfile in `cat /tmp/under_replicated_files`; do echo "Fixing $hdfsfile :" ;  hadoop fs -setrep 3 $hdfsfile; done

data.frame rows to a list

Eureka!

xy.list <- as.list(as.data.frame(t(xy.df)))

How to make a JFrame Modal in Swing java

The only code that have worked for me:

childFrame.setAlwaysOnTop(true);

This code should be called on the main/parent frame before making the child/modal frame visible. Your child/modal frame should also have this code:

parentFrame.setFocusableWindowState(false);
this.mainFrame.setEnabled(false);

Time in milliseconds in C

The standard C library provides timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer so you can get time in milliseconds.

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

Unlike clock, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep.

How to convert datetime format to date format in crystal report using C#?

This formula works for me:

// Converts CR TimeDate format to AssignDate for WeightedAverageDate calculation.

Date( Year({DWN00500.BUDDT}), Month({DWN00500.BUDDT}), Day({DWN00500.BUDDT}) ) - CDate(1899, 12, 30)

Detecting IE11 using CSS Capability/Feature Detection

Here's an answer for 2017 on, where you probably only care about distinguishing <=IE11 from >IE11 ("Edge"):

@supports not (old: ie) { /* code for not old IE here */ }

More demonstrative example:

body:before { content: 'old ie'; }
/**/@supports not (old: ie) {
body:before { content: 'not old ie'; }
/**/}

This works because IE11 doesn't actually even support @supports, and all other relevant browser/version combinations do.

How to get the value from the GET parameters?

Use dojo. No other solution on here is this short or as well-tested:

require(["dojo/io-query"], function(ioQuery){
    var uri = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ";
    var query = uri.substring(uri.indexOf("?") + 1, uri.length);
    var queryObject = ioQuery.queryToObject(query);
    console.log(queryObject.c); //prints m2-m3-m4-m5
});

How do you iterate through every file/directory recursively in standard C++?

You can make it even simpler with the new C++11 range based for and Boost:

#include <boost/filesystem.hpp>

using namespace boost::filesystem;    
struct recursive_directory_range
{
    typedef recursive_directory_iterator iterator;
    recursive_directory_range(path p) : p_(p) {}

    iterator begin() { return recursive_directory_iterator(p_); }
    iterator end() { return recursive_directory_iterator(); }

    path p_;
};

for (auto it : recursive_directory_range(dir_path))
{
    std::cout << it << std::endl;
}

Strip double quotes from a string in .NET

This worked for me

//Sentence has quotes
string nameSentence = "Take my name \"Wesley\" out of quotes";
//Get the index before the quotes`enter code here`
int begin = nameSentence.LastIndexOf("name") + "name".Length;
//Get the index after the quotes
int end = nameSentence.LastIndexOf("out");
//Get the part of the string with its quotes
string name = nameSentence.Substring(begin, end - begin);
//Remove its quotes
string newName = name.Replace("\"", "");
//Replace new name (without quotes) within original sentence
string updatedNameSentence = nameSentence.Replace(name, newName);

//Returns "Take my name Wesley out of quotes"
return updatedNameSentence;

Return JSON for ResponseEntity<String>

An alternative solution is to use a wrapper for the String, for instances this:

public class StringResponse {
    private String response;
    public StringResponse(String response) {
        this.response = response;
    }
    public String getResponse() {
        return response;
    }
}

Then return this in your controller's methods:

ResponseEntity<StringResponse>

SQLAlchemy IN clause

Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.

import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]   
query = sa.text(""" 
                SELECT *
                FROM my_table
                WHERE col1 IN :values; 
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)

What's the difference between @Component, @Repository & @Service annotations in Spring?

all these annotations are type of stereo type type of annotation,the difference between these three annotations are

  • If we add the @Component then it tells the role of class is a component class it means it is a class consisting some logic,but it does not tell whether a class containing a specifically business or persistence or controller logic so we don't use directly this @Component annotation
  • If we add @Service annotation then it tells that a role of class consisting business logic
  • If we add @Repository on top of class then it tells that a class consisting persistence logic
  • Here @Component is a base annotation for @Service,@Repository and @Controller annotations

for example

package com.spring.anno;
@Service
public class TestBean
{
    public void m1()
    {
       //business code
    }
}

package com.spring.anno;
@Repository
public class TestBean
{
    public void update()
    {
       //persistence code
    }
}
  • whenever we adds the @Service or @Repositroy or @Controller annotation by default @Component annotation is going to existence on top of the class

(HTML) Download a PDF file instead of opening them in browser when clicked

If you are using HTML5 (and i guess now a days everyone uses that), there is an attribute called download.

ex. <a href="somepathto.pdf" download="filename">

here filename is optional, but if provided, it will take this name for downloaded file.

What is the Oracle equivalent of SQL Server's IsNull() function?

Also use NVL2 as below if you want to return other value from the field_to_check:

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

In Python, how do I use urllib to see if a website is 404 or 200?

import urllib2

try:
    fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
    data = fileHandle.read()
    fileHandle.close()
except urllib2.URLError, e:
    print 'you got an error with the code', e

Find object by id in an array of JavaScript objects

You can use filters,

  function getById(id, myArray) {
    return myArray.filter(function(obj) {
      if(obj.id == id) {
        return obj 
      }
    })[0]
  }

get_my_obj = getById(73, myArray);

XSS filtering function in PHP

I found a solution for my problem with the posts with german umlaut. To provide from totally cleaning (killing) the posts, i encode the incoming data:

    *$data = utf8_encode($data);
    ... function ...*

And at last i decode the output to get correct signs:

    *$data = utf8_decode($data);*

Now the post go through the filter function and i get a correct result...

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

How to select the last column of dataframe

df.T.iloc[-1]

df.T.tail(1)

pd.Series(df.values[:, -1], name=df.columns[-1])

How to reload .bash_profile from the command line?

I like the fact that after you have just edited the file, all you need to do is type:

. !$

This sources the file you had just edited in history. See What is bang dollar in bash.

Bootstrap 4 Dropdown Menu not working?

Make sure to include the Bootstrap CSS either via the Bootstrap CDN or download it and link it locally

How to create two columns on a web page?

The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.

  • They perform better than CSS
  • They work on all browsers without any fuss
  • You can debug them easily with the border=1 attribute

Attach to a processes output for viewing

I wanted to remotely watch a yum upgrade process that had been run locally, so while there were probably more efficient ways to do this, here's what I did:

watch cat /dev/vcsa1

Obviously you'd want to use vcsa2, vcsa3, etc., depending on which terminal was being used.

So long as my terminal window was of the same width as the terminal that the command was being run on, I could see a snapshot of their current output every two seconds. The other commands recommended elsewhere did not work particularly well for my situation, but that one did the trick.

How to implement a Navbar Dropdown Hover in Bootstrap v4?

Neither of the top solutions worked for me.

This works perfectly, keeps submenus open while browsing, add uses the native Bootstrap javascript.

// Mouse over
$('body').on('mouseover', '.dropdown', function(e) { 
    $(this).children('.dropdown-toggle').dropdown('show');
});

// Mouse leave
$('body').on('mouseleave', '.dropdown', function(e) { 
    $(this).children('.dropdown-toggle').dropdown('hide');
});

CSS Printing: Avoiding cut-in-half DIVs between pages?

I have the same problem bu no solution yet. page-break-inside does not work on browsers but Opera. An alternative might be to use page-break-after: avoid; on all child elements of the div to keep togehter ... but in my tests, the avoid-Attribute does not work eg. in Firefox ...

What works in all ppular browsers are forced page breaks using eg. page-break-after: always

How to create range in Swift?

If anyone want to create NSRange object can create as:

let range: NSRange = NSRange.init(location: 0, length: 5)

this will create range with position 0 and length 5

How to fast get Hardware-ID in C#?

The following approach was inspired by this answer to a related (more general) question.

The approach is to read the MachineGuid value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography. This value is generated during OS installation.

There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid value.

However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.

public string GetMachineGuid()
{
   string location = @"SOFTWARE\Microsoft\Cryptography";
   string name = "MachineGuid";

   using (RegistryKey localMachineX64View = 
       RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
   {
       using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
       {
           if (rk == null)
               throw new KeyNotFoundException(
                   string.Format("Key Not Found: {0}", location));

           object machineGuid = rk.GetValue(name);
           if (machineGuid == null)
               throw new IndexOutOfRangeException(
                   string.Format("Index Not Found: {0}", name));

           return machineGuid.ToString();
       }
   }
}

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

Generating CSV file for Excel, how to have a newline inside a value

Test this: It fully works for me: Put the following lines in a xxxx.csv file

hola_x,="este es mi text1"&CHAR(10)&"I sigo escribiendo",hola_a

hola_y,="este es mi text2"&CHAR(10)&"I sigo escribiendo",hola_b

hola_z,="este es mi text3"&CHAR(10)&"I sigo escribiendo",hola_c

Open with excel.

in some cases will open directly otherwise will need to use column to data conversion. expand the column width and hit the wrap text button. or format cells and activate wrap text.

and thanks for the other suggestions, but they did not work for me. I am in a pure windows env, and did not want to play with unicode or other funny thing.

This way you putting a formula from csv to excel. It may be many uses for this method of work. (note the = before the quotes)

pd:In your suggestions please put some samples of the data not only the code.

Get Substring between two characters using javascript

You can try this

var mySubString = str.substring(
    str.lastIndexOf(":") + 1, 
    str.lastIndexOf(";")
);

Getting the current Fragment instance in the viewpager

Override setPrimaryItem from your FragmentPagerAdapter: the object is the visible fragment:

 @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            if (mCurrentFragment != object) {
                mCurrentFragment = (LeggiCapitoloFragment) object;
            }
            super.setPrimaryItem(container, position, object);
        }

REST API Best practices: Where to put parameters?

It's a very interesting question.

You can use both of them, there's not any strict rule about this subject, but using URI path variables has some advantages:

  • Cache: Most of the web cache services on the internet don't cache GET request when they contains query parameters. They do that because there are a lot of RPC systems using GET requests to change data in the server (fail!! Get must be a safe method)

But if you use path variables, all of this services can cache your GET requests.

  • Hierarchy: The path variables can represent hierarchy: /City/Street/Place

It gives the user more information about the structure of the data.

But if your data doesn't have any hierarchy relation you can still use Path variables, using comma or semi-colon:

/City/longitude,latitude

As a rule, use comma when the ordering of the parameters matter, use semi-colon when the ordering doesn't matter:

/IconGenerator/red;blue;green

Apart of those reasons, there are some cases when it's very common to use query string variables:

  • When you need the browser to automatically put HTML form variables into the URI
  • When you are dealing with algorithm. For example the google engine use query strings:

http:// www.google.com/search?q=rest

To sum up, there's not any strong reason to use one of this methods but whenever you can, use URI variables.

Capture close event on Bootstrap Modal

Alternative way to check would be:

if (!$('#myModal').is(':visible')) {
    // if modal is not shown/visible then do something
}

How to check for an undefined or null variable in JavaScript?

this is the only case in which == and != should be used:

if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')

For any other comparisons, the strict comparators (=== and !==) should be used.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Ignoring SSL certificate in Apache HttpClient 4.3

You can use following code snippet for get the HttpClient instance without ssl certification checking.

private HttpClient getSSLHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        LogLoader.serverLog.trace("In getSSLHttpClient()");

        SSLContext context = SSLContext.getInstance("SSL");

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        context.init(null, new TrustManager[] { tm }, null);

        HttpClientBuilder builder = HttpClientBuilder.create();
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context);
        builder.setSSLSocketFactory(sslConnectionFactory);

        PlainConnectionSocketFactory plainConnectionSocketFactory = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory).register("http", plainConnectionSocketFactory).build();

        PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
        ccm.setMaxTotal(BaseConstant.CONNECTION_POOL_SIZE);
        ccm.setDefaultMaxPerRoute(BaseConstant.CONNECTION_POOL_SIZE);
        builder.setConnectionManager((HttpClientConnectionManager) ccm);

        builder.disableRedirectHandling();

        LogLoader.serverLog.trace("Out getSSLHttpClient()");

        return builder.build();
    }

Is it correct to use alt tag for an anchor link?

For anchors, you should use title instead. alt is not valid atribute of a. See http://w3schools.com/tags/tag_a.asp

Opacity of background-color, but not the text

I've created that effect on my blog Landman Code.

What I did was

_x000D_
_x000D_
#Header {
  position: relative;
}
#Header H1 {
  font-size: 3em;
  color: #00FF00;
  margin:0;
  padding:0;
}
#Header H2 {
  font-size: 1.5em;
  color: #FFFF00;
  margin:0;
  padding:0;
}
#Header .Background {
  background: #557700;
  filter: alpha(opacity=30);
  filter: progid: DXImageTransform.Microsoft.Alpha(opacity=30);
  -moz-opacity: 0.30;
  opacity: 0.3;
  zoom: 1;
}
#Header .Background * {
  visibility: hidden; // hide the faded text
}
#Header .Foreground {
  position: absolute; // position on top of the background div
  left: 0;
  top: 0;
}
_x000D_
<div id="Header">
  <div class="Background">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
  <div class="Foreground">
    <h1>Title</h1>
    <h2>Subtitle</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

The important thing that every padding/margin and content must be the same in both the .Background as .Foreground.

Android ListView with onClick items

for what kind of Hell implementing Parcelable ?

he is passing to adapter String[] so

  • get item(String) at position
  • create intent
  • put it as extra
  • start activity
  • in activity get extra

to store product list you can use here HashMap (for example as STATIC object)

example class describing product:

public class Product {
    private String _name;
    private String _description;
    private int _id

    public Product(String name, String description,int id) {
        _name = name;
        _desctription = description;
        _id = id;
    }

    public String getName() {
        return _name;
    }

    public String getDescription() {
        return _description;
    }
}

Product dell = new Product("dell","this is dell",1);

HashMap<String,Product> _hashMap = new HashMap<>();
_hashMap.put(dell.getName(),dell);

then u pass to adapter set of keys as:

String[] productNames =  _hashMap.keySet().toArray(new String[_hashMap.size()]);

when in adapter u return view u set listener like this for example:

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

     Context context = parent.getContext(); 

     String itemName = getItem(position)

     someView.setOnClikListener(new MyOnClickListener(context, itemName));

 }


 private class MyOnClickListener implements View.OnClickListener { 

     private  String _itemName; 
     private  Context _context

     public MyOnClickListener(Context context, String itemName) {
         _context = context;
         _itemName = itemName; 
     }

     @Override 
     public void onClick(View view) {
         //------listener onClick example method body ------
         Intent intent = new Intent(_context, SomeClassToHandleData.class);
         intent.putExtra(key_to_product_name,_itemName);
         _context.startActivity(intent);
     }
 }

then in other activity:

@Override 
public void onCreate(Bundle) {

    String productName = getIntent().getExtra(key_to_product_name);
    Product product = _hashMap.get(productName);

}

*key_to_product_name is a public static String to serve as key for extra

ps. sorry for typo i was in hurry :) ps2. this shoud give you a idea how to do it ps3. when i will have more time i I'll add a detailed description

MY COMMENT:

  • DO NOT USE ANY SWITCH STATEMENT
  • DO NOT CREATE SEPARATE ACTIVITIES FOR EACH PRODUCT ( U NEED ONLY ONE)

AttributeError("'str' object has no attribute 'read'")

If you get a python error like this:

AttributeError: 'str' object has no attribute 'some_method'

You probably poisoned your object accidentally by overwriting your object with a string.

How to reproduce this error in python with a few lines of code:

#!/usr/bin/env python
import json
def foobar(json):
    msg = json.loads(json)

foobar('{"batman": "yes"}')

Run it, which prints:

AttributeError: 'str' object has no attribute 'loads'

But change the name of the variablename, and it works fine:

#!/usr/bin/env python
import json
def foobar(jsonstring):
    msg = json.loads(jsonstring)

foobar('{"batman": "yes"}')

This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.

Overflow Scroll css is not working in the div

I edited your: Fiddle

html, body{ margin:0; padding:0; overflow:hidden; height:100% }
.header { margin: 0 auto; width:500px; height:30px; background-color:#dadada;}
.wrapper{ margin: 0 auto; width:500px; overflow:scroll; height: 100%;}

Giving the html-tag a 100% height is the solution. I also deleted the container div. You don't need it when your layout stays like this.

How to compare strings in Bash

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash, IMO.

Here are some examples in Bash 4+:

Example 1, check for 'yes' in string (case insensitive):

    if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

    if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive):

     if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

     if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

     if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

     if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match:

     if [ "$a" = "$b" ] ;then

Enjoy.

Creating default object from empty value in PHP?

This message has been E_STRICT for PHP <= 5.3. Since PHP 5.4, it was unluckilly changed to E_WARNING. Since E_WARNING messages are useful, you don't want to disable them completely.

To get rid of this warning, you must use this code:

if (!isset($res)) 
    $res = new stdClass();

$res->success = false;

This is fully equivalent replacement. It assures exactly the same thing which PHP is silently doing - unfortunatelly with warning now - implicit object creation. You should always check if the object already exists, unless you are absolutely sure that it doesn't. The code provided by Michael is no good in general, because in some contexts the object might sometimes be already defined at the same place in code, depending on circumstances.

Handling NULL values in Hive

Try to include length > 0 as well.

column1 is not NULL AND column1 <> '' AND length(column1) > 0 

How do you make Vim unhighlight what you searched for?

/lkjasdf has always been faster than :noh for me.

label or @html.Label ASP.net MVC 4

Depends on what your are doing.

If you have SPA (Single-Page Application) the you can use:

<input id="txtName" type="text" />

Otherwise using Html helpers is recommended, to get your controls bound with your model.

Is there any way to call a function periodically in JavaScript?

Everyone has a setTimeout/setInterval solution already. I think that it is important to note that you can pass functions to setInterval, not just strings. Its actually probably a little "safer" to pass real functions instead of strings that will be "evaled" to those functions.

// example 1
function test() {
  alert('called');
}
var interval = setInterval(test, 10000);

Or:

// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);

Scala how can I count the number of occurrences in a list

If you want to use it like list.count(2) you have to implement it using an Implicit Class.

implicit class Count[T](list: List[T]) {
  def count(n: T): Int = list.count(_ == n)
}

List(1,2,4,2,4,7,3,2,4).count(2)  // returns 3
List(1,2,4,2,4,7,3,2,4).count(5)  // returns 0

release Selenium chromedriver.exe from memory

I am using Protractor with directConnect. Disabling the "--no-sandbox" option fixed the issue for me.

// Capabilities to be passed to the webdriver instance.
capabilities: {
  'directConnect': true,
  'browserName': 'chrome',
  chromeOptions: {
      args: [
        //"--headless",
        //"--hide-scrollbars",
        "--disable-software-rasterizer",
        '--disable-dev-shm-usage',
        //"--no-sandbox",
        "incognito",
        "--disable-gpu",
        "--window-size=1920x1080"]
  }
},

Convert one date format into another in PHP

The easiest way to do this is

$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('m/d/Y');

You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.

This also avoids the use of strtotime, which can be hard to work with at times.

If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:

$now = new DateTime();
$timestring = $now->format('Y-m-d h:i:s');

This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.

Where is the IIS Express configuration / metabase file found?

Since the introduction of Visual Studio 2015, this location has changed and is added into your solution root under the following location:

C:\<Path\To\Solution>\.vs\config\applicationhost.config

I hope this saves you some time!

PostgreSQL: How to change PostgreSQL user password?

I believe the best way to change the password is simply to use:

\password

in the Postgres console.

Per ALTER USER documentation:

Caution must be exercised when specifying an unencrypted password with this command. The password will be transmitted to the server in cleartext, and it might also be logged in the client's command history or the server log. psql contains a command \password that can be used to change a role's password without exposing the cleartext password.

Note: ALTER USER is an alias for ALTER ROLE

Comprehensive methods of viewing memory usage on Solaris

Here are the basics. I'm not sure that any of these count as "clear and simple" though.

ps(1)

For process-level view:

$ ps -opid,vsz,rss,osz,args
  PID  VSZ  RSS   SZ COMMAND
 1831 1776 1008  222 ps -opid,vsz,rss,osz,args
 1782 3464 2504  433 -bash
$

vsz/VSZ: total virtual process size (kb)

rss/RSS: resident set size (kb, may be inaccurate(!), see man)

osz/SZ: total size in memory (pages)

To compute byte size from pages:

$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"

vmstat(1M)

$ vmstat 5 5 
 kthr      memory            page            disk          faults      cpu
 r b w   swap  free  re  mf pi po fr de sr rm s3 -- --   in   sy   cs us sy id
 0 0 0 535832 219880  1   2  0  0  0  0  0 -0  0  0  0  402   19   97  0  1 99
 0 0 0 514376 203648  1   4  0  0  0  0  0  0  0  0  0  402   19   96  0  1 99
^C

prstat(1M)

   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP       
  1852 martin   4840K 3600K cpu0    59    0   0:00:00 0.3% prstat/1
  1780 martin   9384K 2920K sleep   59    0   0:00:00 0.0% sshd/1
  ...

swap(1)

"Long listing" and "summary" modes:

$ swap -l
swapfile             dev  swaplo blocks   free
/dev/zvol/dsk/rpool/swap 256,1      16 1048560 1048560
$ swap -s 
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$

top(1)

An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported". More recent binary packages available from sunfreeware.com or blastwave.org.

load averages:  0.02,  0.00,  0.00;                      up 2+12:31:38                                                                                            08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle,  0.0% user,  2.0% kernel,  0.0% iowait,  0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap

   PID USERNAME LWP PRI NICE  SIZE   RES STATE    TIME    CPU COMMAND
  1898 martin     1  54    0 3336K 1808K cpu      0:00  0.96% top
     7 root      11  59    0   10M 7912K sleep    0:09  0.02% svc.startd

sar(1M)

And just what's wrong with sar? :)

Display Image On Text Link Hover CSS Only

From w3 schools:

<style>
/* Tooltip container */
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  /* Position the tooltip text - see examples below! */
  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
</style>

<div class="tooltip">Hover over me
  <img src="/pathtoimage" class="tooltiptext">
</div>

Sounds like about what you want

"Non-static method cannot be referenced from a static context" error

setLoanItem() isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.

Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.

You probably want to pass in a media object on which to call the method:

public void loanItem(Media m) {
    m.setLoanItem("Yes");
}

Composer update memory limit

If there's enough memory composer would internally consume it and run without any problem. No need to specifically tell the composer to do it.

Have you tried to increase your swap memory, coz it worked for me. I increased the swap memory to 4096Mb (4GB) and now it all looks great to me.

first use "sudo free" to see available memory and swap memory. and configure swap as,

For Debian:

sudo fallocate -l 4G /swapfile
sudo dd if=/dev/zero of=/swapfile bs=4096k count=1048
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

to make it permenant add this to /etc/fstab file, /swapfile swap swap defaults 0 0

For CentOS :

[root@myserver]:/# cd /var
[root@myserver]:/var# touch swap.img
[root@myserver]:/var# chmod 600 swap.img
[root@myserver]:/var# mkswap /var/swap.img

[root@myserver]:/var# dd if=/dev/zero of=/var/swap.img bs=4096k count=1000
[root@myserver]:/var# mkswap /var/swap.img 
[root@myserver]:/var# swapon /var/swap.img

you can increase your swap memory by changin bs= 1024k or 2048k or 8096k depending on your physical volume size. use 'swapon' and swapoff commands to see the difference.

check 'swappiness' (60 should do good,)

cat /proc/sys/vm/swappiness

Git on Windows: How do you set up a mergetool?

I had to drop the extra quoting using msysGit on windows 7, not sure why.

git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge $BASE $LOCAL $REMOTE $MERGED'

Time calculation in php (add 10 hours)?

$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.

see DateTime Class (PHP 5 >= 5.2.0)

When would you use the different git merge strategies?

I'm not familiar with resolve, but I've used the others:

Recursive

Recursive is the default for non-fast-forward merges. We're all familiar with that one.

Octopus

I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.

An octopus branch merges multiple heads in one commit as long as it can do it cleanly.

For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).

A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):

series of recursive merges

However, a single octopus merge would look like this:

commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...

octopus merge

Ours

Ours == I want to pull in another head, but throw away all of the changes that head introduces.

This keeps the history of a branch without any of the effects of the branch.

(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours)

Subtree

Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.

How can I strip first and last double quotes?

If you can't assume that all the strings you process have double quotes you can use something like this:

if string.startswith('"') and string.endswith('"'):
    string = string[1:-1]

Edit:

I'm sure that you just used string as the variable name for exemplification here and in your real code it has a useful name, but I feel obliged to warn you that there is a module named string in the standard libraries. It's not loaded automatically, but if you ever use import string make sure your variable doesn't eclipse it.

Android ADB doesn't see device

I tried all the ways listed on the web for a whole day, but I didn't get any solutions. Then, I followed a link and in just two minutes my problem was solved!

By the way, it's for Windows users!

Find out the vendor id of the device from device manager.
To do this, connect the OTG port to the USB port of your computer.
Go to Start Menu and right-click on “My Computer” and chose “Properties”.
Select the “Devices” option which will open “Device Manager”.
Select your device (mostly in USB devices or Other devices) and right-click and choose “Properties”.
Choose the “Details” tab and select “Hardware Ids” from the property dropdown, you can see the hardware id, in my case it was x2207 .
Open android_winusb.inf and add these lines:

;<Device name>   in our case I gave MK808
%SingleAdbInterface%        = USB_INSTALL, USB\VID_2207&PID_0010&MI_01
%CompositeAdbInterface%     = USB_INSTALL, USB\VID_2207&PID_0010&REV_0222&MI_01

Open C:\Users\.android\adb_usb.ini and add the following entry

0x<device id>  .. in our case it is 0x2207

Restart ADB by

adb kill-server
adb start-server

Now ADB should recognize the device.

Finding Variable Type in JavaScript

I find it frustrating that typeof is so limited. Here’s an improved version:

var realtypeof = function (obj) {
    switch (typeof(obj)) {
        // object prototypes
        case 'object':
            if (obj instanceof Array)
                return '[object Array]';
            if (obj instanceof Date)
                return '[object Date]';
            if (obj instanceof RegExp)
                return '[object regexp]';
            if (obj instanceof String)
                return '[object String]';
            if (obj instanceof Number)
                return '[object Number]';

            return 'object';
        // object literals
        default:
            return typeof(obj);
    }   
};

sample test:

realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]" 

libpng warning: iCCP: known incorrect sRGB profile

Libpng-1.6 is more stringent about checking ICC profiles than previous versions. You can ignore the warning. To get rid of it, remove the iCCP chunk from the PNG image.

Some applications treat warnings as errors; if you are using such an application you do have to remove the chunk. You can do that with any of a variety of PNG editors such as ImageMagick's

convert in.png out.png

To remove the invalid iCCP chunk from all of the PNG files in a folder (directory), you can use mogrify from ImageMagick:

mogrify *.png

This requires that your ImageMagick was built with libpng16. You can easily check it by running:

convert -list format | grep PNG

If you'd like to find out which files need to be fixed instead of blindly processing all of them, you can run

pngcrush -n -q *.png

where the -n means don't rewrite the files and -q means suppress most of the output except for warnings. Sorry, there's no option yet in pngcrush to suppress everything but the warnings.


Binary Releases of ImageMagick are here


For Android Projects (Android Studio) navigate into res folder.

For example:

C:\{your_project_folder}\app\src\main\res\drawable-hdpi\mogrify *.png

Converting a string to a date in JavaScript

I wrote a reusable function that i use when i get date strings from the server.
you can pass your desired delimiter( / - etc..) that separates the day month and year in order to use the split() method.
you can see & test it on this working example.

<!DOCTYPE html>
<html>
  <head>
    <style>
    </style>
  </head>
  <body>
    <div>
      <span>day:
      </span> 
      <span id='day'>
      </span>
    </div>
    <div>
      <span>month:
      </span> 
      <span id='month'>
      </span>
    </div>
    <div>
      <span>year:
      </span> 
      <span id='year'>
      </span>
    </div>
    <br/>
    <input type="button" id="" value="convert" onClick="convert('/','28/10/1980')"/>
    <span>28/10/1980
    </span>
    <script>
      function convert(delimiter,dateString)
      {
        var splitted = dateString.split('/');
        // create a new date from the splitted string 
        var myDate = new Date(splitted[2],splitted[1],splitted[0]);
        // now you can access the Date and use its methods 
        document.getElementById('day').innerHTML = myDate.getDate();
        document.getElementById('month').innerHTML = myDate.getMonth();
        document.getElementById('year').innerHTML = myDate.getFullYear();
      }
    </script>
  </body>
</html>

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Found another (manual) answer which worked well for me

  1. Select the column.
  2. Choose Data tab
  3. Text to Columns - opens new box
  4. (choose Delimited), Next
  5. (uncheck all boxes, use "none" for text qualifier), Next
  6. use the ymd option from the Date dropdown.
  7. Click Finish

Div height 100% and expands to fit content

Set the height to auto and min-height to 100%. This should solve it for most browsers.

body {
  position: relative;
  height: auto;
  min-height: 100% !important;
}

How to call Android contacts list?

-> Add a permission to read contacts data to your application manifest.

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

-> Use Intent.Action_Pick in your Activity like below

Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);

-> Then Override the onActivityResult()

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // check whether the result is ok
        if (resultCode == RESULT_OK) {
            // Check for the request code, we might be usign multiple startActivityForReslut
            switch (requestCode) {
            case RESULT_PICK_CONTACT:
               Cursor cursor = null;
        try {
            String phoneNo = null ;
            String name = null;           
            Uri uri = data.getData();            
            cursor = getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();           
            int  phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            phoneNo = cursor.getString(phoneIndex); 

            textView2.setText(phoneNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
                break;
            }
        } else {
            Log.e("MainActivity", "Failed to pick contact");
        }
    }

This will work check it out

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');