Programs & Examples On #Sequences

A sequence is any type for which there is a bijective relation between the integers `0..n` and the elements of the sequence, and the elements may be accessed in the order `0..n`, where `n` is the number of elements in the sequence.

List all sequences in a Postgres db 8.1 with SQL

after a little bit of pain, i got it.

the best way to achieve this is to list all tables

select * from pg_tables where schemaname = '<schema_name>'

and then, for each table, list all columns with attributes

select * from information_schema.columns where table_name = '<table_name>'

then, for each column, test if it has a sequence

select pg_get_serial_sequence('<table_name>', '<column_name>')

and then, get the information about this sequence

select * from <sequence_name>

How to write the Fibonacci Sequence?

Basically translated from Ruby:

def fib(n):
    a = 0
    b = 1
    for i in range(1,n+1):
            c = a + b
            print c
            a = b
            b = c

...

Can someone explain __all__ in Python?

From (An Unofficial) Python Reference Wiki:

The public names defined by a module are determined by checking the module's namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module's namespace which do not begin with an underscore character ("_"). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

Changing the row height of a datagridview

dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
}

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You have mentioned "user" twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:

FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author\_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified\_by = **user2**.id
WHERE article.id = '1'

(You may need something different - I guessed which user is which, but the SQL engine won't guess.)

Also, maybe you only needed one "user". Who knows?

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

Maybe you can change your buildToolsVersion num.

this is my problem:

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'D:\ProgramTools\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1

my build.gradle:

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0"

    defaultConfig {
        applicationId "com.pioneers.recyclerviewitemanimation"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

I just change buildToolsVersion to buildToolsVersion "23.0.2" and the problem was solved.

How to handle calendar TimeZones using Java?

It looks like your TimeStamp is being set to the timezone of the originating system.

This is deprecated, but it should work:

cal.setTimeInMillis(ts_.getTime() - ts_.getTimezoneOffset());

The non-deprecated way is to use

Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)

but that would need to be done on the client side, since that system knows what timezone it is in.

anaconda/conda - install a specific package version

There is no version 1.3.0 for rope. 1.3.0 refers to the package cached-property. The highest available version of rope is 0.9.4.

You can install different versions with conda install package=version. But in this case there is only one version of rope so you don't need that.

The reason you see the cached-property in this listing is because it contains the string "rope": "cached-p rope erty"

py35_0 means that you need python version 3.5 for this specific version. If you only have python3.4 and the package is only for version 3.5 you cannot install it with conda.

I am not quite sure on the defaults either. It should be an indication that this package is inside the default conda channel.

How to replace a hash key with another key

you can do

hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}

This should work for your case!

Viewing localhost website from mobile device

Try this https://ngrok.com/docs#expose

Just run ngrok 3000 , 3000 is the port number you want to expose to the internet. You can insert the port number which you want to expose, for rails its 3000. This will tunnel your localhost to the internet and you will be able to view your local host from anywhere

Symfony - generate url with parameter in controller

If you want absolute urls, you have the third parameter.

$product_url = $this->generateUrl('product_detail', 
    array(
        'slug' => 'slug'
    ),
    UrlGeneratorInterface::ABSOLUTE_URL
);

Remember to include UrlGeneratorInterface.

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

Test if a string contains any of the strings from an array

Try this:

if (Arrays.asList(item1, item2, item3).stream().anyMatch(string::contains))

How to convert map to url query string?

Update June 2016

Felt compelled to add an answer having seen far too many SOF answers with dated or inadequate answers to very common problem - a good library and some solid example usage for both parse and format operations.

Use org.apache.httpcomponents.httpclient library. The library contains this org.apache.http.client.utils.URLEncodedUtils class utility.

For example, it is easy to download this dependency from Maven:

 <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
 </dependency>

For my purposes I only needed to parse (read from query string to name-value pairs) and format (read from name-value pairs to query string) query strings. However, there are equivalents for doing the same with a URI (see commented out line below).

// Required imports

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

// code snippet

public static void parseAndFormatExample() throws UnsupportedEncodingException {
        final String queryString = "nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk";
        System.out.println(queryString);
        // => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk

        final List<NameValuePair> params =
                URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
        // List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");

        for (final NameValuePair param : params) {
            System.out.println(param.getName() + " : " + param.getValue());
            // => nonce : 12345
            // => redirectCallbackUrl : http://www.bbc.co.uk
        }

        final String newQueryStringEncoded =
                URLEncodedUtils.format(params, StandardCharsets.UTF_8);


        // decode when printing to screen
        final String newQueryStringDecoded =
                URLDecoder.decode(newQueryStringEncoded, StandardCharsets.UTF_8.toString());
        System.out.println(newQueryStringDecoded);
        // => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk
    }

This library did exactly what I needed and was able to replace some hacked custom code.

What's wrong with nullable columns in composite primary keys?

Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input.

Per definition, NULL cannot be part of a successful comparison. Even a comparison to itself (NULL = NULL) will fail. This means a key containing NULL would not work.

Additonally, NULL is allowed in a foreign key, to mark an optional relationship.(*) Allowing it in the PK as well would break this.


(*)A word of caution: Having nullable foreign keys is not clean relational database design.

If there are two entities A and B where A can optionally be related to B, the clean solution is to create a resolution table (let's say AB). That table would link A with B: If there is a relationship then it would contain a record, if there isn't then it would not.

Save and load weights in keras

Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :

enter image description here

Why is there an unexplainable gap between these inline-block div elements?

simply add a border: 2px solid #e60000; to your 2nd div tag CSS.

Definitely it works

#Div2Id {
    border: 2px solid #e60000; --> color is your preference
}

What is the difference between Google App Engine and Google Compute Engine?

To put it simply: compute engine gives you a server which you have full control/responsibility for. You have direct access to the operating system, and you install all the software that you want, which is usually a web server, database, etc...

In app engine you don't manage the operating system of any of the underlying software. You only upload code (Java, PHP, Python, or Go) and voila - it just runs...

App engine saves tons of headache, especially for inexperienced people but it has 2 significant drawbacks: 1. more expensive (but it does have a free quota which compute engine doesn't) 2. you have less control, thus certain things are just not possible, or only possible in one specific way (for example saving and writing files).

How do you remove Subversion control for a folder?

Another (simpler) Linux solution:

rm -r `find /path/to/foo -name .svn`

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

import the HttpClientModule in your app.module.ts

import {HttpClientModule} from '@angular/common/http';

...
@NgModule({
...
  imports: [
    //other content,
    HttpClientModule
  ]
})

Sending a file over TCP sockets in Python

Client need to notify that it finished sending, using socket.shutdown (not socket.close which close both reading/writing part of the socket):

...
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()

UPDATE

Client sends Hello server! to the server; which is written to the file in the server side.

s.send("Hello server!")

Remove above line to avoid it.

How to iterate over a column vector in Matlab?

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

m = [1:numel(list)]';
elm = list.*m;

vectorized algorithms in matlab are in general much faster.

Basic example of using .ajax() with JSONP?

There is even easier way how to work with JSONP using jQuery

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.

For more detail refer to the jQuery.getJSON documentation.

How does String substring work in Swift

Came across this fairly short and simple way of achieving this.

var str = "Hello, World"
let arrStr = Array(str)
print(arrStr[0..<5]) //["H", "e", "l", "l", "o"]
print(arrStr[7..<12]) //["W", "o", "r", "l", "d"]
print(String(arrStr[0..<5])) //Hello
print(String(arrStr[7..<12])) //World

Fastest Convert from Collection to List<T>

You could try:

List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.ToArray());

Not sure if .ToArray() is available for the collection. If you do use the code you posted, make sure you initialize the List with the number of existing elements:

List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.Count);  // or .Length

How do I get the current date in JavaScript?

Use new Date() to generate a new Date object containing the current date and time.

_x000D_
_x000D_
var today = new Date();_x000D_
var dd = String(today.getDate()).padStart(2, '0');_x000D_
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!_x000D_
var yyyy = today.getFullYear();_x000D_
_x000D_
today = mm + '/' + dd + '/' + yyyy;_x000D_
document.write(today);
_x000D_
_x000D_
_x000D_

This will give you today's date in the format of mm/dd/yyyy.

Simply change today = mm +'/'+ dd +'/'+ yyyy; to whatever format you wish.

How to make a cross-module variable?

I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__ module, it will be accessible as if a global from any other module that includes __builtin__ -- which is all of them, by default.

a.py contains

print foo

b.py contains

import __builtin__
__builtin__.foo = 1
import a

The result is that "1" is printed.

Edit: The __builtin__ module is available as the local symbol __builtins__ -- that's the reason for the discrepancy between two of these answers. Also note that __builtin__ has been renamed to builtins in python3.

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

Just notice that if you work with Fragments using ViewPager, it's pretty easy. You only need to call this method: setOffscreenPageLimit().

Accordign to the docs:

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.

Similar issue here

Error inflating class android.support.v7.widget.Toolbar?

For me it worked after I did:

  • Cleaning solution.
  • Deleting the app from the phone I've debugged it at.
  • Closing Visual Studio.
  • Deleting folders /bin/ and /obj/ in android projects.
  • Launching solution again.

When do I use the PHP constant "PHP_EOL"?

Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.

Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.

How to read one single line of csv data in Python?

you could get just the first row like:

with open('some.csv', newline='') as f:
  csv_reader = csv.reader(f)
  csv_headings = next(csv_reader)
  first_line = next(csv_reader)

Display date in dd/mm/yyyy format in vb.net

First, uppercase MM are months and lowercase mm are minutes.

You have to pass CultureInfo.InvariantCulture to ToString to ensure that / as date separator is used since it would normally be replaced with the current culture's date separator:

MsgBox(dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture))

Another option is to escape that custom format specifier by embedding the / within ':

dt.ToString("dd'/'MM'/'yyyy")

MSDN: The "/" Custom Format Specifier:

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

How to open Console window in Eclipse?

The easiest way is to just click on the 'Console' icon in Eclipse, like this:

enter image description here

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

Drawing a dot on HTML5 canvas

If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing.

var canvas = document.getElementById("myCanvas");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var ctx = canvas.getContext("2d");
var canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);

// That's how you define the value of a pixel //
function drawPixel (x, y, r, g, b, a) {
    var index = (x + y * canvasWidth) * 4;

    canvasData.data[index + 0] = r;
    canvasData.data[index + 1] = g;
    canvasData.data[index + 2] = b;
    canvasData.data[index + 3] = a;
}

// That's how you update the canvas, so that your //
// modification are taken in consideration //
function updateCanvas() {
    ctx.putImageData(canvasData, 0, 0);
}

Then, you can use it in this way :

drawPixel(1, 1, 255, 0, 0, 255);
drawPixel(1, 2, 255, 0, 0, 255);
drawPixel(1, 3, 255, 0, 0, 255);
updateCanvas();

For more information, you can take a look at this Mozilla blog post : http://hacks.mozilla.org/2009/06/pushing-pixels-with-canvas/

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

