Programs & Examples On #Access violation

An access violation (also known as segmentation fault) is generally an attempt to access memory that the CPU cannot physically address. It is often caused when attempting to access a null reference or a reference to memory that has been freed.

Attempted to read or write protected memory

The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved. For safety try bulinding for 32bit x86 architecture because it is the most compatible.

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

0xC0000005: Access violation reading location 0x00000000

The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.

Injecting @Autowired private field during testing

The accepted answer (use MockitoJUnitRunner and @InjectMocks) is great. But if you want something a little more lightweight (no special JUnit runner), and less "magical" (more transparent) especially for occasional use, you could just set the private fields directly using introspection.

If you use Spring, you already have a utility class for this : org.springframework.test.util.ReflectionTestUtils

The use is quite straightforward :

ReflectionTestUtils.setField(myLauncher, "myService", myService);

The first argument is your target bean, the second is the name of the (usually private) field, and the last is the value to inject.

If you don't use Spring, it is quite trivial to implement such a utility method. Here is the code I used before I found this Spring class :

public static void setPrivateField(Object target, String fieldName, Object value){
        try{
            Field privateField = target.getClass().getDeclaredField(fieldName);
            privateField.setAccessible(true);
            privateField.set(target, value);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

Can I replace groups in Java regex?

Here is a different solution, that also allows the replacement of a single group in multiple matches. It uses stacks to reverse the execution order, so the string operation can be safely executed.

private static void demo () {

    final String sourceString = "hello world!";

    final String regex = "(hello) (world)(!)";
    final Pattern pattern = Pattern.compile(regex);

    String result = replaceTextOfMatchGroup(sourceString, pattern, 2, world -> world.toUpperCase());
    System.out.println(result);  // output: hello WORLD!
}

public static String replaceTextOfMatchGroup(String sourceString, Pattern pattern, int groupToReplace, Function<String,String> replaceStrategy) {
    Stack<Integer> startPositions = new Stack<>();
    Stack<Integer> endPositions = new Stack<>();
    Matcher matcher = pattern.matcher(sourceString);

    while (matcher.find()) {
        startPositions.push(matcher.start(groupToReplace));
        endPositions.push(matcher.end(groupToReplace));
    }
    StringBuilder sb = new StringBuilder(sourceString);
    while (! startPositions.isEmpty()) {
        int start = startPositions.pop();
        int end = endPositions.pop();
        if (start >= 0 && end >= 0) {
            sb.replace(start, end, replaceStrategy.apply(sourceString.substring(start, end)));
        }
    }
    return sb.toString();       
}

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

In ASP.NET MVC 4, the namespace is not System.Web.WebPages.Razor, but System.Web.Razor

That worked for me, change your web.config.

If "0" then leave the cell blank

You can change the number format of the column to this custom format:

0;-0;;@

which will hide all 0 values.

To do this, select the column, right-click > Format Cells > Custom.

Generate SQL Create Scripts for existing tables with Query

Possible this be helpful for you. This script generate indexes, FK's, PK and common structure for any table.

For example -

DDL:

CREATE TABLE [dbo].[WorkOut](
    [WorkOutID] [bigint] IDENTITY(1,1) NOT NULL,
    [TimeSheetDate] [datetime] NOT NULL,
    [DateOut] [datetime] NOT NULL,
    [EmployeeID] [int] NOT NULL,
    [IsMainWorkPlace] [bit] NOT NULL,
    [DepartmentUID] [uniqueidentifier] NOT NULL,
    [WorkPlaceUID] [uniqueidentifier] NULL,
    [TeamUID] [uniqueidentifier] NULL,
    [WorkShiftCD] [nvarchar](10) NULL,
    [WorkHours] [real] NULL,
    [AbsenceCode] [varchar](25) NULL,
    [PaymentType] [char](2) NULL,
    [CategoryID] [int] NULL,
    [Year]  AS (datepart(year,[TimeSheetDate])),
 CONSTRAINT [PK_WorkOut] PRIMARY KEY CLUSTERED 
(
    [WorkOutID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[WorkOut] ADD  
CONSTRAINT [DF__WorkOut__IsMainW__2C1E8537]  DEFAULT ((1)) FOR [IsMainWorkPlace]

ALTER TABLE [dbo].[WorkOut]  WITH CHECK ADD  CONSTRAINT [FK_WorkOut_Employee_EmployeeID] FOREIGN KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([EmployeeID])

ALTER TABLE [dbo].[WorkOut] CHECK CONSTRAINT [FK_WorkOut_Employee_EmployeeID]

Query:

DECLARE @table_name SYSNAME
SELECT @table_name = 'dbo.WorkOut'

DECLARE 
      @object_name SYSNAME
    , @object_id INT

SELECT 
      @object_name = '[' + s.name + '].[' + o.name + ']'
    , @object_id = o.[object_id]
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE s.name + '.' + o.name = @table_name
    AND o.[type] = 'U'
    AND o.is_ms_shipped = 0

DECLARE @SQL NVARCHAR(MAX) = ''

;WITH index_column AS 
(
    SELECT 
          ic.[object_id]
        , ic.index_id
        , ic.is_descending_key
        , ic.is_included_column
        , c.name
    FROM sys.index_columns ic WITH (NOWAIT)
    JOIN sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id
    WHERE ic.[object_id] = @object_id
),
fk_columns AS 
(
     SELECT 
          k.constraint_object_id
        , cname = c.name
        , rcname = rc.name
    FROM sys.foreign_key_columns k WITH (NOWAIT)
    JOIN sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id AND rc.column_id = k.referenced_column_id 
    JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id AND c.column_id = k.parent_column_id
    WHERE k.parent_object_id = @object_id
)
SELECT @SQL = 'CREATE TABLE ' + @object_name + CHAR(13) + '(' + CHAR(13) + STUFF((
    SELECT CHAR(9) + ', [' + c.name + '] ' + 
        CASE WHEN c.is_computed = 1
            THEN 'AS ' + cc.[definition] 
            ELSE UPPER(tp.name) + 
                CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('nvarchar', 'nchar', 'ntext')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset') 
                       THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')'
                     WHEN tp.name = 'decimal' 
                       THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')'
                    ELSE ''
                END +
                CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END +
                CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END +
                CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END + 
                CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END 
        END + CHAR(13)
    FROM sys.columns c WITH (NOWAIT)
    JOIN sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
    LEFT JOIN sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id
    LEFT JOIN sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id
    LEFT JOIN sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
    WHERE c.[object_id] = @object_id
    ORDER BY c.column_id
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ')
    + ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' + 
                    (SELECT STUFF((
                         SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END
                         FROM sys.index_columns ic WITH (NOWAIT)
                         JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
                         WHERE ic.is_included_column = 0
                             AND ic.[object_id] = k.parent_object_id 
                             AND ic.index_id = k.unique_index_id     
                         FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ''))
            + ')' + CHAR(13)
            FROM sys.key_constraints k WITH (NOWAIT)
            WHERE k.parent_object_id = @object_id 
                AND k.[type] = 'PK'), '') + ')'  + CHAR(13)
    + ISNULL((SELECT (
        SELECT CHAR(13) +
             'ALTER TABLE ' + @object_name + ' WITH' 
            + CASE WHEN fk.is_not_trusted = 1 
                THEN ' NOCHECK' 
                ELSE ' CHECK' 
              END + 
              ' ADD CONSTRAINT [' + fk.name  + '] FOREIGN KEY(' 
              + STUFF((
                SELECT ', [' + k.cname + ']'
                FROM fk_columns k
                WHERE k.constraint_object_id = fk.[object_id]
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
               + ')' +
              ' REFERENCES [' + SCHEMA_NAME(ro.[schema_id]) + '].[' + ro.name + '] ('
              + STUFF((
                SELECT ', [' + k.rcname + ']'
                FROM fk_columns k
                WHERE k.constraint_object_id = fk.[object_id]
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
               + ')'
            + CASE 
                WHEN fk.delete_referential_action = 1 THEN ' ON DELETE CASCADE' 
                WHEN fk.delete_referential_action = 2 THEN ' ON DELETE SET NULL'
                WHEN fk.delete_referential_action = 3 THEN ' ON DELETE SET DEFAULT' 
                ELSE '' 
              END
            + CASE 
                WHEN fk.update_referential_action = 1 THEN ' ON UPDATE CASCADE'
                WHEN fk.update_referential_action = 2 THEN ' ON UPDATE SET NULL'
                WHEN fk.update_referential_action = 3 THEN ' ON UPDATE SET DEFAULT'  
                ELSE '' 
              END 
            + CHAR(13) + 'ALTER TABLE ' + @object_name + ' CHECK CONSTRAINT [' + fk.name  + ']' + CHAR(13)
        FROM sys.foreign_keys fk WITH (NOWAIT)
        JOIN sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id
        WHERE fk.parent_object_id = @object_id
        FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)')), '')
    + ISNULL(((SELECT
         CHAR(13) + 'CREATE' + CASE WHEN i.is_unique = 1 THEN ' UNIQUE' ELSE '' END 
                + ' NONCLUSTERED INDEX [' + i.name + '] ON ' + @object_name + ' (' +
                STUFF((
                SELECT ', [' + c.name + ']' + CASE WHEN c.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END
                FROM index_column c
                WHERE c.is_included_column = 0
                    AND c.index_id = i.index_id
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')'  
                + ISNULL(CHAR(13) + 'INCLUDE (' + 
                    STUFF((
                    SELECT ', [' + c.name + ']'
                    FROM index_column c
                    WHERE c.is_included_column = 1
                        AND c.index_id = i.index_id
                    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')', '')  + CHAR(13)
        FROM sys.indexes i WITH (NOWAIT)
        WHERE i.[object_id] = @object_id
            AND i.is_primary_key = 0
            AND i.[type] = 2
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
    ), '')

PRINT @SQL
--EXEC sys.sp_executesql @SQL

Output:

CREATE TABLE [dbo].[WorkOut]
(
      [WorkOutID] BIGINT NOT NULL IDENTITY(1,1)
    , [TimeSheetDate] DATETIME NOT NULL
    , [DateOut] DATETIME NOT NULL
    , [EmployeeID] INT NOT NULL
    , [IsMainWorkPlace] BIT NOT NULL DEFAULT((1))
    , [DepartmentUID] UNIQUEIDENTIFIER NOT NULL
    , [WorkPlaceUID] UNIQUEIDENTIFIER NULL
    , [TeamUID] UNIQUEIDENTIFIER NULL
    , [WorkShiftCD] NVARCHAR(10) COLLATE Cyrillic_General_CI_AS NULL
    , [WorkHours] REAL NULL
    , [AbsenceCode] VARCHAR(25) COLLATE Cyrillic_General_CI_AS NULL
    , [PaymentType] CHAR(2) COLLATE Cyrillic_General_CI_AS NULL
    , [CategoryID] INT NULL
    , [Year] AS (datepart(year,[TimeSheetDate]))
    , CONSTRAINT [PK_WorkOut] PRIMARY KEY ([WorkOutID] ASC)
)

ALTER TABLE [dbo].[WorkOut] WITH CHECK ADD CONSTRAINT [FK_WorkOut_Employee_EmployeeID] FOREIGN KEY([EmployeeID]) REFERENCES [dbo].[Employee] ([EmployeeID])
ALTER TABLE [dbo].[WorkOut] CHECK CONSTRAINT [FK_WorkOut_Employee_EmployeeID]

CREATE NONCLUSTERED INDEX [IX_WorkOut_WorkShiftCD_AbsenceCode] ON [dbo].[WorkOut] ([WorkShiftCD] ASC, [AbsenceCode] ASC)
INCLUDE ([WorkOutID], [WorkHours])

Also check this article -

How to Generate a CREATE TABLE Script For an Existing Table: Part 1

Mocking HttpClient in unit tests

One alternative would be to setup a stub HTTP server that returns canned responses based on pattern matching the request url, meaning you test real HTTP requests not mocks. Historically this would have taken significant develoment effort and would have been far to slow to be considered for unit testing, however OSS library WireMock.net is easy to use and fast enough to be run with lots of tests so may be worth considering. Setup is a few lines of code:

var server = FluentMockServer.Start();
server.Given(
      Request.Create()
      .WithPath("/some/thing").UsingGet()
   )
   .RespondWith(
       Response.Create()
       .WithStatusCode(200)
       .WithHeader("Content-Type", "application/json")
       .WithBody("{'attr':'value'}")
   );

You can find a more details and guidance on using wiremock in tests here.

initialize a const array in a class initializer in C++

ISO standard C++ doesn't let you do this. If it did, the syntax would probably be:

a::a(void) :
b({2,3})
{
    // other initialization stuff
}

Or something along those lines. From your question it actually sounds like what you want is a constant class (aka static) member that is the array. C++ does let you do this. Like so:

#include <iostream>

class A 
{
public:
    A();
    static const int a[2];
};

const int A::a[2] = {0, 1};

A::A()
{
}

int main (int argc, char * const argv[]) 
{
    std::cout << "A::a => " << A::a[0] << ", " << A::a[1] << "\n";
    return 0;
}

The output being:

A::a => 0, 1

Now of course since this is a static class member it is the same for every instance of class A. If that is not what you want, ie you want each instance of A to have different element values in the array a then you're making the mistake of trying to make the array const to begin with. You should just be doing this:

#include <iostream>

class A 
{
public:
    A();
    int a[2];
};

A::A()
{
    a[0] = 9; // or some calculation
    a[1] = 10; // or some calculation
}

int main (int argc, char * const argv[]) 
{
    A v;
    std::cout << "v.a => " << v.a[0] << ", " << v.a[1] << "\n";
    return 0;
}

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get an access token: facebook Graph API Explorer

You can customize specific access permissions, basic permissions are included by default.

How do I Sort a Multidimensional Array in PHP

I tried several popular array_multisort() and usort() answers and none of them worked for me. The data just gets jumbled and the code is unreadable. Here's a quick a dirty solution. WARNING: Only use this if you're sure a rogue delimiter won't come back to haunt you later!

Let's say each row in your multi array looks like: name, stuff1, stuff2:

// Sort by name, pull the other stuff along for the ride
foreach ($names_stuff as $name_stuff) {
    // To sort by stuff1, that would be first in the contatenation
    $sorted_names[] = $name_stuff[0] .','. name_stuff[1] .','. $name_stuff[2];
}
sort($sorted_names, SORT_STRING);

Need your stuff back in alphabetical order?

foreach ($sorted_names as $sorted_name) {
    $name_stuff = explode(',',$sorted_name);
    // use your $name_stuff[0] 
    // use your $name_stuff[1] 
    // ... 
}

Yeah, it's dirty. But super easy, won't make your head explode.

CSS How to set div height 100% minus nPx

If you need to support IE6, use JavaScript so manage the size of the wrapper div (set the position of the element in pixels after reading the window size). If you don't want to use JavaScript, then this can't be done. There are workarounds but expect a week or two to make it work in every case and in every browser.

For other modern browsers, use this css:

position: absolute;
top: 60px;
bottom: 0px;

How to use Angular4 to set focus by element id

Here is an Angular4+ directive that you can re-use in any component. Based on code given in the answer by Niel T in this question.

import { NgZone, Renderer, Directive, Input } from '@angular/core';

@Directive({
    selector: '[focusDirective]'
})
export class FocusDirective {
    @Input() cssSelector: string

    constructor(
        private ngZone: NgZone,
        private renderer: Renderer
    ) { }

    ngOnInit() {
        console.log(this.cssSelector);
        this.ngZone.runOutsideAngular(() => {
            setTimeout(() => {
                this.renderer.selectRootElement(this.cssSelector).focus();
            }, 0);
        });
    }
}

You can use it in a component template like this:

<input id="new-email" focusDirective cssSelector="#new-email"
  formControlName="email" placeholder="Email" type="email" email>

Give the input an id and pass the id to the cssSelector property of the directive. Or you can pass any cssSelector you like.

Comments from Niel T:

Since the only thing I'm doing is setting the focus on an element, I don't need to concern myself with change detection, so I can actually run the call to renderer.selectRootElement outside of Angular. Because I need to give the new sections time to render, the element section is wrapped in a timeout to allow the rendering threads time to catch up before the element selection is attempted. Once all that is setup, I can simply call the element using basic CSS selectors.

Java String split removed empty values

you may have multiple separators, including whitespace characters, commas, semicolons, etc. take those in repeatable group with []+, like:

 String[] tokens = "a , b,  ,c; ;d,      ".split( "[,; \t\n\r]+" );

you'll have 4 tokens -- a, b, c, d

leading separators in the source string need to be removed before applying this split.

as answer to question asked:

String data = "5|6|7||8|9||";
String[] split = data.split("[\\| \t\n\r]+");

whitespaces added just in case if you'll have those as separators along with |

Passing event and argument to v-on in Vue.js

You can also do something like this...

<input @input="myHandler('foo', 'bar', ...arguments)">

Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.

How do I access an access array item by index in handlebars?

The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:

{{people.[1].name}}
{{people.1.name}}

However, the square brackets are required in:

{{#with people.[1]}}
  {{name}}
{{/with}}

In the latter, using the index number without the square brackets would get one:

Error: Parse error on line ...:
...     {{#with people.1}}                
-----------------------^
Expecting 'ID', got 'INTEGER'

As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?

(Tested with Handlebars in YUI.)

2.xx Update

You can now use the get helper for this:

(get people index)

although if you get an error about index needing to be a string, do:

(get people (concat index ""))

ASP.NET set hiddenfield a value in Javascript

asp:HiddenField as:

<asp:HiddenField runat="server" ID="hfProduct" ClientIDMode="Static" />

js code:

$("#hfProduct").val("test")

and the code behind:

hfProduct.Value.ToString();

Intent.putExtra List

Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data)

Here is a skeleton of the code you need:

  1. Declare List

    private List<String> test;
    
  2. Init List at appropriate place

    test = new ArrayList<String>();
    

    and add data as appropriate to test.

  3. Pass to intent as follows:

    Intent intent = getIntent();  
    intent.putStringArrayListExtra("test", (ArrayList<String>) test);
    
  4. Retrieve data as follows:

    ArrayList<String> test = getIntent().getStringArrayListExtra("test");
    

Hope that helps.

How to get bean using application context in spring boot

Using SpringApplication.run(Class<?> primarySource, String... arg) worked for me. E.g.:

@SpringBootApplication
public class YourApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class, args);

    }
}

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

TCPDF ERROR: Some data has already been output, can't send PDF file

Add the function ob_end_clean(); before call the Output function. It worked for me within a custom Wordpress function!

ob_end_clean();
$pdf->Output($pdf_name, 'I');

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

According to Google Developers article, you can:

Load Image from javascript

Simplest load image from JS to DOM-element:

element.innerHTML += "<img src='image.jpg'></img>";

With onload event:

element.innerHTML += "<img src='image.jpg' onload='javascript:showImage();'></img>";

How can I switch word wrap on and off in Visual Studio Code?

In version 1.52 and above go to File > Preferences > Settings > Text Editor > Diff Editor and change Word Wrap parameter as you wish

Link to all Visual Studio $ variables

To add to the other answers, note that property sheets can be configured for the project, creating custom project-specific parameters.

To access or create them navigate to(at least in Visual Studio 2013) View -> Other Windows -> Property Manager. You can also find them in the source folder as .prop files

Does IE9 support console.log, and is it a real function?

I know this is a very old question but feel this adds a valuable alternative of how to deal with the console issue. Place the following code before any call to console.* (so your very first script).

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

Reference:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js

Remove .php extension with .htaccess

Try this
The following code will definitely work

RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]

How to change row color in datagridview?

You have not mentioned how value is changed. I have used similar functionality when user is entering value. i.e. entering and leaving edit mode.

Using CellEndEdit event of datagridview.

private void dgMapTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    double newInteger;

    if (double.TryParse(dgMapTable[e.ColumnIndex,e.RowIndex].Value.ToString(), out newInteger)
    {
        if (newInteger < 0 || newInteger > 50)
        {
            dgMapTable[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red; 

            dgMapTable[e.ColumnIndex, e.RowIndex].ErrorText 
                = "Keep value in Range:" + "0 to " + "50";
        }
    }                               
}

You may add logic for clearing error notification in a similar way.

if in your case, if data is loaded programmatically, then CellLeave event can be used with same code.

How to prevent scrollbar from repositioning web page?

overflow-y:scroll is correct, but you should use it with the html tag, not body or else you get a double scrollbar in IE 7
So the correct css would be:

html {
  overflow-y: scroll;
}

How to have multiple conditions for one if statement in python

Might be a bit odd or bad practice but this is one way of going about it.

(arg1, arg2, arg3) = (1, 2, 3)

if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
    print('Example.')

Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.

UINavigationBar Hide back Button Text

In iOS 11, we found that setting UIBarButtonItem appearance's text font/color to a very small value or clear color will result other bar item to disappear (system does not honor the class of UIBarButton item anymore, it will convert it to a _UIModernBarButton). Also setting the offset of back text to offscreen will result flash during interactive pop.

So we swizzled addSubView:

+ (void)load {
    if (@available(iOS 11, *)) {
        [NSClassFromString(@"_UIBackButtonContainerView")     jr_swizzleMethod:@selector(addSubview:) withMethod:@selector(MyiOS11BackButtonNoTextTrick_addSubview:) error:nil];
    }
}

- (void)MyiOS11BackButtonNoTextTrick_addSubview:(UIView *)view {
    view.alpha = 0;
    if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (id)view;
        [button setTitle:@" " forState:UIControlStateNormal];
    }
    [self MyiOS11BackButtonNoTextTrick_addSubview:view];
}

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

The following function does

  • use a default value (error_result) for not castable results e.g abc or 999999999999999999999999999999999999999999
  • keeps null as null
  • trims away spaces and other whitespace in input
  • values casted as valid bigints are compared against lower_bound to e.g enforce positive values only
CREATE OR REPLACE FUNCTION cast_to_bigint(text) 
RETURNS BIGINT AS $$
DECLARE big_int_value BIGINT DEFAULT NULL;
DECLARE error_result  BIGINT DEFAULT -1;
DECLARE lower_bound   BIGINT DEFAULT 0;
BEGIN
    BEGIN
        big_int_value := CASE WHEN $1 IS NOT NULL THEN GREATEST(TRIM($1)::BIGINT, lower_bound) END;
    EXCEPTION WHEN OTHERS THEN
        big_int_value := error_result;
    END;
RETURN big_int_value;
END;

Custom toast on Android: a simple example

To avoid problems with layout_* params not being properly used, you need to make sure that when you inflate your custom layout that you specify a correct ViewGroup as a parent.

Many examples pass null here, but instead you can pass the existing Toast ViewGroup as your parent.

val toast = Toast.makeText(this, "", Toast.LENGTH_LONG)
val layout = LayoutInflater.from(this).inflate(R.layout.view_custom_toast, toast.view.parent as? ViewGroup?)
toast.view = layout
toast.show()

Here we replace the existing Toast view with our custom view. Once you have a reference to your layout "layout" you can then update any images/text views that it may contain.

This solution also prevents any "View not attached to window manager" crashes from using null as a parent.

Also, avoid using ConstraintLayout as your custom layout root, this seems to not work when used inside a Toast.

Python: find position of element in array

You should do:

try:
    value_index = my_list.index(value)
except:
    value_index = -1;

Magento - Retrieve products with a specific attribute value

To Get TEXT attributes added from admin to front end on product listing page.

Thanks Anita Mourya

I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.

METHOD 1

on list.phtml

<?php $i=0; foreach ($_productCollection as $_product): ?>

FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH

<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>

<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>

METHOD 2

Mage/Catalog/Block/Product/List.phtml OVER RIDE and set in 'local folder'

i.e. Copy From

Mage/Catalog/Block/Product/List.phtml

and PASTE TO

app/code/local/Mage/Catalog/Block/Product/List.phtml

change the function by adding 2 lines shown in bold below.

protected function _getProductCollection()
{
       if (is_null($this->_productCollection)) {
           $layer = Mage::getSingleton('catalog/layer');
           /* @var $layer Mage_Catalog_Model_Layer */
           if ($this->getShowRootCategory()) {
               $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
           }

           // if this is a product view page
           if (Mage::registry('product')) {
               // get collection of categories this product is associated with
               $categories = Mage::registry('product')->getCategoryCollection()
                   ->setPage(1, 1)
                   ->load();
               // if the product is associated with any category
               if ($categories->count()) {
                   // show products from this category
                   $this->setCategoryId(current($categories->getIterator()));
               }
           }

           $origCategory = null;
           if ($this->getCategoryId()) {
               $category = Mage::getModel('catalog/category')->load($this->getCategoryId());

               if ($category->getId()) {
                   $origCategory = $layer->getCurrentCategory();
                   $layer->setCurrentCategory($category);
               }
           }
           $this->_productCollection = $layer->getProductCollection();

           $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

           if ($origCategory) {
               $layer->setCurrentCategory($origCategory);
           }
       }
       **//CMI-PK added na_author to filter on product listing page//
       $this->_productCollection->addAttributeToSelect('na_author');**
       return $this->_productCollection;

}

and you will be happy to see it....!!

IO Error: The Network Adapter could not establish the connection

For me the basic oracle only was not installed. Please ensure you have oracle installed and then try checking host and port.

How to find the last field using 'cut'

Adding an approach to this old question just for the fun of it:

$ cat input.file # file containing input that needs to be processed
a;b;c;d;e
1;2;3;4;5
no delimiter here
124;adsf;15454
foo;bar;is;null;info

$ cat tmp.sh # showing off the script to do the job
#!/bin/bash
delim=';'
while read -r line; do  
    while [[ "$line" =~ "$delim" ]]; do
        line=$(cut -d"$delim" -f 2- <<<"$line")
    done
    echo "$line"
done < input.file

$ ./tmp.sh # output of above script/processed input file
e
5
no delimiter here
15454
info

Besides bash, only cut is used. Well, and echo, I guess.

How do I tell Maven to use the latest version of a dependency?

NOTE:

The mentioned LATEST and RELEASE metaversions have been dropped for plugin dependencies in Maven 3 "for the sake of reproducible builds", over 6 years ago. (They still work perfectly fine for regular dependencies.) For plugin dependencies please refer to this Maven 3 compliant solution.


If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using.

When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all.

See the POM Syntax section of the Maven book for more details. Or see this doc on Dependency Version Ranges, where:

  • A square bracket ( [ & ] ) means "closed" (inclusive).
  • A parenthesis ( ( & ) ) means "open" (exclusive).

Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata:

<?xml version="1.0" encoding="UTF-8"?><metadata>
  <groupId>com.foo</groupId>
  <artifactId>my-foo</artifactId>
  <version>2.0.0</version>
  <versioning>
    <release>1.1.1</release>
    <versions>
      <version>1.0</version>
      <version>1.0.1</version>
      <version>1.1</version>
      <version>1.1.1</version>
      <version>2.0.0</version>
    </versions>
    <lastUpdated>20090722140000</lastUpdated>
  </versioning>
</metadata>

If a dependency on that artifact is required, you have the following options (other version ranges can be specified of course, just showing the relevant ones here):

Declare an exact version (will always resolve to 1.0.1):

<version>[1.0.1]</version>

Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version):

<version>1.0.1</version>

Declare a version range for all 1.x (will currently resolve to 1.1.1):

<version>[1.0.0,2.0.0)</version>

Declare an open-ended version range (will resolve to 2.0.0):

<version>[1.0.0,)</version>

Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x)

<version>LATEST</version>

Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x):

<version>RELEASE</version>

Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the Maven super POM. You can do this with either "-Prelease-profile" or "-DperformRelease=true"


It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results).

It is therefore generally a good idea to define exact versions in releases. As Tim's answer points out, the maven-versions-plugin is a handy tool for updating dependency versions, particularly the versions:use-latest-versions and versions:use-latest-releases goals.

Removing duplicate values from a PowerShell array

$a | sort -unique

This works with case-insensitive, therefore removing duplicates strings with differing cases. Solved my problem.

$ServerList = @(
    "FS3",
    "HQ2",
    "hq2"
) | sort -Unique

$ServerList

The above outputs:

FS3
HQ2

Failed to start mongod.service: Unit mongod.service not found

For those that run into this and end up on this answer, as I did, where they got this error during uninstall orupgrade and Ubuntu keeps failing to uninstall the previous because the service doesn't exist this one line will get you past that and allow the uninstall or upgrade to continue.

sudo touch /lib/systemd/system/mongod.service

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I solved this problem by removing --deploy-mode cluster from spark-submit code. By default , spark submit takes client mode which has following advantage :

1. It opens up Netty HTTP server and distributes all jars to the worker nodes.
2. Driver program runs on master node , which means dedicated resources to driver process.

While in cluster mode :

 1.  It runs on worker node.
 2. All the jars need to be placed in a common folder of the cluster so that it is accessible to all the worker nodes or in folder of each worker node.

Here it's not able to access hive metastore due to unavailability of hive jar to any of the nodes in cluster. enter image description here

Swift - Split string over multiple lines

Multi-line strings are possible as of Swift 4.0, but there are some rules:

  1. You need to start and end your strings with three double quotes, """.
  2. Your string content should start on its own line.
  3. The terminating """ should also start on its own line.

Other than that, you're good to go! Here's an example:

let longString = """
When you write a string that spans multiple
lines make sure you start its content on a
line all of its own, and end it with three
quotes also on a line of their own.
Multi-line strings also let you write "quote marks"
freely inside your strings, which is great!
"""

See what's new in Swift 4 for more information.

count (non-blank) lines-of-code in bash

This gives the count of number of lines without counting the blank lines:

grep -v ^$ filename wc -l | sed -e 's/ //g' 

Copy Image from Remote Server Over HTTP

make folder and name it foe example download open note pad and insert this code

only change http://www.google.com/aa.zip to your file and save it to m.php for example

chamod the php file to 666 and the folder download to 777

<?php
define('BUFSIZ', 4095);
$url = 'http://www.google.com/aa.zip';
$rfile = fopen($url, 'r');
$lfile = fopen(basename($url), 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);
?>

finally from your browser enter to these URL http://www.example.com/download/m.php

you will see in download folder the file download from other server

thanks

How to convert an int to a hex string?

You are looking for the chr function.

You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.

>>> chr(0x65) == '\x65'
True


>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True

Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.

Best way to access a control on another form in Windows Forms?

Change modifier from public to internal. .Net deliberately uses private modifier instead of the public, due to preventing any illegal access to your methods/properties/controls out of your project. In fact, public modifier can accessible wherever, so They are really dangerous. Any body out of your project can access to your methods/properties. But In internal modifier no body (other of your current project) can access to your methods/properties.

Suppose you are creating a project, which has some secret fields. So If these fields being accessible out of your project, it can be dangerous, and against to your initial ideas. As one good recommendation, I can say always use internal modifier instead of public modifier.

But some strange!

I must tell also in VB.Net while our methods/properties are still private, it can be accessible from other forms/class by calling form as a variable with no any problem else.

I don't know why in this programming language behavior is different from C#. As we know both are using same Platform and they claim they are almost same Back end Platform, but as you see, they still behave differently.

But I've solved this problem with two approaches. Either; by using Interface (Which is not a recommend, as you know, Interfaces usually need public modifier, and using a public modifier is not recommend (As I told you above)),

Or

Declare your whole Form in somewhere static class and static variable and there is still internal modifier. Then when you suppose to use that form for showing to users, so pass new Form() construction to that static class/variable. Now It can be Accessible every where as you wish. But you still need some thing more. You declare your element internal modifier too in Designer File of Form. While your Form is open, it can be accessible everywhere. It can work for you very well.

Consider This Example.

Suppose you want to access to a Form's TextBox.

So the first job is declaration of a static variable in a static class (The reason of static is ease of access without any using new keywork at future).

Second go to designer class of that Form which supposes to be accessed by other Forms. Change its TextBox modifier declaration from private to internal. Don't worry; .Net never change it again to private modifier after your changing.

Third when you want to call that form to open, so pass the new Form Construction to that static variable-->>static class.

Fourth; from any other Forms (wherever in your project) you can access to that form/control while From is open.

Look at code below (We have three object. 1- a static class (in our example we name it A)

2 - Any Form else which wants to open the final Form (has TextBox, in our example FormB).

3 - The real Form which we need to be opened, and we suppose to access to its internal TextBox1 (in our example FormC).

Look at codes below:

internal static class A
{
    internal static FormC FrmC;
}

FormB ...
{
    '(...)
    A.FrmC = new FormC();
    '(...)
}

FormC (Designer File) . . . 
{
     internal System.Windows.Forms.TextBox TextBox1;
}

You can access to that static Variable (here FormC) and its internal control (here Textbox1) wherever and whenever as you wish, while FormC is open.


Any Comment/idea let me know. I glad to hear from you or any body else about this topic more. Honestly I have had some problems regard to this mentioned problem in past. The best way was the second solution that I hope it can work for you. Let me know any new idea/suggestion.

How to set viewport meta for iPhone that handles rotation properly?

Was just trying to work this out myself, and the solution I came up with was:

<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />

This seems to lock the device into 1.0 scale regardless of it's orientation. As a side effect, it does however completely disable user scaling (pinch zooming, etc).

Swift Open Link in Safari

Swift 5

if let url = URL(string: "https://www.google.com") {
    UIApplication.shared.open(url)
}

Could not find module FindOpenCV.cmake ( Error in configuration process)

I am using Windows and get the same error message. I find another problem which is relevant. I defined OpenCV_DIR in my path at the end of the line. However when I typed "path" in the command line, my OpenCV_DIR was not shown. I found because Windows probably has a limit on how long the path can be, it cut my OpenCV_DIR to be only part of what I defined. So I removed some other part of the path, now it works.

Maven: How to include jars, which are not available in reps into a J2EE project?

Install alone didn't work for me.

mvn deploy:deploy-file -Durl=file:///home/me/project/lib/ \
  -Dfile=target/jzmq-2.1.3-SNAPSHOT.jar -DgroupId=org.zeromq \  
  -DartifactId=zeromq -Dpackaging=jar -Dversion=2.1.3

How can I check for existence of element in std::vector, in one line?

Try std::find

vector<int>::iterator it = std::find(v.begin(), v.end(), 123);

if(it==v.end()){

    std::cout<<"Element not found";
}

kubectl apply vs kubectl create?

kubectl create can work with one object configuration file at a time. This is also known as imperative management

kubectl create -f filename|url

kubectl apply works with directories and its sub directories containing object configuration yaml files. This is also known as declarative management. Multiple object configuration files from directories can be picked up. kubectl apply -f directory/

Details :
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/ https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-config/

UIScrollView Scrollable Content Size Ambiguity

See below: content view in scrollview vertical and horizontal centralized. you got ambiguity error, always make sure two added into scrollview from your content view is 1).button space to container.2)trailing space to constraint that is highlighted in screenshot,

these constraint means in scroll is how much you can scroll after your content view height or width.

enter image description here

it may help you.

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

Open-Source Examples of well-designed Android Applications?

All of the applications delivered with Android (Calendar, Contacts, Email, etc) are all open-source, but not part of the SDK. The source for those projects is here: https://android.googlesource.com/ (look at /platform/packages/apps). I've referred to those sources several times when I've used an application on my phone and wanted to see how a particular feature was implemented.

How to give ASP.NET access to a private key in a certificate in the certificate store?

Although I have attended the above, I have come to this point after many attempts. 1- If you want access to the certificate from the store, you can do this as an example 2- It is much easier and cleaner to produce the certificate and use it via a path

Asp.net Core 2.2 OR1:

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Operators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Tursys.Pool.Storage.Api.Utility
{
    class CertificateManager
    {
        public static X509Certificate2 GetCertificate(string caller)
        {
            AsymmetricKeyParameter caPrivateKey = null;
            X509Certificate2 clientCert;
            X509Certificate2 serverCert;

            clientCert = GetCertificateIfExist("CN=127.0.0.1", StoreName.My, StoreLocation.LocalMachine);
            serverCert = GetCertificateIfExist("CN=MyROOTCA", StoreName.Root, StoreLocation.LocalMachine);
            if (clientCert == null || serverCert == null)
            {
                var caCert = GenerateCACertificate("CN=MyROOTCA", ref caPrivateKey);
                addCertToStore(caCert, StoreName.Root, StoreLocation.LocalMachine);

                clientCert = GenerateSelfSignedCertificate("CN=127.0.0.1", "CN=MyROOTCA", caPrivateKey);
                var p12 = clientCert.Export(X509ContentType.Pfx);

                addCertToStore(new X509Certificate2(p12, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet), StoreName.My, StoreLocation.LocalMachine);
            }

            if (caller == "client")
                return clientCert;

            return serverCert;
        }

        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            //const string signatureAlgorithm = "SHA256WithRSA";
            //certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN = new X509Name(issuerName);
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);
            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);


            // correcponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);


            // merge into X509Certificate2
            X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKeyAlgorithm.GetDerEncoded());
            if (seq.Count != 9)
            {
                //throw new PemException("malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(info.ParsePrivateKey());
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            try
            {
                var rsap = DotNetUtilities.ToRSA(rsaparams);
                x509 = x509.CopyWithPrivateKey(rsap);

                //x509.PrivateKey = ToDotNetKey(rsaparams);
            }
            catch(Exception ex)
            {
                ;
            }
            //x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return x509;

        }

        public static AsymmetricAlgorithm ToDotNetKey(RsaPrivateCrtKeyParameters privateKey)
        {
            var cspParams = new CspParameters
            {
                KeyContainerName = Guid.NewGuid().ToString(),
                KeyNumber = (int)KeyNumber.Exchange,
                Flags = CspProviderFlags.UseMachineKeyStore
            };

            var rsaProvider = new RSACryptoServiceProvider(cspParams);
            var parameters = new RSAParameters
            {
                Modulus = privateKey.Modulus.ToByteArrayUnsigned(),
                P = privateKey.P.ToByteArrayUnsigned(),
                Q = privateKey.Q.ToByteArrayUnsigned(),
                DP = privateKey.DP.ToByteArrayUnsigned(),
                DQ = privateKey.DQ.ToByteArrayUnsigned(),
                InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
                D = privateKey.Exponent.ToByteArrayUnsigned(),
                Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
            };

            rsaProvider.ImportParameters(parameters);
            return rsaProvider;
        }

        public static X509Certificate2 GenerateCACertificate(string subjectName, ref AsymmetricKeyParameter CaPrivateKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            //const string signatureAlgorithm = "SHA256WithRSA";
            //certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            //Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);
            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);


            X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            CaPrivateKey = issuerKeyPair.Private;

            return x509;
            //return issuerKeyPair.Private;

        }

        public static bool addCertToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
        {
            bool bRet = false;

            try
            {
                X509Store store = new X509Store(st, sl);
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);

                store.Close();
            }
            catch
            {

            }

            return bRet;
        }

        protected internal static X509Certificate2 GetCertificateIfExist(string subjectName, StoreName store, StoreLocation location)
        {
            using (var certStore = new X509Store(store, location))
            {
                certStore.Open(OpenFlags.ReadOnly);
                var certCollection = certStore.Certificates.Find(
                                           X509FindType.FindBySubjectDistinguishedName, subjectName, false);
                X509Certificate2 certificate = null;
                if (certCollection.Count > 0)
                {
                    certificate = certCollection[0];
                }
                return certificate;
            }
        }

    }
}

OR 2:

    services.AddDataProtection()
//.PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp-keys"))
.ProtectKeysWithCertificate(
        new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "clientCert.pfx"), "Password")
        )
.UnprotectKeysWithAnyCertificate(
        new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "clientCert.pfx"), "Password")
        );

How to apply an XSLT Stylesheet in C#

I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;

Edit:

But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);

Disable firefox same origin policy

The cors-everywhere addon works for me until Firefox 68, after 68 I need to adjust 'privacy.file_unique_origin' -> false (by open 'about:config') to solve 'CORS request not HTTP' for new CORS same-origin rule introduced.

Position last flex item at the end of container

Flexible Box Layout Module - 8.1. Aligning with auto margins

Auto margins on flex items have an effect very similar to auto margins in block flow:

  • During calculations of flex bases and flexible lengths, auto margins are treated as 0.

  • Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Therefore you could use margin-top: auto to distribute the space between the other elements and the last element.

This will position the last element at the bottom.

p:last-of-type {
  margin-top: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  flex-direction: column;
  border: 1px solid #000;
  min-height: 200px;
  width: 100px;
}
p {
  height: 30px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-top: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

vertical example


Likewise, you can also use margin-left: auto or margin-right: auto for the same alignment horizontally.

p:last-of-type {
  margin-left: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  width: 100%;
  border: 1px solid #000;
}
p {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-left: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

horizontal example

Convert UTC to local time in Rails 3

If you're actually doing it just because you want to get the user's timezone then all you have to do is change your timezone in you config/applications.rb.

Like this:

Rails, by default, will save your time record in UTC even if you specify the current timezone.

config.time_zone = "Singapore"

So this is all you have to do and you're good to go.

Why does Java have an "unreachable statement" compiler error?

It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need. Usually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.

How to run php files on my computer

In short:

  1. Install WAMP

  2. Put this file to C:\wamp\www\ProjectName\filename.php

  3. Go to browser: http://localhost/ProjectName/filename.php

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

In my case I was getting this error while making an AJAX post, it turned out to be that the __RequestVerificationToken value wasn't being passed across in the call. I had to manually find the value of this field and set this as a property on the data object that's sent to the endpoint.

i.e.

data.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();

Example

HTML

  <form id="myForm">
    @Html.AntiForgeryToken()

    <!-- other input fields -->

    <input type="submit" class="submitButton" value="Submit" />
  </form>

Javascript

$(document).on('click', '#myForm .submitButton', function () {
  var myData = { ... };
  myData.__RequestVerificationToken = $('#myForm input[name="__RequestVerificationToken"]').val();

  $.ajax({
    type: 'POST',
    url: myUrl,
    data: myData,
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    dataType: 'json',
    success: function (response) {
      alert('Form submitted');
    },
    error: function (e) {
      console.error('Error submitting form', e);
      alert('Error submitting form');
    },
  });
  return false; //prevent form reload
});

Controller

[HttpPost]
[Route("myUrl")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> MyUrlAsync(MyDto dto)
{
    ...
}

Call a global variable inside module

If it is something that you reference but never mutate, then use const:

declare const bootbox;

Is there an easy way to check the .NET Framework version?

I find it easier to work with the Version class:

using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace System.Runtime.InteropServices {
  public static class RuntimeInformationEx {

    public static Version? GetDotnetFrameworkVersion() {
      using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full");
      if (key is object) {
        if (!Int32.TryParse(key.GetValue("Release", "").ToString(), out var release)) return null;
        return release switch
        {
          378389 => new Version(4, 5, 0),
          378675 => new Version(4, 5, 1),
          378758 => new Version(4, 5, 1),
          379893 => new Version(4, 5, 2),
          393295 => new Version(4, 6, 0),
          393297 => new Version(4, 6, 0),
          394254 => new Version(4, 6, 1),
          394271 => new Version(4, 6, 1),
          394802 => new Version(4, 6, 2),
          394806 => new Version(4, 6, 2),
          460798 => new Version(4, 7, 0),
          460805 => new Version(4, 7, 0),
          461308 => new Version(4, 7, 1),
          461310 => new Version(4, 7, 1),
          461808 => new Version(4, 7, 2),
          461814 => new Version(4, 7, 2),
          528040 => new Version(4, 8, 0),
          528209 => new Version(4, 8, 0),
          528049 => new Version(4, 8, 0),
          _ => null
        };

      } else { // .NET version < 4.5
        using var key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
        if (key1 is null) return null;
        var parts = key1.GetSubKeyNames()[^1].Substring(1).Split('.'); // get lastsub key, remove 'v' prefix, and split
        if (parts.Length == 2) parts = new string[] { parts[0], parts[1], "0" };
        if (parts.Length != 3) return null;
        Func<string, int> Parse = s => Int32.TryParse(s, out var i) ? i : -1;
        try { return new Version(Parse(parts[0]), Parse(parts[1]), Parse(parts[2])); } catch { return null; }
      }
    }

    public static Version? GetDotnetCoreVersion() {
      if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Core ")) return null;
      var parts = RuntimeInformation.FrameworkDescription.Substring(10).Split('.');
      if (parts.Length == 2) parts = new string[] { parts[0], parts[1], "0" };
      if (parts.Length != 3) return null;
      Func<string, int> Parse = s => Int32.TryParse(s, out var i) ? i : -1;
      try { return new Version(Parse(parts[0]), Parse(parts[1]), Parse(parts[2])); } catch { return null; }
    }
  }
}

(code is C#8)

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

This is a problem with your web server sending out an HTTP header that does not match the one you define. For instructions on how to make the server send the correct headers, see this page.

Otherwise, you can also use PHP to modify the headers, but this has to be done before outputting any text using this code:

header('Content-Type: text/html; charset=utf-8');

More information on how to send out headers using PHP can be found in the documentation for the header function.

Using await outside of an async function

As of Node.js 14.3.0 the top-level await is supported.

Required flag: --experimental-top-level-await.

Further details: https://v8.dev/features/top-level-await

How to set default value for HTML select?

You could use...

<option <?= ($temp == $value) ? "SELECTED" : "" ?> >$value</opton>

Edit: I thought I was looking at PHP questions... Sorry.

How do you do dynamic / dependent drop downs in Google Sheets?

Here you have another solution based on the one provided by @tarheel

function onEdit() {
    var sheetWithNestedSelectsName = "Sitemap";
    var columnWithNestedSelectsRoot = 1;
    var sheetWithOptionPossibleValuesSuffix = "TabSections";

    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = SpreadsheetApp.getActiveSheet();

    // If we're not in the sheet with nested selects, exit!
    if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
        return;
    }

    var activeCell = SpreadsheetApp.getActiveRange();

    // If we're not in the root column or a content row, exit!
    if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
        return;
    }

    var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );

    // Get all possible values
    var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );

    var possibleValuesValidation = SpreadsheetApp.newDataValidation();
    possibleValuesValidation.setAllowInvalid( false );
    possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );

    activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}

