Programs & Examples On #Lastpasswordset

What's the best way to loop through a set of elements in JavaScript?

I too advise to use the simple way (KISS !-)

-- but some optimization could be found, namely not to test the length of an array more than once:

var elements = document.getElementsByTagName('div');
for (var i=0, im=elements.length; im>i; i++) {
    doSomething(elements[i]);
}

jQuery loop over JSON result from AJAX Success?

I use .map for foreach. For example

success: function(data) {
  let dataItems = JSON.parse(data)
  dataItems = dataItems.map((item) => {
    return $(`<article>
                <h2>${item.post_title}</h2>
                <p>${item.post_excerpt}</p>
              </article>`)
  })
},

What exactly is \r in C language?

There are a few characters which can indicate a new line. The usual ones are these two: '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF). '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).

Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:

DOS and Windows

They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).

Unix (and hence Linux as well)

Unix uses a single '\n' to indicate a new line.

Mac

Macs use a single '\r'.

Refused to load the script because it violates the following Content Security Policy directive

Try replacing your meta tag with this below:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />

Or in addition to what you have, you should add http://* to both style-src and script-src as seen above added after 'self'.

If your server is including the Content-Security-Policy header, the header will override the meta.

'readline/readline.h' file not found

You reference a Linux distribution, so you need to install the readline development libraries

On Debian based platforms, like Ubuntu, you can run:

sudo apt-get install libreadline-dev 

and that should install the correct headers in the correct places,.

If you use a platform with yum, like SUSE, then the command should be:

yum install readline-devel

How to run a single RSpec test?

There are many options:

rspec spec                           # All specs
rspec spec/models                    # All specs in the models directory
rspec spec/models/a_model_spec.rb    # All specs in the some_model model spec
rspec spec/models/a_model_spec.rb:nn # Run the spec that includes line 'nn'
rspec -e"text from a test"           # Runs specs that match the text
rspec spec --tag focus               # Runs specs that have :focus => true
rspec spec --tag focus:special       # Run specs that have :focus => special
rspec spec --tag focus ~skip         # Run tests except those with :focus => true

Check if table exists and if it doesn't exist, create it in SQL Server 2008

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE  TABLE_NAME = 'd020915'))
BEGIN
  declare @result int
  set @result=1
  select @result as result
END

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

Create html documentation for C# code

In 2017, the thing closest to Javadoc would probably DocFx which was developed by Microsoft and comes as a Commmand-Line-Tool as well as a VS2017 plugin.

It's still a little rough around the edges but it looks promising.

Another alternative would be Wyam which has a documentation recipe suitable for net aplications. Look at the cake documentation for an example.

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

SoapUI "failed to load url" error when loading WSDL

This could be a problem with IPV6 address SOAP UI picking. Adding the following JVM option fixed it for me:

-Djava.net.preferIPv4Stack=true

I added it here:

C:\Program Files\SmartBear\soapUI-4.5.2\bin\soapUI-4.5.2.vmoptions

Sort ArrayList of custom Objects by property

New since 1.8 is a List.sort() method instead of using the Collection.sort() so you directly call mylistcontainer.sort()

Here is a code snippet which demonstrates the List.sort() feature:

List<Fruit> fruits = new ArrayList<Fruit>();
fruits.add(new Fruit("Kiwi","green",40));
fruits.add(new Fruit("Banana","yellow",100));
fruits.add(new Fruit("Apple","mixed green,red",120));
fruits.add(new Fruit("Cherry","red",10));

// a) using an existing compareto() method
fruits.sort((Fruit f1,Fruit f2) -> f1.getFruitName().compareTo(f2.getFruitName()));
System.out.println("Using String.compareTo(): " + fruits);
//Using String.compareTo(): [Apple is: mixed green,red, Banana is: yellow, Cherry is: red, Kiwi is: green]

// b) Using a comparable class
fruits.sort((Fruit f1,Fruit f2) -> f1.compareTo(f2));  
System.out.println("Using a Comparable Fruit class (sort by color): " + fruits);
// Using a Comparable Fruit class (sort by color): [Kiwi is green, Apple is: mixed green,red, Cherry is: red, Banana is: yellow]

The Fruit class is:

public class Fruit implements Comparable<Fruit>
{
    private String name;
    private String color;
    private int quantity;

    public Fruit(String name,String color,int quantity)
    { this.name = name; this.color = color; this.quantity = quantity; }

    public String getFruitName() { return name; }        
    public String getColor() { return color; }  
    public int getQuantity() { return quantity; }

    @Override public final int compareTo(Fruit f) // sorting the color
    {
        return this.color.compareTo(f.color);
    }     
    @Override public String toString()
    {   
        return (name + " is: " + color);
    }
} // end of Fruit class   

how to implement a pop up dialog box in iOS

Since the release of iOS 8, UIAlertView is now deprecated; UIAlertController is the replacement.

Here is a sample of how it looks in Swift:

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
    (UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
    () -> Void in
}

As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!

Updated for Swift 4.2

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
        {
            (UIAlertAction) -> Void in
        }
        alert.addAction(alertAction)
        present(alert, animated: true)
        {
            () -> Void in
        }

Detect Route Change with react-router

Update for React Router 5.1+.

import React from 'react';
import { useLocation, Switch } from 'react-router-dom'; 

const App = () => {
  const location = useLocation();

  React.useEffect(() => {
    console.log('Location changed');
  }, [location]);

  return (
    <Switch>
      {/* Routes go here */}
    </Switch>
  );
};

How do I find the caller of a method using stacktrace or reflection?

This method does the same thing but a little more simply and possibly a little more performant and in the event you are using reflection, it skips those frames automatically. The only issue is it may not be present in non-Sun JVMs, although it is included in the runtime classes of JRockit 1.4-->1.6. (Point is, it is not a public class).

sun.reflect.Reflection

    /** Returns the class of the method <code>realFramesToSkip</code>
        frames up the stack (zero-based), ignoring frames associated
        with java.lang.reflect.Method.invoke() and its implementation.
        The first frame is that associated with this method, so
        <code>getCallerClass(0)</code> returns the Class object for
        sun.reflect.Reflection. Frames associated with
        java.lang.reflect.Method.invoke() and its implementation are
        completely ignored and do not count toward the number of "real"
        frames skipped. */
    public static native Class getCallerClass(int realFramesToSkip);

As far as what the realFramesToSkip value should be, the Sun 1.5 and 1.6 VM versions of java.lang.System, there is a package protected method called getCallerClass() which calls sun.reflect.Reflection.getCallerClass(3), but in my helper utility class I used 4 since there is the added frame of the helper class invocation.

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

If you want to use it as a date instead of a varchar again afterwards, don't forget to convert it back:

select convert(datetime,CONVERT(char(10), GetDate(),126))

What is the difference between iterator and iterable and how to use them?

As explained here, The “Iterable” was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.

Redirecting to a page after submitting form in HTML

You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

Example:

 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      window.location.href = 'https://website.com/my-account';
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();

Running a Python script from PHP

In my case I needed to create a new folder in the www directory called scripts. Within scripts I added a new file called test.py.

I then used sudo chown www-data:root scripts and sudo chown www-data:root test.py.

Then I went to the new scripts directory and used sudo chmod +x test.py.

My test.py file it looks like this. Note the different Python version:

#!/usr/bin/env python3.5
print("Hello World!")

From php I now do this:

$message = exec("/var/www/scripts/test.py 2>&1");
print_r($message);

And you should see: Hello World!

Setting the filter to an OpenFileDialog to allow the typical image formats?

This is extreme, but I built a dynamic, database-driven filter using a 2 column database table named FILE_TYPES, with field names EXTENSION and DOCTYPE:

---------------------------------
| EXTENSION  |  DOCTYPE         |
---------------------------------
|   .doc     |  Document        |
|   .docx    |  Document        |
|   .pdf     |  Document        |
|   ...      |  ...             |
|   .bmp     |  Image           |
|   .jpg     |  Image           |
|   ...      |  ...             |
---------------------------------