For Genymotion "Lollipop Preview - Nexus 5" virtual device

More GApps here

Note that Google+ shows lot of errors before updated.

How to get column by number in Pandas?

The following is taken from http://pandas.pydata.org/pandas-docs/dev/indexing.html. There are a few more examples... you have to scroll down a little

In [816]: df1

           0         2         4         6
0   0.569605  0.875906 -2.211372  0.974466
2  -2.006747 -0.410001 -0.078638  0.545952
4  -1.219217 -1.226825  0.769804 -1.281247
6  -0.727707 -0.121306 -0.097883  0.695775
8   0.341734  0.959726 -1.110336 -0.619976
10  0.149748 -0.732339  0.687738  0.176444

Select via integer slicing

In [817]: df1.iloc[:3]

          0         2         4         6
0  0.569605  0.875906 -2.211372  0.974466
2 -2.006747 -0.410001 -0.078638  0.545952
4 -1.219217 -1.226825  0.769804 -1.281247

In [818]: df1.iloc[1:5,2:4]

          4         6
2 -0.078638  0.545952
4  0.769804 -1.281247
6 -0.097883  0.695775
8 -1.110336 -0.619976

Select via integer list

In [819]: df1.iloc[[1,3,5],[1,3]]

           2         6
2  -0.410001  0.545952
6  -0.121306  0.695775
10 -0.732339  0.176444

how to align img inside the div to the right?

<div style="width:300px; text-align:right;">
        <img src="someimgage.gif">
</div>

Possible reason for NGINX 499 error codes

I encountered this issue and the cause was due to Kaspersky Protection plugin on the browser. If you are encountering this, try to disable your plugins and see if that fixes your issue.

iOS - Dismiss keyboard when touching outside of UITextField

I mashed up a few answers.

Use an ivar that gets initialized during viewDidLoad:

UIGestureRecognizer *tapper;

- (void)viewDidLoad
{
    [super viewDidLoad];
    tapper = [[UITapGestureRecognizer alloc]
                initWithTarget:self action:@selector(handleSingleTap:)];
    tapper.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapper];
}

Dismiss what ever is currently editing:

- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
    [self.view endEditing:YES];
}

Change the class from factor to numeric of many columns in a data frame

Based on @SDahm's answer, this was an "optimal" solution for my tibble:

data %<>% lapply(type.convert) %>% as.data.table()

This requires dplyr and magrittr.

How to remove last n characters from a string in Bash?

What worked for me was:

echo "hello world" | rev | cut -c5- | rev
# hello w

But I used it to trim lines in a file so that's why it looks awkward. The real use was:

cat somefile | rev | cut -c5- | rev

cut only gets you as far as trimming from some starting position, which is bad if you need variable length rows. So this solution reverses (rev) the string and now we relate to its ending position, then uses cut as mentioned, and reverses (again, rev) it back to its original order.

What's the difference between a Python module and a Python package?

First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path) to create the module object.

(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path and other settings. This is exactly what happens with python -m my.module followed by an import my.module in the interpreter; there will be two module objects, __main__ and my.module, both created from the same file on disk, my/module.py.)

A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:

$ mkdir -p a/b
$ touch a/b/c.py

Ensure that there are no other files under a. Start a Python 3.4 or later interpreter (e.g., with python3 -i) and examine the results of the following statements:

import a
a                ? <module 'a' (namespace)>
a.b              ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b              ? <module 'a.b' (namespace)>
a.b.c            ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>

Modules a and a.b are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c is not a package. We can demonstrate this by adding another file, a/b.py to the directory structure above and starting a fresh interpreter:

import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a                ? <module 'a' (namespace)>
a.__path__       ? _NamespacePath(['/.../a'])
a.b              ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__     ? AttributeError: 'module' object has no attribute '__path__'

Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/ is a directory, and so creates a namespace package a, and that a/b.py is a Python source file which it loads and uses to create a (non-package) module a.b. At this point you cannot have a module a.b.c because a.b is not a package, and thus cannot have submodules.

You can also see here that the package module a has a __path__ attribute (packages must have this) but the non-package module a.b does not.

Using module 'subprocess' with timeout

Here is Alex Martelli's solution as a module with proper process killing. The other approaches do not work because they do not use proc.communicate(). So if you have a process that produces lots of output, it will fill its output buffer and then block until you read something from it.

from os import kill
from signal import alarm, signal, SIGALRM, SIGKILL
from subprocess import PIPE, Popen

def run(args, cwd = None, shell = False, kill_tree = True, timeout = -1, env = None):
    '''
    Run a command with a timeout after which it will be forcibly
    killed.
    '''
    class Alarm(Exception):
        pass
    def alarm_handler(signum, frame):
        raise Alarm
    p = Popen(args, shell = shell, cwd = cwd, stdout = PIPE, stderr = PIPE, env = env)
    if timeout != -1:
        signal(SIGALRM, alarm_handler)
        alarm(timeout)
    try:
        stdout, stderr = p.communicate()
        if timeout != -1:
            alarm(0)
    except Alarm:
        pids = [p.pid]
        if kill_tree:
            pids.extend(get_process_children(p.pid))
        for pid in pids:
            # process might have died before getting to this line
            # so wrap to avoid OSError: no such process
            try: 
                kill(pid, SIGKILL)
            except OSError:
                pass
        return -9, '', ''
    return p.returncode, stdout, stderr

def get_process_children(pid):
    p = Popen('ps --no-headers -o pid --ppid %d' % pid, shell = True,
              stdout = PIPE, stderr = PIPE)
    stdout, stderr = p.communicate()
    return [int(p) for p in stdout.split()]

if __name__ == '__main__':
    print run('find /', shell = True, timeout = 3)
    print run('find', shell = True)

Angular: conditional class with *ngClass

Let, YourCondition is your condition or a boolean property, then do like this

[class.yourClass]="YourCondition"

import httplib ImportError: No module named httplib

If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'

enter image description here

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

How to set an HTTP proxy in Python 2.7?

For installing pip with get-pip.py behind a proxy I went with the steps below. My server was even behind a jump server.

From the jump server:

ssh -R 18080:proxy-server:8080 my-python-server

On the "python-server"

export https_proxy=https://localhost:18080 ; export http_proxy=http://localhost:18080 ; export ftp_proxy=$http_proxy
python get-pip.py

Success.

WPF Databinding: How do I access the "parent" data context?

This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

Find intersection of two nested lists?

The functional approach:

input_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]

result = reduce(set.intersection, map(set, input_list))

and it can be applied to the more general case of 1+ lists

What does "O(1) access time" mean?

In essence, It means that it takes the same amount of time to look up a value in your collection whether you have a small number of items in your collection or very very many (within the constraints of your hardware)

O(n) would mean that the time it takes to look up an item is proportional to the number of items in the collection.

Typical examples of these are arrays, which can be accessed directly, regardless of their size, and linked lists, which must be traversed in order from the beginning to access a given item.

The other operation usually discussed is insert. A collection can be O(1) for access but O(n) for insert. In fact an array has exactly this behavior, because to insert an item in the middle, You would have to move each item to the right by copying it into the following slot.

Convert a Unicode string to a string in Python (containing extra symbols)

file contain unicode-esaped string

\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0437\\u0430\\u0446\\u0438\\u044f .....\",

for me

 f = open("56ad62-json.log", encoding="utf-8")
 qq=f.readline() 

 print(qq)                          
 {"log":\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0440\\u0438\\u0437\\u0430\\u0446\\u0438\\u044f \\u043f\\u043e\\u043b\\u044c\\u0437\\u043e\\u0432\\u0430\\u0442\\u0435\\u043b\\u044f\"}

(qq.encode().decode("unicode-escape").encode().decode("unicode-escape")) 
# '{"log":"message": "??????????? ????????????"}\n'

CFLAGS vs CPPFLAGS

To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:

make -p

For instance:

%.o: %.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<

which expands

COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

This will also print # environment data. Here, you will find GCC's include path among other useful info.

C_INCLUDE_PATH=/usr/include

In make, when it comes to search, the paths are many, the light is one... or something to that effect.

  1. C_INCLUDE_PATH is system-wide, set it in your shell's *.rc.
  2. $(CPPFLAGS) is for the preprocessor include path.
  3. If you need to add a general search path for make, use:
VPATH = my_dir_to_search

... or even more specific

vpath %.c src
vpath %.h include

make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.

How to wait for a process to terminate to execute another process in batch file

I liked the "START /W" answer, though for my situation I found something even more basic. My processes were console applications. And in my ignorance I thought I would need something special in BAT syntax to make sure that the 1st one completed before the 2nd one started. However BAT appears to make a distinction between console apps and windows apps, and it executes them a little differently. The OP shows that window apps will get launched as an asynchronous call from BAT. But for console apps, that are invoked synchronously, inside the same command window as the BAT itself is running in.

For me it was actually better not to use "START /W", because everything could run inside one command window. The annoying thing about "START /W" is that it will spawn a new command window to execute your console application in.

how to convert image to byte array in java?

BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.

if you want the data from DataBufferByte, use:

public byte[] extractBytes (String ImageName) throws IOException {
 // open image
 File imgPath = new File(ImageName);
 BufferedImage bufferedImage = ImageIO.read(imgPath);

 // get DataBufferBytes from Raster
 WritableRaster raster = bufferedImage .getRaster();
 DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

 return ( data.getData() );
}

now you can process these bytes by hiding text in lsb for example, or process it the way you want.

How do I check if a cookie exists?

regexObject.test( String ) is faster than string.match( RegExp ).

The MDN site describes the format for document.cookie, and has an example regex to grab a cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");). Based on that, I'd go for this:

/^(.*;)?\s*cookie1\s*=/.test(document.cookie);

The question seems to ask for a solution which returns false when the cookie is set, but empty. In that case:

/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);

Tests

function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));

Test results (Chrome 55.0.2883.87)

How to add column if not exists on PostgreSQL?

For those who use Postgre 9.5+(I believe most of you do), there is a quite simple and clean solution

ALTER TABLE if exists <tablename> add if not exists <columnname> <columntype>

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

Can I specify multiple users for myself in .gitconfig?

If you do not want to have a default email address (email address links to a github user), you can configure that you want to be asked. How you can do that depends on the version of git you use, see below.

The (intended) drawback is that you have to configure your email address (and your name) once for every repository. So, you cannot forget to do it.

Version < 2.7.0

[user]
    name = Your name
    email = "(none)"

in your global configuration ~/.gitconfig as stated in a comment by Dan Aloni in Orr Sella's blog post. When trying to do the first commit in a repository, git fails with the nice message:

*** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got '(none)')

The name is taken from the global config when the email address is set locally (the message is not perfectly accurate).

2.7.0 = Version < 2.8.0

The behaviour in versions < 2.7.0 was not intended and fixed with 2.7.0. You can still use a pre-commit hook as described in Orr Sella's blog post. This solution works also for other versions, but the other solutions not for this version.

Version = 2.8.0