It has some benefits over the other approach:

  • You don't need to edit the script every time you add a "root option". You only have to create a new sheet with the nested options of this root option.
  • I've refactored the script providing more semantic names for the variables and so on. Furthermore, I've extracted some parameters to variables in order to make it easier to adapt to your specific case. You only have to set the first 3 values.
  • There's no limit of nested option values (I've used the getSheetValues method with the -1 value).

So, how to use it:

  1. Create the sheet where you'll have the nested selectors
  2. Go to the "Tools" > "Script Editor…" and select the "Blank project" option
  3. Paste the code attached to this answer
  4. Modify the first 3 variables of the script setting up your values and save it
  5. Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

Enjoy!

Use of "instanceof" in Java

instanceof is a keyword that can be used to test if an object is of a specified type.

Example :

public class MainClass {
    public static void main(String[] a) {

    String s = "Hello";
    int i = 0;
    String g;
    if (s instanceof java.lang.String) {
       // This is going to be printed
       System.out.println("s is a String");
    }
    if (i instanceof Integer) {
       // This is going to be printed as autoboxing will happen (int -> Integer)
       System.out.println("i is an Integer");
    }
    if (g instanceof java.lang.String) {
       // This case is not going to happen because g is not initialized and
       // therefore is null and instanceof returns false for null. 
       System.out.println("g is a String");
    } 
} 

Here is my source.

add elements to object array

If you can, use a List<Subject> instead of Subject[]... this will let you do Student.Subject.Add(new Subject()). If that is not possible, you'll have to resize your array... look at Array.Resize() at http://msdn.microsoft.com/en-us/library/bb348051.aspx

What is the best project structure for a Python application?

In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses.

As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.

With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.

Can I add background color only for padding?

There is no exact functionality to do this.

Without wrapping another element inside, you could replace the border by a box-shadow and the padding by the border. But remember the box-shadow does not add to the dimensions of the element.

jsfiddle is being really slow, otherwise I'd add an example.

How does the Java 'for each' loop work?

It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.

How to import CSV file data into a PostgreSQL table?

Most other solutions here require that you create the table in advance/manually. This may not be practical in some cases (e.g., if you have a lot of columns in the destination table). So, the approach below may come handy.

Providing the path and column count of your csv file, you can use the following function to load your table to a temp table that will be named as target_table:

The top row is assumed to have the column names.

create or replace function data.load_csv_file
(
    target_table text,
    csv_path text,
    col_count integer
)

returns void as $$

declare

iter integer; -- dummy integer to iterate columns with
col text; -- variable to keep the column name at each iteration
col_first text; -- first column name, e.g., top left corner on a csv file or spreadsheet

begin
    create table temp_table ();