Obviously I had many different types and extensions, but I'm simplifying it for this example. Here is my function:

    private static string GetUploadFilter()
    {
        // Desired format:
        // "Document files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf|"
        // "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|"

        string filter = String.Empty;
        string nameFilter = String.Empty;
        string extFilter = String.Empty;

        // Used to get extensions
        DataTable dt = new DataTable();
        dt = DataLayer.Get_DataTable("SELECT * FROM FILE_TYPES ORDER BY EXTENSION");

        // Used to cycle through doctype groupings ("Images", "Documents", etc.)
        DataTable dtDocTypes = new DataTable();
        dtDocTypes = DataLayer.Get_DataTable("SELECT DISTINCT DOCTYPE FROM FILE_TYPES ORDER BY DOCTYPE");

        // For each doctype grouping...
        foreach (DataRow drDocType in dtDocTypes.Rows)
        {
            nameFilter = drDocType["DOCTYPE"].ToString() + " files (";

            // ... add its associated extensions
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["DOCTYPE"].ToString() == drDocType["DOCTYPE"].ToString())
                {
                    nameFilter += "*" + dr["EXTENSION"].ToString() + ", ";
                    extFilter += "*" + dr["EXTENSION"].ToString() + ";";
                }                    
            }

            // Remove endings put in place in case there was another to add, and end them with pipe characters:
            nameFilter = nameFilter.TrimEnd(' ').TrimEnd(',');
            nameFilter += ")|";
            extFilter = extFilter.TrimEnd(';');
            extFilter += "|";

            // Add the name and its extensions to our main filter
            filter += nameFilter + extFilter;

            extFilter = ""; // clear it for next round; nameFilter will be reset to the next DOCTYPE on next pass
        }

        filter = filter.TrimEnd('|');
        return filter;
    }

    private void UploadFile(string fileType, object sender)
    {            
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        string filter = GetUploadFilter();
        dlg.Filter = filter;

        if (dlg.ShowDialog().Value == true)
        {
            string fileName = dlg.FileName;

            System.IO.FileStream fs = System.IO.File.OpenRead(fileName);
            byte[] array = new byte[fs.Length];

            // This will give you just the filename
            fileName = fileName.Split('\\')[fileName.Split('\\').Length - 1];
            ...

Should yield a filter that looks like this:

enter image description here

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

I was getting the same error in python 3.4.3 too and I tried using the solutions mentioned here and elsewhere with no success.

Microsoft makes a compiler available for Python 2.7 but it didn't do me much good since I am on 3.4.3.

Python since 3.3 has transitioned over to 2010 and you can download and install Visual C++ 2010 Express for free here: https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express

Here is the official blog post talking about the transition to 2010 for 3.3: http://blog.python.org/2012/05/recent-windows-changes-in-python-33.html

Because previous versions gave a different error for vcvarsall.bat I would double check the version you are using with "pip -V"

C:\Users\B>pip -V
pip 6.0.8 from C:\Python34\lib\site-packages (python 3.4)

As a side note, I too tried using the latest version of VC++ (2013) first but it required installing 2010 express.

From that point forward it should work for anyone using the 32 bit version, if you are on the 64 bit version you will then get the ValueError: ['path'] message because VC++ 2010 doesn't have a 64 bit compuler. For that you have to get the Microsoft SDK 7.1. I can't hyperlink the instruction for 64 bit because I am limited to 2 links per post but its at

Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

How do I write stderr to a file while using "tee" with a pipe?

why not simply:

./aaa.sh 2>&1 | tee -a log

This simply redirects stderr to stdout, so tee echoes both to log and to screen. Maybe I'm missing something, because some of the other solutions seem really complicated.

Note: Since bash version 4 you may use |& as an abbreviation for 2>&1 |:

./aaa.sh |& tee -a log

T-SQL: Looping through an array of known values

You can try as below :

declare @list varchar(MAX), @i int
select @i=0, @list ='4,7,12,22,19,'

while( @i < LEN(@list))
begin
    declare @item varchar(MAX)
    SELECT  @item = SUBSTRING(@list,  @i,CHARINDEX(',',@list,@i)-@i)
    select @item

     --do your stuff here with @item 
     exec p_MyInnerProcedure @item 

    set @i = CHARINDEX(',',@list,@i)+1
    if(@i = 0) set @i = LEN(@list) 
end

Change route params without reloading in Angular 2

You could use location.go(url) which will basically change your url, without change in route of application.

NOTE this could cause other effect like redirect to child route from the current route.

Related question which describes location.go will not intimate to Router to happen changes.

The most efficient way to implement an integer based power function pow(int, int)

Just as a follow up to comments on the efficiency of exponentiation by squaring.

The advantage of that approach is that it runs in log(n) time. For example, if you were going to calculate something huge, such as x^1048575 (2^20 - 1), you only have to go thru the loop 20 times, not 1 million+ using the naive approach.

Also, in terms of code complexity, it is simpler than trying to find the most optimal sequence of multiplications, a la Pramod's suggestion.

Edit:

I guess I should clarify before someone tags me for the potential for overflow. This approach assumes that you have some sort of hugeint library.

How to use CMAKE_INSTALL_PREFIX

That should be (see the docs):

cmake -DCMAKE_INSTALL_PREFIX=/usr ..

In vb.net, how to get the column names from a datatable

Do you have access to your database, if so just open it up and look up the column and use an SQL call to retrieve the needed.

A short example on a form to retrieve data from a database table:

Form contain only a GataGridView named DataGrid

Database name: DB.mdf

Table name: DBtable

Column names in table: Name as varchar(50), Age as int, Gender as bit.

Private Sub DatabaseTest_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Public ConString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\{username}\documents\visual studio 2010\Projects\Userapplication prototype v1.0\Userapplication prototype v1.0\Database\DB.mdf;" & "Integrated Security=True;User Instance=True"
    Dim conn As New SqlClient.SqlConnection
    Dim cmd As New SqlClient.SqlCommand
    Dim da As New SqlClient.SqlDataAdapter
    Dim dt As New DataTable
    Dim sSQL As String = String.Empty
    Try
        conn = New SqlClient.SqlConnection(ConString)
        conn.Open() 'connects to the database
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        sSQL = "SELECT * FROM DBtable" 'Sql to be executed
        cmd.CommandText = sSQL 'makes the string a command
        da.SelectCommand = cmd 'puts the command into the sqlDataAdapter
        da.Fill(dt) 'populates the dataTable by performing the command above
        Me.DataGrid.DataSource = dt 'Updates the grid using the populated dataTable

        'the following is only if any errors happen:
        If dt.Rows.Count = 0 Then
            MsgBox("No record found!")
        End If
    Catch ex As Exception
        MsgBox(ErrorToString)
    Finally
        conn.Close() 'closes the connection again so it can be accessed by other users or programs
    End Try
End Sub

This will fetch all the rows and columns from your database table for review.
If you want to only fetch the names just change the sql call with: "SELECT Name FROM DBtable" this way the DataGridView will only show the column names.

I'm only a rookie but i would strongly advise to get rid of theses auto generate wizards. Using SQL you have full access to your database and what happens.
Also one last thing, if your database doesn't use SQLClient just change it to OleDB.

Example: "Dim conn As New SqlClient.SqlConnection" becomes: Dim conn As New OleDb.OleDbConnection

How can I drop a table if there is a foreign key constraint in SQL Server?

Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;

MySQL – Temporarily disable Foreign Key Checks or Constraints

How to return value from Action()?

You can use Func<T, TResult> generic delegate. (See MSDN)

Func<MyType, ReturnType> func = (db) => { return new MyType(); }

Also there are useful generic delegates which considers a return value:

  • Converter<TInput, TOutput> (MSDN)
  • Predicate<TInput> - always return bool (MSDN)

Method:

public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory)

Generic delegate:

Func<InputArgumentType, MyType> createInstance = db => return new MyType();

Execute:

MyType myTypeInstance = SimpleUsing.DoUsing(
                            createInstance(new InputArgumentType()));

OR explicitly:

MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType());

putting a php variable in a HTML form value

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

Is there a way to add/remove several classes in one single instruction with classList?

Assume that you have an array of classes to being added, you can use ES6 spread syntax:

let classes = ['first', 'second', 'third']; elem.classList.add(...classes);

Impersonate tag in Web.Config

Put the identity element before the authentication element

How to bind an enum to a combobox control in WPF?

If you are binding to an actual enum property on your ViewModel, not a int representation of an enum, things get tricky. I found it is necessary to bind to the string representation, NOT the int value as is expected in all of the above examples.

You can tell if this is the case by binding a simple textbox to the property you want to bind to on your ViewModel. If it shows text, bind to the string. If it shows a number, bind to the value. Note I have used Display twice which would normally be an error, but it's the only way it works.

<ComboBox SelectedValue="{Binding ElementMap.EdiDataType, Mode=TwoWay}"
                      DisplayMemberPath="Display"
                      SelectedValuePath="Display"
                      ItemsSource="{Binding Source={core:EnumToItemsSource {x:Type edi:EdiDataType}}}" />

Greg

Multiple submit buttons in the same form calling different Servlets

You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.

function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});

Python Infinity - Any caveats?

Python's implementation follows the IEEE-754 standard pretty well, which you can use as a guidance, but it relies on the underlying system it was compiled on, so platform differences may occur. Recently¹, a fix has been applied that allows "infinity" as well as "inf", but that's of minor importance here.

The following sections equally well apply to any language that implements IEEE floating point arithmetic correctly, it is not specific to just Python.

Comparison for inequality

When dealing with infinity and greater-than > or less-than < operators, the following counts:

  • any number including +inf is higher than -inf
  • any number including -inf is lower than +inf
  • +inf is neither higher nor lower than +inf
  • -inf is neither higher nor lower than -inf
  • any comparison involving NaN is false (inf is neither higher, nor lower than NaN)

Comparison for equality

When compared for equality, +inf and +inf are equal, as are -inf and -inf. This is a much debated issue and may sound controversial to you, but it's in the IEEE standard and Python behaves just like that.

Of course, +inf is unequal to -inf and everything, including NaN itself, is unequal to NaN.

Calculations with infinity

Most calculations with infinity will yield infinity, unless both operands are infinity, when the operation division or modulo, or with multiplication with zero, there are some special rules to keep in mind:

  • when multiplied by zero, for which the result is undefined, it yields NaN
  • when dividing any number (except infinity itself) by infinity, which yields 0.0 or -0.0².
  • when dividing (including modulo) positive or negative infinity by positive or negative infinity, the result is undefined, so NaN.
  • when subtracting, the results may be surprising, but follow common math sense:
    • when doing inf - inf, the result is undefined: NaN;
    • when doing inf - -inf, the result is inf;
    • when doing -inf - inf, the result is -inf;
    • when doing -inf - -inf, the result is undefined: NaN.
  • when adding, it can be similarly surprising too:
    • when doing inf + inf, the result is inf;
    • when doing inf + -inf, the result is undefined: NaN;
    • when doing -inf + inf, the result is undefined: NaN;
    • when doing -inf + -inf, the result is -inf.
  • using math.pow, pow or ** is tricky, as it doesn't behave as it should. It throws an overflow exception when the result with two real numbers is too high to fit a double precision float (it should return infinity), but when the input is inf or -inf, it behaves correctly and returns either inf or 0.0. When the second argument is NaN, it returns NaN, unless the first argument is 1.0. There are more issues, not all covered in the docs.
  • math.exp suffers the same issues as math.pow. A solution to fix this for overflow is to use code similar to this:

    try:
        res = math.exp(420000)
    except OverflowError:
        res = float('inf')
    

Notes

Note 1: as an additional caveat, that as defined by the IEEE standard, if your calculation result under-or overflows, the result will not be an under- or overflow error, but positive or negative infinity: 1e308 * 10.0 yields inf.

Note 2: because any calculation with NaN returns NaN and any comparison to NaN, including NaN itself is false, you should use the math.isnan function to determine if a number is indeed NaN.