Dan Aloni added an option to achieve that behaviour (see release notes). Use it with:

[user]
    useConfigOnly = true

To make it work you may not give a name or email address in the global config. Then, at the first commit, you get an error message

fatal: user.useConfigOnly set but no name given

So the message is not very instructive, but since you set the option explicitly, you should know what to do. In contrast to the solution of versions < 2.7.0, you always have to set both name and email manually.

Test if a vector contains a given element

The any() function makes for readable code

> w <- c(1,2,3)
> any(w==1)
[1] TRUE

> v <- c('a','b','c')
> any(v=='b')
[1] TRUE

> any(v=='f')
[1] FALSE

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being null means "use the current culture". If you either escape the slashes ("M'/'d'/'yyyy") or you specify CultureInfo.InvariantCulture, it will be okay.

If anyone's interested in reproducing this:

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy", 
                                  new CultureInfo("de-DE"));

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  new CultureInfo("en-US"));

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  CultureInfo.InvariantCulture);

// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  new CultureInfo("de-DE"));

RegEx for validating an integer with a maximum length of 10 characters

Don't forget that integers can be negative:

^\s*-?[0-9]{1,10}\s*$

Here's the meaning of each part:

  • ^: Match must start at beginning of string
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • -: The hyphen-minus character, used to denote a negative integer
    • ?: May or may not occur
  • [0-9]: Any character whose ASCII code (or Unicode code point) is between '0' and '9'
    • {1,10}: Occurring at least one, but not more than ten times
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • $: Match must end at end of string

This ignores leading and trailing whitespace and would be more complex if you consider commas acceptable or if you need to count the minus sign as one of the ten allowed characters.

How to parse a JSON Input stream

{
    InputStream is = HTTPClient.get(url);
    InputStreamReader reader = new InputStreamReader(is);
    JSONTokener tokenizer = new JSONTokener(reader);
    JSONObject jsonObject = new JSONObject(tokenizer);
}

Is the Javascript date object always one day off?

I faced some issue like this. But my issue was the off set while getting date from database.

this is stroed in the database and it is in the UTC format.

2019-03-29 19:00:00.0000000 +00:00

So when i get from database and check date it is adding offset with it and send back to javascript.

enter image description here

It is adding +05:00 because this is my server timezone. My client is on different time zone +07:00.

2019-03-28T19:00:00+05:00 // this is what i get in javascript.

So here is my solution what i do with this issue.

var dates = price.deliveryDate.split(/-|T|:/);
var expDate = new Date(dates[0], dates[1] - 1, dates[2], dates[3], dates[4]);
var expirationDate = new Date(expDate);

So when date come from the server and have server offset so i split date and remove server offset and then convert to date. It resolves my issue.

How to change xampp localhost to another folder ( outside xampp folder)?

Please follow @Sourav's advice.

If after restarting the server you get errors, you may need to set your directory options as well. This is done in the <Directory> tag in httpd.conf. Make sure the final config looks like this:

DocumentRoot "C:\alan"
<Directory "C:\alan">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

How do you uninstall the package manager "pip", if installed from source?

That way you haven't installed pip, you installed just the easy_install i.e. setuptools.

First you should remove all the packages you installed with easy_install using (see uninstall):

easy_install -m PackageName

This includes pip if you installed it using easy_install pip.

After this you remove the setuptools following the instructions from here:

If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:

setuptools-*.egg

If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:

pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/

How does the SQL injection from the "Bobby Tables" XKCD comic work?

In this case, ' is not a comment character. It's used to delimit string literals. The comic artist is banking on the idea that the school in question has dynamic sql somewhere that looks something like this:

$sql = "INSERT INTO `Students` (FirstName, LastName) VALUES ('" . $fname . "', '" . $lname . "')";

So now the ' character ends the string literal before the programmer was expecting it. Combined with the ; character to end the statement, an attacker can now add whatever sql they want. The -- comment at the end is to make sure any remaining sql in the original statement does not prevent the query from compiling on the server.

FWIW, I also think the comic in question has an important detail wrong: if you're thinking about sanitizing your database inputs, as the comic suggests, you're still doing it wrong. Instead, you should think in terms of quarantining your database inputs, and the correct way to do this is via parameterized queries.

Bootstrap modal appearing under background

An other way to approach this is to remove the z-index from the .modal-backdrop in bootstrap.css. This will cause the backdrop to be on the same level as the rest of your body (it will still fade) and your modal to be on top.

.modal-backdrop looks like this

.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #000000;
}

Show Image View from file path?

How To Show Images From Folder path in Android

Very First: Make Sure You Have Add Permissions into Mainfest file:

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

:Make a Class MyGallery

public class MyGallery extends Activity {


    private GridView gridView;
    private String _location;

    private String newFolder = "/IslamicGif/";
    private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    private AdView mAdView;
    private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
    public static String[] imageFileList;
    TextView gallerytxt;

    public static ImageAdapter imageAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.mygallery);
        /*if (MenuClass.mInterstitialAd.isLoaded()) {
            MenuClass.mInterstitialAd.show();
        }*/

        gallerytxt = (TextView) findViewById(R.id.gallerytxt);
        /*gallerytxt.setTextSize(20);
        int[] color = {Color.YELLOW,Color.WHITE};
        float[] position = {0, 1};
        Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
        LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
        Shader shader_gradient0 = lin_grad0;
        gallerytxt.getPaint().setShader(shader_gradient0);*/
        ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyGallery.this.finish();
            }
        });


        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
        gridView = (GridView) findViewById(R.id.gridView);

        new MyGalleryAsy().execute();

        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MyGallery.this, ImageDetail.class);
                intent.putExtra("ImgUrl", imageFileList[pos]);

                //Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
                startActivity(intent);
            }
        });


    }

    protected void onStart() {
        super.onStart();
        if (ImageDetail.deleted) {
            photo = new ArrayList<Bitmap>();
            new MyGalleryAsy().execute();
            ImageDetail.deleted = false;
        }

    }

    public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
        private ProgressDialog dialog;
        Bitmap mBitmap;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            readImage();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            dialog.dismiss();
            DisplayMetrics displayMatrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
            int screenWidth = displayMatrics.widthPixels / 3;

            if (photo.size() > 0) {
                imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
                gridView.setAdapter(imageAdapter);
            }

        }

    }


    private void readImage() {
        // TODO Auto-generated method stub


        try {
            if (isSdPresent()) {
                _location = extStorageDirectory + newFolder;
            } else
                _location = getFilesDir() + newFolder;
            File file1 = new File(_location);

            if (file1.isDirectory()) { // sdCard == true
                imageFileList = file1.list();
                if (imageFileList != null) {
                    for (int i = 0; i < imageFileList.length; i++) {
                        try {
                            photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
                        } catch (Exception e) {
                            // TODO: handle exception
                            //Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public class ImageAdapter extends BaseAdapter {

        private Context context;
        private LayoutInflater layoutInflater;
        private int width;
        private int mGalleryItemBackground;

        public ImageAdapter(Context c) {
            context = c;

        }

        public ImageAdapter(Context c, int width) {
            context = c;
            this.width = width;
        }

        public int getCount() {
            return photo.size();
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = layoutInflater.inflate(R.layout.galleryadapter, null);

            RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);

            ImageView imageView = new ImageView(context);
            layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
            imageView.setImageBitmap(photo.get(position));

            return v;

        }

        public void updateItemList(ArrayList<Bitmap> newItemList) {
            photo = newItemList;
            notifyDataSetChanged();
        }
    }


}

Now create its Xml Class

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/colorPrimary"
    android:minHeight="?attr/actionBarSize">

    <TextView
        android:id="@+id/gallerytxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:fontFamily="@string/font_fontFamily_medium"
        android:text="My Gallery"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold" />

    <ImageButton
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="12dp"
        android:background="@drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>


<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_gravity="center|bottom"
    android:visibility="gone"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_id" />

<GridView
    android:id="@+id/gridView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/adView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/relativeLayout"
    android:horizontalSpacing="5dp"
    android:numColumns="2"
    android:smoothScrollbar="true"
    android:verticalSpacing="5dp"></GridView>
## Also Make Adapter galleryadapter.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="@+id/galleryLayout"
android:padding="2dp">
[![enter image description here][1]][1]

To see the Image in Detail create a new Class ImageDetail:##

 public class ImageDetail extends Activity implements OnClickListener {
    public static InterstitialAd mInterstitialAd;
    private ImageView mainImageView;
    private LinearLayout menuTop;
    private TableLayout menuBottom;
    private Boolean onOff = true;
    private ImageView delButton, mailButton, shareButton;

    private String imgUrl = null;
    private AdView mAdView;
    TextView titletxt;
    private String newFolder = "/IslamicGif/";
    private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    public static boolean deleted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_detail);

        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                mAdView.setVisibility(View.VISIBLE);
            }
        });
        mainImageView = (ImageView) findViewById(R.id.mainImageView);
        menuTop = (LinearLayout) findViewById(R.id.menuTop);
        menuBottom = (TableLayout) findViewById(R.id.menuBottom);
        titletxt = (TextView) findViewById(R.id.titletxt);
        titletxt.setTextSize(22);
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();

            }
        });
        requestNewInterstitial();
        delButton = (ImageView) findViewById(R.id.delButton);
        mailButton = (ImageView) findViewById(R.id.mailButton);
        shareButton = (ImageView) findViewById(R.id.shareButton);

        Bundle exBundle = getIntent().getExtras();
        if (exBundle != null) {
            imgUrl = exBundle.getString("ImgUrl");
        }
        if (isSdPresent()) {
            imgUrl = extStorageDirectory + newFolder + imgUrl;
        } else
            imgUrl = getFilesDir() + newFolder + imgUrl;

        if (imgUrl != null) {
            GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
            Glide.with(this).load(imgUrl).into(imageViewTarget);

        }


        delButton.setOnClickListener(this);
        mailButton.setOnClickListener(this);
        shareButton.setOnClickListener(this);


    }

    public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.shareButton:
                Image_Link();
                break;
            case R.id.delButton:
                deleted();
                break;
            case R.id.mailButton:
                sendemail();
                break;
            default:
                break;
        }
    }

    private void sendemail() {

        try {

            File photo = new File(imgUrl);
            Uri imageuri = Uri.fromFile(photo);


            String url = Constant.AppUrl;

            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("Face Placer App Available here..Play Link");
            int start = builder.length();
            builder.append(url);
            int end = builder.length();

            builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
            String[] recipients2 = new String[]{"[email protected]", "",};
            emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
            emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
            emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
            emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
            emailIntent2.setType("text/html");
            emailIntent2.setType("image/JPEG");
            startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));

        } catch (Exception e) {
            // TODO: handle exception

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    private void Image_Link() {

        try {

            File photo = new File(imgUrl);
            Uri imageuri = Uri.fromFile(photo);


            String url = Constant.AppUrl;

            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("Face Placer App Available here..Play Link");
            int start = builder.length();
            builder.append(url);
            int end = builder.length();

            builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
            String[] recipients2 = new String[]{"[email protected]", "",};
            emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
            emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
            emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
            emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
            emailIntent2.setType("text/html");
            emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
            emailIntent2.setType("image/JPEG");
            startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));

        } catch (Exception e) {
            // TODO: handle exception

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    private void deleted() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
        builder.setTitle(getString(R.string.removeoption));
        builder.setMessage(getString(R.string.deleteimage));
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.cancel();
                File fileDel = new File(imgUrl);
                boolean isCheck1 = fileDel.delete();

                if (isCheck1) {
                    deleted = true;
                    finish();
                    MyGallery.imageAdapter.notifyDataSetChanged();

                } else {
                    Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
                }
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.cancel();

            }
        });
        Dialog dialog = builder.create();
        dialog.show();


    }


    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }

    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
                .build();

        mInterstitialAd.loadAd(adRequest);
    }

}