    -- add just enough number of columns
    for iter in 1..col_count
    loop
        execute format('alter table temp_table add column col_%s text;', iter);
    end loop;

    -- copy the data from csv file
    execute format('copy temp_table from %L with delimiter '','' quote ''"'' csv ', csv_path);

    iter := 1;
    col_first := (select col_1 from temp_table limit 1);

    -- update the column names based on the first row which has the column names
    for col in execute format('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first)
    loop
        execute format('alter table temp_table rename column col_%s to %s', iter, col);
        iter := iter + 1;
    end loop;

    -- delete the columns row
    execute format('delete from temp_table where %s = %L', col_first, col_first);

    -- change the temp table name to the name given as parameter, if not blank
    if length(target_table) > 0 then
        execute format('alter table temp_table rename to %I', target_table);
    end if;

end;

$$ language plpgsql;

Set cellpadding and cellspacing in CSS?

This worked for me:

table {border-collapse: collapse}
table th, table td {padding: 0}

Warning: The method assertEquals from the type Assert is deprecated

this method also encounter a deprecate warning:

org.junit.Assert.assertEquals(float expected,float actual) //deprecated

It is because currently junit prefer a third parameter rather than just two float variables input.

The third parameter is delta:

public static void assertEquals(double expected,double actual,double delta) //replacement

this is mostly used to deal with inaccurate Floating point calculations

for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values

Android: Create a toggle button with image and no text

ToggleButton inherits from TextView so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_info_details"
    android:gravity="center"
    android:textOff=""
    android:textOn=""
    android:textSize="0dp" />

The result compared to regular ToggleButton looks like

enter image description here

The seconds option is to use an ImageSpan to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.

You create a plain ToggleButton

<ToggleButton
    android:id="@+id/toggleButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false" />

Then set the "text" programmatially

ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);

The result here in the middle - icon is placed slightly lower since it takes the place of the text.

enter image description here

How do I escape a single quote ( ' ) in JavaScript?

The answer here is very simple:

You're already containing it in double quotes, so there's no need to escape it with \.

If you want to escape single quotes in a single quote string:

var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
//           ^         ^ same types, hence we need to escape it with a backslash

or if you want to escape \', you can escape the bashslash to \\ and the quote to \' like so:

var string = 'this isn\\\'t a double quoted string';
//                    vvvv
//                     \ ' (the escaped characters)

However, if you contain the string with a different quote type, you don't need to escape:

var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
//           ^        ^ different types, hence we don't need escaping

recursively use scp but excluding some folders

This one works fine for me as the directories structure is not important for me.

scp -r USER@HOSTNAME:~/bench1/?cpu/p_?/image/ .

Assuming /bench1 is in the home directory of the current user. Also, change USER and HOSTNAME to the real values.

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Lot of very detailed answers here but I don't think you are answering the right questions. As I understand the question, there are two concerns:

  1. How to I score a multiclass problem?
  2. How do I deal with unbalanced data?

1.

You can use most of the scoring functions in scikit-learn with both multiclass problem as with single class problems. Ex.:

from sklearn.metrics import precision_recall_fscore_support as score

predicted = [1,2,3,4,5,1,2,1,1,4,5] 
y_test = [1,2,3,4,5,1,2,1,1,4,1]

precision, recall, fscore, support = score(y_test, predicted)

print('precision: {}'.format(precision))
print('recall: {}'.format(recall))
print('fscore: {}'.format(fscore))
print('support: {}'.format(support))

This way you end up with tangible and interpretable numbers for each of the classes.

| Label | Precision | Recall | FScore | Support |
|-------|-----------|--------|--------|---------|
| 1     | 94%       | 83%    | 0.88   | 204     |
| 2     | 71%       | 50%    | 0.54   | 127     |
| ...   | ...       | ...    | ...    | ...     |
| 4     | 80%       | 98%    | 0.89   | 838     |
| 5     | 93%       | 81%    | 0.91   | 1190    |

Then...

2.

... you can tell if the unbalanced data is even a problem. If the scoring for the less represented classes (class 1 and 2) are lower than for the classes with more training samples (class 4 and 5) then you know that the unbalanced data is in fact a problem, and you can act accordingly, as described in some of the other answers in this thread. However, if the same class distribution is present in the data you want to predict on, your unbalanced training data is a good representative of the data, and hence, the unbalance is a good thing.

Splitting dataframe into multiple dataframes

Groupby can helps you:

grouped = data.groupby(['name'])

Then you can work with each group like with a dataframe for each participant. And DataFrameGroupBy object methods such as (apply, transform, aggregate, head, first, last) return a DataFrame object.

Or you can make list from grouped and get all DataFrame's by index:

l_grouped = list(grouped)

l_grouped[0][1] - DataFrame for first group with first name.

T-SQL XOR Operator

The xor operator is ^

For example: SELECT A ^ B where A and B are integer category data types.

SVN 405 Method Not Allowed

If you use code.google.com to host your Subversion repository.

You know below things, right?

If you plan to make changes, use this command to check out the code as yourself using HTTPS:

# Project members authenticate over HTTPS to allow committing changes.
svn checkout https://.../svn/trunk/ user-...

When prompted, enter your generated googlecode.com password.
Use this command to anonymously check out the latest project source code:

# Non-members may check out a read-only working copy anonymously over HTTP.
svn checkout http://.../svn/trunk/ ...-read-only

The error you mentioned exactly you are using Non-members may check out a read-only working copy anonymously over HTTP status. Therefore, you can not commit or do anything so far.

You must use Project members authenticate over HTTPS to allow committing changes thing.

It will be fine now.

How to document a method with parameter(s)?

Docstrings are only useful within interactive environments, e.g. the Python shell. When documenting objects that are not going to be used interactively (e.g. internal objects, framework callbacks), you might as well use regular comments. Here’s a style I use for hanging indented comments off items, each on their own line, so you know that the comment is applying to:

def Recomputate \
  (
    TheRotaryGyrator,
      # the rotary gyrator to operate on
    Computrons,
      # the computrons to perform the recomputation with
    Forthwith,
      # whether to recomputate forthwith or at one's leisure
  ) :
  # recomputates the specified rotary gyrator with
  # the desired computrons.
  ...
#end Recomputate

You can’t do this sort of thing with docstrings.

What is the equivalent to getLastInsertId() in Cakephp?

CakePHP has two methods for getting the last inserted id: Model::getLastInsertID() and Model::getInsertID(). Actually these methods are identical so it really doesn't matter which method you use.

echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();

This methods can be found in cake/libs/model/model.php on line 2768

jQuery .on('change', function() {} not triggering for dynamically created inputs

You can apply any one approach:

$("#Input_Id").change(function(){   // 1st
    // do your code here
    // When your element is already rendered
});


$("#Input_Id").on('change', function(){    // 2nd (A)
    // do your code here
    // It will specifically called on change of your element
});

$("body").on('change', '#Input_Id', function(){    // 2nd (B)
    // do your code here
    // It will filter the element "Input_Id" from the "body" and apply "onChange effect" on it
});

Getting "type or namespace name could not be found" but everything seems ok?

Check the Build Action of the .cs file containing the missing type. Make sure it's C# compiler.

  1. Click on the .cs file containing the missing type.
  2. Press F4 to bring up Properties.
  3. Make sure Build Action is set to C# compiler.

Before:

The properties of a C# file whose build action is set to "None"

After:

The properties of a C# file whose build action is set to "C# compiler"

Refer to a cell in another worksheet by referencing the current worksheet's name?

Here is how I made monthly page in similar manner as Fernando:

  1. I wrote manually on each page number of the month and named that place as ThisMonth. Note that you can do this only before you make copies of the sheet. After copying Excel doesn't allow you to use same name, but with sheet copy it does it still. This solution works also without naming.
  2. I added number of weeks in the month to location C12. Naming is fine also.
  3. I made five weeks on every page and on fifth week I made function

      =IF(C12=5,DATE(YEAR(B48),MONTH(B48),DAY(B48)+7),"")
    

    that empties fifth week if this month has only four weeks. C12 holds the number of weeks.

  4. ...
  5. I created annual Excel, so I had 12 sheets in it: one for each month. In this example name of the sheet is "Month". Note that this solutions works also with the ODS file standard except you need to change all spaces as "_" characters.
  6. I renamed first "Month" sheet as "Month (1)" so it follows the same naming principle. You could also name it as "Month1" if you wish, but "January" would require a bit more work.
  7. Insert following function on the first day field starting sheet #2:

     =INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!B15"))+INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!C12"))*7
    