Note 3: though Python supports writing float('-NaN'), the sign is ignored, because there exists no sign on NaN internally. If you divide -inf / +inf, the result is NaN, not -NaN (there is no such thing).

Note 4: be careful to rely on any of the above, as Python relies on the C or Java library it was compiled for and not all underlying systems implement all this behavior correctly. If you want to be sure, test for infinity prior to doing your calculations.

¹) Recently means since version 3.2.
²) Floating points support positive and negative zero, so: x / float('inf') keeps its sign and -1 / float('inf') yields -0.0, 1 / float(-inf) yields -0.0, 1 / float('inf') yields 0.0 and -1/ float(-inf) yields 0.0. In addition, 0.0 == -0.0 is true, you have to manually check the sign if you don't want it to be true.

How do I get first element rather than using [0] in jQuery?

With the assumption that there's only one element:

 $("#grid_GridHeader")[0]
 $("#grid_GridHeader").get(0)
 $("#grid_GridHeader").get()

...are all equivalent, returning the single underlying element.

From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0] approach:

 // Return just the object
 ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );

Re-ordering columns in pandas dataframe based on column name

print df.sort_index(by='Frequency',ascending=False)

where by is the name of the column,if you want to sort the dataset based on column

How do I run a simple bit of code in a new thread?

Put that code in a function (the code that can't be executed on the same thread as the GUI), and to trigger that code's execution put the following.

Thread myThread= new Thread(nameOfFunction);

workerThread.Start();

Calling the start function on the thread object will cause the execution of your function call in a new thread.

How to check a string against null in java?

With Java 7 you can use

if (Objects.equals(foo, null)) {
    ...
}

which will return true if both parameters are null.

Background color in input and text fields

input[type="text"], textarea {

  background-color : #d1d1d1; 

}

Hope that helps :)

Edit: working example, http://jsfiddle.net/C5WxK/

How do I capture the output into a variable from an external process in PowerShell?

If you want to redirect the error output as well, you have to do:

$cmdOutput = command 2>&1

Or, if the program name has spaces in it:

$cmdOutput = & "command with spaces" 2>&1

Artisan, creating tables in database

In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......

phpmyadmin logs out after 1440 secs

For Ubuntu 18.04 I just edited the file /usr/share/phpmyadmin/libraries/config.default.php

Change: $cfg['LoginCookieValidity'] = 1440

How to perform a sum of an int[] array

int sum=0;
for(int i:A)
  sum+=i;

How to solve java.lang.NullPointerException error?

Just a shot in the dark(since you did not share the compiler initialization code with us): the way you retrieve the compiler causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE.

Writing string to a file on a new line every time

Ok, here is a safe way of doing it.

with open('example.txt', 'w') as f:
 for i in range(10):
  f.write(str(i+1))
  f.write('\n')


This writes 1 to 10 each number on a new line.

Shortest way to print current year in a website

_x000D_
_x000D_
<div>&copy;<script>document.write(new Date().getFullYear());</script>, Company._x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if an element of a list is a list (in Python)?

you can simply write:

for item,i in zip(your_list, range(len(your_list)):

    if type(item) == list:
        print(f"{item} at index {i} is a list")

How to Find App Pool Recycles in Event Log

As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:

Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}

From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.

This along with @BlackHawkDesign comment should help you find what you need.

I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00

How to get input from user at runtime

its very simple

just write:

//first create table named test....

create table test (name varchar2(10),age number(5));

//when you run the above code a table will be created....

//now we have to insert a name & an age..

Make sure age will be inserted via opening a form that seeks our help to enter the value in it

insert into test values('Deepak', :age);

//now run the above code and you'll get "1 row inserted" output...

/now run the select query to see the output

select * from test;

//that's all ..Now i think no one has any queries left over accepting a user data...

Where to find the complete definition of off_t type?

If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();

Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?

jQuery: Count number of list elements?

Try:

$("#mylist li").length

Just curious: why do you need to know the size? Can't you just use:

$("#mylist").append("<li>New list item</li>");

?

Options for initializing a string array

string[] str = new string[]{"1","2"};
string[] str = new string[4];

ERROR 1148: The used command is not allowed with this MySQL version

If you are using Java8 or + version, JDBC and MySql8 and facing this issue then try this:

Add parameter to connection string:

jdbc:mysql://localhost:3306/tempDB?allowLoadLocalInfile=true

Also, set

local_infile = 1

in my.cnf file.

The latest version of mysql-java-connector might be wont allow directly to connect to local file. So with this parameter, you can able to enable it. This works for me.

How to copy and edit files in Android shell?

I could suggest just install Terminal-ide on you device which available in play market. Its free, does not require root and provide convenient *nix environment like cp, find, du, mc and many other utilities which installed in binary form by one button tap.

Convert HH:MM:SS string to seconds only in javascript

This function works for MM:SS as well:

_x000D_
_x000D_
const convertTime = (hms) => {_x000D_
        if (hms.length <3){_x000D_
         return hms_x000D_
        } else if (hms.length <6){_x000D_
          const a = hms.split(':')_x000D_
          return hms = (+a[0]) * 60 + (+a[1])_x000D_
        } else {_x000D_
          const a = hms.split(':')_x000D_
          return hms = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2])_x000D_
        }_x000D_
      }
_x000D_
_x000D_
_x000D_

Select a dummy column with a dummy value in SQL?

If you meant just ABC as simple value, answer above is the one that works fine.

If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.

Something like this may work:

SELECT t1.col1, 
t1.col2, 
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM  Table1 t2 WHERE t2.col1 != 0) as col3 
FROM Table1 t1
WHERE t1.col1 = 0;

Actual syntax maybe a bit off though

How to position a div in the middle of the screen when the page is bigger than the screen

Two ways to position a tag in the middle of screen or its parent tag:

Using positions:

Set the parent tag position to relative (if the target tag has a parent tag) and then set the target tag style like this:

#center {
  ...  
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Using flex:

The parent tag style should looks like this:

#parent-tag {
  display: flex;
  align-items: center;
  justify-content: center;
}

What is the best way to left align and right align two div tags?

This solution has left aligned text and button on the far right.

If anyone is looking for a material design answer:

<div layout="column" layout-align="start start">
 <div layout="row" style="width:100%">
    <div flex="grow">Left Aligned text</div>
    <md-button aria-label="help" ng-click="showHelpDialog()">
      <md-icon md-svg-icon="help"></md-icon>
    </md-button>
 </div>
</div>  

Extract digits from string - StringUtils Java

Try this approach if you have symbols and you want just numbers:

    String s  = "@##9823l;Azad9927##$)(^738#";
    System.out.println(s=s.replaceAll("[^0-9]", ""));
    StringTokenizer tok = new StringTokenizer(s,"`~!@#$%^&*()-_+=\\.,><?");
    String s1 = "";
    while(tok.hasMoreTokens()){
        s1+= tok.nextToken();
    }
    System.out.println(s1);

How to get text and a variable in a messagebox

MsgBox("Variable {0} " , variable)

Find which commit is currently checked out in Git

You can just do:

git rev-parse HEAD

To explain a bit further: git rev-parse is git's basic command for interpreting any of the exotic ways that you can specify the name of a commit and HEAD is a reference to your current commit or branch. (In a git bisect session, it points directly to a commit ("detached HEAD") rather than a branch.)

Alternatively (and easier to remember) would be to just do:

git show

... which defaults to showing the commit that HEAD points to. For a more concise version, you can do:

$ git show --oneline -s
c0235b7 Autorotate uploaded images based on EXIF orientation

Download file using libcurl in C/C++

Just for those interested you can avoid writing custom function by passing NULL as last parameter (if you do not intend to do extra processing of returned data).
In this case default internal function is used.

Details
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA

Example

#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://stackoverflow.com";
    char outfilename[FILENAME_MAX] = "page.html";
    curl = curl_easy_init();                                                                                                                                                                                                                                                           
    if (curl)
    {   
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }   
    return 0;
}

Converting datetime.date to UTC timestamp in Python

i'm impressed of the deep discussion.

my 2 cents:

from datetime import datetime import time

the timestamp in utc is:

timestamp = \
(datetime.utcnow() - datetime(1970,1,1)).total_seconds()

or,

timestamp = time.time()

if now results from datetime.now(), in the same DST

utcoffset = (datetime.now() - datetime.utcnow()).total_seconds()
timestamp = \
(now - datetime(1970,1,1)).total_seconds() - utcoffset

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I had the same issue after an upgrade from VS2013 to VS2015.

The project I was working at referenced itself. While VS2013 didn't care, VS2015 didn't like that and I got that error. After deleting the reference, the error was gone. It took me around 4 hours to find that out...

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

Labeling file upload button

You get your browser's language for your button. There's no way to change it programmatically.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:

def book_author(self):
  return self.book.author

Then the admin part works nicely.

A html space is showing as %2520 instead of %20

Try this?

encodeURIComponent('space word').replace(/%20/g,'+')

How can I count the occurrences of a list item?

It was suggested to use numpy's bincount, however it works only for 1d arrays with non-negative integers. Also, the resulting array might be confusing (it contains the occurrences of the integers from min to max of the original list, and sets to 0 the missing integers).

A better way to do it with numpy is to use the unique function with the attribute return_counts set to True. It returns a tuple with an array of the unique values and an array of the occurrences of each unique value.

# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True)  # array([0, 1, 2, 3]), array([2, 3, 1, 2]

and then we can pair them as

dict(zip(a_uniq, counts))  # {0: 2, 1: 3, 2: 1, 3: 2}

It also works with other data types and "2d lists", e.g.

>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 2}

phpmyadmin "no data received to import" error, how to fix?

xampp in ubuntu

cd /opt/lampp/etc
vim php.ini

Find:
  post_max_size = 8M
  upload_max_filesize = 2M
  max_execution_time = 30
  max_input_time = 60
  memory_limit = 8M

Change to:
  post_max_size = 750M
  upload_max_filesize = 750M
  max_execution_time = 5000
  max_input_time = 5000
  memory_limit = 1000M