Create its xml image_detail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
android:orientation="vertical">

<ImageView
    android:id="@+id/mainImageView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:contentDescription="@string/app_name"
    android:focusable="true"
    android:focusableInTouchMode="true" />

<LinearLayout
    android:id="@+id/adlayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal"
    android:visibility="gone"></LinearLayout>

<LinearLayout
    android:id="@+id/menuTop"
    android:layout_width="fill_parent"
    android:layout_height="56dp"
    android:layout_alignWithParentIfMissing="true"
    android:layout_below="@+id/adlayout"
    android:background="@color/colorPrimary"
    android:orientation="vertical"
    android:padding="10.0dip"
    android:visibility="visible">

    <TextView
        android:id="@+id/titletxt"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Islamic Gifs"
        android:textColor="#000000"
        android:textSize="22sp"
        android:textStyle="bold" />
</LinearLayout>

<TableLayout
    android:id="@+id/menuBottom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="@color/colorPrimary"
    android:padding="10.0dip"
    android:stretchColumns="*"
    android:visibility="visible">

    <TableRow>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/mailButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_shareimage"
                android:contentDescription="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/shareButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_shareimage_small"
                android:contentDescription="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/delButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_delete"
                android:contentDescription="@string/app_name" />
        </LinearLayout>
    </TableRow>
</TableLayout>

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/menuTop"
    android:layout_centerHorizontal="true"
    android:visibility="gone"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_id"></com.google.android.gms.ads.AdView>

Add your own Drawable to Selector class,and create it res>drawable>selector_shareimage.xml

<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="@drawable/result_bt_mail_s"/>

enter image description here

Dont forget to add in application tag for sdk version 29 and 30 legacy to add this line

android:requestLegacyExternalStorage="true"

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:requestLegacyExternalStorage="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

CSS image resize percentage of itself?

Another solution is to use:

<img srcset="example.png 2x">

It won't validate because the src attribute is required, but it works (except on any version of IE because srcset is not supported).

Difference between declaring variables before or in loop?

I had this very same question for a long time. So I tested an even simpler piece of code.

Conclusion: For such cases there is NO performance difference.

Outside loop case

int intermediateResult;
for(int i=0; i < 1000; i++){
    intermediateResult = i+2;
    System.out.println(intermediateResult);
}

Inside loop case

for(int i=0; i < 1000; i++){
    int intermediateResult = i+2;
    System.out.println(intermediateResult);
}

I checked the compiled file on IntelliJ's decompiler and for both cases, I got the same Test.class

for(int i = 0; i < 1000; ++i) {
    int intermediateResult = i + 2;
    System.out.println(intermediateResult);
}

I also disassembled code for both the case using the method given in this answer. I'll show only the parts relevant to the answer

Outside loop case

Code:
  stack=2, locals=3, args_size=1
     0: iconst_0
     1: istore_2
     2: iload_2
     3: sipush        1000
     6: if_icmpge     26
     9: iload_2
    10: iconst_2
    11: iadd
    12: istore_1
    13: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
    16: iload_1
    17: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
    20: iinc          2, 1
    23: goto          2
    26: return
LocalVariableTable:
        Start  Length  Slot  Name   Signature
           13      13     1 intermediateResult   I
            2      24     2     i   I
            0      27     0  args   [Ljava/lang/String;

Inside loop case

Code:
      stack=2, locals=3, args_size=1
         0: iconst_0
         1: istore_1
         2: iload_1
         3: sipush        1000
         6: if_icmpge     26
         9: iload_1
        10: iconst_2
        11: iadd
        12: istore_2
        13: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
        16: iload_2
        17: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
        20: iinc          1, 1
        23: goto          2
        26: return
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
           13       7     2 intermediateResult   I
            2      24     1     i   I
            0      27     0  args   [Ljava/lang/String;

If you pay close attention, only the Slot assigned to i and intermediateResult in LocalVariableTable is swapped as a product of their order of appearance. The same difference in slot is reflected in other lines of code.

  • No extra operation is being performed
  • intermediateResult is still a local variable in both cases, so there is no difference access time.

BONUS

Compilers do a ton of optimization, take a look at what happens in this case.

Zero work case

for(int i=0; i < 1000; i++){
    int intermediateResult = i;
    System.out.println(intermediateResult);
}

Zero work decompiled

for(int i = 0; i < 1000; ++i) {
    System.out.println(i);
}

Git commit date

if you got troubles with windows cmd command and .bat just escape percents like that

git show -s --format=%%ct

The % character has a special meaning for command line parameters and FOR parameters. To treat a percent as a regular character, double it: %%

Syntax : Escape Characters, Delimiters and Quotes

SUM of grouped COUNT in SQL Query

SELECT name, COUNT(name) AS count
FROM table
GROUP BY name

UNION ALL

SELECT 'SUM' name, COUNT(name)
FROM table

OUTPUT:

name                                               count
-------------------------------------------------- -----------
alpha                                              1
beta                                               3
Charlie                                            2
SUM                                                6

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

Installing Bootstrap 3 on Rails App

This answer is for those of you looking to Install Bootstrap 3 in your Rails app without using a gem. There are two simple ways to do this that take less than 10 minutes. Pick the one that suites your needs best. Glyphicons and Javascript work and I've tested them with the latest beta of Rails 4.1.0 as well.

  1. Using Bootstrap 3 with Rails 4 - The Bootstrap 3 files are copied into the vendor directory of your application.

  2. Adding Bootstrap from a CDN to your Rails application - The Bootstrap 3 files are served from the Bootstrap CDN.

Number 2 above is the most flexible. All you need to do is change the version number that is stored in a layout helper. So you can run the Bootstrap version of your choice, whether that is 3.0.0, 3.0.3 or even older Bootstrap 2 releases.

R: Plotting a 3D surface from x, y, z

You could look at using Lattice. In this example I have defined a grid over which I want to plot z~x,y. It looks something like this. Note that most of the code is just building a 3D shape that I plot using the wireframe function.

The variables "b" and "s" could be x or y.

require(lattice)

# begin generating my 3D shape
b <- seq(from=0, to=20,by=0.5)
s <- seq(from=0, to=20,by=0.5)
payoff <- expand.grid(b=b,s=s)
payoff$payoff <- payoff$b - payoff$s
payoff$payoff[payoff$payoff < -1] <- -1
# end generating my 3D shape


wireframe(payoff ~ s * b, payoff, shade = TRUE, aspect = c(1, 1),
    light.source = c(10,10,10), main = "Study 1",
    scales = list(z.ticks=5,arrows=FALSE, col="black", font=10, tck=0.5),
    screen = list(z = 40, x = -75, y = 0))

What is the documents directory (NSDocumentDirectory)?

You can access documents directory using this code it is basically used for storing file in plist format:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

Is either GET or POST more secure than the other?

Neither one magically confers security on a request, however GET implies some side effects that generally prevent it from being secure.

GET URLs show up in browser history and webserver logs. For this reason, they should never be used for things like login forms and credit card numbers.

However, just POSTing that data doesn't make it secure, either. For that you want SSL. Both GET and POST send data in plaintext over the wire when used over HTTP.

There are other good reasons to POST data, too - like the ability to submit unlimited amounts of data, or hide parameters from casual users.

The downside is that users can't bookmark the results of a query sent via POST. For that, you need GET.

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

Take the content of a list and append it to another list

To recap on the previous answers. If you have a list with [0,1,2] and another one with [3,4,5] and you want to merge them, so it becomes [0,1,2,3,4,5], you can either use chaining or extending and should know the differences to use it wisely for your needs.

Extending a list

Using the list classes extend method, you can do a copy of the elements from one list onto another. However this will cause extra memory usage, which should be fine in most cases, but might cause problems if you want to be memory efficient.

a = [0,1,2]
b = [3,4,5]
a.extend(b)
>>[0,1,2,3,4,5]

enter image description here

Chaining a list

Contrary you can use itertools.chain to wire many lists, which will return a so called iterator that can be used to iterate over the lists. This is more memory efficient as it is not copying elements over but just pointing to the next list.

import itertools
a = [0,1,2]
b = [3,4,5]
c = itertools.chain(a, b)

enter image description here

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

How to write the code for the back button?

You need to tell the browser you are using javascript:

<a href="javascript:history.back(1)">Back</a> 

Also, your input element seems out of place in your code.

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

python to arduino serial read & write

I found it is better to use the command Serial.readString() to replace the Serial.read() to obtain the continuous I/O for Arduino.

Text in HTML Field to disappear when clicked?

Simple as this: <input type="text" name="email" value="e-mail..." onFocus="this.value=''">

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

For me, IIS Express was not accessible when I added iplisten on DOS Prompt like this: netsh http add iplisten MyIPAddress. I fixed it by deleting the iplisten like this: netsh http delete iplisten MyIPAddress.

How to find my Subversion server version number?

Try this:

ssh your_user@your_server svnserve --version

svnserve, version 1.3.1 (r19032)
   compiled May  8 2006, 07:38:44

I hope it helps.

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

POSTing JsonObject With HttpClient From Web API

The easiest way is to use a StringContent, with the JSON representation of your JSON object.

httpClient.Post(
    "",
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));

How Can I Override Style Info from a CSS Class in the Body of a Page?

you can test a color by writing the CSS inline like <div style="color:red";>...</div>

Get a Windows Forms control by name in C#

You can do the following:

private ToolStripMenuItem getToolStripMenuItemByName(string nameParam)
   {
      foreach (Control ctn in this.Controls)
         {
            if (ctn is ToolStripMenuItem)
               {
                   if (ctn.Name = nameParam)
                      {
                         return ctn;
                      }
                }
         }
         return null;
    }

How to run eclipse in clean mode? what happens if we do so?

Two ways to run eclipse in clean mode.

1 ) In Eclipse.ini file

  • Open the eclipse.ini file located in the Eclipse installation directory.
  • Add -clean first line in the file.
  • Save the file.
  • Restart Eclipse.

enter image description here

2 ) From Command prompt (cmd/command)

  • Go to folder where Eclipse installed.
  • Take the path of Eclipse
  • C:..\eclipse\eclipse.exe -clean
  • press enter button