    So in another word, if you fill four or five weeks on the previous sheet, this calculates date correctly and continues from correct date.

Bootstrap 4 - Responsive cards in card-columns

I have created a Cards Layout - 3 cards in a row using Bootstrap 4 / CSS3 (of course its responsive). The following example uses basic Bootstrap 4 classes such as container, row, col-x, list-group and list-group-item. Thought to share here if someone is interested in this sort of a layout.

enter image description here

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">        
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
  </div>
</div>

CSS / SCSS

$primary-color: #ccc;
$col-bg-color: #eee;
$col-footer-bg-color: #eee;
$col-header-bg-color: #007bff;
$col-content-bg-color: #fff;

body {
  background-color: $primary-color;
}  

.custom-column {  
  background-color: $col-bg-color;
  border: 5px solid $col-bg-color;    
  padding: 10px;
  box-sizing: border-box;  
}

.custom-column-header {
  font-size: 24px;
  background-color: #007bff;  
  color: white;
  padding: 15px;  
  text-align: center;
}

.custom-column-content {
  background-color: $col-content-bg-color;
  border: 2px solid white;  
  padding: 20px;  
}

.custom-column-footer {
  background-color: $col-footer-bg-color;   
  padding-top: 20px;
  text-align: center;
}

Link :- https://codepen.io/anjanasilva/pen/JmdOpb

Clone only one branch

I have done with below single git command:

git clone [url] -b [branch-name] --single-branch

Object comparison in JavaScript

Here is my version, pretty much stuff from this thread is integrated (same counts for the test cases):

Object.defineProperty(Object.prototype, "equals", {
    enumerable: false,
    value: function (obj) {
        var p;
        if (this === obj) {
            return true;
        }

        // some checks for native types first

        // function and sring
        if (typeof(this) === "function" || typeof(this) === "string" || this instanceof String) { 
            return this.toString() === obj.toString();
        }

        // number
        if (this instanceof Number || typeof(this) === "number") {
            if (obj instanceof Number || typeof(obj) === "number") {
                return this.valueOf() === obj.valueOf();
            }
            return false;
        }

        // null.equals(null) and undefined.equals(undefined) do not inherit from the 
        // Object.prototype so we can return false when they are passed as obj
        if (typeof(this) !== typeof(obj) || obj === null || typeof(obj) === "undefined") {
            return false;
        }

        function sort (o) {
            var result = {};

            if (typeof o !== "object") {
                return o;
            }

            Object.keys(o).sort().forEach(function (key) {
                result[key] = sort(o[key]);
            });

            return result;
        }

        if (typeof(this) === "object") {
            if (Array.isArray(this)) { // check on arrays
                return JSON.stringify(this) === JSON.stringify(obj);                
            } else { // anyway objects
                for (p in this) {
                    if (typeof(this[p]) !== typeof(obj[p])) {
                        return false;
                    }
                    if ((this[p] === null) !== (obj[p] === null)) {
                        return false;
                    }
                    switch (typeof(this[p])) {
                    case 'undefined':
                        if (typeof(obj[p]) !== 'undefined') {
                            return false;
                        }
                        break;
                    case 'object':
                        if (this[p] !== null 
                                && obj[p] !== null 
                                && (this[p].constructor.toString() !== obj[p].constructor.toString() 
                                        || !this[p].equals(obj[p]))) {
                            return false;
                        }
                        break;
                    case 'function':
                        if (this[p].toString() !== obj[p].toString()) {
                            return false;
                        }
                        break;
                    default:
                        if (this[p] !== obj[p]) {
                            return false;
                        }
                    }
                };

            }
        }

        // at least check them with JSON
        return JSON.stringify(sort(this)) === JSON.stringify(sort(obj));
    }
});

Here is my TestCase:

    assertFalse({}.equals(null));
    assertFalse({}.equals(undefined));

    assertTrue("String", "hi".equals("hi"));
    assertTrue("Number", new Number(5).equals(5));
    assertFalse("Number", new Number(5).equals(10));
    assertFalse("Number+String", new Number(1).equals("1"));

    assertTrue([].equals([]));
    assertTrue([1,2].equals([1,2]));
    assertFalse([1,2].equals([2,1]));
    assertFalse([1,2].equals([1,2,3]));

    assertTrue(new Date("2011-03-31").equals(new Date("2011-03-31")));
    assertFalse(new Date("2011-03-31").equals(new Date("1970-01-01")));

    assertTrue({}.equals({}));
    assertTrue({a:1,b:2}.equals({a:1,b:2}));
    assertTrue({a:1,b:2}.equals({b:2,a:1}));
    assertFalse({a:1,b:2}.equals({a:1,b:3}));