sudo /opt/lampp/lampp restart

How to persist data in a dockerized postgres database using volumes

I would avoid using a relative path. Remember that docker is a daemon/client relationship.

When you are executing the compose, it's essentially just breaking down into various docker client commands, which are then passed to the daemon. That ./database is then relative to the daemon, not the client.

Now, the docker dev team has some back and forth on this issue, but the bottom line is it can have some unexpected results.

In short, don't use a relative path, use an absolute path.

Google Maps API 3 - Custom marker color for default (dot) marker

Here is a nice solution using the Gooogle Maps API itself. No external service, no extra library. And it enables custom shapes and multiple colors and styles. The solution uses vectorial markers, which googlemaps api calls Symbols.

Besides the few and limited predefined symbols, you can craft any shape of any color by specifying an SVG path string (Spec).

To use it, instead of setting the 'icon' marker option to the image url, you set it to a dictionary containing the symbol options. As example, I managed to craft one symbol that is quite similar to the standard marker:

function pinSymbol(color) {
    return {
        path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
        fillColor: color,
        fillOpacity: 1,
        strokeColor: '#000',
        strokeWeight: 2,
        scale: 1,
   };
}

var marker = new google.maps.Marker({
   map: map,
   position: new google.maps.LatLng(latitude, longitude),
   icon: pinSymbol("#FFF"),
});

Vector Marker

I you are careful to keep the shape key point at 0,0 you avoid having to define marker icon centering parameters. Another path example, the same marker without the dot:

    path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',

Dotless Vector Marker

And here you have a very simple and ugly coloured flag:

    path: 'M 0,0 -1,-2 V -43 H 1 V -2 z M 1,-40 H 30 V -20 H 1 z',

Vector Flag

You can also create the paths using a visual tool like Inkscape (GNU-GPL, multiplatform). Some useful hints:

  • Google API just accepts a single path, so you have to turn any other object (square, cercle...) into a path and join them as a single one. Both commands at the Path menu.
  • To move the path to the (0,0), go to the Path Edit mode (F2) select all the control nodes and drag them. Moving the object with F1, won't change the path node coords.
  • To ensure the reference point is at (0,0), you can select it alone and edit the coords by hand on the top toolbar.
  • After saving the SVG file, which is an XML, open it with an editor, look for the svg:path element and copy the content of the 'd' attribute.

How to download a Nuget package without nuget.exe or Visual Studio extension?

Although building the URL or using tools is still possible, it is not needed anymore.

https://www.nuget.org/ currently has a download link named "Download package", that is available even if you don't have an account on the site.

(at the bottom of the right column).


Example of EntityFramework's detail page: https://www.nuget.org/packages/EntityFramework/: (Updated after comment of kwitee.)

Example of EntityFramework's detail page

Completely cancel a rebase

You are lucky that you didn't complete the rebase, so you can still do git rebase --abort. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.

'gulp' is not recognized as an internal or external command

The best solution, you can manage the multiple node versions using nvm installer. then, install the required node's version using below command

nvm install version

Use below command as a working node with mentioned version alone

nvm use version

now, you can use any version node without uninstalling previous installed node.

Returning value from Thread

With small modifications to your code, you can achieve it in a more generic way.

 final Handler responseHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                //txtView.setText((String) msg.obj);
                Toast.makeText(MainActivity.this,
                        "Result from UIHandlerThread:"+(int)msg.obj,
                        Toast.LENGTH_LONG)
                        .show();
            }
        };

        HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
            public void run(){
                Integer a = 2;
                Message msg = new Message();
                msg.obj = a;
                responseHandler.sendMessage(msg);
                System.out.println(a);
            }
        };
        handlerThread.start();

Solution :

  1. Create a Handler in UI Thread,which is called as responseHandler
  2. Initialize this Handler from Looper of UI Thread.
  3. In HandlerThread, post message on this responseHandler
  4. handleMessgae shows a Toast with value received from message. This Message object is generic and you can send different type of attributes.

With this approach, you can send multiple values to UI thread at different point of times. You can run (post) many Runnable objects on this HandlerThread and each Runnable can set value in Message object, which can be received by UI Thread.

How to do a Jquery Callback after form submit?

$("#formid").ajaxForm({ success: function(){ //to do after submit } });

How to submit an HTML form without redirection

Okay, I'm not going to tell you a magical way of doing it because there isn't. If you have an action attribute set for a form element, it will redirect.

If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"

In your someFunction() you do whatever you want, (with AJAX or not) and in the ending, you add return false; to tell the browser not to submit the form...

What are Maven goals and phases and what is their difference?

Credit to Sandeep Jindal and Premraj. Their explanation help me to understand after confused about this for a while.

I created some full code examples & some simple explanations here https://www.surasint.com/maven-life-cycle-phase-and-goal-easy-explained/ . I think it may help others to understand.

In short from the link, You should not try to understand all three at once, first you should understand the relationship in these groups:

  • Life Cycle vs Phase
  • Plugin vs Goal

1. Life Cycle vs Phase

Life Cycle is a collection of phase in sequence see here Life Cycle References. When you call a phase, it will also call all phase before it.

For example, the clean life cycle has 3 phases (pre-clean, clean, post-clean).

mvn clean

It will call pre-clean and clean.

2. Plugin vs Goal

Goal is like an action in Plugin. So if plugin is a class, goal is a method.

you can call a goal like this:

mvn clean:clean

This means "call the clean goal, in the clean plugin" (Nothing relates to the clean phase here. Don't let the word"clean" confusing you, they are not the same!)

3. Now the relation between Phase & Goal:

Phase can (pre)links to Goal(s).For example, normally, the clean phase links to the clean goal. So, when you call this command:

mvn clean

It will call the pre-clean phase and the clean phase which links to the clean:clean goal.

It is almost the same as:

mvn pre-clean clean:clean

More detail and full examples are in https://www.surasint.com/maven-life-cycle-phase-and-goal-easy-explained/

utf-8 special characters not displaying

set meta tag in head as

 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> 

use the link http://www.i18nqa.com/debug/utf8-debug.html to replace the symbols character you want.

then use str_replace like

    $find = array('“', '’', '…', '—', '–', '‘', 'é', 'Â', '•', 'Ëœ', 'â€'); // en dash
                        $replace = array('“', '’', '…', '—', '–', '‘', 'é', '', '•', '˜', '”');
$content = str_replace($find, $replace, $content);

Its the method i use and help alot. Thanks!

Executing Javascript code "on the spot" in Chrome?

I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.

Updating PartialView mvc 4

Controller :

public ActionResult Refresh(string ID)
    {
        DetailsViewModel vm = new DetailsViewModel();  // Model
        vm.productDetails = _product.GetproductDetails(ID); 
        /* "productDetails " is a property in "DetailsViewModel"
        "GetProductDetails" is a method in "Product" class
        "_product" is an interface of "Product" class */

        return PartialView("_Details", vm); // Details is a partial view
    }

In yore index page you should to have refresh link :

     <a href="#" id="refreshItem">Refresh</a>

This Script should be also in your index page:

<script type="text/javascript">

    $(function () {
    $('a[id=refreshItem]:last').click(function (e) {
        e.preventDefault();

        var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            success: function (grid) {
                $('#tabItemDetails').html(grid);
                clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
            }
        });
    });
});

What is the string concatenation operator in Oracle?

Using CONCAT(CONCAT(,),) worked for me when concatenating more than two strings.

My problem required working with date strings (only) and creating YYYYMMDD from YYYY-MM-DD as follows (i.e. without converting to date format):

CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

I just solved this issue on HackerRank, so I'm here to share my result

function timeConversion(s) {
    const isPM = s.indexOf('PM') !== -1;
    let [hours, minutes, seconds] = s.replace(isPM ? 'PM':'AM', '').split(':');

    if (isPM) {
        hours = parseInt(hours, 10) + 12;
        hours = hours === 24 ? 12 : hours;
    } else {
        hours = parseInt(hours, 10);
        hours = hours === 12 ? 0 : hours;
        if (String(hours).length === 1) hours = '0' + hours;
    }

    const time = [hours, minutes, seconds].join(':');

    return time;
}

This works for inputs like 06:40:03AM.

POST data in JSON format

Another example is available here:

Sending a JSON to server and retrieving a JSON in return, without JQuery

Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.

MySQL, create a simple function

Try to change CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR this portion to CREATE FUNCTION F_TEST(PID INT) RETURNS TEXT

and change the following line too.

DECLARE NAME_FOUND TEXT DEFAULT "";

It should work.

How to call javascript from a href?

<a href="javascript:call_func();">...</a>

where the function then has to return false so that the browser doesn't go to another page.

But I'd recommend to use jQuery (with $(...).click(function () {})))

How do I conditionally apply CSS styles in AngularJS?

One thing to watch is - if the CSS style has dashes - you must remove them. So if you want to set background-color, the correct way is:

ng-style="{backgroundColor:myColor}" 

Check if value already exists within list of dictionaries?

Here's one way to do it:

if not any(d['main_color'] == 'red' for d in a):
    # does not exist

The part in parentheses is a generator expression that returns True for each dictionary that has the key-value pair you are looking for, otherwise False.


If the key could also be missing the above code can give you a KeyError. You can fix this by using get and providing a default value. If you don't provide a default value, None is returned.

if not any(d.get('main_color', default_value) == 'red' for d in a):
    # does not exist

How do you force a CIFS connection to unmount

On RHEL 6 this worked for me also:

umount -f -a -t cifs -l FOLDER_NAME

What is the purpose of the var keyword and when should I use it (or omit it)?

Here's quite a good example of how you can get caught out from not declaring local variables with var:

<script>
one();

function one()
{
    for (i = 0;i < 10;i++)
    {
        two();
        alert(i);
    }
}

function two()
{
    i = 1;
}
</script>

(i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally) eventually resulting in infinite loop

Pandas: sum DataFrame rows for given columns

You can just sum and set param axis=1 to sum the rows, this will ignore none numeric columns:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

How to implement a ConfigurationSection with a ConfigurationElementCollection

The previous answer is correct but I'll give you all the code as well.

Your app.config should look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
   </configSections>
   <ServicesSection>
      <Services>
         <add Port="6996" ReportType="File" />
         <add Port="7001" ReportType="Other" />
      </Services>
   </ServicesSection>
</configuration>

Your ServiceConfig and ServiceCollection classes remain unchanged.

You need a new class:

public class ServiceConfigurationSection : ConfigurationSection
{
   [ConfigurationProperty("Services", IsDefaultCollection = false)]
   [ConfigurationCollection(typeof(ServiceCollection),
       AddItemName = "add",
       ClearItemsName = "clear",
       RemoveItemName = "remove")]
   public ServiceCollection Services
   {
      get
      {
         return (ServiceCollection)base["Services"];
      }
   }
}

And that should do the trick. To consume it you can use:

ServiceConfigurationSection serviceConfigSection =
   ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;

ServiceConfig serviceConfig = serviceConfigSection.Services[0];

How do you specify a debugger program in Code::Blocks 12.11?

  1. Go to Settings -> Debugger -> Common -> GDB/CDB Debugger -> Default
  2. Click on executable path to find the address to gdb32.exe
  3. Locate where your codeblock is installed
  4. Follow the given path:

CodeBlock -> MinGW -> bin -> gdb32.exe (locate it and double click on it)

  1. Press OK

Convert.ToDateTime: how to set format

If value is a string in that format and you'd like to convert it into a DateTime object, you can use DateTime.ParseExact static method:

DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);

Example:

string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

Console.WriteLine(myDate.ToShortDateString());

Result:

2012-12-01

How do I get the day of week given a date?

This don't need to day of week comments.
I recommend this code~!

import datetime


DAY_OF_WEEK = {
    "MONDAY": 0,
    "TUESDAY": 1,
    "WEDNESDAY": 2,
    "THURSDAY": 2,
    "FRIDAY": 2,
    "SATURDAY": 2,
    "SUNDAY": 6
}

def string_to_date(dt, format='%Y%m%d'):
    return datetime.datetime.strptime(dt, format)

def date_to_string(date, format='%Y%m%d'):
    return datetime.datetime.strftime(date, format)

def day_of_week(dt):
    return string_to_date(dt).weekday()


dt = '20210101'
if day_of_week(dt) == DAY_OF_WEEK['SUNDAY']:
    None

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

  1. Make sure ruby-dev is installed
  2. Make sure make is installed
  3. If you still get the error, look for suggested packages. If you are trying to install something like gem install pg you will also need to install the lib libpq-dev (sudo apt-get install libpq-dev).

How to get my activity context?

Ok, I will give a small example on how to do what you ask

public class ClassB extends Activity
{

 ClassA A1 = new ClassA(this); // for activity context

 ClassA A2 = new ClassA(getApplicationContext());  // for application context. 

}

How to convert a pymongo.cursor.Cursor into a dict?

The find method returns a Cursor instance, which allows you to iterate over all matching documents.

To get the first document that matches the given criteria you need to use find_one. The result of find_one is a dictionary.

You can always use the list constructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.

You should do that if you need to reuse the cursor and have a good reason not to use rewind()


Demo using find:

>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()  
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
...     print(doc)  # or do something with the document
... 
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}