enter image description here

How to append data to a json file?

One possible solution is do the concatenation manually, here is some useful code:

import json
def append_to_json(_dict,path): 
    with open(path, 'ab+') as f:
        f.seek(0,2)                                #Go to the end of file    
        if f.tell() == 0 :                         #Check if file is empty
            f.write(json.dumps([_dict]).encode())  #If empty, write an array
        else :
            f.seek(-1,2)           
            f.truncate()                           #Remove the last character, open the array
            f.write(' , '.encode())                #Write the separator
            f.write(json.dumps(_dict).encode())    #Dump the dictionary
            f.write(']'.encode())                  #Close the array

You should be careful when editing the file outside the script not add any spacing at the end.

How to override equals method in Java

//Written by K@stackoverflow
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Person> people = new ArrayList<Person>();
        people.add(new Person("Subash Adhikari", 28));
        people.add(new Person("K", 28));
        people.add(new Person("StackOverflow", 4));
        people.add(new Person("Subash Adhikari", 28));

        for (int i = 0; i < people.size() - 1; i++) {
            for (int y = i + 1; y <= people.size() - 1; y++) {
                boolean check = people.get(i).equals(people.get(y));

                System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());
                System.out.println(check);
            }
        }
    }
}

//written by K@stackoverflow
public class Person {
    private String name;
    private int age;

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj.getClass() != this.getClass()) {
            return false;
        }

        final Person other = (Person) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }

        if (this.age != other.age) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + this.age;
        return hash;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Output:

run:

-- Subash Adhikari - VS - K false

-- Subash Adhikari - VS - StackOverflow false

-- Subash Adhikari - VS - Subash Adhikari true

-- K - VS - StackOverflow false

-- K - VS - Subash Adhikari false

-- StackOverflow - VS - Subash Adhikari false

-- BUILD SUCCESSFUL (total time: 0 seconds)

Is there a way to automatically generate getters and setters in Eclipse?

Bring up the context menu (i.e. right click) in the source code window of the desired class. Then select the Source submenu; from that menu selecting Generate Getters and Setters... will cause a wizard window to appear.

Source -> Generate Getters and Setters...

Select the variables you wish to create getters and setters for and click OK.

How to convert current date to epoch timestamp?

Short-hand to convert python date/datetime to Epoch (without microseconds)

int(current_date.strftime("%s")) # 2020-01-14  ---> 1578956400
int(current_datetime.strftime("%s")) # 2020-01-14 16:59:30.251176 -----> 1579017570

Hide Twitter Bootstrap nav collapse on click

The navigation should be closed any time a user clicks anywhere on the body - not just navigation elements. Say menu is open, but user clicks in the page body. User expects to see menu close.

You also have to make sure toggle button is visible, otherwise a jump is seen in menu.

$(document).ready(function() { 

$("body").click(function(event) {
        // only do this if navigation is visible, otherwise you see jump in navigation while collapse() is called 
         if ($(".navbar-collapse").is(":visible") && $(".navbar-toggle").is(":visible") ) {
            $('.navbar-collapse').collapse('toggle');
        }
  });

});

What is PHPSESSID?

Check php.ini for auto session id.

If you enable it, you will have PHPSESSID in your cookies.

How to create an executable .exe file from a .m file

If your code is more of a data analysis routine (vs. visualization / GUI), try GNU Octave. It's free and many of its functions are compatible with MATLAB. (Not 100% but maybe 99.5%.)

How do I download and save a file locally on iOS using objective C?

I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath atomically:YES];
}

How do I pass multiple attributes into an Angular.js attribute directive?

You do it exactly the same way as you would with an element directive. You will have them in the attrs object, my sample has them two-way binding via the isolate scope but that's not required. If you're using an isolated scope you can access the attributes with scope.$eval(attrs.sample) or simply scope.sample, but they may not be defined at linking depending on your situation.

app.directive('sample', function () {
    return {
        restrict: 'A',
        scope: {
            'sample' : '=',
            'another' : '='
        },
        link: function (scope, element, attrs) {
            console.log(attrs);
            scope.$watch('sample', function (newVal) {
                console.log('sample', newVal);
            });
            scope.$watch('another', function (newVal) {
                console.log('another', newVal);
            });
        }
    };
});

used as:

<input type="text" ng-model="name" placeholder="Enter a name here">
<input type="text" ng-model="something" placeholder="Enter something here">
<div sample="name" another="something"></div>

How to schedule a stored procedure in MySQL

In order to create a cronjob, follow these steps:

  1. run this command : SET GLOBAL event_scheduler = ON;

  2. If ERROR 1229 (HY000): Variable 'event_scheduler' is a GLOBAL variable and should be set with SET GLOBAL: mportant

It is possible to set the Event Scheduler to DISABLED only at server startup. If event_scheduler is ON or OFF, you cannot set it to DISABLED at runtime. Also, if the Event Scheduler is set to DISABLED at startup, you cannot change the value of event_scheduler at runtime.

To disable the event scheduler, use one of the following two methods:

  1. As a command-line option when starting the server:

    --event-scheduler=DISABLED
    
  2. In the server configuration file (my.cnf, or my.ini on Windows systems): include the line where it will be read by the server (for example, in a [mysqld] section):

    event_scheduler=DISABLED
    

    Read MySQL documentation for more information.

     DROP EVENT IF EXISTS EVENT_NAME;
      CREATE EVENT EVENT_NAME
     ON SCHEDULE EVERY 10 SECOND/minute/hour
     DO
     CALL PROCEDURE_NAME();
    

Change font color and background in html on mouseover

It would be great if you use :hover pseudo class over the onmouseover event

td:hover
{
   background-color:white
}

and for the default styling just use

td
{
  background-color:black
}

As you want to use these styling not over all the td elements then you need to specify the class to those elements and add styling to that class like this

.customTD
{
   background-color:black
}
.customTD:hover
{
  background-color:white;
}

You can also use :nth-child selector to select the td elements

What is the OR operator in an IF statement

The conditional or operator is ||:

if (expr1 || expr2) {do stuff}

if (title == "User greeting" || title == "User name") {do stuff}

The conditional (the OR) and it's parts are boolean expressions.

MSDN lists the C# operators in precedence order here http://msdn.microsoft.com/en-us/library/6a71f45d.aspx . And the MSDN page for boolean expressions is http://msdn.microsoft.com/en-us/library/dya2szfk.aspx .

If you are just starting to learn programming, you should read up on Conditional Statements from an introductory text or tutorial. This one seems to cover most of the basics: http://www.functionx.com/csharp/Lesson10.htm .

White spaces are required between publicId and systemId

The error message is actually correct if not obvious. It says that your DOCTYPE must have a SYSTEM identifier. I assume yours only has a public identifier.

You'll get the error with (for instance):

<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

You won't with:

<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" "">

Notice "" at the end in the second one -- that's the system identifier. The error message is confusing: it should say that you need a system identifier, not that you need a space between the publicId and the (non-existent) systemId.

By the way, an empty system identifier might not be ideal, but it might be enough to get you moving.

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

This command loads class of Oracle jdbc driver to be available for DriverManager instance. After the class is loaded system can connect to Oracle using it. As an alternative you can use registerDriver method of DriverManager and pass it with instance of JDBC driver you need.

proper name for python * operator?

I believe it's most commonly called the "splat operator." Unpacking arguments is what it does.

Display TIFF image in all web browser

This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:

http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support

Where are you getting the tiff images from? Is it possible for them to be generated in a different format?

If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.

If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.

unable to set private key file: './cert.pem' type PEM

Im not sure If this will help anyone but I was getting this error (although I was using php to create it instead of the command line) and to fix it I had to ensure that no old .key or .pem files were in the directory I was looking at. By deleting them and making fresh files with the authentication it worked perfectly!

JavaScriptSerializer - JSON serialization of enum as string

I have put together all of the pieces of this solution using the Newtonsoft.Json library. It fixes the enum issue and also makes the error handling much better, and it works in IIS hosted services. It's quite a lot of code, so you can find it on GitHub here: https://github.com/jongrant/wcfjsonserializer/blob/master/NewtonsoftJsonFormatter.cs

You have to add some entries to your Web.config to get it to work, you can see an example file here: https://github.com/jongrant/wcfjsonserializer/blob/master/Web.config

Php - testing if a radio button is selected and get the value

<?php
if (isset($_POST['submit']) and ! empty($_POST['submit'])) {
    if (isset($_POST['radio'])) {
        $radio_input = $_POST['radio'];
        echo $radio_input;
    }
} else {

}
?>
<form action="radio.php" method="post">
   <input type="radio" name="radio" value="v1"/>
   <input type="radio" name="radio" value="v2"/>
   <input type="radio" name="radio" value="v3"/>
   <input type="radio" name="radio" value="v4"/>
   <input type="radio" name="radio" value="v5"/>
   <input type= "submit" name="submit"value="submit"/>
</form>

How do I calculate a trendline for a graph?

If anyone needs the JS code for calculating the trendline of many points on a graph, here's what worked for us in the end:

_x000D_
_x000D_
/**@typedef {{_x000D_
 * x: Number;_x000D_
 * y:Number;_x000D_
 * }} Point_x000D_
 * @param {Point[]} data_x000D_
 * @returns {Function} */_x000D_
function _getTrendlineEq(data) {_x000D_
    const xySum = data.reduce((acc, item) => {_x000D_
        const xy = item.x * item.y_x000D_
        acc += xy_x000D_
        return acc_x000D_
    }, 0)_x000D_
    const xSum = data.reduce((acc, item) => {_x000D_
        acc += item.x_x000D_
        return acc_x000D_
    }, 0)_x000D_
    const ySum = data.reduce((acc, item) => {_x000D_
        acc += item.y_x000D_
        return acc_x000D_
    }, 0)_x000D_
    const aTop = (data.length * xySum) - (xSum * ySum)_x000D_
    const xSquaredSum = data.reduce((acc, item) => {_x000D_
        const xSquared = item.x * item.x_x000D_
        acc += xSquared_x000D_
        return acc_x000D_
    }, 0)_x000D_
    const aBottom = (data.length * xSquaredSum) - (xSum * xSum)_x000D_
    const a = aTop / aBottom_x000D_
    const bTop = ySum - (a * xSum)_x000D_
    const b = bTop / data.length_x000D_
    return function trendline(x) {_x000D_
        return a * x + b_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

It takes an array of (x,y) points and returns the function of a y given a certain x Have fun :)

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

Android Use Done button on Keyboard to click button

if you want to catch the keyboard enter button for doing your job which you want to done through any event like button click, you can write the below simple code for that text view

Edittext ed= (EditText) findViewById(R.id.edit_text);

ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        // Do you job here which you want to done through event
    }
    return false;
}
});

Unable to establish SSL connection, how do I fix my SSL cert?

I had this problem when setting up a new EC2 instance. I had not added HTTPS to my security group, and so port 443 was not open.

asp.net mvc @Html.CheckBoxFor

Use this code:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}