    assertTrue({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
    assertFalse({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));

    assertTrue("Function", (function(x){return x;}).equals(function(x){return x;}));
    assertFalse("Function", (function(x){return x;}).equals(function(y){return y+2;}));

    var a = {a: 'text', b:[0,1]};
    var b = {a: 'text', b:[0,1]};
    var c = {a: 'text', b: 0};
    var d = {a: 'text', b: false};
    var e = {a: 'text', b:[1,0]};
    var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
    var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
    var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
    var i = {
        a: 'text',
        c: {
            b: [1, 0],
            f: function(){
                this.a = this.b;
            }
        }
    };
    var j = {
        a: 'text',
        c: {
            b: [1, 0],
            f: function(){
                this.a = this.b;
            }
        }
    };
    var k = {a: 'text', b: null};
    var l = {a: 'text', b: undefined};

    assertTrue(a.equals(b));
    assertFalse(a.equals(c));
    assertFalse(c.equals(d));
    assertFalse(a.equals(e));
    assertTrue(f.equals(g));
    assertFalse(h.equals(g));
    assertTrue(i.equals(j));
    assertFalse(d.equals(k));
    assertFalse(k.equals(l));

UPDATE and REPLACE part of a string

replace for persian word

UPDATE dbo.TblNews
SET keyWords = REPLACE(keyWords, '-', N'?')

help: dbo.TblNews -- table name

keyWords -- fild name

Run function from the command line

With the -c (command) argument (assuming your file is named foo.py):

$ python -c 'import foo; print foo.hello()'

Alternatively, if you don't care about namespace pollution:

$ python -c 'from foo import *; print hello()'

And the middle ground:

$ python -c 'from foo import hello; print hello()'

Output of git branch in tree like fashion

You can use a tool called gitk.

C++ Redefinition Header Files (winsock2.h)

By using "header guards":

#ifndef MYCLASS_H
#define MYCLASS_H

// This is unnecessary, see comments.
//#pragma once

// MyClass.h

#include <winsock2.h>

class MyClass
{

// methods
public:
    MyClass(unsigned short port);
    virtual ~MyClass(void);
};

#endif

bootstrap button shows blue outline when clicked

Try this

.btn
{
    box-shadow: none;
    outline: none;
}

sql query distinct with Row_Number

Using DISTINCT causes issues as you add fields and it can also mask problems in your select. Use GROUP BY as an alternative like this:

SELECT id
      ,ROW_NUMBER() OVER (ORDER BY  id) AS RowNum
  FROM table
 where fid = 64
 group by id

Then you can add other interesting information from your select like this:

,count(*) as thecount

or

,max(description) as description

Counting the number of files in a directory using Java

If you have directories containing really (>100'000) many files, here is a (non-portable) way to go:

String directoryPath = "a path";

// -f flag is important, because this way ls does not sort it output,
// which is way faster
String[] params = { "/bin/sh", "-c",
    "ls -f " + directoryPath + " | wc -l" };
Process process = Runtime.getRuntime().exec(params);
BufferedReader reader = new BufferedReader(new InputStreamReader(
    process.getInputStream()));
String fileCount = reader.readLine().trim() - 2; // accounting for .. and .
reader.close();
System.out.println(fileCount);

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

How to create an empty DataFrame with a specified schema?

I had a special requirement wherein I already had a dataframe but given a certain condition I had to return an empty dataframe so I returned df.limit(0) instead.

How to verify CuDNN installation?

Run ./mnistCUDNN in /usr/src/cudnn_samples_v7/mnistCUDNN

Here is an example:

cudnnGetVersion() : 7005 , CUDNN_VERSION from cudnn.h : 7005 (7.0.5)
Host compiler version : GCC 5.4.0
There are 1 CUDA capable devices on your machine :
device 0 : sms 30  Capabilities 6.1, SmClock 1645.0 Mhz, MemSize (Mb) 24446, MemClock 4513.0 Mhz, Ecc=0,    boardGroupID=0
Using device 0

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Start writing, then just press CTRL+SPACE and there you go ...

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

WordPress is giving me 404 page not found for all pages except the homepage

Basically the .htaccess file should exists and the httpd.conf should be correct.

In my case, I changed the file /etc/apache2/apache2.conf in section:

<Directory "/var/www/html">

Line changed is:

AllowOverride None

to

AllowOverride All

And restart the web server with

systemctl restart apache2

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

I had the same issue, but I have resolved it the next:

1) Install jdk1.8...

2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.

3) Click Ok.

@import vs #import - iOS 7

Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)

Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:

#import "someFile.h"

Or in the case of frameworks:

#import <SomeLibrary/SomeFile.h>

Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h and SomeFileB.h; SomeFileA.h includes SomeFileB.h, and SomeFileB.h includes SomeFileA.h. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.

When using #import, you don’t need to worry about this issue or write header guards to avoid it. However, #import is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)

Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import.

Returning to the previous example of importing a framework:

#import <SomeLibrary/SomeFile.h>

To import this library as a module, the code would be changed to:

@import SomeLibrary;

This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:

@import AwesomeLibrary.AwesomeObject;

For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import and @import statements in your code together without any concern.

C error: undefined reference to function, but it IS defined

I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c file) from C++ code.

The .h file for the C function wasn't wrapped in this sort of guard:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:

extern "C" {
#include "legacy_C_header.h"
}

(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)

Installing python module within code

You can also use something like:

import pip

def install(package):
    if hasattr(pip, 'main'):
        pip.main(['install', package])
    else:
        pip._internal.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')

Java method: Finding object in array list given a known attribute value

To improve performance of the operation, if you're always going to want to look up objects by some unique identifier, then you might consider using a Map<Integer,Dog>. This will provide constant-time lookup by key. You can still iterate over the objects themselves using the map values().

A quick code fragment to get you started:

// Populate the map
Map<Integer,Dog> dogs = new HashMap<Integer,Dog>();
for( Dog dog : /* dog source */ ) {
    dogs.put( dog.getId(), dog );
}

// Perform a lookup
Dog dog = dogs.get( id );

This will help speed things up a bit if you're performing multiple lookups of the same nature on the list. If you're just doing the one lookup, then you're going to incur the same loop overhead regardless.

Sending Windows key using SendKeys

Alt+F4 is working only in brackets

SendKeys.SendWait("(%{F4})");

IntelliJ - show where errors are

I ran into the problem of not having set my sources root folder (project window--right click folder, mark directory as > sources root). If you don't set this IDEA doesn't parse the file.

How can I pass an Integer class correctly by reference?

You are correct here:

Integer i = 0;
i = i + 1;  // <- I think that this is somehow creating a new object!

First: Integer is immutable.

Second: the Integer class is not overriding the + operator, there is autounboxing and autoboxing involved at that line (In older versions of Java you would get an error on the above line).
When you write i + 1 the compiler first converts the Integer to an (primitive) int for performing the addition: autounboxing. Next, doing i = <some int> the compiler converts from int to an (new) Integer: autoboxing.
So + is actually being applied to primitive ints.

How can I get the error message for the mail() function?

If you are on Windows using SMTP, you can use error_get_last() when mail() returns false. Keep in mind this does not work with PHP's native mail() function.

$success = mail('[email protected]', 'My Subject', $message);
if (!$success) {
    $errorMessage = error_get_last()['message'];
}

With print_r(error_get_last()), you get something like this:

[type] => 2
[message] => mail(): Failed to connect to mailserver at "x.x.x.x" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
[file] => C:\www\X\X.php
[line] => 2

How to create an exit message

I got here searching for a way to execute some code whenever the program ends.
Found this:

Kernel.at_exit { puts "sayonara" }
# do whatever
# [...]
# call #exit or #abort or just let the program end
# calling #exit! will skip the call

Called multiple times will register multiple handlers.

php codeigniter count rows

replace the query inside your model function with this

$query = $this->db->query("SELECT id FROM home");

in view:

echo $query->num_rows();

Draw on HTML5 Canvas using a mouse

Here's the most straightforward way to create a drawing application with canvas:

  1. Attach a mousedown, mousemove, and mouseup event listener to the canvas DOM
  2. on mousedown, get the mouse coordinates, and use the moveTo() method to position your drawing cursor and the beginPath() method to begin a new drawing path.
  3. on mousemove, continuously add a new point to the path with lineTo(), and color the last segment with stroke().
  4. on mouseup, set a flag to disable the drawing.

From there, you can add all kinds of other features like giving the user the ability to choose a line thickness, color, brush strokes, and even layers.

How can I draw vertical text with CSS cross-browser?

The CSS Writing Modes module introduces orthogonal flows with vertical text.

Just use the writing-mode property with the desired value.

_x000D_
_x000D_
span { margin: 20px; }_x000D_
#vertical-lr { writing-mode: vertical-lr; }_x000D_
#vertical-rl { writing-mode: vertical-rl; }_x000D_
#sideways-lr { writing-mode: sideways-lr; }_x000D_
#sideways-rl { writing-mode: sideways-rl; }
_x000D_
<span id="vertical-lr">_x000D_
  ? (1) vertical-lr ?<br />_x000D_
  ? (2) vertical-lr ?<br />_x000D_
  ? (3) vertical-lr ?_x000D_
</span>_x000D_
<span id="vertical-rl">_x000D_
  ? (1) vertical-rl ?<br />_x000D_
  ? (2) vertical-rl ?<br />_x000D_
  ? (3) vertical-rl ?_x000D_
</span>_x000D_
<span id="sideways-lr">_x000D_
  ? (1) sideways-lr ?<br />_x000D_
  ? (2) sideways-lr ?<br />_x000D_
  ? (3) sideways-lr ?_x000D_
</span>_x000D_
<span id="sideways-rl">_x000D_
  ? (1) sideways-rl ?<br />_x000D_
  ? (2) sideways-rl ?<br />_x000D_
  ? (3) sideways-rl ?_x000D_
</span>
_x000D_
_x000D_
_x000D_

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

Simple java8 solution with capturing both outputs and reactive processing using CompletableFuture:

static CompletableFuture<String> readOutStream(InputStream is) {
    return CompletableFuture.supplyAsync(() -> {
        try (
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
        ){
            StringBuilder res = new StringBuilder();
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                res.append(inputLine).append(System.lineSeparator());
            }
            return res.toString();
        } catch (Throwable e) {
            throw new RuntimeException("problem with executing program", e);
        }
    });
}

And the usage:

Process p = Runtime.getRuntime().exec(cmd);
CompletableFuture<String> soutFut = readOutStream(p.getInputStream());
CompletableFuture<String> serrFut = readOutStream(p.getErrorStream());
CompletableFuture<String> resultFut = soutFut.thenCombine(serrFut, (stdout, stderr) -> {
         // print to current stderr the stderr of process and return the stdout
        System.err.println(stderr);
        return stdout;
        });
// get stdout once ready, blocking
String result = resultFut.get();

iOS: Multi-line UILabel in Auto Layout

Use -setPreferredMaxLayoutWidth on the UILabel and autolayout should handle the rest.

[label setPreferredMaxLayoutWidth:200.0];

See the UILabel documentation on preferredMaxLayoutWidth.

Update:

Only need to set the height constraint in storyboard to Greater than or equal to, no need to setPreferredMaxLayoutWidth.

Listing available com ports with Python

Basically mentioned this in pyserial documentation https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports

import serial.tools.list_ports
ports = serial.tools.list_ports.comports()

for port, desc, hwid in sorted(ports):
        print("{}: {} [{}]".format(port, desc, hwid))

Result :

COM1: Communications Port (COM1) [ACPI\PNP0501\1]

COM7: MediaTek USB Port (COM7) [USB VID:PID=0E8D:0003 SER=6 LOCATION=1-2.1]

Insert line at middle of file with Python?

Below is a slightly awkward solution for the special case in which you are creating the original file yourself and happen to know the insertion location (e.g. you know ahead of time that you will need to insert a line with an additional name before the third line, but won't know the name until after you've fetched and written the rest of the names). Reading, storing and then re-writing the entire contents of the file as described in other answers is, I think, more elegant than this option, but may be undesirable for large files.

You can leave a buffer of invisible null characters ('\0') at the insertion location to be overwritten later:

num_names = 1_000_000    # Enough data to make storing in a list unideal
max_len = 20             # The maximum allowed length of the inserted line
line_to_insert = 2       # The third line is at index 2 (0-based indexing)

with open(filename, 'w+') as file:
    for i in range(line_to_insert):
        name = get_name(i)                    # Returns 'Alfred' for i = 0, etc.
        file.write(F'{i + 1}. {name}\n')

    insert_position = file.tell()             # Position to jump back to for insertion
    file.write('\0' * max_len + '\n')         # Buffer will show up as a blank line

    for i in range(line_to_insert, num_names):
        name = get_name(i)
        file.write(F'{i + 2}. {name}\n')      # Line numbering now bumped up by 1.

# Later, once you have the name to insert...
with open(filename, 'r+') as file:            # Must use 'r+' to write to middle of file 
    file.seek(insert_position)                # Move stream to the insertion line
    name = get_bonus_name()                   # This lucky winner jumps up to 3rd place
    new_line = F'{line_to_insert + 1}. {name}'
    file.write(new_line[:max_len])            # Slice so you don't overwrite next line

Unfortunately there is no way to delete-without-replacement any excess null characters that did not get overwritten (or in general any characters anywhere in the middle of a file), unless you then re-write everything that follows. But the null characters will not affect how your file looks to a human (they have zero width).

Visual Studio: How to break on handled exceptions?

Took me a while to find the new place for expection settings, therefore a new answer.

Since Visual Studio 2015 you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still Ctrl-Alt-E.

The simplest way to handle custom exceptions is selecting "all exceptions not in this list".

Here is a screenshot from the english version:

enter image description here

Here is a screenshot from the german version:

enter image description here

Change UITextField and UITextView Cursor / Caret Color

A more general approach would be to set the UIView's appearance's tintColor.

UIColor *myColor = [UIColor purpleColor];
[[UIView appearance] setTintColor:myColor];

Makes sense if you're using many default UI elements.

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

horizontal line and right way to code it in html, css

_x000D_
_x000D_
.line {_x000D_
  width: 53px;_x000D_
  height: 0;_x000D_
  border: 1px solid #C4C4C4;_x000D_
  margin: 3px;_x000D_
  display:inline-block;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<div class="line"></div>_x000D_
<div style="display:inline-block;">OR</div>_x000D_
<div class="line"></div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I make my own event in C#?

I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:

public event EventHandler Foo;

If you need more complicated subscription/unsubscription logic, you can do that explicitly:

public event EventHandler Foo
{
    add
    {
        // Subscription logic here
    }
    remove
    {
        // Unsubscription logic here
    }
}

How to split a string and assign it to variables

The IPv6 addresses for fields like RemoteAddr from http.Request are formatted as "[::1]:53343"

So net.SplitHostPort works great:

package main

    import (
        "fmt"
        "net"
    )

    func main() {
        host1, port, err := net.SplitHostPort("127.0.0.1:5432")
        fmt.Println(host1, port, err)

        host2, port, err := net.SplitHostPort("[::1]:2345")
        fmt.Println(host2, port, err)

        host3, port, err := net.SplitHostPort("localhost:1234")
        fmt.Println(host3, port, err)
    }

Output is:

127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>

What is the difference between Promises and Observables?

The basic difference between observable and promises are:

enter image description here

Why won't eclipse switch the compiler to Java 8?

Old question, but posting the answer incase it helps someone. Already build path was configured to use JDK 1.2.81 However, build was failing with the error below:

 lambda expressions are not supported in -source 1.5
[ERROR]   (use -source 8 or higher to enable lambda expressions)

In the latest Eclipse (Photon), adding the below entry to pom.xml worked.

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

Bash Shell Script - Check for a flag and grab its value

Here is a generalized simple command argument interface you can paste to the top of all your scripts.

#!/bin/bash

declare -A flags
declare -A booleans
args=()

while [ "$1" ];
do
    arg=$1
    if [ "${1:0:1}" == "-" ]
    then
      shift
      rev=$(echo "$arg" | rev)
      if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
      then
        bool=$(echo ${arg:1} | sed s/://g)
        booleans[$bool]=true
        echo \"$bool\" is boolean
      else
        value=$1
        flags[${arg:1}]=$value
        shift
        echo \"$arg\" is flag with value \"$value\"
      fi
    else
      args+=("$arg")
      shift
      echo \"$arg\" is an arg
    fi
done


echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}

echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"

By running the command:

bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f

The output will be this:

"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean


booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg

Boolean types:
    Precedes Flag(pf): true
    Final Arg(f): true
    Colon Terminated(Ct): true
    Not Mentioned(nm): 

Flag: myFlag => my flag value

Args: one => firstArg, two => secondArg, three => thirdArg

Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.

Allowing me and now you to never deal with bash argument parsing again!

You can view an updated script here

This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.

Just call the script like

replace() (
  source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@"
  echo ${replaceFlags[f]}
  echo ${replaceBooleans[b]}
)

Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.

What is App.config in C#.NET? How to use it?

You can access keys in the App.Config using:

ConfigurationSettings.AppSettings["KeyName"]

Take alook at this Thread

What algorithms compute directions from point A to point B on a map?

I was very curious about the heuristics used, when a while back we got routes from the same starting location near Santa Rosa, to two different campgrounds in Yosemite National Park. These different destinations produced quite different routes (via I-580 or CA-12) despite the fact that both routes converged for the last 100 miles (along CA-120) before diverging again by a few miles at the end. This was quite repeatable. The two routes were up to 50 miles apart for around 100 miles, but the distances/times were pretty close to each other as you would expect.

Alas I cannot reproduce that - the algorithms must have changed. But it had me curious about the algorithm. All I can speculate is that there was some directional pruning which happened to be exquisitely sensitive to the tiny angular difference between the destinations as seen from far away, or there were different precomputed segments selected by the choice of final destination.

How to create EditText with rounded corners?

Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>

</shape>

What is base 64 encoding used for?

When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings).

So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings.

Why 64?
Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.

How to check whether a Button is clicked by using JavaScript

if(button.clicked==true) {
    console.log("Button Clicked");
} ==> // This Code Doesn't Work Properly So Please Use Below One // 


function check() { 
    console.log("Button Clicked");
}; // This Code Works Fine // 