Demo using find_one:

>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}

How to properly add include directories with CMake

CMake is more like a script language if comparing it with other ways to create Makefile (e.g. make or qmake). It is not very cool like Python, but still.

There are no such thing like a "proper way" if looking in various opensource projects how people include directories. But there are two ways to do it.

  1. Crude include_directories will append a directory to the current project and all other descendant projects which you will append via a series of add_subdirectory commands. Sometimes people say that such approach is legacy.

  2. A more elegant way is with target_include_directories. It allows to append a directory for a specific project/target without (maybe) unnecessary inheritance or clashing of various include directories. Also allow to perform even a subtle configuration and append one of the following markers for this command.

PRIVATE - use only for this specified build target

PUBLIC - use it for specified target and for targets which links with this project

INTERFACE -- use it only for targets which links with the current project

PS:

  1. Both commands allow to mark a directory as SYSTEM to give a hint that it is not your business that specified directories will contain warnings.

  2. A similar answer is with other pairs of commands target_compile_definitions/add_definitions, target_compile_options/CMAKE_C_FLAGS

What is the difference between statically typed and dynamically typed languages?

Statically typed languages like C++, Java and Dynamically typed languages like Python differ only in terms of the execution of the type of the variable. Statically typed languages have static data type for the variable, here the data type is checked during compiling so debugging is much simpler...whereas Dynamically typed languages don't do the same, the data type is checked which executing the program and hence the debugging is bit difficult.

Moreover they have a very small difference and can be related with strongly typed and weakly typed languages. A strongly typed language doesn't allow you to use one type as another eg. C and C++ ...whereas weakly typed languages allow eg.python

ETag vs Header Expires

In my view, With Expire Header, server can tell the client when my data would be stale, while with Etag, server would check the etag value for client' each request.

Triggering a checkbox value changed event in DataGridView

I finally implemented it this way

  private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {

        if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
        {
            if (dataGridView1[e.ColumnIndex, e.RowIndex].GetContentBounds(e.RowIndex).Contains(e.Location))
            {
                cellEndEditTimer.Start();
            }
        }

    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    { /*place your code here*/}


    private void cellEndEditTimer_Tick(object sender, EventArgs e)
    {
        dataGridView1.EndEdit();
        cellEndEditTimer.Stop();
    }

Create a batch file to run an .exe with an additional parameter

Found another solution for the same. It will be more helpful.

START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"

finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".

Apache Name Virtual Host with SSL

Apache doesn't support SSL on name-based virtual host, only on IP based Virtual Hosts.

Source: Apache 2.2 SSL FAQ question Why is it not possible to use Name-Based Virtual Hosting to identify different SSL virtual hosts?

Unlike SSL, the TLS specification allows for name-based hosts (SNI as mentioned by someone else), but Apache doesn't yet support this feature. It supposedly will in a future release when compiled against openssl 0.9.8.

Also, mod_gnutls claims to support SNI, but I've never actually tried it.

How to use org.apache.commons package?

You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.

For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.

If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.

For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.

If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.

Why use Select Top 100 Percent?

Kindly try the below, Hope it will work for you.

      SELECT TOP
              ( SELECT COUNT(foo) 
                  From MyTable 
                 WHERE ISNUMERIC (foo) = 1) * 
                  FROM bar WITH(NOLOCK) 
              ORDER BY foo
                 WHERE CAST(foo AS int) > 100
               )

How can I recover a lost commit in Git?

Before answering, let's add some background, explaining what this HEAD is.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time (excluding git worktree).

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history it's called detached HEAD.

Enter image description here

On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch:

Enter image description here

Enter image description here


A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

Enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7) you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there, reset && checkout modify the HEAD.

Enter image description here

Integer ASCII value to character in BASH using printf

this prints all the "printable" characters of your basic bash setup:

printf '%b\n' $(printf '\\%03o' {30..127})

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Change size of axes title and labels in ggplot2

You can change axis text and label size with arguments axis.text= and axis.title= in function theme(). If you need, for example, change only x axis title size, then use axis.title.x=.

g+theme(axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"))

There is good examples about setting of different theme() parameters in ggplot2 page.

How can I remove a substring from a given String?

This works good for me.

String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");

or you can use

String no_o = hi.replace("o", "");

How to add a local repo and treat it as a remote repo

You have your arguments to the remote add command reversed:

git remote add <NAME> <PATH>

So:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

See git remote --help for more information.

How to calculate age (in years) based on Date of Birth and getDate()

I have used this query in our production code for nearly 10 years:

SELECT FLOOR((CAST (GetDate() AS INTEGER) - CAST(Date_of_birth AS INTEGER)) / 365.25) AS Age

Refresh certain row of UITableView based on Int in Swift

Swift 4.1

use it when you delete row using selectedTag of row.

self.tableView.beginUpdates()

        self.yourArray.remove(at:  self.selectedTag)
        print(self.allGroups)

        let indexPath = NSIndexPath.init(row:  self.selectedTag, section: 0)

        self.tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)

        self.tableView.endUpdates()

        self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .automatic)

Convert A String (like testing123) To Binary In Java

You can also do this with the ol' good method :

String inputLine = "test123";
String translatedString = null;
char[] stringArray = inputLine.toCharArray();
for(int i=0;i<stringArray.length;i++){
      translatedString += Integer.toBinaryString((int) stringArray[i]);
}

How to save RecyclerView's scroll position using RecyclerView.State?

Store

lastFirstVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();

Restore

((LinearLayoutManager) rv.getLayoutManager()).scrollToPosition(lastFirstVisiblePosition);

and if that doesn't work, try

((LinearLayoutManager) rv.getLayoutManager()).scrollToPositionWithOffset(lastFirstVisiblePosition,0)

Put store in onPause() and restore in onResume()

How do I select a random value from an enumeration?

Here is a generic function for it. Keep the RNG creation outside the high frequency code.

public static Random RNG = new Random();

public static T RandomEnum<T>()
{  
    Type type = typeof(T);
    Array values = Enum.GetValues(type);
    lock(RNG)
    {
        object value= values.GetValue(RNG.Next(values.Length));
        return (T)Convert.ChangeType(value, type);
    }
}

Usage example:

System.Windows.Forms.Keys randomKey = RandomEnum<System.Windows.Forms.Keys>();

How to save data file into .RData?

Alternatively, when you want to save individual R objects, I recommend using saveRDS.

You can save R objects using saveRDS, then load them into R with a new variable name using readRDS.

Example:

# Save the city object
saveRDS(city, "city.rds")

# ...

# Load the city object as city
city <- readRDS("city.rds")

# Or with a different name
city2 <- readRDS("city.rds")

But when you want to save many/all your objects in your workspace, use Manetheran's answer.