How to get previous page url using jquery

document.referrer is not working always.

You can use:

window.location.origin

Function pointer to member function

The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:

class A {
public:
 int f();
 int (A::*x)(); // <- declare by saying what class it is a pointer to
};

int A::f() {
 return 1;
}


int main() {
 A a;
 a.x = &A::f; // use the :: syntax
 printf("%d\n",(a.*(a.x))()); // use together with an object of its class
}

a.x does not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the object a. Prepending a another time as the left operand to the .* operator will tell the compiler on what object to call the function on.

Execute ssh with password authentication via windows command prompt

Windows Solution

  1. Install PuTTY
  2. Press Windows-Key + R
  3. Enter putty.exe -ssh [username]@[hostname] -pw [password]

How to show SVG file on React Native?

you can do this using a simple way

first, you should take installation,

  1. npm install -s react-native-svg
  2. react-native link react-native-svg
  3. npm install -s react-native-svg-transformer

then, you should add the following code in your metro.config.js file

_x000D_
_x000D_
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts }
  } = await getDefaultConfig();
  return {
    transformer: {
      babelTransformerPath: require.resolve("react-native-svg-transformer")
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== "svg"),
      sourceExts: [...sourceExts, "svg"]
    }
  };
})();
_x000D_
_x000D_
_x000D_

after that, you should create a new file in your root directory with the name of declarations.d.js with the following code

_x000D_
_x000D_
declare module "*.svg" {
  import { SvgProps } from "react-native-svg";
  const content: React.FC<SvgProps>;
  export default content;
}
_x000D_
_x000D_
_x000D_

Finally, This is a import mathod

_x000D_
_x000D_
import USER from "../../assets/icons/user.svg"
_x000D_
_x000D_
_x000D_

and, this is for jsx

_x000D_
_x000D_
<USER width="100%" height="100%"/>
_x000D_
_x000D_
_x000D_

Find nearest value in numpy array

If you don't want to use numpy this will do it:

def find_nearest(array, value):
    n = [abs(i-value) for i in array]
    idx = n.index(min(n))
    return array[idx]

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

Please check following snippet

_x000D_
_x000D_
 /* DEBUG */_x000D_
.lwb-col {_x000D_
    transition: box-shadow 0.5s ease;_x000D_
}_x000D_
.lwb-col:hover{_x000D_
    box-shadow: 0 15px 30px -4px rgba(136, 155, 166, 0.4);_x000D_
 _x000D_
}_x000D_
_x000D_
_x000D_
.lwb-col--link {_x000D_
    font-weight: 500;_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}_x000D_
.lwb-col--link::after{_x000D_
    border-bottom: 2px solid;_x000D_
    bottom: -3px;_x000D_
    content: "";_x000D_
    display: block;_x000D_
    left: 0;_x000D_
    position: absolute;_x000D_
    width: 100%;_x000D_
    color: #E5E9EC;_x000D_
_x000D_
}_x000D_
.lwb-col--link::before{_x000D_
    border-bottom: 2px solid;_x000D_
    bottom: -3px;_x000D_
    content: "";_x000D_
    display: block;_x000D_
    left: 0;_x000D_
    position: absolute;_x000D_
    width: 100%;_x000D_
    color: #57B0FB;_x000D_
    transform: scaleX(0);_x000D_
    _x000D_
_x000D_
}_x000D_
.lwb-col:hover .lwb-col--link::before {_x000D_
    border-color: #57B0FB;_x000D_
    display: block;_x000D_
    z-index: 2;_x000D_
    transition: transform 0.3s;_x000D_
    transform: scaleX(1);_x000D_
    transform-origin: left center;_x000D_
}
_x000D_
<div class="lwb-col">_x000D_
  <h2>Webdesign</h2>_x000D_
  <p>Steigern Sie Ihre Bekanntheit im Web mit individuellem &amp; professionellem Webdesign. Organisierte Codestruktur, sowie perfekte SEO Optimierung und jahrelange Erfahrung sprechen für uns.</p>_x000D_
<span class="lwb-col--link">Mehr erfahren</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You need to encode your parameter's values before concatenating them to URL.
Backslash \ is special character which have to be escaped as %5C

Escaping example:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is properly formatted url string.

Array of an unknown length in C#

You can create an array with the size set to a variable, i.e.

int size = 50;
string[] words = new string[size]; // contains 50 strings

However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.

Is there a difference between "throw" and "throw ex"?

int a = 0;
try {
    int x = 4;
    int y ;
    try {
        y = x / a;
    } catch (Exception e) {
        Console.WriteLine("inner ex");
        //throw;   // Line 1
        //throw e;   // Line 2
        //throw new Exception("devide by 0");  // Line 3
    }
} catch (Exception ex) {
    Console.WriteLine(ex);
    throw ex;
}
  1. if all Line 1 ,2 and 3 are commented - Output - inner ex

  2. if all Line 2 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------

  3. if all Line 1 and 2 are commented - Output - inner ex System.Exception: devide by 0 ----

  4. if all Line 1 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------

and StackTrace will be reset in case of throw ex;

Django: How can I call a view function from template?

For example, a logout button can be written like this:

<button class="btn btn-primary" onclick="location.href={% url 'logout'%}">Logout</button>

Where logout endpoint:

#urls.py:
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

How can I check if a string only contains letters in Python?

You can leverage regular expressions.

>>> import re
>>> pattern = re.compile("^[a-zA-Z]+$")
>>> pattern.match("hello")
<_sre.SRE_Match object; span=(0, 5), match='hello'>
>>> pattern.match("hel7lo")
>>>

The match() method will return a Match object if a match is found. Otherwise it will return None.


An easier approach is to use the .isalpha() method

>>> "Hello".isalpha()
True
>>> "Hel7lo".isalpha()
False

isalpha() returns true if there is at least 1 character in the string and if all the characters in the string are alphabets.

How can I change the class of an element with jQuery>

To set a class completely, instead of adding one or removing one, use this:

$(this).attr("class","newclass");

Advantage of this is that you'll remove any class that might be set in there and reset it to how you like. At least this worked for me in one situation.

How to split long commands over multiple lines in PowerShell

Splat Method with Calculations

If you choose splat method, beware calculations that are made using other parameters. In practice, sometimes I have to set variables first then create the hash table. Also, the format doesn't require single quotes around the key value or the semi-colon (as mentioned above).

Example of a call to a function that creates an Excel spreadsheet

$title = "Cut-off File Processing on $start_date_long_str"
$title_row = 1
$header_row = 2
$data_row_start = 3
$data_row_end = $($data_row_start + $($file_info_array.Count) - 1)

# use parameter hash table to make code more readable
$params = @{
    title = $title
    title_row = $title_row
    header_row = $header_row
    data_row_start = $data_row_start
    data_row_end = $data_row_end
}
$xl_wksht = Create-Excel-Spreadsheet @params

Note: The file array contains information that will affect how the spreadsheet is populated.

Convert PEM to PPK file format

Convert .pem file to .ppk for Windows 10

You need to do following:


1. Download PuTTYGen with Pageant.
2. Press "load" button and select your ".pem" file.
3. Press "save private key" button and save your ".ppk" file.
4. Open Pageant and press "add key" button. Just all. Keep running Pageant in background.
5. Now login through SSH or SFTP without selecting password field.


enter image description here


enter image description here


enter image description here

How to use an arraylist as a prepared statement parameter

@JulienD Best way is to break above process into two steps.

Step 1 : Lets say 'rawList' as your list that you want to add as parameters in prepared statement.

Create another list :

ArrayList<String> listWithQuotes = new ArrayList<String>();

for(String element : rawList){
    listWithQuotes.add("'"+element+"'");
}

Step 2 : Make 'listWithQuotes' comma separated.

String finalString = StringUtils.join(listWithQuotes.iterator(),",");

'finalString' will be string parameters with each element as single quoted and comma separated.

How To: Best way to draw table in console app (C#)

Edit: thanks to @superlogical, you can now find and improve the following code in github!


I wrote this class based on some ideas here. The columns width is optimal, an it can handle object arrays with this simple API:

static void Main(string[] args)
{
  IEnumerable<Tuple<int, string, string>> authors =
    new[]
    {
      Tuple.Create(1, "Isaac", "Asimov"),
      Tuple.Create(2, "Robert", "Heinlein"),
      Tuple.Create(3, "Frank", "Herbert"),
      Tuple.Create(4, "Aldous", "Huxley"),
    };

  Console.WriteLine(authors.ToStringTable(
    new[] {"Id", "First Name", "Surname"},
    a => a.Item1, a => a.Item2, a => a.Item3));

  /* Result:        
  | Id | First Name | Surname  |
  |----------------------------|
  | 1  | Isaac      | Asimov   |
  | 2  | Robert     | Heinlein |
  | 3  | Frank      | Herbert  |
  | 4  | Aldous     | Huxley   |
  */
}

Here is the class:

public static class TableParser
{
  public static string ToStringTable<T>(
    this IEnumerable<T> values,
    string[] columnHeaders,
    params Func<T, object>[] valueSelectors)
  {
    return ToStringTable(values.ToArray(), columnHeaders, valueSelectors);
  }

  public static string ToStringTable<T>(
    this T[] values,
    string[] columnHeaders,
    params Func<T, object>[] valueSelectors)
  {
    Debug.Assert(columnHeaders.Length == valueSelectors.Length);

    var arrValues = new string[values.Length + 1, valueSelectors.Length];

    // Fill headers
    for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
    {
      arrValues[0, colIndex] = columnHeaders[colIndex];
    }

    // Fill table rows
    for (int rowIndex = 1; rowIndex < arrValues.GetLength(0); rowIndex++)
    {
      for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
      {
        arrValues[rowIndex, colIndex] = valueSelectors[colIndex]
          .Invoke(values[rowIndex - 1]).ToString();
      }
    }

    return ToStringTable(arrValues);
  }

  public static string ToStringTable(this string[,] arrValues)
  {
    int[] maxColumnsWidth = GetMaxColumnsWidth(arrValues);
    var headerSpliter = new string('-', maxColumnsWidth.Sum(i => i + 3) - 1);

    var sb = new StringBuilder();
    for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
    {
      for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
      {
        // Print cell
        string cell = arrValues[rowIndex, colIndex];
        cell = cell.PadRight(maxColumnsWidth[colIndex]);
        sb.Append(" | ");
        sb.Append(cell);
      }

      // Print end of line
      sb.Append(" | ");
      sb.AppendLine();

      // Print splitter
      if (rowIndex == 0)
      {
        sb.AppendFormat(" |{0}| ", headerSpliter);
        sb.AppendLine();
      }
    }

    return sb.ToString();
  }

  private static int[] GetMaxColumnsWidth(string[,] arrValues)
  {
    var maxColumnsWidth = new int[arrValues.GetLength(1)];
    for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
    {
      for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
      {
        int newLength = arrValues[rowIndex, colIndex].Length;
        int oldLength = maxColumnsWidth[colIndex];

        if (newLength > oldLength)
        {
          maxColumnsWidth[colIndex] = newLength;
        }
      }
    }

    return maxColumnsWidth;
  }
}

Edit: I added a minor improvement - if you want the column headers to be the property name, add the following method to TableParser (note that it will be a bit slower due to reflection):

public static string ToStringTable<T>(
    this IEnumerable<T> values,
    params Expression<Func<T, object>>[] valueSelectors)
{
  var headers = valueSelectors.Select(func => GetProperty(func).Name).ToArray();
  var selectors = valueSelectors.Select(exp => exp.Compile()).ToArray();
  return ToStringTable(values, headers, selectors);
}

private static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expresstion)
{
  if (expresstion.Body is UnaryExpression)
  {
    if ((expresstion.Body as UnaryExpression).Operand is MemberExpression)
    {
      return ((expresstion.Body as UnaryExpression).Operand as MemberExpression).Member as PropertyInfo;
    }
  }

  if ((expresstion.Body is MemberExpression))
  {
    return (expresstion.Body as MemberExpression).Member as PropertyInfo;
  }
  return null;
}