var button= document.querySelector("button"); // Accessing The Button // 
button.addEventListener("click", check); // Adding event to call function when clicked // 

What is the difference between background and background-color

About CSS performance :

background vs background-color :

Comparison of 18 color swatches rendered 100 times on a page as small rectangles, once with background and once with background-color.

Background vs background-color

While these numbers are from a single page reload, with subsequent refreshes the render times changed, but the percent difference was basically the same every time.

That's a savings of almost 42.6ms, almost twice as fast, when using background instead of background-color in Safari 7.0.1. Chrome 33 appears to be about the same.

This honestly blew me away because for the longest time for two reasons:

  • I usually always argue for explicitness in CSS properties, especially with backgrounds because it can adversely affect specificity down the road.
  • I thought that when a browser sees background: #000;, they really see background: #000 none no-repeat top center;. I don't have a link to a resource here, but I recall reading this somewhere.

Ref : https://github.com/mdo/css-perf#background-vs-background-color

Concatenate a vector of strings/character

Matt's answer is definitely the right answer. However, here's an alternative solution for comic relief purposes:

do.call(paste, c(as.list(sdata), sep = ""))

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

How to install SQL Server Management Studio 2008 component only

I found some articles to be of major use:

This link is an experience someone else had: http://goneale.com/2009/05/24/cant-install-microsoft-sql-server-2008-management-studio-express/

This link has the exact steps involved to install everything properly: http://www.codefrenzy.net/2011/06/03/how-to-install-sql-server-2008-management-studio/

This link confirms the previous link: https://superuser.com/questions/88244/installing-sql-server-management-studio-when-vs2010-beta-2-is-already-installed

My Instructions

I am not sure if my instructions will be 100% accurate, but in my instance, because I installed VS2010 on a fresh copy of Windows 7, the VS2010 installer installs SQL Server 2008 Express for you, so from this point I just need the Management Studio.

What I gathered from these explanations is to do the following:

  1. Download the SQL Server Management Studio install from http://www.microsoft.com/download/en/details.aspx?id=22973

  2. Run the setup, when you get to the point where it asks you to "Perform a new installation of SQL Server 2008" or "Add features to an existing instance of SQL Server 2008", this part is the CONFUSING PART (HEY MICROSOFT TAKE NOTES, DON'T DO THIS KIND OF STUFF).

    As much as you want to select "Add features to an existing instance of SQL Server 2008" DON'T!!!!

    You need to select "Perform a new installation of SQL Server 2008". It doesn't sound right I know - it is very confusing and counter intuitive, but this seems to be the way to install management studio. :(

  3. Press next until you see the features selection portion. Heeeeeyyyy look at that, it has a check box for Management Studio. It should be selected already, if not then select it of course and press next.

  4. Press Next next next next next next... basically just install it at this point.

  5. Enjoy, it has installed.

Passing arguments to C# generic new() of templated type

This will not work in your situation. You can only specify the constraint that it has an empty constructor:

public static string GetAllItems<T>(...) where T: new()

What you could do is use property injection by defining this interface:

public interface ITakesAListItem
{
   ListItem Item { set; }
}

Then you could alter your method to be this:

public static string GetAllItems<T>(...) where T : ITakesAListItem, new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
       tabListItems.Add(new T() { Item = listItem });
   } 
   ...
}

The other alternative is the Func method described by JaredPar.

How to disable a button when an input is empty?

Another way to check is to inline the function, so that the condition will be checked on every render (every props and state change)

const isDisabled = () => 
  // condition check

This works:

<button
  type="button"
  disabled={this.isDisabled()}
>
  Let Me In
</button>

but this will not work:

<button
   type="button"
   disabled={this.isDisabled}
>
  Let Me In
</button>

HTML - Alert Box when loading page

<script type="text/javascript">
    window.alert("My name is George. Welcome!")
</script>

What is a lambda expression in C++11?

Lambda expressions are typically used to encapsulate algorithms so that they can be passed to another function. However, it is possible to execute a lambda immediately upon definition:

[&](){ ...your code... }(); // immediately executed lambda expression

is functionally equivalent to

{ ...your code... } // simple code block

This makes lambda expressions a powerful tool for refactoring complex functions. You start by wrapping a code section in a lambda function as shown above. The process of explicit parameterization can then be performed gradually with intermediate testing after each step. Once you have the code-block fully parameterized (as demonstrated by the removal of the &), you can move the code to an external location and make it a normal function.

Similarly, you can use lambda expressions to initialize variables based on the result of an algorithm...

int a = []( int b ){ int r=1; while (b>0) r*=b--; return r; }(5); // 5!

As a way of partitioning your program logic, you might even find it useful to pass a lambda expression as an argument to another lambda expression...

[&]( std::function<void()> algorithm ) // wrapper section
   {
   ...your wrapper code...
   algorithm();
   ...your wrapper code...
   }
([&]() // algorithm section
   {
   ...your algorithm code...
   });

Lambda expressions also let you create named nested functions, which can be a convenient way of avoiding duplicate logic. Using named lambdas also tends to be a little easier on the eyes (compared to anonymous inline lambdas) when passing a non-trivial function as a parameter to another function. Note: don't forget the semicolon after the closing curly brace.

auto algorithm = [&]( double x, double m, double b ) -> double
   {
   return m*x+b;
   };

int a=algorithm(1,2,3), b=algorithm(4,5,6);

If subsequent profiling reveals significant initialization overhead for the function object, you might choose to rewrite this as a normal function.

HTTP authentication logout via PHP

Mu. No correct way exists, not even one that's consistent across browsers.

This is a problem that comes from the HTTP specification (section 15.6):

Existing HTTP clients and user agents typically retain authentication information indefinitely. HTTP/1.1. does not provide a method for a server to direct clients to discard these cached credentials.

On the other hand, section 10.4.2 says:

If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.

In other words, you may be able to show the login box again (as @Karsten says), but the browser doesn't have to honor your request - so don't depend on this (mis)feature too much.

How do I change file permissions in Ubuntu

If you just want to change file permissions, you want to be careful about using -R on chmod since it will change anything, files or folders. If you are doing a relative change (like adding write permission for everyone), you can do this:

sudo chmod -R a+w /var/www

But if you want to use the literal permissions of read/write, you may want to select files versus folders:

sudo find /var/www -type f -exec chmod 666 {} \;

(Which, by the way, for security reasons, I wouldn't recommend either of these.)

Or for folders:

sudo find /var/www -type d -exec chmod 755 {} \;

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

From This page, the container dies after running everything correctly but crashes because all the commands ended. Either you make your services run on the foreground, or you create a keep alive script. By doing so, Kubernetes will show that your application is running. We have to note that in the Docker environment, this problem is not encountered. It is only Kubernetes that wants a running app.

Update (an example):

Here's how to avoid CrashLoopBackOff, when launching a Netshoot container:

kubectl run netshoot --image nicolaka/netshoot -- sleep infinity

Java reflection: how to get field value from an object, not knowing its class

If you know what class the field is on you can access it using reflection. This example (it's in Groovy but the method calls are identical) gets a Field object for the class Foo and gets its value for the object b. It shows that you don't have to care about the exact concrete class of the object, what matters is that you know the class the field is on and that that class is either the concrete class or a superclass of the object.

groovy:000> class Foo { def stuff = "asdf"}
===> true
groovy:000> class Bar extends Foo {}
===> true
groovy:000> b = new Bar()
===> Bar@1f2be27
groovy:000> f = Foo.class.getDeclaredField('stuff')
===> private java.lang.Object Foo.stuff
groovy:000> f.getClass()
===> class java.lang.reflect.Field
groovy:000> f.setAccessible(true)
===> null
groovy:000> f.get(b)
===> asdf

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

As pointed out, you can use getElementById instead, but you can also still achieve the same with a querySelector:

document.querySelector("[id='22']")

SQL Server Linked Server Example Query

Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.

SELECT *
FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')

How do you set your pythonpath in an already-created virtualenv?

It's already answered here -> Is my virtual environment (python) causing my PYTHONPATH to break?

UNIX/LINUX

Add "export PYTHONPATH=/usr/local/lib/python2.0" this to ~/.bashrc file and source it by typing "source ~/.bashrc" OR ". ~/.bashrc".

WINDOWS XP

1) Go to the Control panel 2) Double click System 3) Go to the Advanced tab 4) Click on Environment Variables

In the System Variables window, check if you have a variable named PYTHONPATH. If you have one already, check that it points to the right directories. If you don't have one already, click the New button and create it.

PYTHON CODE

Alternatively, you can also do below your code:-

import sys
sys.path.append("/home/me/mypy") 

Change CSS properties on click

<div id="foo">hello world!</div>
<img src="zoom.png" id="click_me" />

JS

$('#click_me').click(function(){
  $('#foo').css({
    'background-color':'red',
    'color':'white',
    'font-size':'44px'
  });
});

How to run a cron job inside a docker container?

this line was the one that helped me run my pre-scheduled task.

ADD mycron/root /etc/cron.d/root

RUN chmod 0644 /etc/cron.d/root

RUN crontab /etc/cron.d/root

RUN touch /var/log/cron.log

CMD ( cron -f -l 8 & ) && apache2-foreground # <-- run cron

--> My project run inside: FROM php:7.2-apache

Add floating point value to android resources/values

If you have simple floats that you control the range of, you can also have an integer in the resources and divide by the number of decimal places you need straight in code.

So something like this

<integer name="strokeWidth">356</integer>

is used with 2 decimal places

this.strokeWidthFromResources = resources_.getInteger(R.integer.strokeWidth);    
circleOptions.strokeWidth((float) strokeWidthFromResources/ 100);

and that makes it 3.56f

Not saying this is the most elegant solution but for simple projects, it's convenient.

using stored procedure in entity framework

Simple. Just instantiate your entity, set it to an object and pass it to your view in your controller.

enter image description here

Entity

VehicleInfoEntities db = new VehicleInfoEntities();

Stored Procedure

dbo.prcGetMakes()

or

you can add any parameters in your stored procedure inside the brackets ()

dbo.prcGetMakes("BMW")

Controller

public class HomeController : Controller
{
    VehicleInfoEntities db = new VehicleInfoEntities();

    public ActionResult Index()
    {
        var makes = db.prcGetMakes(null);

        return View(makes);
    }
}

Hide the browse button on a input type=file

HTML - InputFile component can be hide by writing some css. Here I am adding an icon which overrides inputfile component.

<label class="custom-file-upload">
    <InputFile OnChange="HandleFileSelected" />
    <i class="fa fa-cloud-upload"></i> Upload
</label>

css-

<style>
    input[type="file"] {
        display: none;
    }

    .custom-file-upload {
        border: 1px solid #ccc;
        display: inline-block;
        padding: 6px 12px;
        cursor: pointer;
    }
</style>

How do I dynamically change the content in an iframe using jquery?

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["http://webPage1.com", "http://webPage2.com"];
        var len = locations.length;
        var iframe = $('#frame');
        var i = 0;
        setInterval(function () {
            iframe.attr('src', locations[++i % len]);
        }, 30000);
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

Best C# API to create PDF

I used PdfSharp. It's free, open source and quite convenient to use, but I can't say whether it is the best or not, because I haven't really used anything else.

Drawing Circle with OpenGL

We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say base=X and Y=vertical. Now we can write X=hypotenuse*cos? and Y=hypotenuse*sin?. We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

What is a NullReferenceException, and how do I fix it?

NullReference Exception — Visual Basic

The NullReference Exception for Visual Basic is no different from the one in C#. After all, they are both reporting the same exception defined in the .NET Framework which they both use. Causes unique to Visual Basic are rare (perhaps only one).

This answer will use Visual Basic terms, syntax, and context. The examples used come from a large number of past Stack  Overflow questions. This is to maximize relevance by using the kinds of situations often seen in posts. A bit more explanation is also provided for those who might need it. An example similar to yours is very likely listed here.

Note:

  1. This is concept-based: there is no code for you to paste into your project. It is intended to help you understand what causes a NullReferenceException (NRE), how to find it, how to fix it, and how to avoid it. An NRE can be caused many ways so this is unlikely to be your sole encounter.
  2. The examples (from Stack  Overflow posts) do not always show the best way to do something in the first place.
  3. Typically, the simplest remedy is used.

Basic Meaning

The message "Object not set to an instance of Object" means you are trying to use an object which has not been initialized. This boils down to one of these:

  • Your code declared an object variable, but it did not initialize it (create an instance or 'instantiate' it)
  • Something which your code assumed would initialize an object, did not
  • Possibly, other code prematurely invalidated an object still in use

Finding The Cause

Since the problem is an object reference which is Nothing, the answer is to examine them to find out which one. Then determine why it is not initialized. Hold the mouse over the various variables and Visual Studio (VS) will show their values - the culprit will be Nothing.

IDE debug display

You should also remove any Try/Catch blocks from the relevant code, especially ones where there is nothing in the Catch block. This will cause your code to crash when it tries to use an object which is Nothing. This is what you want because it will identify the exact location of the problem, and allow you to identify the object causing it.

A MsgBox in the Catch which displays Error while... will be of little help. This method also leads to very bad Stack  Overflow questions, because you can't describe the actual exception, the object involved or even the line of code where it happens.

You can also use the Locals Window (Debug -> Windows -> Locals) to examine your objects.

Once you know what and where the problem is, it is usually fairly easy to fix and faster than posting a new question.

See also:

Examples and Remedies

Class Objects / Creating an Instance

Dim reg As CashRegister
...
TextBox1.Text = reg.Amount         ' NRE

The problem is that Dim does not create a CashRegister object; it only declares a variable named reg of that Type. Declaring an object variable and creating an instance are two different things.

Remedy

The New operator can often be used to create the instance when you declare it:

Dim reg As New CashRegister        ' [New] creates instance, invokes the constructor

' Longer, more explicit form:
Dim reg As CashRegister = New CashRegister

When it is only appropriate to create the instance later:

Private reg As CashRegister         ' Declare
  ...
reg = New CashRegister()            ' Create instance

Note: Do not use Dim again in a procedure, including the constructor (Sub New):

Private reg As CashRegister
'...

Public Sub New()
   '...
   Dim reg As New CashRegister
End Sub

This will create a local variable, reg, which exists only in that context (sub). The reg variable with module level Scope which you will use everywhere else remains Nothing.

Missing the New operator is the #1 cause of NullReference Exceptions seen in the Stack  Overflow questions reviewed.

Visual Basic tries to make the process clear repeatedly using New: Using the New Operator creates a new object and calls Sub New -- the constructor -- where your object can perform any other initialization.

To be clear, Dim (or Private) only declares a variable and its Type. The Scope of the variable - whether it exists for the entire module/class or is local to a procedure - is determined by where it is declared. Private | Friend | Public defines the access level, not Scope.

For more information, see:


Arrays

Arrays must also be instantiated:

Private arr as String()

This array has only been declared, not created. There are several ways to initialize an array:

Private arr as String() = New String(10){}
' or
Private arr() As String = New String(10){}

' For a local array (in a procedure) and using 'Option Infer':
Dim arr = New String(10) {}

Note: Beginning with VS 2010, when initializing a local array using a literal and Option Infer, the As <Type> and New elements are optional:

Dim myDbl As Double() = {1.5, 2, 9.9, 18, 3.14}
Dim myDbl = New Double() {1.5, 2, 9.9, 18, 3.14}
Dim myDbl() = {1.5, 2, 9.9, 18, 3.14}

The data Type and array size are inferred from the data being assigned. Class/Module level declarations still require As <Type> with Option Strict:

Private myDoubles As Double() = {1.5, 2, 9.9, 18, 3.14}

Example: Array of class objects

Dim arrFoo(5) As Foo

For i As Integer = 0 To arrFoo.Count - 1
   arrFoo(i).Bar = i * 10       ' Exception
Next

The array has been created, but the Foo objects in it have not.

Remedy

For i As Integer = 0 To arrFoo.Count - 1
    arrFoo(i) = New Foo()         ' Create Foo instance
    arrFoo(i).Bar = i * 10
Next

Using a List(Of T) will make it quite difficult to have an element without a valid object:

Dim FooList As New List(Of Foo)     ' List created, but it is empty
Dim f As Foo                        ' Temporary variable for the loop

For i As Integer = 0 To 5
    f = New Foo()                    ' Foo instance created
    f.Bar =  i * 10
    FooList.Add(f)                   ' Foo object added to list
Next

For more information, see:


Lists and Collections

.NET collections (of which there are many varieties - Lists, Dictionary, etc.) must also be instantiated or created.

Private myList As List(Of String)
..
myList.Add("ziggy")           ' NullReference

You get the same exception for the same reason - myList was only declared, but no instance created. The remedy is the same:

myList = New List(Of String)

' Or create an instance when declared:
Private myList As New List(Of String)

A common oversight is a class which uses a collection Type:

Public Class Foo
    Private barList As List(Of Bar)

    Friend Function BarCount As Integer
        Return barList.Count
    End Function

    Friend Sub AddItem(newBar As Bar)
        If barList.Contains(newBar) = False Then
            barList.Add(newBar)
        End If
    End Function

Either procedure will result in an NRE, because barList is only declared, not instantiated. Creating an instance of Foo will not also create an instance of the internal barList. It may have been the intent to do this in the constructor:

Public Sub New         ' Constructor
    ' Stuff to do when a new Foo is created...
    barList = New List(Of Bar)
End Sub

As before, this is incorrect:

Public Sub New()
    ' Creates another barList local to this procedure
     Dim barList As New List(Of Bar)
End Sub

For more information, see List(Of T) Class.


Data Provider Objects

Working with databases presents many opportunities for a NullReference because there can be many objects (Command, Connection, Transaction, Dataset, DataTable, DataRows....) in use at once. Note: It does not matter which data provider you are using -- MySQL, SQL Server, OleDB, etc. -- the concepts are the same.

Example 1

Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim MaxRows As Integer

con.Open()
Dim sql = "SELECT * FROM tblfoobar_List"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "foobar")
con.Close()

MaxRows = ds.Tables("foobar").Rows.Count      ' Error

As before, the ds Dataset object was declared, but an instance was never created. The DataAdapter will fill an existing DataSet, not create one. In this case, since ds is a local variable, the IDE warns you that this might happen:

img

When declared as a module/class level variable, as appears to be the case with con, the compiler can't know if the object was created by an upstream procedure. Do not ignore warnings.

Remedy

Dim ds As New DataSet

Example 2

ds = New DataSet
da = New OleDBDataAdapter(sql, con)
da.Fill(ds, "Employees")

txtID.Text = ds.Tables("Employee").Rows(0).Item(1)
txtID.Name = ds.Tables("Employee").Rows(0).Item(2)

A typo is a problem here: Employees vs Employee. There was no DataTable named "Employee" created, so a NullReferenceException results trying to access it. Another potential problem is assuming there will be Items which may not be so when the SQL includes a WHERE clause.

Remedy

Since this uses one table, using Tables(0) will avoid spelling errors. Examining Rows.Count can also help:

If ds.Tables(0).Rows.Count > 0 Then
    txtID.Text = ds.Tables(0).Rows(0).Item(1)
    txtID.Name = ds.Tables(0).Rows(0).Item(2)
End If

Fill is a function returning the number of Rows affected which can also be tested:

If da.Fill(ds, "Employees") > 0 Then...

Example 3

Dim da As New OleDb.OleDbDataAdapter("SELECT TICKET.TICKET_NO,
        TICKET.CUSTOMER_ID, ... FROM TICKET_RESERVATION AS TICKET INNER JOIN
        FLIGHT_DETAILS AS FLIGHT ... WHERE [TICKET.TICKET_NO]= ...", con)
Dim ds As New DataSet
da.Fill(ds)

If ds.Tables("TICKET_RESERVATION").Rows.Count > 0 Then

The DataAdapter will provide TableNames as shown in the previous example, but it does not parse names from the SQL or database table. As a result, ds.Tables("TICKET_RESERVATION") references a non-existent table.

The Remedy is the same, reference the table by index:

If ds.Tables(0).Rows.Count > 0 Then

See also DataTable Class.


Object Paths / Nested

If myFoo.Bar.Items IsNot Nothing Then
   ...

The code is only testing Items while both myFoo and Bar may also be Nothing. The remedy is to test the entire chain or path of objects one at a time:

If (myFoo IsNot Nothing) AndAlso
    (myFoo.Bar IsNot Nothing) AndAlso
    (myFoo.Bar.Items IsNot Nothing) Then
    ....

AndAlso is important. Subsequent tests will not be performed once the first False condition is encountered. This allows the code to safely 'drill' into the object(s) one 'level' at a time, evaluating myFoo.Bar only after (and if) myFoo is determined to be valid. Object chains or paths can get quite long when coding complex objects:

myBase.myNodes(3).Layer.SubLayer.Foo.Files.Add("somefilename")

It is not possible to reference anything 'downstream' of a null object. This also applies to controls:

myWebBrowser.Document.GetElementById("formfld1").InnerText = "some value"

Here, myWebBrowser or Document could be Nothing or the formfld1 element may not exist.


UI Controls

Dim cmd5 As New SqlCommand("select Cartons, Pieces, Foobar " _
     & "FROM Invoice where invoice_no = '" & _
     Me.ComboBox5.SelectedItem.ToString.Trim & "' And category = '" & _
     Me.ListBox1.SelectedItem.ToString.Trim & "' And item_name = '" & _
     Me.ComboBox2.SelectedValue.ToString.Trim & "' And expiry_date = '" & _
     Me.expiry.Text & "'", con)

Among other things, this code does not anticipate that the user may not have selected something in one or more UI controls. ListBox1.SelectedItem may well be Nothing, so ListBox1.SelectedItem.ToString will result in an NRE.

Remedy

Validate data before using it (also use Option Strict and SQL parameters):

Dim expiry As DateTime         ' for text date validation
If (ComboBox5.SelectedItems.Count > 0) AndAlso
    (ListBox1.SelectedItems.Count > 0) AndAlso
    (ComboBox2.SelectedItems.Count > 0) AndAlso
    (DateTime.TryParse(expiry.Text, expiry) Then

    '... do stuff
Else
    MessageBox.Show(...error message...)
End If

Alternatively, you can use (ComboBox5.SelectedItem IsNot Nothing) AndAlso...


Visual Basic Forms

Public Class Form1

    Private NameBoxes = New TextBox(5) {Controls("TextBox1"), _
                   Controls("TextBox2"), Controls("TextBox3"), _
                   Controls("TextBox4"), Controls("TextBox5"), _
                   Controls("TextBox6")}

    ' same thing in a different format:
    Private boxList As New List(Of TextBox) From {TextBox1, TextBox2, TextBox3 ...}

    ' Immediate NRE:
    Private somevar As String = Me.Controls("TextBox1").Text

This is a fairly common way to get an NRE. In C#, depending on how it is coded, the IDE will report that Controls does not exist in the current context, or "cannot reference non-static member". So, to some extent, this is a VB-only situation. It is also complex because it can result in a failure cascade.

The arrays and collections cannot be initialized this way. This initialization code will run before the constructor creates the Form or the Controls. As a result:

  • Lists and Collection will simply be empty
  • The Array will contain five elements of Nothing
  • The somevar assignment will result in an immediate NRE because Nothing doesn't have a .Text property

Referencing array elements later will result in an NRE. If you do this in Form_Load, due to an odd bug, the IDE may not report the exception when it happens. The exception will pop up later when your code tries to use the array. This "silent exception" is detailed in this post. For our purposes, the key is that when something catastrophic happens while creating a form (Sub New or Form Load event), exceptions may go unreported, the code exits the procedure and just displays the form.

Since no other code in your Sub New or Form Load event will run after the NRE, a great many other things can be left uninitialized.

Sub Form_Load(..._
   '...
   Dim name As String = NameBoxes(2).Text        ' NRE
   ' ...
   ' More code (which will likely not be executed)
   ' ...
End Sub

Note this applies to any and all control and component references making these illegal where they are:

Public Class Form1

    Private myFiles() As String = Me.OpenFileDialog1.FileName & ...
    Private dbcon As String = OpenFileDialog1.FileName & ";Jet Oledb..."
    Private studentName As String = TextBox13.Text

Partial Remedy

It is curious that VB does not provide a warning, but the remedy is to declare the containers at the form level, but initialize them in form load event handler when the controls do exist. This can be done in Sub New as long as your code is after the InitializeComponent call:

' Module level declaration
Private NameBoxes as TextBox()
Private studentName As String

' Form Load, Form Shown or Sub New:
'
' Using the OP's approach (illegal using OPTION STRICT)
NameBoxes = New TextBox() {Me.Controls("TextBox1"), Me.Controls("TestBox2"), ...)
studentName = TextBox32.Text           ' For simple control references

The array code may not be out of the woods yet. Any controls which are in a container control (like a GroupBox or Panel) will not be found in Me.Controls; they will be in the Controls collection of that Panel or GroupBox. Nor will a control be returned when the control name is misspelled ("TeStBox2"). In such cases, Nothing will again be stored in those array elements and an NRE will result when you attempt to reference it.

These should be easy to find now that you know what you are looking for: VS shows you the error of your ways

"Button2" resides on a Panel

Remedy

Rather than indirect references by name using the form's Controls collection, use the control reference:

' Declaration
Private NameBoxes As TextBox()

' Initialization -  simple and easy to read, hard to botch:
NameBoxes = New TextBox() {TextBox1, TextBox2, ...)

' Initialize a List
NamesList = New List(Of TextBox)({TextBox1, TextBox2, TextBox3...})
' or
NamesList = New List(Of TextBox)
NamesList.AddRange({TextBox1, TextBox2, TextBox3...})

Function Returning Nothing

Private bars As New List(Of Bars)        ' Declared and created

Public Function BarList() As List(Of Bars)
    bars.Clear
    If someCondition Then
        For n As Integer = 0 to someValue
            bars.Add(GetBar(n))
        Next n
    Else
        Exit Function
    End If

    Return bars
End Function

This is a case where the IDE will warn you that 'not all paths return a value and a NullReferenceException may result'. You can suppress the warning, by replacing Exit Function with Return Nothing, but that does not solve the problem. Anything which tries to use the return when someCondition = False will result in an NRE:

bList = myFoo.BarList()
For Each b As Bar in bList      ' EXCEPTION
      ...

Remedy

Replace Exit Function in the function with Return bList. Returning an empty List is not the same as returning Nothing. If there is a chance that a returned object can be Nothing, test before using it:

 bList = myFoo.BarList()
 If bList IsNot Nothing Then...

Poorly Implemented Try/Catch

A badly implemented Try/Catch can hide where the problem is and result in new ones:

Dim dr As SqlDataReader
Try
    Dim lnk As LinkButton = TryCast(sender, LinkButton)
    Dim gr As GridViewRow = DirectCast(lnk.NamingContainer, GridViewRow)
    Dim eid As String = GridView1.DataKeys(gr.RowIndex).Value.ToString()
    ViewState("username") = eid
    sqlQry = "select FirstName, Surname, DepartmentName, ExtensionName, jobTitle,
             Pager, mailaddress, from employees1 where username='" & eid & "'"
    If connection.State <> ConnectionState.Open Then
        connection.Open()
    End If
    command = New SqlCommand(sqlQry, connection)

    'More code fooing and barring

    dr = command.ExecuteReader()
    If dr.Read() Then
        lblFirstName.Text = Convert.ToString(dr("FirstName"))
        ...
    End If
    mpe.Show()
Catch

Finally
    command.Dispose()
    dr.Close()             ' <-- NRE
    connection.Close()
End Try

This is a case of an object not being created as expected, but also demonstrates the counter usefulness of an empty Catch.

There is an extra comma in the SQL (after 'mailaddress') which results in an exception at .ExecuteReader. After the Catch does nothing, Finally tries to perform clean up, but since you cannot Close a null DataReader object, a brand new NullReferenceException results.

An empty Catch block is the devil's playground. This OP was baffled why he was getting an NRE in the Finally block. In other situations, an empty Catch may result in something else much further downstream going haywire and cause you to spend time looking at the wrong things in the wrong place for the problem. (The "silent exception" described above provides the same entertainment value.)

Remedy

Don't use empty Try/Catch blocks - let the code crash so you can a) identify the cause b) identify the location and c) apply a proper remedy. Try/Catch blocks are not intended to hide exceptions from the person uniquely qualified to fix them - the developer.


DBNull is not the same as Nothing

For Each row As DataGridViewRow In dgvPlanning.Rows
    If Not IsDBNull(row.Cells(0).Value) Then
        ...

The IsDBNull function is used to test if a value equals System.DBNull: From MSDN:

The System.DBNull value indicates that the Object represents missing or non-existent data. DBNull is not the same as Nothing, which indicates that a variable has not yet been initialized.

Remedy

If row.Cells(0) IsNot Nothing Then ...

As before, you can test for Nothing, then for a specific value:

If (row.Cells(0) IsNot Nothing) AndAlso (IsDBNull(row.Cells(0).Value) = False) Then

Example 2

Dim getFoo = (From f In dbContext.FooBars
               Where f.something = something
               Select f).FirstOrDefault

If Not IsDBNull(getFoo) Then
    If IsDBNull(getFoo.user_id) Then
        txtFirst.Text = getFoo.first_name
    Else
       ...

FirstOrDefault returns the first item or the default value, which is Nothing for reference types and never DBNull:

If getFoo IsNot Nothing Then...

Controls

Dim chk As CheckBox

chk = CType(Me.Controls(chkName), CheckBox)
If chk.Checked Then
    Return chk
End If

If a CheckBox with chkName can't be found (or exists in a GroupBox), then chk will be Nothing and be attempting to reference any property will result in an exception.

Remedy

If (chk IsNot Nothing) AndAlso (chk.Checked) Then ...

The DataGridView

The DGV has a few quirks seen periodically:

dgvBooks.DataSource = loan.Books
dgvBooks.Columns("ISBN").Visible = True       ' NullReferenceException
dgvBooks.Columns("Title").DefaultCellStyle.Format = "C"
dgvBooks.Columns("Author").DefaultCellStyle.Format = "C"
dgvBooks.Columns("Price").DefaultCellStyle.Format = "C"

If dgvBooks has AutoGenerateColumns = True, it will create the columns, but it does not name them, so the above code fails when it references them by name.

Remedy

Name the columns manually, or reference by index:

dgvBooks.Columns(0).Visible = True

Example 2 — Beware of the NewRow

xlWorkSheet = xlWorkBook.Sheets("sheet1")

For i = 0 To myDGV.RowCount - 1
    For j = 0 To myDGV.ColumnCount - 1
        For k As Integer = 1 To myDGV.Columns.Count
            xlWorkSheet.Cells(1, k) = myDGV.Columns(k - 1).HeaderText
            xlWorkSheet.Cells(i + 2, j + 1) = myDGV(j, i).Value.ToString()
        Next
    Next
Next

When your DataGridView has AllowUserToAddRows as True (the default), the Cells in the blank/new row at the bottom will all contain Nothing. Most attempts to use the contents (for example, ToString) will result in an NRE.

Remedy

Use a For/Each loop and test the IsNewRow property to determine if it is that last row. This works whether AllowUserToAddRows is true or not:

For Each r As DataGridViewRow in myDGV.Rows
    If r.IsNewRow = False Then
         ' ok to use this row

If you do use a For n loop, modify the row count or use Exit For when IsNewRow is true.


My.Settings (StringCollection)

Under certain circumstances, trying to use an item from My.Settings which is a StringCollection can result in a NullReference the first time you use it. The solution is the same, but not as obvious. Consider:

My.Settings.FooBars.Add("ziggy")         ' foobars is a string collection

Since VB is managing Settings for you, it is reasonable to expect it to initialize the collection. It will, but only if you have previously added an initial entry to the collection (in the Settings editor). Since the collection is (apparently) initialized when an item is added, it remains Nothing when there are no items in the Settings editor to add.

Remedy

Initialize the settings collection in the form's Load event handler, if/when needed:

If My.Settings.FooBars Is Nothing Then
    My.Settings.FooBars = New System.Collections.Specialized.StringCollection
End If

Typically, the Settings collection will only need to be initialized the first time the application runs. An alternate remedy is to add an initial value to your collection in Project -> Settings | FooBars, save the project, then remove the fake value.


Key Points

You probably forgot the New operator.

or

Something yo

How to make blinking/flashing text with CSS 3

Use the alternate value for animation-direction (and you don't need to add any keframes this way).

alternate

The animation should reverse direction each cycle. When playing in reverse, the animation steps are performed backward. In addition, timing functions are also reversed; for example, an ease-in animation is replaced with an ease-out animation when played in reverse. The count to determinate if it is an even or an odd iteration starts at one.

CSS:

.waitingForConnection {
  animation: blinker 1.7s cubic-bezier(.5, 0, 1, 1) infinite alternate;  
}
@keyframes blinker { to { opacity: 0; } }

I've removed the from keyframe. If it's missing, it gets generated from the value you've set for the animated property (opacity in this case) on the element, or if you haven't set it (and you haven't in this case), from the default value (which is 1 for opacity).

And please don't use just the WebKit version. Add the unprefixed one after it as well. If you just want to write less code, use the shorthand.

_x000D_
_x000D_
.waitingForConnection {
  animation: blinker 1.7s cubic-bezier(.5, 0, 1, 1) infinite alternate;  
}
@keyframes blinker { to { opacity: 0; } }

.waitingForConnection2 {
  animation: blinker2 0.6s cubic-bezier(1, 0, 0, 1) infinite alternate;  
}
@keyframes blinker2 { to { opacity: 0; } }

.waitingForConnection3 {
  animation: blinker3 1s ease-in-out infinite alternate;  
}
@keyframes blinker3 { to { opacity: 0; } }
_x000D_
<div class="waitingForConnection">X</div>
<div class="waitingForConnection2">Y</div>
<div class="waitingForConnection3">Z</div>
_x000D_
_x000D_
_x000D_

Can one do a for each loop in java in reverse order?

All answers above only fulfill the requirement, either by wrapping another method or calling some foreign code outside;

Here is the solution copied from the Thinking in Java 4th edition, chapter 11.13.1 AdapterMethodIdiom;

Here is the code:

// The "Adapter Method" idiom allows you to use foreach
// with additional kinds of Iterables.
package holding;
import java.util.*;

@SuppressWarnings("serial")
class ReversibleArrayList<T> extends ArrayList<T> {
  public ReversibleArrayList(Collection<T> c) { super(c); }
  public Iterable<T> reversed() {
    return new Iterable<T>() {
      public Iterator<T> iterator() {
        return new Iterator<T>() {
          int current = size() - 1; //why this.size() or super.size() wrong?
          public boolean hasNext() { return current > -1; }
          public T next() { return get(current--); }
          public void remove() { // Not implemented
            throw new UnsupportedOperationException();
          }
        };
      }
    };
  }
}   

public class AdapterMethodIdiom {
  public static void main(String[] args) {
    ReversibleArrayList<String> ral =
      new ReversibleArrayList<String>(
        Arrays.asList("To be or not to be".split(" ")));
    // Grabs the ordinary iterator via iterator():
    for(String s : ral)
      System.out.print(s + " ");
    System.out.println();
    // Hand it the Iterable of your choice
    for(String s : ral.reversed())
      System.out.print(s + " ");
  }
} /* Output:
To be or not to be
be to not or be To
*///:~

How do I create a local database inside of Microsoft SQL Server 2014?

install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB

Python: OSError: [Errno 2] No such file or directory: ''

Have you noticed that you don't get the error if you run

python ./script.py

instead of

python script.py

This is because sys.argv[0] will read ./script.py in the former case, which gives os.path.dirname something to work with. When you don't specify a path, sys.argv[0] reads simply script.py, and os.path.dirname cannot determine a path.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

This error message can also be caused by SELinux. Check if SELinux is enabled with getenforce

You need to adjust SELinux to use your port and restart.

I.E.

semanage port -a -t http_port_t -p tcp 9080 2>/dev/null || semanage port -m -t http_port_t -p tcp 9080

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

apache and httpd running but I can't see my website

There are several possibilities.

  • firewall, iptables configuration
  • apache listen address / port

More information is needed about your configuration. What distro are you using? Can you connect via 127.0.0.1?

If the issue is with the firewall/iptables, you can add the following lines to /etc/sysconfig/iptables:

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

(Second line is only needed for https)

Make sure this is above any lines that would globally restrict access, like the following:

-A INPUT -j REJECT --reject-with icmp-host-prohibited

Tested on CentOS 6.3

And finally

service iptables restart

PHPExcel set border and format for all sheets in spreadsheet

To answer your extra question:

You can set which rows should be repeated on every page using:

$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);

Now, row 1, 2, 3, 4 and 5 will be repeated.

Regular Expression Match to test for a valid year

Building on @r92 answer, for years 1970-2019:

(19[789]\d|20[01]\d)

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

Does Python support short-circuiting?

Yep, both and and or operators short-circuit -- see the docs.

SQLite UPSERT / UPDATE OR INSERT

Q&A Style

Well, after researching and fighting with the problem for hours, I found out that there are two ways to accomplish this, depending on the structure of your table and if you have foreign keys restrictions activated to maintain integrity. I'd like to share this in a clean format to save some time to the people that may be in my situation.


Option 1: You can afford deleting the row

In other words, you don't have foreign key, or if you have them, your SQLite engine is configured so that there no are integrity exceptions. The way to go is INSERT OR REPLACE. If you are trying to insert/update a player whose ID already exists, the SQLite engine will delete that row and insert the data you are providing. Now the question comes: what to do to keep the old ID associated?

Let's say we want to UPSERT with the data user_name='steven' and age=32.

Look at this code:

INSERT INTO players (id, name, age)

VALUES (
    coalesce((select id from players where user_name='steven'),
             (select max(id) from drawings) + 1),
    32)

The trick is in coalesce. It returns the id of the user 'steven' if any, and otherwise, it returns a new fresh id.


Option 2: You cannot afford deleting the row

After monkeying around with the previous solution, I realized that in my case that could end up destroying data, since this ID works as a foreign key for other table. Besides, I created the table with the clause ON DELETE CASCADE, which would mean that it'd delete data silently. Dangerous.

So, I first thought of a IF clause, but SQLite only has CASE. And this CASE can't be used (or at least I did not manage it) to perform one UPDATE query if EXISTS(select id from players where user_name='steven'), and INSERT if it didn't. No go.

And then, finally I used the brute force, with success. The logic is, for each UPSERT that you want to perform, first execute a INSERT OR IGNORE to make sure there is a row with our user, and then execute an UPDATE query with exactly the same data you tried to insert.

Same data as before: user_name='steven' and age=32.

-- make sure it exists
INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32); 

-- make sure it has the right data
UPDATE players SET user_name='steven', age=32 WHERE user_name='steven'; 

And that's all!

EDIT

As Andy has commented, trying to insert first and then update may lead to firing triggers more often than expected. This is not in my opinion a data safety issue, but it is true that firing unnecessary events makes little sense. Therefore, a improved solution would be:

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

-- Make sure it exists
INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32); 

Color Tint UIButton Image

In Swift you can do that like so:

var exampleImage = UIImage(named: "ExampleImage.png")?.imageWithRenderingMode(.AlwaysTemplate)

Then in your viewDidLoad

exampleButtonOutlet.setImage(exampleImage, forState: UIControlState.Normal)

And to modify the color

exampleButtonOutlet.tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) //your color

EDIT Xcode 8 Now you can also just the rendering mode of the image in your .xcassets to Template Image and then you don't need to specifically declare it in the var exampleImage anymore

'NoneType' object is not subscriptable?

The [0] needs to be inside the ).