Installing R with Homebrew

brew install cask
brew cask install xquartz
brew tap homebrew/science
brew install r

This way, everything is packager managed, so there's no need to manually download and install anything.

Ternary operator (?:) in Bash

to answer to : int a = (b == 5) ? c : d;

just write:

b=5
c=1
d=2
let a="(b==5)?c:d"

echo $a # 1

b=6;
c=1;
d=2;
let a="(b==5)?c:d"

echo $a # 2

remember that " expression " is equivalent to $(( expression ))

Is there a difference between /\s/g and /\s+/g?

In the first regex, each space character is being replaced, character by character, with the empty string.

In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +.

However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.

If you change the replacement string to '#', the difference becomes much clearer:

var str = '  A B  C   D EF ';
console.log(str.replace(/\s/g, '#'));  // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#

HTML/Javascript change div content

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="radio" name="radiobutton" value="A" onclick = "populateData(event)">
  <input type="radio" name="radiobutton" value="B" onclick = "populateData(event)">

    <div id="content"></div>
</body>
</html>

-----------------JS- code------------

var targetDiv = document.getElementById('content');
    var htmlContent = '';

    function populateData(event){
      switch(event.target.value){
        case 'A':{
         htmlContent = 'Content for A';
          break;
        }
        case 'B':{
          htmlContent = "content for B";
break;
        }
      }
      targetDiv.innerHTML = htmlContent;
    }

Step1: on click of the radio button it calls function populate data, with event (an object that has event details such as name of the element, value etc..);

Step2: I extracted the value through event.target.value and then simple switch will give me freedom to add custom text.

Live Code

https://jsbin.com/poreway/edit?html,js,output

Dynamically changing font size of UILabel

Its a little bit not sophisticated but this should work, for example lets say you want to cap your uilabel to 120x120, with max font size of 28:

magicLabel.numberOfLines = 0;
magicLabel.lineBreakMode = NSLineBreakByWordWrapping;
...
magicLabel.text = text;
    for (int i = 28; i>3; i--) {
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:(CGFloat)i] constrainedToSize:CGSizeMake(120.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        if (size.height < 120) {
            magicLabel.font = [UIFont systemFontOfSize:(CGFloat)i];
            break;
        }
    }

Stack, Static, and Heap in C++

The following is of course all not quite precise. Take it with a grain of salt when you read it :)

Well, the three things you refer to are automatic, static and dynamic storage duration, which has something to do with how long objects live and when they begin life.


Automatic storage duration

You use automatic storage duration for short lived and small data, that is needed only locally within some block:

if(some condition) {
    int a[3]; // array a has automatic storage duration
    fill_it(a);
    print_it(a);
}

The lifetime ends as soon as we exit the block, and it starts as soon as the object is defined. They are the most simple kind of storage duration, and are way faster than in particular dynamic storage duration.


Static storage duration

You use static storage duration for free variables, which might be accessed by any code all times, if their scope allows such usage (namespace scope), and for local variables that need extend their lifetime across exit of their scope (local scope), and for member variables that need to be shared by all objects of their class (classs scope). Their lifetime depends on the scope they are in. They can have namespace scope and local scope and class scope. What is true about both of them is, once their life begins, lifetime ends at the end of the program. Here are two examples:

// static storage duration. in global namespace scope
string globalA; 
int main() {
    foo();
    foo();
}

void foo() {
    // static storage duration. in local scope
    static string localA;
    localA += "ab"
    cout << localA;
}

The program prints ababab, because localA is not destroyed upon exit of its block. You can say that objects that have local scope begin lifetime when control reaches their definition. For localA, it happens when the function's body is entered. For objects in namespace scope, lifetime begins at program startup. The same is true for static objects of class scope:

class A {
    static string classScopeA;
};

string A::classScopeA;

A a, b; &a.classScopeA == &b.classScopeA == &A::classScopeA;

As you see, classScopeA is not bound to particular objects of its class, but to the class itself. The address of all three names above is the same, and all denote the same object. There are special rule about when and how static objects are initialized, but let's not concern about that now. That's meant by the term static initialization order fiasco.


Dynamic storage duration

The last storage duration is dynamic. You use it if you want to have objects live on another isle, and you want to put pointers around that reference them. You also use them if your objects are big, and if you want to create arrays of size only known at runtime. Because of this flexibility, objects having dynamic storage duration are complicated and slow to manage. Objects having that dynamic duration begin lifetime when an appropriate new operator invocation happens:

int main() {
    // the object that s points to has dynamic storage 
    // duration
    string *s = new string;
    // pass a pointer pointing to the object around. 
    // the object itself isn't touched
    foo(s);
    delete s;
}

void foo(string *s) {
    cout << s->size();
}

Its lifetime ends only when you call delete for them. If you forget that, those objects never end lifetime. And class objects that define a user declared constructor won't have their destructors called. Objects having dynamic storage duration requires manual handling of their lifetime and associated memory resource. Libraries exist to ease use of them. Explicit garbage collection for particular objects can be established by using a smart pointer:

int main() {
    shared_ptr<string> s(new string);
    foo(s);
}

void foo(shared_ptr<string> s) {
    cout << s->size();
}

You don't have to care about calling delete: The shared ptr does it for you, if the last pointer that references the object goes out of scope. The shared ptr itself has automatic storage duration. So its lifetime is automatically managed, allowing it to check whether it should delete the pointed to dynamic object in its destructor. For shared_ptr reference, see boost documents: http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm

How do I compare version numbers in Python?

Posting my full function based on Kindall's solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.

While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#) value appropriately if you have long strings in your versioning system.)

def versiontuple(v):
   filled = []
   for point in v.split("."):
      filled.append(point.zfill(8))
   return tuple(filled)

.

>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True


>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

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

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

How to declare an array inside MS SQL Server Stored Procedure?

Is there a reason why you aren't using a table variable and the aggregate SUM operator, instead of a cursor? SQL excels at set-oriented operations. 99.87% of the time that you find yourself using a cursor, there's a set-oriented alternative that's more efficient:

declare @MonthsSale table
(
MonthNumber int,
MonthName varchar(9),
MonthSale decimal(18,2)
)

insert into @MonthsSale
select
    1, 'January', 100.00
union select    
    2, 'February', 200.00
union select    
    3, 'March', 300.00
union select    
    4, 'April', 400.00
union select    
    5, 'May', 500.00
union select    
    6, 'June', 600.00
union select    
    7, 'July', 700.00
union select    
    8, 'August', 800.00
union select    
    9, 'September', 900.00
union select    
    10, 'October', 1000.00
union select    
    11, 'November', 1100.00
union select    
    12, 'December', 1200.00

select * from @MonthsSale   
select SUM(MonthSale) as [TotalSales] from @MonthsSale

jQuery counting elements by class - what is the best way to implement this?

for counting:

$('.yourClass').length;

should work fine.

storing in a variable is as easy as:

var count = $('.yourClass').length;

Why is it common to put CSRF prevention tokens in cookies?

Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.

The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.

The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.

setup android on eclipse but don't know SDK directory

The Android SDK directory is just the folder you get after uncompressing one of these files:

http://developer.android.com/sdk/index.html

There's no such "SDK installation"... may be, what you installed was the ADT plugin (which does not include the SDK). You have to download one of the ZIP files you find in the link above, uncompress it and boila! you have the SDK Folder.

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

ORA-01031: insufficient privileges Solution: Go to Your System User. then Write This Code:

SQL> grant dba to UserName; //Put This username which user show this error message.

Grant succeeded.

In a Bash script, how can I exit the entire script if a certain condition occurs?

A SysOps guy once taught me the Three-Fingered Claw technique:

yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }

These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try() your statement and code on.

Explanation

(based on flying sheep comment).

  • yell: print the script name and all arguments to stderr:
    • $0 is the path to the script ;
    • $* are all arguments.
    • >&2 means > redirect stdout to & pipe 2. pipe 1 would be stdout itself.
  • die does the same as yell, but exits with a non-0 exit status, which means “fail”.
  • try uses the || (boolean OR), which only evaluates the right side if the left one failed.

Using BufferedReader.readLine() in a while loop properly

In case if you are still stumbling over this question. Nowadays things look nicer with Java 8:

try {
  Files.lines(Paths.get(targetsFile)).forEach(
    s -> {
      System.out.println(s);
      // do more stuff with s
    }
  );
} catch (IOException exc) {
  exc.printStackTrace();
}

Python def function: How do you specify the end of the function?

To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block For example, the following print ends two blocks at the same time:

def foo():
    if bar:
        print "bar"

print "baz" # ends the if and foo at the same time

The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.

Lines with no statement, no matter the indentation, does not matter

def foo():
    print "The line below has no indentation"

    print "Still part of foo"

But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:

def foo():
    print "Still correct"
   print "Error because there is no block at this indentation"

Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.

BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.

Add up a column of numbers at the Unix shell

I would use "du" instead.

$ cat files.txt | xargs du -c | tail -1
4480    total

If you just want the number:

cat files.txt | xargs du -c | tail -1 | awk '{print $1}'

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

Got the same problem, non of the answers worked for me. After a lot of debugging I found out that the size of one image was smaller than 32. This leads to a broken array with wrong dimensions and the above mentioned error.

To solve the problem, make sure that all images have the correct dimensions.

gnuplot : plotting data from multiple input files in a single graph

You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.

e.g.

filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines

and

filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines

This Activity already has an action bar supplied by the window decor

If you are using Appcompact Activity use these three lines in your theme.

<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowActionBarOverlay">false</item>

Using BeautifulSoup to extract text without tags

you can try this indside findall for loop:

item_price = item.find('span', attrs={'class':'s-item__price'}).text

it extracts only text and assigs it to "item_pice"

How do I get and set Environment variables in C#?

Get and Set

Get

string getEnv = Environment.GetEnvironmentVariable("envVar");

Set

string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv);

PostgreSQL function for last inserted ID

For the ones who need to get the all data record, you can add

returning *

to the end of your query to get the all object including the id.