Show ProgressDialog Android

I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.

// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... urls) {
        try {
            String xmlUrl = urls[0];

            URL u = new URL(xmlUrl);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int lengthOfFile = c.getContentLength();

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; // total = total + len1
                publishProgress("" + (int) ((total * 100) / lengthOfFile));
                xmlContent += buffer;
            }
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        Log.d("ANDRO_ASYNC", progress[0]);
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Retrieving latest announcements...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }

}

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

Why can't I push to this bare repository?

git push --all

is the canonical way to push everything to a new bare repository.

Another way to do the same thing is to create your new, non-bare repository and then make a bare clone with

git clone --bare

then use

git remote add origin <new-remote-repo>

in the original (non-bare) repository.

How to kill a process in MacOS?

in the spotlight, search for Activity Monitor. You can force fully remove any application from here.

enter image description here

Applying an ellipsis to multiline text

If you also have multiple elements and you want a link with read more button after ellipsis, take a look on https://stackoverflow.com/a/51418807/10104342

If you want something like this:

Every month first 10 TB are are not charged. All other traffic... Read more

Is it possible to display my iPhone on my computer monitor?

use screensplitr on jailbrocken iphone/ipod touch it works

How do I escape spaces in path for scp copy in Linux?

works

scp localhost:"f/a\ b\ c" .

scp localhost:'f/a\ b\ c' .

does not work

scp localhost:'f/a b c' .

The reason is that the string is interpreted by the shell before the path is passed to the scp command. So when it gets to the remote the remote is looking for a string with unescaped quotes and it fails

To see this in action, start a shell with the -vx options ie bash -vx and it will display the interpolated version of the command as it runs it.

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

here is my implementation
that if you want to disable the swipe animation you can you use the swipeListener left and right and still want the scroll by finger but without animation

1-Override Viewpager method onInterceptTouchEvent and onTouchEvent

2- create your own GestureDetector

3- detect the swipe gesture and use the setCurrentItem(item, false)

ViewPager

public class ViewPagerNoSwipe extends ViewPager {
    private final GestureDetector gestureDetector;
    private OnSwipeListener mOnSwipeListener;

    public void setOnSwipeListener(OnSwipeListener onSwipeListener) {
        mOnSwipeListener = onSwipeListener;
    }

    public ViewPagerNoSwipe(@NonNull Context context) {
        super(context);
        gestureDetector = new GestureDetector(context, new GestureListener());

    }

    public ViewPagerNoSwipe(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        gestureDetector = new GestureDetector(context, new GestureListener());


    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        gestureDetector.onTouchEvent(ev);
        return false;
    }

    public class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            if(mOnSwipeListener!=null)
                            mOnSwipeListener.onSwipeRight();
                        } else {
                            if(mOnSwipeListener!=null)
                                mOnSwipeListener.onSwipeLeft();
                        }
                        result = true;
                    }
                } else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        if(mOnSwipeListener!=null)
                            mOnSwipeListener.onSwipeBottom();
                    } else {
                        if(mOnSwipeListener!=null)
                            mOnSwipeListener.onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public interface OnSwipeListener {

         void onSwipeRight();

        void onSwipeLeft();

        void onSwipeTop();

        void onSwipeBottom();
    }
}

the when you are set up the ViewPager set the swipeListener

postsPager.setOnSwipeListener(new ViewPagerNoSwipe.OnSwipeListener() {
            @Override
            public void onSwipeRight() {

              postsPager.setCurrentItem(postsPager.getCurrentItem() + 1,false);

            }

            @Override
            public void onSwipeLeft() {

            postsPager.setCurrentItem(postsPager.getCurrentItem() - 1, false);

            }
             ...
           }

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

Setting an int to Infinity in C++

Integers are finite, so sadly you can't have set it to a true infinity. However you can set it to the max value of an int, this would mean that it would be greater or equal to any other int, ie:

a>=b

is always true.

You would do this by

#include <limits>

//your code here

int a = std::numeric_limits<int>::max();

//go off and lead a happy and productive life

This will normally be equal to 2,147,483,647

If you really need a true "infinite" value, you would have to use a double or a float. Then you can simply do this

float a = std::numeric_limits<float>::infinity();

Additional explanations of numeric limits can be found here

Happy Coding!

Note: As WTP mentioned, if it is absolutely necessary to have an int that is "infinite" you would have to write a wrapper class for an int and overload the comparison operators, though this is probably not necessary for most projects.

jQuery select option elements by value

options = $("#span_id>select>option[value='"+i+"']");
option = options.text();
alert(option); 

here is the fiddle http://jsfiddle.net/hRFYF/

WPF MVVM: How to close a window

Very clean and MVVM way is to use InteractionTrigger and CallMethodAction defined in Microsoft.Interactivity.Core

You will need to add a new namespace as below

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

You will need the Microsoft.Xmal.Behaviours.Wpf assembly and then the below xaml code will work.

<Button Content="Save" Command="{Binding SaveCommand}">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <i:CallMethodAction MethodName="Close"
                           TargetObject="{Binding RelativeSource={RelativeSource
                                                  Mode=FindAncestor,
                                                  AncestorType=Window}}" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

You don't need any code behind or anything else and can also call any other method of Window.

How to increment a variable on a for loop in jinja template?

As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.

You can defeat this behavior by using an object rather than a scalar for 'count':

{% set count = [1] %}

You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):

{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}

How is length implemented in Java Arrays?

I believe its just a property as you access it as a property.

String[] s = new String[]{"abc","def","ghi"}
System.out.println(s.length)

returns 3

if it was a method then you would call s.length() right?

Java 6 Unsupported major.minor version 51.0

add jdk8 or higher version at JAVA_HOME and path.

add JAVA_HOME add C:\ProgramFiles\Java\jdk1.8.0_201

For Path =>

add %MAVEN_HOME%\bin

and finally restart your pc.

Log all queries in mysql

Besides what I came across here, running the following was the simplest way to dump queries to a log file without restarting

SET global log_output = 'FILE';
SET global general_log_file='/Applications/MAMP/logs/mysql_general.log';
SET global general_log = 1;

can be turned off with

SET global general_log = 0;

Measure the time it takes to execute a t-sql query

DECLARE @StartTime datetime
DECLARE @EndTime datetime
SELECT @StartTime=GETDATE() 

 -- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(MS,@StartTime,@EndTime) AS [Duration in millisecs]

You can also See this solution

Apache 13 permission denied in user's home directory

Apache's errorlog will explain why you get a permission denied. Also, serverfault.com is a better forum for a question like this.

If the error log simply says "permission denied", su to the user that the webserver is running as and try to read from the file in question. So for example:

sudo -s
su - nobody
cd /
cd /home
cd user
cd xxx
cat index.html

See if one of those gives you the "permission denied" error.

set the width of select2 input (through Angular-ui directive)

With > 4.0 of select2 I am using

$("select").select2({
  dropdownAutoWidth: true
});

These others did not work:

  • dropdownCssClass: 'bigdrop'
  • width: '100%'
  • width: 'resolve'

How do you make a div tag into a link

If you have to set your anchor tag inside the div, you can also use CSS to set the anchor to fill the div via display:block.

As such:

<div style="height: 80px"><a href="#" style="display: block">Text</a></div>

Now when the user floats their cursor in that div the anchor tag will fill the div.

Converting Integer to Long

If the Integer is not null

Integer i;
Long long = Long.valueOf(i);

i will be automatically typecast to a long.

Using valueOf instead of new allows caching of this value (if its small) by the compiler or JVM , resulting in faster code.

Integer expression expected error in shell script

If you are using -o (or -a), it needs to be inside the brackets of the test command:

if [ "$age" -le "7" -o "$age" -ge " 65" ]

However, their use is deprecated, and you should use separate test commands joined by || (or &&) instead:

if [ "$age" -le "7" ] || [ "$age" -ge " 65" ]