Incrementing a variable inside a Bash loop

USCOUNTER=$(grep -c "^US " "$FILE")

Replace words in the body text

I am new to Javascript and just started learning these skills. Please check if the below method is useful to replace the text.

<script>

    var txt=document.getElementById("demo").innerHTML;
    var pos = txt.replace(/Hello/g, "hi")
    document.getElementById("demo").innerHTML = pos;

</script>

PyCharm import external library

Update (2018-01-06): This answer is obsolete. Modern versions of PyCharm provide Paths via Settings ? Project Interpreter ? ? ? Show All ? Show paths button.


PyCharm Professional Edition has the Paths tab in Python Interpreters settings, but Community Edition apparently doesn't have it.

As a workaround, you can create a symlink for your imported library under your project's root.

For example:

myproject
    mypackage
        __init__.py
    third_party -> /some/other/directory/third_party

Android Studio - Failed to apply plugin [id 'com.android.application']

As in Accepted post, the problem solved with updating gradle to 4.4.1.

  1. Get Latest Gradle 4.4.1 from here
  2. Extract and put it in "C:\Program Files\Android\Android Studio\gradle"
  3. Then from android studio go to "File -> Settings -> Build, Excecution, Deployment -> Gradle", from Project-level settings: Select Use local gradle Distribution and give the above
    address(folder with name "gradle-4.4.1" in "C:\Program Files\ ...")
  4. Then make project.

enter image description here

My Problem solved this way.

Google Maps API v3: InfoWindow not sizing correctly

I was having the same issue, particularly noticeable when my <h2> element wrapped to a second line.

I applied a class to a <div> in the infoWindow, and changed the fonts to a generic system font (in my case, Helvetica) versus an @font-face web font which it had been using. Issue solved.

How can I create persistent cookies in ASP.NET?

As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true It is the main idea.

bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name, 
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
    if (isPersisted)
        authCookie.Expires = authTicket.Expiration;

HttpContext.Current.Response.Cookies.Add(authCookie);

jquery dialog save cancel button styling

I looked at the HTML generated by the UI Dialog. It renders buttons pane like this:

<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
     <button type="button" class="ui-state-default ui-corner-all">Delete all items in recycle bin</button>
     <button type="button" class="ui-state-default ui-corner-all different" style="border: 1px solid blue;">Cancel</button>
</div>

Adding a class to Cancel button should be easy.

$('.ui-dialog-buttonpane :last-child').css('background-color', '#ccc');

This will make the Cancel button little grey. You can style this button however you like.

Above code assumes that the Cancel button is the last button. The fool proof way to do it would be

$('.ui-dialog-buttonpane :button')
    .each(
        function()
        { 
            if($(this).text() == 'Cancel')
            {
                //Do your styling with 'this' object.
            }
        }
    );

jquery disable form submit on enter

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.which == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.

jQuery check if <input> exists and has a value

I would do something like this: $('input[value]').something . This finds all inputs that have value and operates something onto them.

How to "test" NoneType in python?

As pointed out by Aaron Hall's comment:

Since you can't subclass NoneType and since None is a singleton, isinstance should not be used to detect None - instead you should do as the accepted answer says, and use is None or is not None.


Original Answer:

The simplest way however, without the extra line in addition to cardamom's answer is probably:
isinstance(x, type(None))

So how can I question a variable that is a NoneType? I need to use if method

Using isinstance() does not require an is within the if-statement:

if isinstance(x, type(None)): 
    #do stuff

Additional information
You can also check for multiple types in one isinstance() statement as mentioned in the documentation. Just write the types as a tuple.

isinstance(x, (type(None), bytes))

What is the most efficient string concatenation method in python?

Probably "new f-strings in Python 3.6" is the most efficient way of concatenating strings.

Using %s

>>> timeit.timeit("""name = "Some"
... age = 100
... '%s is %s.' % (name, age)""", number = 10000)
0.0029734770068898797

Using .format

>>> timeit.timeit("""name = "Some"
... age = 100
... '{} is {}.'.format(name, age)""", number = 10000)
0.004015227983472869

Using f

>>> timeit.timeit("""name = "Some"
... age = 100
... f'{name} is {age}.'""", number = 10000)
0.0019175919878762215

Source: https://realpython.com/python-f-strings/

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

How to know Hive and Hadoop versions from command prompt?

If you are using hortonworks distro then using CLI you can get the version with the command:

hive --version

Example output

Numbering rows within groups in a data frame

Using the rowid() function in data.table:

> set.seed(100)  
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]  
> df$num <- data.table::rowid(df$cat)
> df
   cat        val num
4  aaa 0.05638315   1
2  aaa 0.25767250   2
1  aaa 0.30776611   3
5  aaa 0.46854928   4
3  aaa 0.55232243   5
10 bbb 0.17026205   1
8  bbb 0.37032054   2
6  bbb 0.48377074   3
9  bbb 0.54655860   4
7  bbb 0.81240262   5
13 ccc 0.28035384   1
14 ccc 0.39848790   2
11 ccc 0.62499648   3
15 ccc 0.76255108   4
12 ccc 0.88216552   5

Install python 2.6 in CentOS

You could also use the EPEL-repository, and then do sudo yum install python26 to install python 2.6

How can I loop through a C++ map of maps?

First solution is Use range_based for loop, like:

Note: When range_expression’s type is std::map then a range_declaration’s type is std::pair.

for ( range_declaration : range_expression )      
  //loop_statement

Code 1:

typedef std::map<std::string, std::map<std::string, std::string>> StringToStringMap;

StringToStringMap my_map;

for(const auto &pair1 : my_map) 
{
   // Type of pair1 is std::pair<std::string, std::map<std::string, std::string>>
   // pair1.first point to std::string (first key)
   // pair1.second point to std::map<std::string, std::string> (inner map)
   for(const auto &pair2 : pair1.second) 
   {
       // pair2.first is the second(inner) key
       // pair2.second is the value
   }
}

The Second Solution:

Code 2

typedef std::map<std::string, std::string> StringMap;
typedef std::map<std::string, StringMap> StringToStringMap;

StringToStringMap my_map;

for(StringToStringMap::iterator it1 = my_map.begin(); it1 != my_map.end(); it1++)
{
    // it1->first point to first key
    // it2->second point to inner map
    for(StringMap::iterator it2 = it1->second.begin(); it2 != it1->second.end(); it2++)
     {
        // it2->second point to value
        // it2->first point to second(inner) key 
     }
 }

'import' and 'export' may only appear at the top level

'import' and 'export' may only appear at the top level

This means that webpack is bundling the non-transpiled ES6 code, which is why these import/export statements are being found. babel-loader must therefore not be transpiling what you expect.

If you simply remove the include and exclude rules from its loader config, the default behavior of transpiling everything besides what's in node_modules will kick in. For some reason or another, the current rules are causing some/all files to be skipped.

module.exports = {
  entry: './src/entry.js',
  output: {
    filename: './public/js/app.js'
  },
  devtool: 'source-map',
  plugins: [
    new ExtractTextPlugin('./public/css/style.css')
  ],
  module: {
    preLoaders: [{
      test: /\.js$/, 
      exclude: /node_modules/,
      loader: 'jshint-loader'
    }],
    loaders: [{
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract(
        'style',
        'css!sass'
      ),
    },
    {
      test: /\.vue$/,
      loader: 'vue'
    },
    {
      test: /\.js$/,
      loader: 'babel-loader',
      query: {
        presets: ['es2015']
      }
    }]
  }
};

Convert Java object to XML string

A convenient option is to use javax.xml.bind.JAXB:

StringWriter sw = new StringWriter();
JAXB.marshal(customer, sw);
String xmlString = sw.toString();

The [reverse] process (unmarshal) would be:

Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);

No need to deal with checked exceptions in this approach.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

CentOS: Copy directory to another directory

As I understand, you want to recursively copy test directory into /home/server/ path...

This can be done as:

-cp -rf /home/server/folder/test/* /home/server/

Hope this helps

How to redirect both stdout and stderr to a file

The simplest syntax to redirect both is:

command &> logfile

If you want to append to the file instead of overwrite:

command &>> logfile

How to use apply a custom drawable to RadioButton?

full solution here:

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:id="@+id/radio0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:checked="true"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:layout_marginTop="20dp"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:layout_marginTop="20dp"
        android:text="RadioButton" />
</RadioGroup>

selector XML

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected"    android:state_checked="false"/>

 </selector>