IntelliJ IDEA generating serialVersionUID

I am not sure if you have an old version of IntelliJ IDEA, but if I go to menu File ? Settings... ? Inspections ? Serialization issues ? Serializable class without 'serialVersionUID'` enabled, the class you provide give me warnings.

Enter image description here

If I try the first class I see:

Enter image description here

BTW: It didn't show me a warning until I added { } to the end of each class to fix the compile error.

Angular - ng: command not found

if you have npm, install run the command

npm install -g @angular/cli

then bind your ng using this:

cd

alias ng=".npm-global/bin/ng"

Follow the Pictures for more help.

enter image description here enter image description here enter image description here enter image description here

Angular 2 Sibling Component Communication

Updated to rc.4: When trying to get data passed between sibling components in angular 2, The simplest way right now (angular.rc.4) is to take advantage of angular2's hierarchal dependency injection and create a shared service.

Here would be the service:

import {Injectable} from '@angular/core';

@Injectable()
export class SharedService {
    dataArray: string[] = [];

    insertData(data: string){
        this.dataArray.unshift(data);
    }
}

Now, here would be the PARENT component

import {Component} from '@angular/core';
import {SharedService} from './shared.service';
import {ChildComponent} from './child.component';
import {ChildSiblingComponent} from './child-sibling.component';
@Component({
    selector: 'parent-component',
    template: `
        <h1>Parent</h1>
        <div>
            <child-component></child-component>
            <child-sibling-component></child-sibling-component>
        </div>
    `,
    providers: [SharedService],
    directives: [ChildComponent, ChildSiblingComponent]
})
export class parentComponent{

} 

and its two children

child 1

import {Component, OnInit} from '@angular/core';
import {SharedService} from './shared.service'

@Component({
    selector: 'child-component',
    template: `
        <h1>I am a child</h1>
        <div>
            <ul *ngFor="#data in data">
                <li>{{data}}</li>
            </ul>
        </div>
    `
})
export class ChildComponent implements OnInit{
    data: string[] = [];
    constructor(
        private _sharedService: SharedService) { }
    ngOnInit():any {
        this.data = this._sharedService.dataArray;
    }
}

child 2 (It's sibling)

import {Component} from 'angular2/core';
import {SharedService} from './shared.service'

@Component({
    selector: 'child-sibling-component',
    template: `
        <h1>I am a child</h1>
        <input type="text" [(ngModel)]="data"/>
        <button (click)="addData()"></button>
    `
})
export class ChildSiblingComponent{
    data: string = 'Testing data';
    constructor(
        private _sharedService: SharedService){}
    addData(){
        this._sharedService.insertData(this.data);
        this.data = '';
    }
}

NOW: Things to take note of when using this method.

  1. Only include the service provider for the shared service in the PARENT component and NOT the children.
  2. You still have to include constructors and import the service in the children
  3. This answer was originally answered for an early angular 2 beta version. All that has changed though are the import statements, so that is all you need to update if you used the original version by chance.

How to recursively find and list the latest modified files in a directory with subdirectories and times

GNU find (see man find) has a -printf parameter for displaying the files in Epoch mtime and relative path name.

redhat> find . -type f -printf '%T@ %P\n' | sort -n | awk '{print $2}'

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

If you're running a WHM-powered VPS (virtual private server) you may find that you do not have permissions to edit PHP.INI directly; the system must do it. In the WHM host control panel, go to Service ConfigurationPHP Configuration Editor and modify memory_limit:

Updating memory_limit on WHM 11.48.4

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

You can also change the pop-up options themselves, to be more convenient for your normal use. Summary:

  1. Run the SQL Management Studio Express 2008
  2. Click the Tools -> Options
  3. Select SQL Server Object Explorer . Now you should be able to see the options

    • Value for Edit Top Rows Command
    • Value for Select Top Rows Command
  4. Give the Values 0 here to select/ Edit all the Records

Full Instructions with screenshots are here: http://m-elshazly.blogspot.com/2011/01/sql-server-2008-change-edit-top-200.html

List<object>.RemoveAll - How to create an appropriate Predicate

I wanted to address something none of the answers have so far:

From what I've read so far, it appears that I can use Vehicles.RemoveAll() to delete an item with a particular VehicleID. As an[sic] supplementary question, is a Generic list the best repository for these objects?

Assuming VehicleID is unique as the name suggests, a list is a terribly inefficient way to store them when you get a lot of vehicles, as removal(and other methods like Find) is still O(n). Have a look at a HashSet<Vehicle> instead, it has O(1) removal(and other methods) using:

int GetHashCode(Vehicle vehicle){return vehicle.VehicleID;}
int Equals(Vehicle v1, Vehicle v2){return v1.VehicleID == v2.VehicleID;}

Removing all vehicles with a specific EnquiryID still requires iterating over all elements this way, so you could consider a GetHashCode that returns the EnquiryID instead, depending on which operation you do more often. This has the downside of a lot of collisions if a lot of Vehicles share the same EnquiryID though.

In this case, a better alternative is to make a Dictionary<int, List<Vehicle>> that maps EnquiryIDs to Vehicles and keep that up to date when adding/removing vehicles. Removing these vehicles from a HashSet is then an O(m) operation, where m is the number of vehicles with a specific EnquiryID.

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You just need to use below code when launching the new activity.

startActivity(new Intent(this, newactivity.class));
finish();

Installing RubyGems in Windows

Installing Ruby

Go to http://rubyinstaller.org/downloads/

Make sure that you check "Add ruby ... to your PATH". enter image description here

Now you can use "ruby" in your "cmd".

If you installed ruby 1.9.3 I expect that the ruby is downloaded in C:\Ruby193.

Installing Gem

install Development Kit in rubyinstaller. Make new folder such as C:\RubyDevKit and unzip.

Go to the devkit directory and type ruby dk.rb init to generate config.yml.

If you installed devkit for 1.9.3, I expect that the config.yml will be written as C:\Ruby193.

If not, please correct path to your ruby folders.

After reviewing the config.yml, you can finally type ruby dk.rb install.

Now you can use "gem" in your "cmd". It's done!

Getting data posted in between two dates

if you want to force using BETWEEN keyword on Codeigniter query helper. You can use where without escape false like this code. Works well on CI version 3.1.5. Hope its help someone.

if(!empty($tglmin) && !empty($tglmax)){
        $this->db->group_start();
        $this->db->where('DATE(create_date) BETWEEN "'.$tglmin.'" AND "'.$tglmax.'"', '',false);
        $this->db->group_end();
    }

Input placeholders for Internet Explorer

I have written a jquery plugin to solve this problem.. it's free..

JQuery Directory:

http://plugins.jquery.com/project/kegles-jquery-placeholder

Site: www.kegles.com.br/jquery-placeholder/

Get AVG ignoring Null or Zero values

worked for me:

AVG(CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)

Convert String to Type in C#

If you really want to get the type by name you may use the following:

System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");

Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.

How to include !important in jquery

If you need to have jquery use !important for more than one item, this is how you would do it.

e.g. set an img tags max-width and max-height to 500px each

$('img').css('cssText', "max-width: 500px !important;' + "max-height: 500px !important;');

How to find index position of an element in a list when contains returns true

int indexOf() can be used. It returns -1 if no matching finds

Looping from 1 to infinity in Python

def to_infinity():
    index = 0
    while True:
        yield index
        index += 1

for i in to_infinity():
    if i > 10:
        break

$_SERVER['HTTP_REFERER'] missing

Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:

$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";

Visual Studio Code includePath

This answer maybe late but I just happened to fix the issue. Here is my c_cpp_properties.json file:

{
"configurations": [
    {
        "name": "Linux",
        "includePath": [
            "${workspaceFolder}/**",                
            "/usr/include/c++/5.4.0/",
            "usr/local/include/",
            "usr/include/"
        ],
        "defines": [],
        "compilerPath": "/usr/bin/gcc",
        "cStandard": "c11",
        "cppStandard": "c++14",
        "intelliSenseMode": "clang-x64"
    }
],
"version": 4

}

Press TAB and then ENTER key in Selenium WebDriver

In python this work for me

self.set_your_value = "your value"

def your_method_name(self):      
    self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`

Append Char To String in C?

C does not have strings per se -- what you have is a char pointer pointing to some read-only memory containing the characters "blablabla\0". In order to append a character there, you need a) writable memory and b) enough space for the string in its new form. The string literal "blablabla\0" has neither.

The solutions are:

1) Use malloc() et al. to dynamically allocate memory. (Don't forget to free() afterwards.)
2) Use a char array.

When working with strings, consider using strn* variants of the str* functions -- they will help you stay within memory bounds.

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Keyboard shortcuts are not active in Visual Studio with Resharper installed

I had the same problem with Visual Studio 2015 and Resharper 9.2

"Resharper 9 keyboard shortcuts not working in Visual Studio 2015"

I had tried all possible resetting and applying keyboard schemes and found the answer from Yuri Fedoseev.

My Windows 10 language configuration only had Swedish in the language preferences "Control Panel\Clock, Language, and Region\Language"

The solution was to add English(I chose the US version) in the language list. And then go to Resharper > Options > Keyboard & Menus > Apply Scheme. (perhaps you do not even need to apply the scheme)

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

I have got the same error but I have resolved the issue in the following ways:

  1. Provide all the mandatory filed of your bean/model class
  2. Don't violet the concept of the unique constraint, Provide unique value in Unique constraints.

While variable is not defined - wait

Very late to the party but I want to supply a more modern solution to any future developers looking at this question. It's based off of Toprak's answer but simplified to make it clearer as to what is happening.

<div>Result: <span id="result"></span></div>