Make sure the closing brackets are preceded with whitespace, as they are technically arguments to [, not simply syntax.

In bash and some other shells, you can use the superior [[ expression as shown in kamituel's answer. The above will work in any POSIX-compliant shell.

How to multiply duration by integer?

For multiplication of variable to time.Second using following code

    oneHr:=3600
    addOneHrDuration :=time.Duration(oneHr)
    addOneHrCurrTime := time.Now().Add(addOneHrDuration*time.Second)

Get the date of next monday, tuesday, etc

For some reason, strtotime('next friday') display the Friday date of the current week. Try this instead:

//Current date 2020-02-03
$fridayNextWeek = date('Y-m-d', strtotime('friday next week'); //Outputs 2020-02-14

$nextFriday = date('Y-m-d', strtotime('next friday'); //Outputs 2020-02-07

Updating a dataframe column in spark

importing col, when from pyspark.sql.functions and updating fifth column to integer(0,1,2) based on the string(string a, string b, string c) into a new DataFrame.

from pyspark.sql.functions import col, when 

data_frame_temp = data_frame.withColumn("col_5",when(col("col_5") == "string a", 0).when(col("col_5") == "string b", 1).otherwise(2))

How to convert Double to int directly?

int average_in_int = ( (Double) Math.ceil( sum/count ) ).intValue();

Printing reverse of any String without using any predefined function?

public static void main(String[] args) {


    String str = "hello world here I am";

    StringTokenizer strToken = new StringTokenizer(str);
    int token = strToken.countTokens();
    String str1 [] = new String[token];

    char chr[] = new char[str.length()];
    int counter = 0;

    for(int j=0; j < str.length(); j++) {

        if(str.charAt(j) != ' ') {
            chr[j] = str.charAt(j);
        }else {
            str1[counter++] = new String(chr).trim();
            chr = new char[str.length()];
        }
    }
    str1[counter++] = new String(chr).trim();

    for(int i=str1.length-1; i >= 0 ; i--) {
        System.out.println(str1[i]);
    }
}

O/P is: am I here world hello

Undo a merge by pull request?

To undo a github pull request with commits throughout that you do not want to delete, you have to run a:

git reset --hard --merge <commit hash>

with the commit hash being the commit PRIOR to merging the pull request. This will remove all commits from the pull request without influencing any commits within the history.

A good way to find this is to go to the now closed pull request and finding this field:

Pull Request Image Pull Request Image

After you run the git reset, run a:

git push origin --force <branch name>

This should revert the branch back before the pull request WITHOUT affecting any commits in the branch peppered into the commit history between commits from the pull request.

EDIT:

If you were to click the revert button on the pull request, this creates an additional commit on the branch. It DOES NOT uncommit or unmerge. This means that if you were to hit the revert button, you cannot open a new pull request to re-add all of this code.

Determine if a cell (value) is used in any formula

Have you tried Tools > Formula Auditing?

Space between Column's children in Flutter

Columns Has no height by default, You can Wrap your Column to the Container and add the specific height to your Container. Then You can use something like below:

Container(
   width: double.infinity,//Your desire Width
   height: height,//Your desire Height
   child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
         Text('One'),
         Text('Two')
      ],
   ),
),

Where does Anaconda Python install on Windows?

To find where Anaconda was installed I used the "where" command on the command line in Windows.

C:\>where anaconda

which for me returned:

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe

Which allowed me to find the Anaconda Python interpreter at

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\python.exe

to update PyDev

How to cache data in a MVC application

I use two classes. First one the cache core object:

public class Cacher<TValue>
    where TValue : class
{
    #region Properties
    private Func<TValue> _init;
    public string Key { get; private set; }
    public TValue Value
    {
        get
        {
            var item = HttpRuntime.Cache.Get(Key) as TValue;
            if (item == null)
            {
                item = _init();
                HttpContext.Current.Cache.Insert(Key, item);
            }
            return item;
        }
    }
    #endregion

    #region Constructor
    public Cacher(string key, Func<TValue> init)
    {
        Key = key;
        _init = init;
    }
    #endregion

    #region Methods
    public void Refresh()
    {
        HttpRuntime.Cache.Remove(Key);
    }
    #endregion
}

Second one is list of cache objects:

public static class Caches
{
    static Caches()
    {
        Languages = new Cacher<IEnumerable<Language>>("Languages", () =>
                                                          {
                                                              using (var context = new WordsContext())
                                                              {
                                                                  return context.Languages.ToList();
                                                              }
                                                          });
    }
    public static Cacher<IEnumerable<Language>> Languages { get; private set; }
}

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

How to use RANK() in SQL Server

Select T.Tamil, T.English, T.Maths, T.Total, Dense_Rank()Over(Order by T.Total Desc) as Std_Rank From (select Tamil,English,Maths,(Tamil+English+Maths) as Total From Student) as T

enter image description here

DISTINCT for only one column

You can over that by using GROUP BY like this:

SELECT ID, Email, ProductName, ProductModel
FROM Products
GROUP BY Email

Console.WriteLine does not show up in Output window

If you intend to use this output in production, then use the Trace class members. This makes the code portable, you can wire up different types of listeners and output to the console window, debug window, log file, or whatever else you like.

If this is just some temporary debugging code that you're using to verify that certain code is being executed or has the correct values, then use the Debug class as Zach suggests.

If you absolutely must use the console, then you can attach a console in the program's Main method.

Percentage calculation

Using Math.Round():

int percentComplete = (int)Math.Round((double)(100 * complete) / total);

or manually rounding:

int percentComplete = (int)(0.5f + ((100f * complete) / total));

Case statement with multiple values in each 'when' block

You might take advantage of ruby's "splat" or flattening syntax.

This makes overgrown when clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:

honda  = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...

if include_concept_cars
  honda += ['ev-ster', 'concept c', 'concept s', ...]
  ...
end

case car
when *toyota
  # Do something for Toyota cars
when *honda
  # Do something for Honda cars
...
end

Another common approach would be to use a hash as a dispatch table, with keys for each value of car and values that are some callable object encapsulating the code you wish to execute.

Finding length of char array

If anyone is looking for a quick fix for this, here's how you do it.

while (array[i] != '\0') i++;

The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.

Best practices with STDIN in Ruby?

I do something like this :

all_lines = ""
ARGV.each do |line|
  all_lines << line + "\n"
end
puts all_lines

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If you don't have the msi and you need the upgrade code, rather than the product code then the answer is here: How can I find the upgrade code for an installed application in C#?

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

you could try

$('*').not('#div').bind('touchmove', false);

add this if necessary

$('#div').bind('touchmove');

note that everything is fixed except #div

Find a file by name in Visual Studio Code

When you have opened a folder in a workspace you can do Ctrl+P (Cmd+P on Mac) and start typing the filename, or extension to filter the list of filenames

if you have:

  • plugin.ts
  • page.css
  • plugger.ts

You can type css and press enter and it will open the page.css. If you type .ts the list is filtered and contains two items.

Parsing xml using powershell

First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]

$doc = [xml]@'
<xml>
    <Section name="BackendStatus">
        <BEName BE="crust" Status="1" />
        <BEName BE="pizza" Status="1" />
        <BEName BE="pie" Status="1" />
        <BEName BE="bread" Status="1" />
        <BEName BE="Kulcha" Status="1" />
        <BEName BE="kulfi" Status="1" />
        <BEName BE="cheese" Status="1" />
    </Section>
</xml>
'@

Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:

$doc.xml.Section.BEName

Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where

$doc.xml.Section.BEName | ? { $_.Status -eq 1 }

The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).

If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:

$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }

Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

For more explanation read THIS LINK, it is option of Babel compiler that commands to not include superfluous whitespace characters and line terminators. some times ago its threshold was 100KB but now is 500KB.

I proffer you disable this option in your development environment, with this code in .babelrc file.

{
    "env": {
      "development" : {
        "compact": false
      }
    }
}

For production environment Babel use the default config which is auto.

Algorithm/Data Structure Design Interview Questions

Follow up any question like this with: "How could you improve this code so the developer who maintains it can figure out how it works easily?"

How to test for $null array in PowerShell

It's an array, so you're looking for Count to test for contents.

I'd recommend

$foo.count -gt 0

The "why" of this is related to how PSH handles comparison of collection objects

Only on Firefox "Loading failed for the <script> with source"

This could also be a simple syntax error. I had a syntax error which threw on FF but not Chrome as follows:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
        defer
    </script>

Why can't Python import Image from PIL?

The current free version is PIL 1.1.7. This release supports Python 1.5.2 and newer, including 2.5 and 2.6. A version for 3.X will be released later.

Python Imaging Library (PIL)

Your python version is 3.4.1, PIL do not support!

Calling Python in PHP

Your call_python_file.php should look like this:

<?php
    $item='Everything is awesome!!';
    $tmp = exec("py.py $item");
    echo $tmp;
?>

This executes the python script and outputs the result to the browser. While in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:

import sys

list1 = ' '.join(sys.argv[1:])

def main():
  print list1

if __name__ == '__main__':
    main()

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

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

Convert .cer certificate to .jks

Use the following will help

keytool -import -v -trustcacerts -alias keyAlias -file server.cer -keystore cacerts.jks -keypass changeit

How to append binary data to a buffer in node.js

Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.

However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

Already this has a lot of useful answers but here is something which might work, it did in my case:

Remove unnecessary imports from your class then Clean project or restart Studio.

SQL Query with Join, Count and Where

SELECT COUNT(*), table1.category_id, table2.category_name 
FROM table1 
INNER JOIN table2 ON table1.category_id=table2.category_id 
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name 

add item to dropdown list in html using javascript

Try this

<script type="text/javascript">
    function AddItem()
    {
        // Create an Option object       
        var opt = document.createElement("option");        

        // Assign text and value to Option object
        opt.text = "New Value";
        opt.value = "New Value";

        // Add an Option object to Drop Down List Box
        document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
    }
<script />

The Value will append to the drop down list.

File name without extension name VBA

The answers given here already may work in limited situations, but are certainly not the best way to go about it. Don't reinvent the wheel. The File System Object in the Microsoft Scripting Runtime library already has a method to do exactly this. It's called GetBaseName. It handles periods in the file name as is.

Public Sub Test()

    Dim fso As New Scripting.FileSystemObject
    Debug.Print fso.GetBaseName(ActiveWorkbook.Name)

End Sub

Public Sub Test2()

    Dim fso As New Scripting.FileSystemObject
    Debug.Print fso.GetBaseName("MyFile.something.txt")

End Sub

Instructions for adding a reference to the Scripting Library

How to drop all user tables?

To remove all objects in oracle :

1) Dynamic

DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE' 
AND OWNER='SCHEMA_NAME';
 CURSOR IY IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE 
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND  OWNER='SCHEMA_NAME';
 CURSOR IZ IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND  OWNER='SCHEMA_NAME';
BEGIN
 FOR X IN IX LOOP
   EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' SCHEMA_NAME.'||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
 END LOOP;
 FOR Y IN IY LOOP
   EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' SCHEMA_NAME.'||Y.OBJECT_NAME);
 END LOOP;
 FOR Z IN IZ LOOP
   EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' SCHEMA_NAME.'||Z.OBJECT_NAME||' FORCE ');
 END LOOP;
END;
/

2)Static

    SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
        union ALL
        select 'drop '||object_type||' '|| object_name || ';' from user_objects 
        where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
        union ALL
        SELECT 'drop '
        ||object_type
        ||' '
        || object_name
        || ' force;'
        FROM user_objects
        WHERE object_type IN ('TYPE');

How to custom switch button?

You can use Android Material Components.

enter image description here

build.gradle:

implementation 'com.google.android.material:material:1.0.0'

layout.xml:

<com.google.android.material.button.MaterialButtonToggleGroup
        android:id="@+id/toggleGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:checkedButton="@id/btn_one_way"
        app:singleSelection="true">

    <Button
            style="@style/Widget.MaterialComponents.Button.OutlinedButton"
            android:id="@+id/btn_one_way"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="One way trip" />

    <Button
            style="@style/Widget.MaterialComponents.Button.OutlinedButton"
            android:id="@+id/btn_round"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Round trip" />

</com.google.android.material.button.MaterialButtonToggleGroup>

Database design for a survey

My design is shown below.

The latest create script is at https://gist.github.com/durrantm/1e618164fd4acf91e372

The script and the mysql workbench.mwb file are also available at
https://github.com/durrantm/survey enter image description here

destination path already exists and is not an empty directory

What works for me is that, I created a new folder that doesn't contain any other files, and selected that new folder I created and put the clone there.

I hope this helps

XPath to select multiple tags

Why not a/b/(c|d|e)? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work. abc.xml is the doc described by OP.

(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
    #<XdmNode <d>D1</d>>
    #<XdmNode <e>E1</e>>
    #<XdmNode <c>C2</c>>
    #<XdmNode <d>D2</d>>
    #<XdmNode <e>E1</e>>)

How to set portrait and landscape media queries in css?

It can also be as simple as this.

@media (orientation: landscape) {

}