<script>
    var output = null;
    
    // Define an asynchronous function which will not block where it is called.
    async function test(){
        // Create a promise with the await operator which instructs the async function to wait for the promise to complete.
        await new Promise(function(resolve, reject){
            // Execute the code that needs to be completed.
            // In this case it is a timeout that takes 2 seconds before returning a result. 
            setTimeout(function(){
                // Just call resolve() with the result wherever the code completes.
                resolve("success output");
            }, 2000);
            
            // Just for reference, an 'error' has been included.
            // It has a chance to occur before resolve() is called in this case, but normally it would only be used when your code fails.
            setTimeout(function(){
                // Use reject() if your code isn't successful.
                reject("error output");
            }, Math.random() * 4000);
        })
        .then(function(result){ 
            // The result variable comes from the first argument of resolve().
            output = result; 
        })
        .catch(function(error){ 
            // The error variable comes from the first argument of reject().
            // Catch will also catch any unexpected errors that occur during execution.
            // In this case, the output variable will be set to either of those results.
            if (error) output = error; 
        });
        
        // Set the content of the result span to output after the promise returns.
        document.querySelector("#result").innerHTML = output;
    }
    
    // Execute the test async function.
    test();

    // Executes immediately after test is called.
    document.querySelector("#result").innerHTML = "nothing yet";
</script>

Here's the code without comments for easy visual understanding.

var output = null;

async function test(){
    await new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve("success output");
        }, 2000);

        setTimeout(function(){
            reject("error output");
        }, Math.random() * 4000);
    })
    .then(function(result){ 
        output = result; 
    })
    .catch(function(error){ 
        if (error) output = error; 
    });

    document.querySelector("#result").innerHTML = output;
}

test();

document.querySelector("#result").innerHTML = "nothing yet";

On a final note, according to MDN, Promises are supported on all modern browsers with Internet Explorer being the only exception. This compatibility information is also supported by caniuse. However with Bootstrap 5 dropping support for Internet Explorer, and the new Edge based on webkit, it is unlikely to be an issue for most developers.

How to link to apps on the app store

Despite there being loads of answers here, none of the suggestions for linking to the developers apps seem to work anymore.

When I last visited I was able to get it working using the format:

itms-apps://itunes.apple.com/developer/developer-name/id123456789

This no longer works, but removing the developer name does:

itms-apps://itunes.apple.com/developer/id123456789

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

Do you have to put Task.Run in a method to make it async?

First, let's clear up some terminology: "asynchronous" (async) means that it may yield control back to the calling thread before it starts. In an async method, those "yield" points are await expressions.

This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".

To futher confuse the issue, async is very different than "awaitable"; there are some async methods whose return types are not awaitable, and many methods returning awaitable types that are not async.

Enough about what they aren't; here's what they are:

  • The async keyword allows an asynchronous method (that is, it allows await expressions). async methods may return Task, Task<T>, or (if you must) void.
  • Any type that follows a certain pattern can be awaitable. The most common awaitable types are Task and Task<T>.

So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run:

private Task<int> DoWorkAsync() // No async because the method does not need await
{
  return Task.Run(() =>
  {
    return 1 + 2;
  });
}

(But this pattern is a poor approach; see below).

But if your question is "how do I create an async method that can yield back to its caller instead of blocking", the answer is to declare the method async and use await for its "yielding" points:

private async Task<int> GetWebPageHtmlSizeAsync()
{
  var client = new HttpClient();
  var html = await client.GetAsync("http://www.example.com/");
  return html.Length;
}

So, the basic pattern of things is to have async code depend on "awaitables" in its await expressions. These "awaitables" can be other async methods or just regular methods returning awaitables. Regular methods returning Task/Task<T> can use Task.Run to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T> or one of its shortcuts (TaskFactory.FromAsync, Task.FromResult, etc). I don't recommend wrapping an entire method in Task.Run; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run:

private int DoWork()
{
  return 1 + 2;
}

private void MoreSynchronousProcessing()
{
  // Execute it directly (synchronously), since we are also a synchronous method.
  var result = DoWork();
  ...
}

private async Task DoVariousThingsFromTheUIThreadAsync()
{
  // I have a bunch of async work to do, and I am executed on the UI thread.
  var result = await Task.Run(() => DoWork());
  ...
}

I have an async/await intro on my blog; at the end are some good followup resources. The MSDN docs for async are unusually good, too.

How can I initialize C++ object member variables in the constructor?

You can specify how to initialize members in the member initializer list:

BigMommaClass {
    BigMommaClass(int, int);

private:
    ThingOne thingOne;
    ThingTwo thingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
    : thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}

Change image onmouseover

I know someone answered this the same way, but I made my own research, and I wrote this before to see that answer. So: I was looking for something simple with inline JavaScript, with just on the img, without "wrapping" it into the a tag (so instead of the document.MyImage, I used this.src)

<img 
onMouseOver="this.src='ico/view.hover.png';" 
onMouseOut="this.src='ico/view.png';" 
src="ico/view.png" alt="hover effect" />

It works on all currently updated browsers; IE 11 (and I also tested it in the Developer Tools of IE from IE5 and above), Chrome, Firefox, Opera, Edge.

How to scroll UITableView to specific position

Use [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES]; Scrolls the receiver until a row identified by index path is at a particular location on the screen.

And

scrollToNearestSelectedRowAtScrollPosition:animated:

Scrolls the table view so that the selected row nearest to a specified position in the table view is at that position.

Defining TypeScript callback type

If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.

class CallbackTest {
  myCallback: Function;
}   

Login to website, via C#

Sometimes, it may help switching off AllowAutoRedirect and setting both login POST and page GET requests the same user agent.

request.UserAgent = userAgent;
request.AllowAutoRedirect = false;

How to stop an app on Heroku?

1> Yes... There is pencil icon when we go to Personal==> <app name> ==>Resources then click on Pencil Icon and drag to left side and Dynos will go down.

2> You can validate using Heroku cli

heroku logs --app {your-appname}

it worked for me.

What underlies this JavaScript idiom: var self = this?

function Person(firstname, lastname) {
  this.firstname = firstname;

  this.lastname = lastname;
  this.getfullname = function () {
    return `${this.firstname}   ${this.lastname}`;
  };

  let that = this;
  this.sayHi = function() {
    console.log(`i am this , ${this.firstname}`);
    console.log(`i am that , ${that.firstname}`);
  };
}

let thisss = new Person('thatbetty', 'thatzhao');

let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};

thisss.sayHi.call(thatt);

Best way to resolve file path too long exception

As the cause of the error is obvious, here's some information that should help you solve the problem:

See this MS article about Naming Files, Paths, and Namespaces

Here's a quote from the link:

Maximum Path Length Limitation In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

And a few workarounds (taken from the comments):

There are ways to solve the various problems. The basic idea of the solutions listed below is always the same: Reduce the path-length in order to have path-length + name-length < MAX_PATH. You may:

  • Share a subfolder
  • Use the commandline to assign a drive letter by means of SUBST
  • Use AddConnection under VB to assign a drive letter to a path

How to read single Excel cell value

 //THIS IS WORKING CODE                        
 Microsoft.Office.Interop.Excel.Range Range_Number,r2;
 Range_Number = wsheet.UsedRange.Find("smth");
 string f_number="";

 r2 = wsheet.Cells;

 int n_c = Range_Number.Column;
 int n_r = Range_Number.Row;
 var number = ((Range)r2[n_r + 1, n_c]).Value;

 f_number = (string)number;

How to atomically delete keys matching a pattern using Redis

Execute in bash:

redis-cli KEYS "prefix:*" | xargs redis-cli DEL

UPDATE

Ok, i understood. What about this way: store current additional incremental prefix and add it to all your keys. For example:

You have values like this:

prefix_prefix_actuall = 2
prefix:2:1 = 4
prefix:2:2 = 10

When you need to purge data, you change prefix_actuall first (for example set prefix_prefix_actuall = 3), so your application will write new data to keys prefix:3:1 and prefix:3:2. Then you can safely take old values from prefix:2:1 and prefix:2:2 and purge old keys.

What is the difference between join and merge in Pandas?

  • Join: Default Index (If any same column name then it will throw an error in default mode because u have not defined lsuffix or rsuffix))
df_1.join(df_2)
  • Merge: Default Same Column Names (If no same column name it will throw an error in default mode)
df_1.merge(df_2)
  • on parameter has different meaning in both cases
df_1.merge(df_2, on='column_1')

df_1.join(df_2, on='column_1') // It will throw error
df_1.join(df_2.set_index('column_1'), on='column_1')

Where does one get the "sys/socket.h" header/source file?

I would like just to add that if you want to use windows socket library you have to :

  • at the beginning : call WSAStartup()

  • at the end : call WSACleanup()

Regards;

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

cURL equivalent in Node.js?

well if you really need a curl equivalent you can try node-curl

npm install node-curl

you will probably need to add libcurl4-gnutls-dev.

Convert List(of object) to List(of string)

You mean something like this?

List<object> objects = new List<object>();
var strings = (from o in objects
              select o.ToString()).ToList();

How can I add an item to a SelectList in ASP.net MVC

I don't if anybody else has a better option...

<% if (Model.VariableName == "" || Model.VariableName== null) { %>
   <%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], "", 
        new{stlye=" "})%>
<% } else{ %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], 
        Model.VariableName, new{stlye=" "})%>
<% }>

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

If nothing helps and you are still getting this exception, review your equals() methods - and don't include child collection in it. Especially if you have deep structure of embedded collections (e.g. A contains Bs, B contains Cs, etc.).

In example of Account -> Transactions:

  public class Account {

    private Long id;
    private String accountName;
    private Set<Transaction> transactions;

    @Override
    public boolean equals(Object obj) {
      if (this == obj)
        return true;
      if (obj == null)
        return false;
      if (!(obj instanceof Account))
        return false;
      Account other = (Account) obj;
      return Objects.equals(this.id, other.id)
          && Objects.equals(this.accountName, other.accountName)
          && Objects.equals(this.transactions, other.transactions); // <--- REMOVE THIS!
    }
  }

In above example remove transactions from equals() checks. This is because hibernate will imply that you are not trying to update old object, but you pass a new object to persist, whenever you change element on the child collection.
Of course this solutions will not fit all applications and you should carefully design what you want to include in the equals and hashCode methods.

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.