Programs & Examples On #Collate

How to use the COLLATE in a JOIN in SQL Server?

As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p
  ON (p.vTreasuryId = f.RFC) COLLATE Database_Default 

Change collations of all columns of all tables in SQL Server

As I did not find a proper way I wrote a script to do it and I'm sharing it here for those who need it. The script runs through all user tables and collects the columns. If the column type is any char type then it tries to convert it to the given collation.

Columns has to be index and constraint free for this to work.

If someone still has a better solution to this please post it!

DECLARE @collate nvarchar(100);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'Latin1_General_CI_AS';

DECLARE local_table_cursor CURSOR FOR

SELECT [name]
FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1

OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @table

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE local_change_cursor CURSOR FOR

    SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
        , c.name column_name
        , t.Name data_type
        , c.max_length
        , c.column_id
    FROM sys.columns c
    JOIN sys.types t ON c.system_type_id = t.system_type_id
    LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
    LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id = OBJECT_ID(@table)
    ORDER BY c.column_id

    OPEN local_change_cursor
    FETCH NEXT FROM local_change_cursor
    INTO @row_id, @column_name, @data_type, @max_length, @column_id

    WHILE @@FETCH_STATUS = 0
    BEGIN

        IF (@max_length = -1) OR (@max_length > 4000) SET @max_length = 4000;

        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' + @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
            PRINT @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR: Some index or constraint rely on the column' + @column_name + '. No conversion possible.'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM local_change_cursor
        INTO @row_id, @column_name, @data_type, @max_length, @column_id

    END

    CLOSE local_change_cursor
    DEALLOCATE local_change_cursor

    FETCH NEXT FROM local_table_cursor
    INTO @table

END

CLOSE local_table_cursor
DEALLOCATE local_table_cursor

GO

How do I code my submit button go to an email address

You might use Form tag with action attribute to submit the mailto.

Here is an example:

<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" /> 
</form>

Import and Export Excel - What is the best library?

I've used Flexcel in the past and it was great. But this was more for programmatically creating and updating excel worksheets.

How to return a PNG image from Jersey REST service method to the browser

I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.

Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:

@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();
}

Add in exception handling, etc etc.

Using varchar(MAX) vs TEXT on SQL Server

You can't search a text field without converting it from text to varchar.

declare @table table (a text)
insert into @table values ('a')
insert into @table values ('a')
insert into @table values ('b')
insert into @table values ('c')
insert into @table values ('d')


select *
from @table
where a ='a'

This give an error:

The data types text and varchar are incompatible in the equal to operator.

Wheras this does not:

declare @table table (a varchar(max))

Interestingly, LIKE still works, i.e.

where a like '%a%'

How to manually send HTTP POST requests from Firefox or Chrome browser?

CURL is AWESOME to do what you want ! It's a simple but effective command line tool.

Rest implementation test commands :

curl -i -X GET http://rest-api.io/items
curl -i -X GET http://rest-api.io/items/5069b47aa892630aae059584
curl -i -X DELETE http://rest-api.io/items/5069b47aa892630aae059584
curl -i -X POST -H 'Content-Type: application/json' -d '{"name": "New item", "year": "2009"}' http://rest-api.io/items
curl -i -X PUT -H 'Content-Type: application/json' -d '{"name": "Updated item", "year": "2010"}' http://rest-api.io/items/5069b47aa892630aae059584

How do I find the time difference between two datetime objects in python?

New at Python 2.7 is the timedelta instance method .total_seconds(). From the Python docs, this is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6.

Reference: http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds

>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds

Best Timer for using in a Windows service

Both System.Timers.Timer and System.Threading.Timer will work for services.

The timers you want to avoid are System.Web.UI.Timer and System.Windows.Forms.Timer, which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building.

Use System.Timers.Timer like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer):

using System;
using System.Timers;

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        // Normally, the timer is declared at the class level,
        // so that it stays in scope as long as it is needed.
        // If the timer is declared in a long-running method,  
        // KeepAlive must be used to prevent the JIT compiler 
        // from allowing aggressive garbage collection to occur 
        // before the method ends. (See end of method.)
        //System.Timers.Timer aTimer;

        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

If you choose System.Threading.Timer, you can use as follows:

using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        AutoResetEvent autoEvent     = new AutoResetEvent(false);
        StatusChecker  statusChecker = new StatusChecker(10);

        // Create the delegate that invokes methods for the timer.
        TimerCallback timerDelegate = 
            new TimerCallback(statusChecker.CheckStatus);

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n", 
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = 
                new Timer(timerDelegate, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(5000, false);
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal Main.
            invokeCount  = 0;
            autoEvent.Set();
        }
    }
}

Both examples comes from the MSDN pages.

element not interactable exception in selenium web automation

Try setting an implicit wait of maybe 10 seconds.

gmail.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Or set an explicit wait. An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. In your case, it is the visibility of the password input field. (Thanks to ainlolcat's comment)

WebDriver gmail= new ChromeDriver();
gmail.get("https://www.gmail.co.in"); 
gmail.findElement(By.id("Email")).sendKeys("abcd");
gmail.findElement(By.id("next")).click();
WebDriverWait wait = new WebDriverWait(gmail, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
gmail.findElement(By.id("Passwd")).sendKeys("xyz");

Explanation: The reason selenium can't find the element is because the id of the password input field is initially Passwd-hidden. After you click on the "Next" button, Google first verifies the email address entered and then shows the password input field (by changing the id from Passwd-hidden to Passwd). So, when the password field is still hidden (i.e. Google is still verifying the email id), your webdriver starts searching for the password input field with id Passwd which is still hidden. And hence, an exception is thrown.

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

A weird thing I found was that the environment variable SYSTEMROOT must be set otherwise getaddrinfo() will fail on Windows 10.

How to use FormData in react-native?

Providing some other solution; we're also using react-native-image-picker; and the server side is using koa-multer; this set-up is working good:

ui

ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {}
      else if (response.error) {}
      else if (response.customButton) {}
      else {
        this.props.addPhoto({ // leads to handleAddPhoto()
          fileName: response.fileName,
          path: response.path,
          type: response.type,
          uri: response.uri,
          width: response.width,
          height: response.height,
        });
      }
    });

handleAddPhoto = (photo) => { // photo is the above object
    uploadImage({ // these 3 properties are required
      uri: photo.uri,
      type: photo.type,
      name: photo.fileName,
    }).then((data) => {
      // ...
    });
  }

client

export function uploadImage(file) { // so uri, type, name are required properties
  const formData = new FormData();
  formData.append('image', file);

  return fetch(`${imagePathPrefix}/upload`, { // give something like https://xx.yy.zz/upload/whatever
    method: 'POST',
    body: formData,
  }
  ).then(
    response => response.json()
  ).then(data => ({
    uri: data.uri,
    filename: data.filename,
  })
  ).catch(
    error => console.log('uploadImage error:', error)
  );
}

server

import multer from 'koa-multer';
import RouterBase from '../core/router-base';

const upload = multer({ dest: 'runtime/upload/' });

export default class FileUploadRouter extends RouterBase {
  setupRoutes({ router }) {
    router.post('/upload', upload.single('image'), async (ctx, next) => {
      const file = ctx.req.file;
      if (file != null) {
        ctx.body = {
          uri: file.filename,
          filename: file.originalname,
        };
      } else {
        ctx.body = {
          uri: '',
          filename: '',
        };
      }
    });
  }
}

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

That URI is for JSTL 1.0, but you're actually using JSTL 1.2 which uses URIs with an additional /jsp path (because JSTL, who invented EL expressions, was since version 1.1 integrated as part of JSP in order to share/reuse the EL logic in plain JSP too).

So, fix the taglib URI accordingly based on JSTL documentation:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Further you need to make absolutely sure that you do not throw multiple different versioned JSTL JAR files together into the runtime classpath. This is a pretty common mistake among Tomcat users. The problem with Tomcat is that it does not offer JSTL out the box and thus you have to manually install it. This is not necessary in normal Jakarta EE servers. See also What exactly is Java EE?

In your specific case, your pom.xml basically tells you that you have jstl-1.2.jar and standard-1.1.2.jar together. This is wrong. You're basically mixing JSTL 1.2 API+impl from Oracle with JSTL 1.1 impl from Apache. You should stick to only one JSTL implementation.

Installing JSTL on Tomcat 10+

In case you're already on Tomcat 10 or newer (the first Jakartified version, with jakarta.* package instead of javax.* package), use JSTL 2.0 via this sole dependency:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>2.0.0</version>
</dependency>

Non-Maven users can achieve the same by dropping the following two physical files in /WEB-INF/lib folder of the web application project (do absolutely not drop standard*.jar or any loose .tld files in there! remove them if necessary).

Installing JSTL on Tomcat 9-

In case you're not on Tomcat 10 yet, but still on Tomcat 9 or older, use JSTL 1.2 via this sole dependency:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>1.2.6</version>
</dependency>

Non-Maven users can achieve the same by dropping the following two physical files in /WEB-INF/lib folder of the web application project (do absolutely not drop standard*.jar or any loose .tld files in there! remove them if necessary).

Installing JSTL on normal JEE server

In case you're actually using a normal Jakarta EE server such as WildFly, Payara, etc instead of a barebones servletcontainer such as Tomcat, Jetty, etc, then you don't need to explicitly install JSTL at all. Normal Jakarta EE servers already provide JSTL out the box. In other words, you don't need to add JSTL to pom.xml nor to drop any JAR/TLD files in webapp. Solely the provided scoped Jakarta EE coordinate is sufficient:

<dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-api</artifactId>
    <version><!-- 9.0.0, 8.0.0, etc depending on your server --></version>
    <scope>provided</scope>
</dependency>

Make sure web.xml version is right

Further you should also make sure that your web.xml is declared conform at least Servlet 2.4 and thus not as Servlet 2.3 or older. Otherwise EL expressions inside JSTL tags would in turn fail to work. Pick the highest version matching your target container and make sure that you don't have a <!DOCTYPE> anywhere in your web.xml. Here's a Servlet 5.0 (Tomcat 10) compatible example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns="https://jakarta.ee/xml/ns/jakartaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
    version="5.0">

    <!-- Config here. -->

</web-app>

And here's a Servlet 4.0 (Tomcat 9) compatible example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">

    <!-- Config here. -->

</web-app>

See also:

Which type of folder structure should be used with Angular 2?

So after doing more investigating I ended up going with a slightly revised version of Method 3 (mgechev/angular2-seed).

I basically moved components to be a main level directory and then each feature will be inside of it.

Why is jquery's .ajax() method not sending my session cookie?

AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script.

This may be a Cross Domain Problem.

Maybe you tried to call a url from www.domain-a.com while your calling script was on www.domain-b.com (In other words: You made a Cross Domain Call in which case the browser won't sent any cookies to protect your privacy).

In this case your options are:

  • Write a small proxy which resides on domain-b and forwards your requests to domain-a. Your browser will allow you to call the proxy because it's on the same server as the calling script.
    This proxy then can be configured by you to accept a cookie name and value parameter which it can send to domain-a. But for this to work you need to know the cookie's name and value your server on domain-a wants for authentication.
  • If you're fetching JSON objects try to use a JSONP request instead. jQuery supports these. But you need to alter your service on domain-a so that it returns valid JSONP responds.

Glad if that helped even a little bit.

Where does this come from: -*- coding: utf-8 -*-

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file

How can I send large messages with Kafka (over 15MB)?

The idea is to have equal size of message being sent from Kafka Producer to Kafka Broker and then received by Kafka Consumer i.e.

Kafka producer --> Kafka Broker --> Kafka Consumer

Suppose if the requirement is to send 15MB of message, then the Producer, the Broker and the Consumer, all three, needs to be in sync.

Kafka Producer sends 15 MB --> Kafka Broker Allows/Stores 15 MB --> Kafka Consumer receives 15 MB

The setting therefore should be:

a) on Broker:

message.max.bytes=15728640 
replica.fetch.max.bytes=15728640

b) on Consumer:

fetch.message.max.bytes=15728640

How do I monitor the computer's CPU, memory, and disk usage in Java?

This works for me perfectly without any external API, just native Java hidden feature :)

import com.sun.management.OperatingSystemMXBean;
...
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
                OperatingSystemMXBean.class);
// What % CPU load this current JVM is taking, from 0.0-1.0
System.out.println(osBean.getProcessCpuLoad());

// What % load the overall system is at, from 0.0-1.0
System.out.println(osBean.getSystemCpuLoad());

How do I hide the PHP explode delimiter from submitted form results?

Instead of adding the line breaks with nl2br() and then removing the line breaks with explode(), try using the line break character '\r' or '\n' or '\r\n'.

<?php     $options= file_get_contents("employees.txt");     $options=explode("\n",$options);        // try \r as well.      foreach ($options as $singleOption){         echo "<option value='".$singleOption."'>".$singleOption."</option>";     }   ?> 

This could also fix the issue if the problem was due to Google Spreadsheets reading the line breaks.

How do I import a pre-existing Java project into Eclipse and get up and running?

This assumes Eclipse and an appropriate JDK are installed on your system

  1. Open Eclipse and create a new Workspace by specifying an empty directory.
  2. Make sure you're in the Java perspective by selecting Window -> Open Perspective ..., select Other... and then Java
  3. Right click anywhere in the Package Explorer pane and select New -> Java Project
  4. In the dialog that opens give the project a name and then click the option that says "Crate project from existing sources."
  5. In the text box below the option you selected in Step 4 point to the root directory where you checked out the project. This should be the directory that contains "com"
  6. Click Finish. For this particular project you don't need to do any additional setup for your classpath since it only depends on classes that are part of the Java SE API.

jQuery multiselect drop down menu

<select id="mycontrolId" multiple="multiple">
   <option value="1" >one</option>
   <option value="2" >two</option>
   <option value="3">three</option>
   <option value="4">four</option>
</select>

var data = "1,3,4"; var dataarray = data.split(",");

$("#mycontrolId").val(dataarray);

"cannot be used as a function error"

Your compiler is right. You can't use the growthRate variable you declared in main as a function.

Maybe you should pick different names for your variables so they don't override function names?

Given final block not properly padded

I met this issue due to operation system, simple to different platform about JRE implementation.

new SecureRandom(key.getBytes())

will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);

"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

Save text file UTF-8 encoded with VBA

I looked into the answer from Máta whose name hints at encoding qualifications and experience. The VBA docs say CreateTextFile(filename, [overwrite [, unicode]]) creates a file "as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it's created as an ASCII file. If omitted, an ASCII file is assumed." It's fine that a file stores unicode characters, but in what encoding? Unencoded unicode can't be represented in a file.

The VBA doc page for OpenTextFile(filename[, iomode[, create[, format]]]) offers a third option for the format:

  • TriStateDefault 2 "opens the file using the system default."
  • TriStateTrue 1 "opens the file as Unicode."
  • TriStateFalse 0 "opens the file as ASCII."

Máta passes -1 for this argument.

Judging from VB.NET documentation (not VBA but I think reflects realities about how underlying Windows OS represents unicode strings and echoes up into MS Office, I don't know) the system default is an encoding using 1 byte/unicode character using an ANSI code page for the locale. UnicodeEncoding is UTF-16. The docs also describe UTF-8 is also a "Unicode encoding," which makes sense to me. But I don't yet know how to specify UTF-8 for VBA output nor be confident that the data I write to disk with the OpenTextFile(,,,1) is UTF-16 encoded. Tamalek's post is helpful.

How do I disable form resizing for users?

I always use this:

// Lock form
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;

This way you can always resize the form from Designer without changing code.

Prepare for Segue in Swift

Change the segue identifier in the right panel in the section with an id. icon to match the string you used in your conditional.

How do I get a list of all the duplicate items using pandas in python?

With Pandas version 0.17, you can set 'keep = False' in the duplicated function to get all the duplicate items.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(['a','b','c','d','a','b'])

In [3]: df
Out[3]: 
       0
    0  a
    1  b
    2  c
    3  d
    4  a
    5  b

In [4]: df[df.duplicated(keep=False)]
Out[4]: 
       0
    0  a
    1  b
    4  a
    5  b

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

In my case, this error was caused by renaming my client machine. I used a new name longer than 13 characters (despite the warning), which resulted in the NETBIOS name being truncated and being different from the full machine name. Once I re-renamed the client to a shorter name, the error went away.

Writing .csv files from C++

Here is a STL-like class

File "csvfile.h"

#pragma once

#include <iostream>
#include <fstream>

class csvfile;

inline static csvfile& endrow(csvfile& file);
inline static csvfile& flush(csvfile& file);

class csvfile
{
    std::ofstream fs_;
    const std::string separator_;
public:
    csvfile(const std::string filename, const std::string separator = ";")
        : fs_()
        , separator_(separator)
    {
        fs_.exceptions(std::ios::failbit | std::ios::badbit);
        fs_.open(filename);
    }

    ~csvfile()
    {
        flush();
        fs_.close();
    }

    void flush()
    {
        fs_.flush();
    }

    void endrow()
    {
        fs_ << std::endl;
    }

    csvfile& operator << ( csvfile& (* val)(csvfile&))
    {
        return val(*this);
    }

    csvfile& operator << (const char * val)
    {
        fs_ << '"' << val << '"' << separator_;
        return *this;
    }

    csvfile& operator << (const std::string & val)
    {
        fs_ << '"' << val << '"' << separator_;
        return *this;
    }

    template<typename T>
    csvfile& operator << (const T& val)
    {
        fs_ << val << separator_;
        return *this;
    }
};


inline static csvfile& endrow(csvfile& file)
{
    file.endrow();
    return file;
}

inline static csvfile& flush(csvfile& file)
{
    file.flush();
    return file;
}

File "main.cpp"

#include "csvfile.h"

int main()
{
    try
    {
        csvfile csv("MyTable.csv"); // throws exceptions!
        // Header
        csv << "X" << "VALUE"        << endrow;
        // Data
        csv <<  1  << "String value" << endrow;
        csv <<  2  << 123            << endrow;
        csv <<  3  << 1.f            << endrow;
        csv <<  4  << 1.2            << endrow;
    }
    catch (const std::exception& ex)
    {
        std::cout << "Exception was thrown: " << e.what() << std::endl;
    }
    return 0;
}

Latest version here

Change URL and redirect using jQuery

tell you the true, I still don't get what you need, but

window.location(url);

should be

window.location = url;

a search on window.location reference will tell you that.

Force overwrite of local file with what's in origin repo?

I believe what you are looking for is "git restore".

The easiest way is to remove the file locally, and then execute the git restore command for that file:

$ rm file.txt
$ git restore file.txt 

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

Use

sudo pip install virtualenv

Apparently you will have powers of administrator when adding "sudo" before the line... just don't forget your password.

Check element CSS display with JavaScript

As sdleihssirhc says below, if the element's display is being inherited or being specified by a CSS rule, you'll need to get its computed style:

return window.getComputedStyle(element, null).display;

Elements have a style property that will tell you what you want, if the style was declared inline or with JavaScript:

console.log(document.getElementById('someIDThatExists').style.display);

will give you a string value.

CSS: Set Div height to 100% - Pixels

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Stash only one file out of multiple files that have changed with Git?

For SourceTree users, pick the uncommited file you want to stash and click on the top toolbar button:

enter image description here

Now stashes will be listed in the sidebar; you can apply them to the new checked out branch using right click.

Wait for a process to finish

On a system like OSX you might not have pgrep so you can try this appraoch, when looking for processes by name:

while ps axg | grep process_name$ > /dev/null; do sleep 1; done

The $ symbol at the end of the process name ensures that grep matches only process_name to the end of line in the ps output and not itself.

How do I run git log to see changes only for a specific branch?

For those using Magit, hit l and =m to toggle --no-merges and =pto toggle --first-parent.

Then either just hit l again to show commits from the current branch (with none of commits merged onto it) down to end of history, or, if you want the log to end where it was branched off from master, hit o and type master.. as your range:

enter image description here

How to simulate "Press any key to continue?"

You can use the getchar routine.

From the above link:

/* getchar example : typewriter */
#include <stdio.h>

int main ()
{
  char c;
  puts ("Enter text. Include a dot ('.') in a sentence to exit:");
  do {
    c=getchar();
    putchar (c);
  } while (c != '.');
  return 0;
}

Escape string Python for MySQL

install sqlescapy package:

pip install sqlescapy

then you can escape variables in you raw query

from sqlescapy import sqlescape

query = """
    SELECT * FROM "bar_table" WHERE id='%s'
""" % sqlescape(user_input)

Truncating all tables in a Postgres database

For removing the data and preserving the table-structures in pgAdmin you can do:

  • Right-click database -> backup, select "Schema only"
  • Drop the database
  • Create a new database and name it like the former
  • Right-click the new database -> restore -> select the backup, select "Schema only"

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

Storing Python dictionaries

If save to a JSON file, the best and easiest way of doing this is:

import json
with open("file.json", "wb") as f:
    f.write(json.dumps(dict).encode("utf-8"))

How can I detect if this dictionary key exists in C#?

Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you

using System;
using System.Collections.Generic;
using System.Collections;

namespace Main
{
    internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
    {
        internal new virtual void Add(TKey key, TValue value)
        {   
            if (!base.ContainsKey(key))
            {
                base.Add(key, value);
            }
        }
    }

    internal partial class List<T> : System.Collections.Generic.List<T>
    {
        internal new virtual void Add(T item)
        {
            if (!base.Contains(item))
            {
                base.Add(item);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1,"b");
            dic.Add(1,"a");
            dic.Add(2,"c");
            dic.Add(1, "b");
            dic.Add(1, "a");
            dic.Add(2, "c");

            string val = "";
            dic.TryGetValue(1, out val);

            Console.WriteLine(val);
            Console.WriteLine(dic.Count.ToString());


            List<string> lst = new List<string>();
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");

            Console.WriteLine(lst[2]);
            Console.WriteLine(lst.Count.ToString());
        }
    }
}

How to get an absolute file path in Python

if you are on a mac

import os
upload_folder = os.path.abspath("static/img/users")

this will give you a full path:

print(upload_folder)

will show the following path:

>>>/Users/myUsername/PycharmProjects/OBS/static/img/user

Making HTTP Requests using Chrome Developer tools

To GET requests with headers, use this format.

   fetch('http://example.com', {
      method: 'GET',
      headers: new Headers({
               'Content-Type': 'application/json',
               'someheader': 'headervalue'
               })
    })
    .then(res => res.json())
    .then(console.log)

Why does the order in which libraries are linked sometimes cause errors in GCC?

Link order certainly does matter, at least on some platforms. I have seen crashes for applications linked with libraries in wrong order (where wrong means A linked before B but B depends on A).

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

SQL how to make null values come last when sorting ascending

In Oracle, you can use NULLS FIRST or NULLS LAST: specifies that NULL values should be returned before / after non-NULL values:

ORDER BY { column-Name | [ ASC | DESC ] | [ NULLS FIRST | NULLS LAST ] }

For example:

ORDER BY date DESC NULLS LAST

Ref: http://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj13658.html

C++ convert string to hexadecimal and vice versa

You can try this. It's Working...

#include <algorithm>
#include <sstream>
#include <iostream>
#include <iterator>
#include <iomanip>

namespace {
   const std::string test="hello world";
}

int main() {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   std::copy(test.begin(), test.end(), std::ostream_iterator<unsigned int>(result, " "));
   std::cout << test << ":" << result.str() << std::endl;
}

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')

...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

Bash script plugin for Eclipse?

I tried ShellEd, but it wouldn't recognize any of my shell scripts, even when I restarted eclipse. I added the ksh interpreter and made it the default, but it made no diffence.

Finally, I closed the tab that was open and displaying a ksh file, then re-opened it. That made it work correctly. After having used it for a while, I can also recommend it.

Difficulty with ng-model, ng-repeat, and inputs

You get into a difficult situation when it is necessary to understand how scopes, ngRepeat and ngModel with NgModelController work. Also try to use 1.0.3 version. Your example will work a little differently.

You can simply use solution provided by jm-

But if you want to deal with the situation more deeply, you have to understand:

  • how AngularJS works;
  • scopes have a hierarchical structure;
  • ngRepeat creates new scope for every element;
  • ngRepeat build cache of items with additional information (hashKey); on each watch call for every new item (that is not in the cache) ngRepeat constructs new scope, DOM element, etc. More detailed description.
  • from 1.0.3 ngModelController rerenders inputs with actual model values.

How your example "Binding to each element directly" works for AngularJS 1.0.3:

  • you enter letter 'f' into input;
  • ngModelController changes model for item scope (names array is not changed) => name == 'Samf', names == ['Sam', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat replaces model value from item scope ('Samf') by value from unchanged names array ('Sam');
  • ngModelController rerenders input with actual model value ('Sam').

How your example "Indexing into the array" works:

  • you enter letter 'f' into input;
  • ngModelController changes item in names array => `names == ['Samf', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat can't find 'Samf' in cache;
  • ngRepeat creates new scope, adds new div element with new input (that is why the input field loses focus - old div with old input is replaced by new div with new input);
  • new values for new DOM elements are rendered.

Also, you can try to use AngularJS Batarang and see how changes $id of the scope of div with input in which you enter.

Python - Move and overwrite files and folders

If you also need to overwrite files with read only flag use this:

def copyDirTree(root_src_dir,root_dst_dir):
"""
Copy directory tree. Overwrites also read only files.
:param root_src_dir: source directory
:param root_dst_dir:  destination directory
"""
for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            try:
                os.remove(dst_file)
            except PermissionError as exc:
                os.chmod(dst_file, stat.S_IWUSR)
                os.remove(dst_file)

        shutil.copy(src_file, dst_dir)

Adding Lombok plugin to IntelliJ project

To install the plugin manually, try:

  1. Download Lombok zip file (ensure Lombok matches the IDE version).
  2. Select Preferences Plugins Install Plugins from Disk.

IntelliJ Plugin Preferences Dialog

Visual Studio Copy Project

If you want a copy, the fastest way of doing this would be to save the project. Then make a copy of the entire thing on the File System. Go back into Visual Studio and open the copy. From there, I would most likely recommend re-naming the project/solution so that you don't have two of the same name, but that is the fastest way to make a copy.

Padding characters in printf

Pure Bash, no external utilities

This demonstration does full justification, but you can just omit subtracting the length of the second string if you want ragged-right lines.

pad=$(printf '%0.1s' "-"{1..60})
padlength=40
string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
     printf '%s' "$string1"
     printf '%*.*s' 0 $((padlength - ${#string1} - ${#string2} )) "$pad"
     printf '%s\n' "$string2"
     string2=${string2:1}
done

Unfortunately, in that technique, the length of the pad string has to be hardcoded to be longer than the longest one you think you'll need, but the padlength can be a variable as shown. However, you can replace the first line with these three to be able to use a variable for the length of the pad:

padlimit=60
pad=$(printf '%*s' "$padlimit")
pad=${pad// /-}

So the pad (padlimit and padlength) could be based on terminal width ($COLUMNS) or computed from the length of the longest data string.

Output:

a--------------------------------bbbbbbb
aa--------------------------------bbbbbb
aaaa-------------------------------bbbbb
aaaaaaaa----------------------------bbbb

Without subtracting the length of the second string:

a---------------------------------------bbbbbbb
aa--------------------------------------bbbbbb
aaaa------------------------------------bbbbb
aaaaaaaa--------------------------------bbbb

The first line could instead be the equivalent (similar to sprintf):

printf -v pad '%0.1s' "-"{1..60}

or similarly for the more dynamic technique:

printf -v pad '%*s' "$padlimit"

You can do the printing all on one line if you prefer:

printf '%s%*.*s%s\n' "$string1" 0 $((padlength - ${#string1} - ${#string2} )) "$pad" "$string2"

spark submit add multiple jars in classpath

You can use --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') to include entire folder of Jars. So, spark-submit -- class com.yourClass \ --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') \ ...

Print in new line, java

/n and /r usage depends on the platform (Window, Mac, Linux) which you are using.
But there are some platform independent separators too:

  1. System.lineSeparator()
    
  2. System.getProperty("line.separator")
    

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

A common misunderstanding among starters is that they think that the call of a forward(), sendRedirect(), or sendError() would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    }
    forward(); // This is STILL invoked when someCondition is true!
}

This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit() of course). When the someCondition in above example is true and you're thus calling forward() after sendRedirect() or sendError() on the same request/response, then the chance is big that you will get the exception:

java.lang.IllegalStateException: Cannot forward after response has been committed

If the if statement calls a forward() and you're afterwards calling sendRedirect() or sendError(), then below exception will be thrown:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

To fix this, you need either to add a return; statement afterwards

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
        return;
    }
    forward();
}

... or to introduce an else block.

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    } else {
        forward();
    }
}

To naildown the root cause in your code, just search for any line which calls a forward(), sendRedirect() or sendError() without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.

In case of sendError(), if your sole purpose is to set the response status, use setStatus() instead.


Another probable cause is that the servlet writes to the response while a forward() will be called, or has been called in the very same method.

protected void doXxx() {
    out.write("some string");
    // ... 
    forward(); // Fail!
}

The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward() will fail the same way:

java.lang.IllegalStateException: Cannot forward after response has been committed

Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string") and then print it in JSP like so ${data}. See also our Servlets wiki page to learn how to use Servlets the right way.


Another probable cause is that the servlet writes a file download to the response after which e.g. a forward() is called.

protected void doXxx() {
    out.write(bytes);
    // ... 
    forward(); // Fail!
}

This is technically not possible. You need to remove the forward() call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page.


Yet another probable cause is that the forward(), sendRedirect() or sendError() methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>, a practice which was officially discouraged since 2001. For example:

<!DOCTYPE html>
<html lang="en">
    <head>
        ... 
    </head>
    <body>
        ...

        <% sendRedirect(); %>
        
        ...
    </body>
</html>

The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...") as soon as it's encountered. This is thus essentially the same problem as explained in previous section.

Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.


See also:


Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?

Java Round up Any Number

10 years later but that problem still caught me.

So this is the answer to those that are too late as me.

This does not work

int b = (int) Math.ceil(a / 100);

Cause the result a / 100 turns out to be an integer and it's rounded so Math.ceil can't do anything about it.

You have to avoid the rounded operation with this

int b = (int) Math.ceil((float) a / 100);

Now it works.

Matching a space in regex

In Perl the switch is \s (whitespace).

Unloading classes in java?

Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes.

As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance.

placeholder for select tag

According to Mozilla Dev Network, placeholder is not a valid attribute on a <select> input.

Instead, add an option with an empty value and the selected attribute, as shown below. The empty value attribute is mandatory to prevent the default behaviour which is to use the contents of the <option> as the <option>'s value.

<select>
    <option value="" selected>select your beverage</option>
    <option value="tea">Tea</option>
    <option value="coffee">Coffee</option>
    <option value="soda">Soda</option>
</select>

In modern browsers, adding the required attribute to the <select> element will not allow the user to submit the form which the element is part of if the selected option has an empty value.

If you want to style the default option inside the list (which appears when clicking the element), there's a limited number of CSS properties that are well-supported. color and background-color are the 2 safest bets, other CSS properties are likely to be ignored.

In my option the best way (in HTML5) to mark the default option is using the custom data-* attributes.1 Here's how to style the default option to be greyed out:

_x000D_
_x000D_
select option[data-default] {_x000D_
  color: #888;_x000D_
}
_x000D_
<select>_x000D_
  <option value="" selected data-default>select your beverage</option>_x000D_
  <option value="tea">Tea</option>_x000D_
  <option value="coffee">Coffee</option>_x000D_
  <option value="soda">Soda</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

However, this will only style the item inside the drop-down list, not the value displayed on the input. If you want to style that with CSS, target your <select> element directly. In that case, you can only change the style of the currently selected element at any time.2

If you wanted to make it slightly harder for the user to select the default item, you could set the display: none; CSS rule on the <option>, but remember that this will not prevent users from selecting it (using e.g. arrow keys/typing), this just makes it harder for them to do so.


1 This answer previously advised the use of a default attribute which is non-standard and has no meaning on its own.
2 It's technically possible to style the select itself based on the selected value using JavaScript, but that's outside the scope of this question. This answer, however, covers this method.

How do I load an HTML page in a <div> using JavaScript?

If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash

For ex : <iframe src="home.html" width="100" height="100"/>

Wrapping text inside input type="text" element HTML/CSS

That is the textarea's job - for multiline text input. The input won't do it; it wasn't designed to do it.

So use a textarea. Besides their visual differences, they are accessed via JavaScript the same way (use value property).

You can prevent newlines being entered via the input event and simply using a replace(/\n/g, '').

How to get equal width of input and select fields

Add this code in css:

 select, input[type="text"]{
      width:100%;
      box-sizing:border-box;
    }

Detach (move) subdirectory into separate Git repository

Check out git_split project at https://github.com/vangorra/git_split

Turn git directories into their very own repositories in their own location. No subtree funny business. This script will take an existing directory in your git repository and turn that directory into an independent repository of its own. Along the way, it will copy over the entire change history for the directory you provided.

./git_split.sh <src_repo> <src_branch> <relative_dir_path> <dest_repo>
        src_repo  - The source repo to pull from.
        src_branch - The branch of the source repo to pull from. (usually master)
        relative_dir_path   - Relative path of the directory in the source repo to split.
        dest_repo - The repo to push to.

How do I separate an integer into separate digits in an array in JavaScript?

Suppose,

let a = 123456

First we will convert it into string and then apply split to convert it into array of characters and then map over it to convert the array to integer.

let b = a.toString().split('').map(val=>parseInt(val))
console.log(b)

Deleting rows from parent and child tables

Two possible approaches.

  1. If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.

  2. Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?

      delete from child_table
          where parent_id in (
               select parent_id from parent_table
                    where updd_tms != (sysdate-30)
    

    -- now delete the parent table records

    delete from parent_table
    where updd_tms != (sysdate-30);
    

---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).

declare
    v_sqlcode number;
    PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
    for v_rec in (select parent_id, child id from child_table
                         where updd_tms != (sysdate-30) ) loop

    -- delete the children
    delete from child_table where child_id = v_rec.child_id;

    -- delete the parent. If we get foreign key violation, 
    -- stop this step and continue the loop
    begin
       delete from parent_table
          where parent_id = v_rec.parent_id;
    exception
       when foreign_key_violated
         then null;
    end;
 end loop;
end;
/

"Fatal error: Cannot redeclare <function>"

I don't like function_exists('fun_name') because it relies on the function name being turned into a string, plus, you have to name it twice. Could easily break with refactoring.

Declare your function as a lambda expression (I haven't seen this solution mentioned):

$generate_salt = function()
{
    ...
};

And use thusly:

$salt = $generate_salt();

Then, at re-execution of said PHP code, the function simply overwrites the previous declaration.

How to use class from other files in C# with visual studio?

Yeah, I just made the same 'noob' error and found this thread. I had in fact added the class to the solution and not to the project. So it looked like this:

Wrong and right description

Just adding this in the hope to be of help to someone.

What do I do when my program crashes with exception 0xc0000005 at address 0?

Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).

So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.

Bootstrap 3 panel header with buttons wrong position

I've found using an additional class on the .panel-heading helps.

<div class="panel-heading contains-buttons">
   <h3 class="panel-title">Panel Title</h3>
   <a class="btn btn-sm btn-success pull-right" href="something.html"><i class="fa fa-plus"></i> Create</a>
</div>

And then using this less code:

.panel-heading.contains-buttons {
    .clearfix;
    .panel-title {
        .pull-left;
        padding-top:5px;
    }
    .btn {
        .pull-right;
    }
}

How do I create a shortcut via command-line in Windows?

I would like to propose different solution which wasn't mentioned here which is using .URL files:

set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%

Notes:

  • By default .url files are intended to open web pages but they are working fine for any properly constructed URI
  • Microsoft Windows does not display the .url file extension even if "Hide extensions for known file types" option in Windows Explorer is disabled
  • IconFile and IconIndex are optional
  • For reference you can check An Unofficial Guide to the URL File Format of Edward Blake

How to take input in an array + PYTHON?

raw_input is your helper here. From documentation -

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So your code will basically look like this.

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...

Android - R cannot be resolved to a variable

I think I found another solution to this question.

Go to Project > Properties > Java Build Path > tab [Order and Export] > Tick Android Version Checkbox enter image description here Then if your workspace does not build automatically…

Properties again > Build Project enter image description here

How to save a BufferedImage as a File

The answer lies within the Java Documentation's Tutorial for Writing/Saving an Image.

The Image I/O class provides the following method for saving an image:

static boolean ImageIO.write(RenderedImage im, String formatName, File output)  throws IOException

The tutorial explains that

The BufferedImage class implements the RenderedImage interface.

so it's able to be used in the method.

For example,

try {
    BufferedImage bi = getMyImage();  // retrieve image
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    // handle exception
}

It's important to surround the write call with a try block because, as per the API, the method throws an IOException "if an error occurs during writing"

Also explained are the method's objective, parameters, returns, and throws, in more detail:

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

Parameters:

im - a RenderedImage to be written.

formatName - a String containg the informal name of the format.

output - a File to be written to.

Returns:

false if no appropriate writer is found.

Throws:

IllegalArgumentException - if any parameter is null.

IOException - if an error occurs during writing.

However, formatName may still seem rather vague and ambiguous; the tutorial clears it up a bit:

The ImageIO.write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.

But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.

For most applications it is sufficient to use one of these standard plugins. They have the advantage of being readily available.

There are, however, additional formats you can use:

The Image I/O class provides a way to plug in support for additional formats which can be used, and many such plug-ins exist. If you are interested in what file formats are available to load or save in your system, you may use the getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These methods return an array of strings listing all of the formats supported in this JRE.

String writerNames[] = ImageIO.getWriterFormatNames();

The returned array of names will include any additional plug-ins that are installed and any of these names may be used as a format name to select an image writer.

For a full and practical example, one can refer to Oracle's SaveImage.java example.

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

I had a problem with this. I didn't use any clever $MyInvocation stuff to fix it though. If you open the ISE by right clicking a script file and selecting edit then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax. My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts. When I invoke one script from another in normal use I just use .\script.ps1, IMO it's wrong to modify the script just to make it work in the ISE properly...

What is an unhandled promise rejection?

In my case was Promise with no reject neither resolve, because my Promise function threw an exception. This mistake cause UnhandledPromiseRejectionWarning message.

How to change the blue highlight color of a UITableViewCell?

I have to set the selection style to UITableViewCellSelectionStyleDefault for custom background color to work. If any other style, the custom background color will be ignored. Tested on iOS 8.

The full code for the cell as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // This is how you change the background color
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor redColor];
    [cell setSelectedBackgroundView:bgColorView];

    return cell;
}

How do you setLayoutParams() for an ImageView?

Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

Remove last character from string. Swift language

Use the function removeAtIndex(i: String.Index) -> Character:

var s = "abc"    
s.removeAtIndex(s.endIndex.predecessor())  // "ab"

Numpy where function multiple conditions

The best way in your particular case would just be to change your two criteria to one criterion:

dists[abs(dists - r - dr/2.) <= dr/2.]

It only creates one boolean array, and in my opinion is easier to read because it says, is dist within a dr or r? (Though I'd redefine r to be the center of your region of interest instead of the beginning, so r = r + dr/2.) But that doesn't answer your question.


The answer to your question:
You don't actually need where if you're just trying to filter out the elements of dists that don't fit your criteria:

dists[(dists >= r) & (dists <= r+dr)]

Because the & will give you an elementwise and (the parentheses are necessary).

Or, if you do want to use where for some reason, you can do:

 dists[(np.where((dists >= r) & (dists <= r + dr)))]

Why:
The reason it doesn't work is because np.where returns a list of indices, not a boolean array. You're trying to get and between two lists of numbers, which of course doesn't have the True/False values that you expect. If a and b are both True values, then a and b returns b. So saying something like [0,1,2] and [2,3,4] will just give you [2,3,4]. Here it is in action:

In [230]: dists = np.arange(0,10,.5)
In [231]: r = 5
In [232]: dr = 1

In [233]: np.where(dists >= r)
Out[233]: (array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),)

In [234]: np.where(dists <= r+dr)
Out[234]: (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]),)

In [235]: np.where(dists >= r) and np.where(dists <= r+dr)
Out[235]: (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]),)

What you were expecting to compare was simply the boolean array, for example

In [236]: dists >= r
Out[236]: 
array([False, False, False, False, False, False, False, False, False,
       False,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True], dtype=bool)

In [237]: dists <= r + dr
Out[237]: 
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True, False, False, False, False, False,
       False, False], dtype=bool)

In [238]: (dists >= r) & (dists <= r + dr)
Out[238]: 
array([False, False, False, False, False, False, False, False, False,
       False,  True,  True,  True, False, False, False, False, False,
       False, False], dtype=bool)

Now you can call np.where on the combined boolean array:

In [239]: np.where((dists >= r) & (dists <= r + dr))
Out[239]: (array([10, 11, 12]),)

In [240]: dists[np.where((dists >= r) & (dists <= r + dr))]
Out[240]: array([ 5. ,  5.5,  6. ])

Or simply index the original array with the boolean array using fancy indexing

In [241]: dists[(dists >= r) & (dists <= r + dr)]
Out[241]: array([ 5. ,  5.5,  6. ])

How to determine the content size of a UIWebView?

None of the suggestions here helped me with my situation, but I read something that did give me an answer. I have a ViewController with a fixed set of UI controls followed by a UIWebView. I wanted the entire page to scroll as though the UI controls were connected to the HTML content, so I disable scrolling on the UIWebView and must then set the content size of a parent scroll view correctly.

The important tip turned out to be that UIWebView does not report its size correctly until rendered to the screen. So when I load the content I set the content size to the available screen height. Then, in viewDidAppear I update the scrollview's content size to the correct value. This worked for me because I am calling loadHTMLString on local content. If you are using loadRequest you may need to update the contentSize in webViewDidFinishLoad also, depending on how quickly the html is retrieved.

There is no flickering, because only the invisible part of the scroll view is changed.

Programmatically getting the MAC of an Android device

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

public String getMacAddress(Context context) {
    WifiManager wimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    String macAddress = wimanager.getConnectionInfo().getMacAddress();
    if (macAddress == null) {
        macAddress = "Device don't have mac address or wi-fi is disabled";
    }
    return macAddress;
}

have others way here

Relative paths based on file location instead of current working directory

Just one line will be OK.

cat "`dirname $0`"/../some.txt

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

The above options works for Google big query file also. I exported a table data to goodle cloud storage and downloaded from there. While loading the same to sql server was facing this issue and could successfully load the file after specifying the row delimiter as

ROWTERMINATOR = '0x0a' 

Pay attention to header record as well and specify

FIRSTROW = 2

My final block for data file export from google bigquery looks like this.

BULK INSERT TABLENAME
        FROM 'C:\ETL\Data\BigQuery\In\FILENAME.csv'
        WITH
        (
         FIRSTROW = 2,
         FIELDTERMINATOR = ',',  --CSV field delimiter
         ROWTERMINATOR = '0x0a',--Files are generated with this row terminator in Google Bigquery
         TABLOCK
        )

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

What is the difference between readonly="true" & readonly="readonly"?

I'm not sure how they're functionally different. My current batch of OS X browsers don't show any difference.

I would assume they are all functionally the same due to legacy HTML attribute handling. Back in the day, any flag (Boolean) attribute need only be present, sans value, eg

<input readonly>
<option selected>

When XHTML came along, this syntax wasn't valid and values were required. Whilst the W3 specified using the attribute name as the value, I'm guessing most browser vendors decided to simply check for attribute existence.

The connection to adb is down, and a severe error has occurred

Judging from what you've posted, and assuming it's not a typo, Eclipse is looking in C:\s\platform-tools...

If that's the case, then you should check Eclipse's Window/Preferences/Android option for the SDK Location. Maybe yours is set to "C:\s". You can't edit it to be a value such as that without causing an error, but maybe it's got corrupted somehow.

arranging div one below the other

Set the main div CSS to somthing like:

<style>
    .wrapper{
        display:flex;
        flex-direction: column;
    }
</style>

<div id="wrapper">
        <div id="inner1">This is inner div 1</div>
        <div id="inner2">This is inner div 2</div>
</div>

For more flexbox CSS refer: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Twitter Bootstrap and ASP.NET GridView

Add property of show header in gridview

 <asp:GridView ID="dgvUsers" runat="server" **showHeader="True"** CssClass="table table-hover table-striped" GridLines="None" 
AutoGenerateColumns="False">

and in columns add header template

<HeaderTemplate>
                   //header column names
</HeaderTemplate>

C# Clear all items in ListView

My guess is that Clear() causes a Changed event to be sent, which in turn triggers an automatic update of your listview from the data source. So this is a feature, not a bug ;-)

Have you tried myListView.Clear() instead of myListView.Items.Clear()? Maybe that works better.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

Android; Check if file exists without creating a new one

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

 File file = new File("FileName");
 if(file.exists()){
 System.out.println("file is already there");
 }else{
 System.out.println("Not find file ");
 }

JavaScript checking for null vs. undefined and difference between == and ===

How do I check a variable if it's null or undefined...

Is the variable null:

if (a === null)
// or
if (a == null) // but see note below

...but note the latter will also be true if a is undefined.

Is it undefined:

if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below

...but again, note that the last one is vague; it will also be true if a is null.

Now, despite the above, the usual way to check for those is to use the fact that they're falsey:

if (!a) {
    // `a` is falsey, which includes `undefined` and `null`
    // (and `""`, and `0`, and `NaN`, and [of course] `false`)
}

This is defined by ToBoolean in the spec.

...and what is the difference between the null and undefined?

They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)

null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).

Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.

What is the difference between "==" and "==="

The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.

Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).

More in the spec:

What's the best way to join on the same table twice?

The first is good unless either Phone1 or (more likely) phone2 can be null. In that case you want to use a Left join instead of an inner join.

It is usually a bad sign when you have a table with two phone number fields. Usually this means your database design is flawed.

Stop Excel from automatically converting certain text values to dates

I know this is an old thread. For the ones like me, who still have this problem using Office 2013 via PowerShell COM object can use the opentext method. The problem is that this method has many arguments, that are sometimes mutual exclusive. To resolve this issue you can use the invoke-namedparameter method introduced in this post. An example would be

$ex = New-Object -com "Excel.Application"
$ex.visible = $true
$csv = "path\to\your\csv.csv"
Invoke-NamedParameter ($ex.workbooks) "opentext" @{"filename"=$csv; "Semicolon"= $true}

Unfortunately I just discovered that this method somehow breaks the CSV parsing when cells contain line breaks. This is supported by CSV but Microsoft's implementation seems to be bugged. Also it did somehow not detect German-specific chars. Giving it the correct culture did not change this behaviour. All files (CSV and script) are saved with utf8 encoding. First I wrote the following code to insert the CSV cell by cell.

$ex = New-Object -com "Excel.Application"
$ex.visible = $true;
$csv = "path\to\your\csv.csv";
$ex.workbooks.add();
$ex.activeWorkbook.activeSheet.Cells.NumberFormat = "@";
$data = import-csv $csv -encoding utf8 -delimiter ";"; 
$row = 1; 
$data | %{ $obj = $_; $col = 1; $_.psobject.properties.Name |%{if($row -eq1){$ex.ActiveWorkbook.activeSheet.Cells.item($row,$col).Value2= $_ };$ex.ActiveWorkbook.activeSheet.Cells.item($row+1,$col).Value2 =$obj.$_; $col++ }; $row++;}

But this is extremely slow, which is why I looked for an alternative. Apparently, Excel allows you to set the values of a range of cells with a matrix. So I used the algorithm in this blog to transform the CSV in a multiarray.

function csvToExcel($csv,$delimiter){
     $a = New-Object -com "Excel.Application"
     $a.visible = $true
     
    $a.workbooks.add()
     $a.activeWorkbook.activeSheet.Cells.NumberFormat = "@"
     $data = import-csv -delimiter $delimiter $csv; 
     $array = ($data |ConvertTo-MultiArray).Value
     $starta = [int][char]'a' - 1
     if ($array.GetLength(1) -gt 26) {
         $col = [char]([int][math]::Floor($array.GetLength(1)/26) + $starta) + [char](($array.GetLength(1)%26) + $Starta)
     } else {
         $col = [char]($array.GetLength(1) + $starta)
     }
     $range = $a.activeWorkbook.activeSheet.Range("a1:"+$col+""+$array.GetLength(0))
     $range.value2 = $array;
     $range.Columns.AutoFit();
     $range.Rows.AutoFit();
     $range.Cells.HorizontalAlignment = -4131
     $range.Cells.VerticalAlignment = -4160
}

 function ConvertTo-MultiArray {
     param(
         [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
         [PSObject[]]$InputObject
     )
     BEGIN {
         $objects = @()
         [ref]$array = [ref]$null
     }
     Process {
         $objects += $InputObject
     }
     END {
         $properties = $objects[0].psobject.properties |%{$_.name}
         $array.Value = New-Object 'object[,]' ($objects.Count+1),$properties.count
         # i = row and j = column
         $j = 0
         $properties |%{
             $array.Value[0,$j] = $_.tostring()
             $j++
         }
         $i = 1
         $objects |% {
             $item = $_
             $j = 0
             $properties | % {
                 if ($item.($_) -eq $null) {
                     $array.value[$i,$j] = ""
                 }
                 else {
                     $array.value[$i,$j] = $item.($_).tostring()
                 }
                 $j++
             }
             $i++
         }
         $array
     } 
} 
csvToExcel "storage_stats.csv" ";"

You can use above code as is; it should convert any CSV into Excel. Just change the path to the CSV and the delimiter character at the bottom.

Throwing multiple exceptions in a method of an interface in java

You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.

public interface MyInterface {
  public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}

Django {% with %} tags within {% if %} {% else %} tags?

if you want to stay DRY, use an include.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

Then in the template:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

Get folder up one level

Also you can use dirname(__DIR__, $level) for access any folding level without traversing

Redirect stdout to a file in Python?

There is contextlib.redirect_stdout() function in Python 3.4+:

from contextlib import redirect_stdout

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        print('it now prints to `help.text`')

It is similar to:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout(new_target):
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value

that can be used on earlier Python versions. The latter version is not reusable. It can be made one if desired.

It doesn't redirect the stdout at the file descriptors level e.g.:

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, redirect_stdout(f):
    print('redirected to a file')
    os.write(stdout_fd, b'not redirected')
    os.system('echo this also is not redirected')

b'not redirected' and 'echo this also is not redirected' are not redirected to the output.txt file.

To redirect at the file descriptor level, os.dup2() could be used:

import os
import sys
from contextlib import contextmanager

def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd

@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    #NOTE: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied: 
        stdout.flush()  # flush library buffers that dup2 knows nothing about
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            #NOTE: dup2 makes stdout_fd inheritable unconditionally
            stdout.flush()
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

The same example works now if stdout_redirected() is used instead of redirect_stdout():

import os
import sys

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, stdout_redirected(f):
    print('redirected to a file')
    os.write(stdout_fd, b'it is redirected now\n')
    os.system('echo this is also redirected')
print('this is goes back to stdout')

The output that previously was printed on stdout now goes to output.txt as long as stdout_redirected() context manager is active.

Note: stdout.flush() does not flush C stdio buffers on Python 3 where I/O is implemented directly on read()/write() system calls. To flush all open C stdio output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O:

try:
    import ctypes
    from ctypes.util import find_library
except ImportError:
    libc = None
else:
    try:
        libc = ctypes.cdll.msvcrt # Windows
    except OSError:
        libc = ctypes.cdll.LoadLibrary(find_library('c'))

def flush(stream):
    try:
        libc.fflush(None)
        stream.flush()
    except (AttributeError, ValueError, IOError):
        pass # unsupported

You could use stdout parameter to redirect other streams, not only sys.stdout e.g., to merge sys.stderr and sys.stdout:

def merged_stderr_stdout():  # $ exec 2>&1
    return stdout_redirected(to=sys.stdout, stdout=sys.stderr)

Example:

from __future__ import print_function
import sys

with merged_stderr_stdout():
     print('this is printed on stdout')
     print('this is also printed on stdout', file=sys.stderr)

Note: stdout_redirected() mixes buffered I/O (sys.stdout usually) and unbuffered I/O (operations on file descriptors directly). Beware, there could be buffering issues.

To answer, your edit: you could use python-daemon to daemonize your script and use logging module (as @erikb85 suggested) instead of print statements and merely redirecting stdout for your long-running Python script that you run using nohup now.

How do I change the hover over color for a hover over table in Bootstrap?

This is for bootstrap v4 compiled via grunt or some other task runner

You would need to change $table-hover-bg to set the highlight on hover

$table-cell-padding:            .75rem !default;
$table-sm-cell-padding:         .3rem !default;

$table-bg:                      transparent !default;
$table-accent-bg:               rgba(0,0,0,.05) !default;
$table-hover-bg:                rgba(0,0,0,.075) !default;
$table-active-bg:               $table-hover-bg !default;

$table-border-width:            $border-width !default;
$table-border-color:            $gray-lighter !default;

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

orphanRemoval has nothing to do with ON DELETE CASCADE.

orphanRemoval is an entirely ORM-specific thing. It marks "child" entity to be removed when it's no longer referenced from the "parent" entity, e.g. when you remove the child entity from the corresponding collection of the parent entity.

ON DELETE CASCADE is a database-specific thing, it deletes the "child" row in the database when the "parent" row is deleted.

Where to put the gradle.properties file

Actually there are 3 places where gradle.properties can be placed:

  1. Under gradle user home directory defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle
  2. The sub-project directory (myProject2 in your case)
  3. The root project directory (under myProject)

Gradle looks for gradle.properties in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).

You can find more details about it in gradle documentation here.

How do you clear a stringstream variable?

You can clear the error state and empty the stringstream all in one line

std::stringstream().swap(m); // swap m with a default constructed stringstream

This effectively resets m to a default constructed state

How can I disable ReSharper in Visual Studio and enable it again?

If you want to do it without clicking too much, open the Command Window (Ctrl + W, A) and type:

ReSharper_Suspend or ReSharper_Resume depending on what you want.

Or you can even set a keyboard shortcut for this purpose. In Visual Studio, go to Tools -> Options -> Environment -> Keyboard.

There you can assign a keyboard shortcut to ReSharper_Suspend and ReSharper_Resume.

The Command Window can also be opened with Ctrl + Alt + A, just in case you're in the editor.

Enter image description here

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

How to correctly represent a whitespace character

Which whitespace character? The most common is the normal space, which is between each word in my sentences. This is just " ".

Char Comparison in C

In C the char type has a numeric value so the > operator will work just fine for example

#include <stdio.h>
main() {

    char a='z';

    char b='h';

    if ( a > b ) {
        printf("%c greater than %c\n",a,b);
    }
}

Call external javascript functions from java code

Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js

jsfunctions.js

var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}

Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
  engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
  Invocable invocable = (Invocable) engine;
  Object result;
  result = invocable.invokeFunction("display", helloWorld);
  System.out.println(result);
  System.out.println(result.getClass());
  } catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
    e.printStackTrace();
    }
  }
}

Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.

Fetch: POST json data

you can use fill-fetch, which is an extension of fetch. Simply, you can post data as below:

import { fill } from 'fill-fetch';

const fetcher = fill();

fetcher.config.timeout = 3000;
fetcher.config.maxConcurrence = 10;
fetcher.config.baseURL = 'http://www.github.com';

const res = await fetcher.post('/', { a: 1 }, {
    headers: {
        'bearer': '1234'
    }
});

What is the difference between rb and r+b modes in file objects

r opens for reading, whereas r+ opens for reading and writing. The b is for binary.

This is spelled out in the documentation:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

What does cmd /C mean?

CMD.exe

Start a new CMD shell

Syntax
      CMD [charset] [options] [My_Command] 

Options       

**/C     Carries out My_Command and then
terminates**

From the help.

What is the main purpose of setTag() getTag() methods of View?

Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.

Reference: http://developer.android.com/reference/android/view/View.html

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here

How to use java.net.URLConnection to fire and handle HTTP requests?

Inspired by this and other questions on SO, I've created a minimal open source basic-http-client that embodies most of the techniques found here.

google-http-java-client is also a great open source resource.

How can I simulate an array variable in MySQL?

DELIMITER $$
CREATE DEFINER=`mysqldb`@`%` PROCEDURE `abc`()
BEGIN
  BEGIN 
    set @value :='11,2,3,1,'; 
    WHILE (LOCATE(',', @value) > 0) DO
      SET @V_DESIGNATION = SUBSTRING(@value,1, LOCATE(',',@value)-1); 
      SET @value = SUBSTRING(@value, LOCATE(',',@value) + 1); 
      select @V_DESIGNATION;
    END WHILE;
  END;
END$$
DELIMITER ;

How to run composer from anywhere?

Some of this may be due to the OS your server is running. I recently did a migration to a new hosting environment running Ubuntu. Adding this alias alias composer="/path/to/your/composer" to .bashrc or .bash_aliases didn't work at first because of two reasons:

The server was running csh, not bash, by default. To check if this is an issue in your case, run echo $0. If the what is returned is -csh you will want to change it to bash, since some processes run by Composer will fail using csh/tcsh.

To change it, first check if bash is available on your server by running cat /etc/shells. If, in the list returned, you see bin/bash, you can change the default to bash by running chsh -s /bin/csh.

Now, at this point, you should be able to run Composer, but normally, on Ubuntu, you will have to load the script at every session by sourcing your Bash scripts by running source ~/.bashrc or source ~/.bash_profile. This is because, in most cases, Ubuntu won't load your Bash script, since it loads .profile as the default script.

To load your Bash scripts when you open a session, try adding this to your .profile (this is if your Bash script is .bashrc—modify accordingly if .bash_profile or other):

if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

To test, close your session and reload. If it's working properly, running composer -v or which composer should behave as expected.

Is it possible to set a number to NaN or infinity?

When using Python 2.4, try

inf = float("9e999")
nan = inf - inf

I am facing the issue when I was porting the simplejson to an embedded device which running the Python 2.4, float("9e999") fixed it. Don't use inf = 9e999, you need convert it from string. -inf gives the -Infinity.

Jquery change <p> text programmatically

Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.

<p id="pTest">Male</p>
<button>change</button>

<script>
$('button').click(function(){
     $('#pTest').text('test')
})
</script>

http://jsfiddle.net/CA5Cs/

read complete file without using loop in java

If the file is small, you can read the whole data once:

File file = new File("a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();

String str = new String(data, "UTF-8");

Linux bash script to extract IP address

To just get your IP address:

echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'`

This will give you the IP address of eth0.

Edit: Due to name changes of interfaces in recent versions of Ubuntu, this doesn't work anymore. Instead, you could just use this:

hostname --all-ip-addresses or hostname -I, which does the same thing (gives you ALL IP addresses of the host).

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

Check if your HTML page includes:

  1. angular.min script
  2. app.js
  3. controller JavaScript page

The order the files are included is important. It was my solution to this problem.

Hope this helps.

How to hide output of subprocess in Python 2.7

Use subprocess.check_output (new in python 2.7). It will suppress stdout and raise an exception if the command fails. (It actually returns the contents of stdout, so you can use that later in your program if you want.) Example:

import subprocess
try:
    subprocess.check_output(['espeak', text])
except subprocess.CalledProcessError:
    # Do something

You can also suppress stderr with:

    subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT)

For earlier than 2.7, use

import os
import subprocess
with open(os.devnull, 'w')  as FNULL:
    try:
        subprocess._check_call(['espeak', text], stdout=FNULL)
    except subprocess.CalledProcessError:
        # Do something

Here, you can suppress stderr with

        subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)

:not(:empty) CSS selector is not working?

This should work in modern browsers:

input[value]:not([value=""])

It selects all inputs with value attribute and then select inputs with non empty value among them.

How to find a parent with a known class in jQuery?

Use .parentsUntil()

$(".d").parentsUntil(".a");

What's a quick way to comment/uncomment lines in Vim?

@CMS's solution is the most "vim native" way to comment in/out lines. In @CMS's second step, after CtrlV, you could also use r# to add comments or x to delete them. Drew Neil's Practical Vim, page 46, explains this technique well.

Another good option is to use an ex mode command. :[range]normali##?. Obviously, to save keystrokes with this one, you'll need to comment out 15+ lines.

ImportError: No module named 'MySQL'

I have found another reason: If your program file's path contains space or special characters, then you'd get this error.

How to insert multiple rows from a single query using eloquent/fluent

using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);

Get all validation errors from Angular 2 FormGroup

Based on the @MixerOID response, here is my final solution as a component (maybe I create a library). I also support FormArray's:

import {Component, ElementRef, Input, OnInit} from '@angular/core';
import {FormArray, FormGroup, ValidationErrors} from '@angular/forms';
import {TranslateService} from '@ngx-translate/core';

interface AllValidationErrors {
  controlName: string;
  errorName: string;
  errorValue: any;
}

@Component({
  selector: 'app-form-errors',
  templateUrl: './form-errors.component.html',
  styleUrls: ['./form-errors.component.scss']
})
export class FormErrorsComponent implements OnInit {

  @Input() form: FormGroup;
  @Input() formRef: ElementRef;
  @Input() messages: Array<any>;

  private errors: AllValidationErrors[];

  constructor(
    private translateService: TranslateService
  ) {
    this.errors = [];
    this.messages = [];
  }

  ngOnInit() {
    this.form.valueChanges.subscribe(() => {
      this.errors = [];
      this.calculateErrors(this.form);
    });

    this.calculateErrors(this.form);
  }

  calculateErrors(form: FormGroup | FormArray) {
    Object.keys(form.controls).forEach(field => {
      const control = form.get(field);
      if (control instanceof FormGroup || control instanceof FormArray) {
        this.errors = this.errors.concat(this.calculateErrors(control));
        return;
      }

      const controlErrors: ValidationErrors = control.errors;
      if (controlErrors !== null) {
        Object.keys(controlErrors).forEach(keyError => {
          this.errors.push({
            controlName: field,
            errorName: keyError,
            errorValue: controlErrors[keyError]
          });
        });
      }
    });

    // This removes duplicates
    this.errors = this.errors.filter((error, index, self) => self.findIndex(t => {
      return t.controlName === error.controlName && t.errorName === error.errorName;
    }) === index);
    return this.errors;
  }

  getErrorMessage(error) {
    switch (error.errorName) {
      case 'required':
        return this.translateService.instant('mustFill') + ' ' + this.messages[error.controlName];
      default:
        return 'unknown error ' + error.errorName;
    }
  }
}

And the HTML:

<div *ngIf="formRef.submitted">
  <div *ngFor="let error of errors" class="text-danger">
    {{getErrorMessage(error)}}
  </div>
</div>

Usage:

<app-form-errors [form]="languageForm"
                 [formRef]="formRef"
                 [messages]="{language: 'Language'}">
</app-form-errors>

Static Initialization Blocks

The non-static block:

{
    // Do Something...
}

Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.

Example:

public class Test {

    static{
        System.out.println("Static");
    }

    {
        System.out.println("Non-static block");
    }

    public static void main(String[] args) {
        Test t = new Test();
        Test t2 = new Test();
    }
}

This prints:

Static
Non-static block
Non-static block

How do I make a delay in Java?

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep.

Further, sleep isn't very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

And in Java 7:

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            myTask();
        }
    }, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

Deserialize JSON string to c# object

solution :

 public Response Get(string jsonData) {
     var json = JsonConvert.DeserializeObject<modelname>(jsonData);
     var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
     return data;
 }

model:

 public class modelname {
     public long parameter{ get; set; }
     public int parameter{ get; set; }
     public int parameter{ get; set; }
     public string parameter{ get; set; }
 }

How to concatenate string variables in Bash

You can do this too:

$ var="myscript"

$ echo $var

myscript


$ var=${var}.sh

$ echo $var

myscript.sh

How do I localize the jQuery UI Datepicker?

$.datepicker.regional["vi-VN"] = { closeText: "Ðóng", prevText: "Tru?c", nextText: "Sau", currentText: "Hôm nay", monthNames: ["Tháng m?t", "Tháng hai", "Tháng ba", "Tháng tu", "Tháng nam", "Tháng sáu", "Tháng b?y", "Tháng tám", "Tháng chín", "Tháng mu?i", "Tháng mu?i m?t", "Tháng mu?i hai"], monthNamesShort: ["M?t", "Hai", "Ba", "B?n", "Nam", "Sáu", "B?y", "Tám", "Chín", "Mu?i", "Mu?i m?t", "Mu?i hai"], dayNames: ["Ch? nh?t", "Th? hai", "Th? ba", "Th? tu", "Th? nam", "Th? sáu", "Th? b?y"], dayNamesShort: ["CN", "Hai", "Ba", "Tu", "Nam", "Sáu", "B?y"], dayNamesMin: ["CN", "T2", "T3", "T4", "T5", "T6", "T7"], weekHeader: "Tu?n", dateFormat: "dd/mm/yy", firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: "" };

        $.datepicker.setDefaults($.datepicker.regional["vi-VN"]);

html5 - canvas element - Multiple layers

You can create multiple canvas elements without appending them into document. These will be your layers:

Then do whatever you want with them and at the end just render their content in proper order at destination canvas using drawImage on context.

Example:

/* using canvas from DOM */
var domCanvas = document.getElementById('some-canvas');
var domContext = domCanvas.getContext('2d');
domContext.fillRect(50,50,150,50);

/* virtual canvase 1 - not appended to the DOM */
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50,50,150,150);

/* virtual canvase 2 - not appended to the DOM */    
var canvas2 = document.createElement('canvas')
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'yellow';
ctx2.fillRect(50,50,100,50)

/* render virtual canvases on DOM canvas */
domContext.drawImage(canvas, 0, 0, 200, 200);
domContext.drawImage(canvas2, 0, 0, 200, 200);

And here is some codepen: https://codepen.io/anon/pen/mQWMMW

Removing all script tags from html with JS Regular Expression

If you want to remove all JavaScript code from some HTML text, then removing <script> tags isn't enough, because JavaScript can still live in "onclick", "onerror", "href" and other attributes.

Try out this npm module which handles all of this: https://www.npmjs.com/package/strip-js

Using the Web.Config to set up my SQL database connection string?

http://www.connectionstrings.com is a site where you can find a lot of connection strings. All that you need to do is copy-paste and modify it to suit your needs. It is sure to have all the connection strings for all of your needs.

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

In typescript you can do the following to suppress the error:

let subString?: string;

subString > !null; - Note the added exclamation mark before null.

How do I get a button to open another activity?

Using an OnClickListener

Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

Button yourButton = (Button) findViewById(R.id.your_buttons_id);

yourButton.setOnClickListener(new OnClickListener(){
    public void onClick(View v){                        
        startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
    }
});

This is probably most developers preferred method. However, there is a common alternative.

Using onClick in XML

Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

public void yourMethodName(View v){
    startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}

Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

References;

Pure CSS to make font-size responsive based on dynamic amount of characters

Edit: Watch out for attr() Its related to calc() in css. You may be able to achieve it in future.

Unfortunately for now there isn't a css only solution. This is what I suggest you do. To your element give a title attribute. And use text-overflow ellipsis to prevent breakage of the design and let user know more text is there.

<div style="width: 200px; height: 1em; text-overflow: ellipsis;" title="Some sample dynamic amount of text here">
 Some sample dynamic amount of text here
</div>

.

.

.

Alternatively, If you just want to reduce size based on the viewport. CSS3 supports new dimensions that are relative to view port.

body {
   font-size: 3.2vw;
}
  1. 3.2vw = 3.2% of width of viewport
  2. 3.2vh = 3.2% of height of viewport
  3. 3.2vmin = Smaller of 3.2vw or 3.2vh
  4. 3.2vmax = Bigger of 3.2vw or 3.2vh see css-tricks.com/.... and also look at caniuse.com/....

Detect Browser Language in PHP

why dont you keep it simple and clean

<?php
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    $acceptLang = ['fr', 'it', 'en']; 
    $lang = in_array($lang, $acceptLang) ? $lang : 'en';
    require_once "index_{$lang}.php"; 

?>

HTML text input allow only numeric input

_x000D_
_x000D_
var userName = document.querySelector('#numberField');

userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {  
  var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
  this.value = newValue;
}
_x000D_
<input type="text" id="numberField">
_x000D_
_x000D_
_x000D_

How to install a certificate in Xcode (preparing for app store submission)

Under

Provisioning -> Distribution -> Distribution Provisioning Profiles

I downloaded the desired certificate again and installed it. Now I don't see an empty file in Xcode. The build also works now (no code sign error).

What I also did: I downloaded the WWDR and installed it, but I don't know if that was the reason (because I think it's always the same)

How can I get the session object if I have the entity-manager?

To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.

JPA 1.0

With JPA 1.0, you'd have to use EntityManager#getDelegate(). But keep in mind that the result of this method is implementation specific i.e. non portable from application server using Hibernate to the other. For example with JBoss you would do:

org.hibernate.Session session = (Session) manager.getDelegate();

But with GlassFish, you'd have to do:

org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession(); 

I agree, that's horrible, and the spec is to blame here (not clear enough).

JPA 2.0

With JPA 2.0, there is a new (and much better) EntityManager#unwrap(Class<T>) method that is to be preferred over EntityManager#getDelegate() for new applications.

So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:

Session session = entityManager.unwrap(Session.class);

Silent installation of a MSI package

The proper way to install an MSI silently is via the msiexec.exe command line as follows:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging
 /QN = run completely silently
 /i = run install sequence 

There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

Server.UrlEncode vs. HttpUtility.UrlEncode

Fast-forward almost 9 years since this was first asked, and in the world of .NET Core and .NET Standard, it seems the most common options we have for URL-encoding are WebUtility.UrlEncode (under System.Net) and Uri.EscapeDataString. Judging by the most popular answer here and elsewhere, Uri.EscapeDataString appears to be preferable. But is it? I did some analysis to understand the differences and here's what I came up with:

  • WebUtility.UrlEncode encodes space as +; Uri.EscapeDataString encodes it as %20.
  • Uri.EscapeDataString percent-encodes !, (, ), and *; WebUtility.UrlEncode does not.
  • WebUtility.UrlEncode percent-encodes ~; Uri.EscapeDataString does not.
  • Uri.EscapeDataString throws a UriFormatException on strings longer than 65,520 characters; WebUtility.UrlEncode does not. (A more common problem than you might think, particularly when dealing with URL-encoded form data.)
  • Uri.EscapeDataString throws a UriFormatException on the high surrogate characters; WebUtility.UrlEncode does not. (That's a UTF-16 thing, probably a lot less common.)

For URL-encoding purposes, characters fit into one of 3 categories: unreserved (legal in a URL); reserved (legal in but has special meaning, so you might want to encode it); and everything else (must always be encoded).

According to the RFC, the reserved characters are: :/?#[]@!$&'()*+,;=

And the unreserved characters are alphanumeric and -._~

The Verdict

Uri.EscapeDataString clearly defines its mission: %-encode all reserved and illegal characters. WebUtility.UrlEncode is more ambiguous in both definition and implementation. Oddly, it encodes some reserved characters but not others (why parentheses and not brackets??), and stranger still it encodes that innocently unreserved ~ character.

Therefore, I concur with the popular advice - use Uri.EscapeDataString when possible, and understand that reserved characters like / and ? will get encoded. If you need to deal with potentially large strings, particularly with URL-encoded form content, you'll need to either fall back on WebUtility.UrlEncode and accept its quirks, or otherwise work around the problem.


EDIT: I've attempted to rectify ALL of the quirks mentioned above in Flurl via the Url.Encode, Url.EncodeIllegalCharacters, and Url.Decode static methods. These are in the core package (which is tiny and doesn't include all the HTTP stuff), or feel free to rip them from the source. I welcome any comments/feedback you have on these.


Here's the code I used to discover which characters are encoded differently:

var diffs =
    from i in Enumerable.Range(0, char.MaxValue + 1)
    let c = (char)i
    where !char.IsHighSurrogate(c)
    let diff = new {
        Original = c,
        UrlEncode = WebUtility.UrlEncode(c.ToString()),
        EscapeDataString = Uri.EscapeDataString(c.ToString()),
    }
    where diff.UrlEncode != diff.EscapeDataString
    select diff;

foreach (var diff in diffs)
    Console.WriteLine($"{diff.Original}\t{diff.UrlEncode}\t{diff.EscapeDataString}");

Why is semicolon allowed in this python snippet?

Multiple statements on one line may include semicolons as separators. For example: http://docs.python.org/reference/compound_stmts.html In your case, it makes for an easy insertion of a point to break into the debugger.

Also, as mentioned by Mark Lutz in the Learning Python Book, it is technically legal (although unnecessary and annoying) to terminate all your statements with semicolons.

Finding Key associated with max Value in a Java Map

int maxValue = 0;
int mKey = 0;
for(Integer key: map.keySet()){
    if(map.get(key) > maxValue){
        maxValue = map.get(key);
        mKey = key;
    }
}
System.out.println("Max Value " + maxValue + " is associated with " + mKey + " key");

How many parameters are too many?

One of Alan Perlis's well-known programming epigrams (recounted in ACM SIGPLAN Notices 17(9), September, 1982) states that "If you have a procedure with 10 parameters, you probably missed some."

How can I find out what version of git I'm running?

$ git --version
git version 1.7.3.4

git help and man git both hint at the available arguments you can pass to the command-line tool

Spring Boot - Cannot determine embedded database driver class for database type NONE

From the Spring manual.

Spring Boot can auto-configure embedded H2, HSQL, and Derby databases. You don’t need to provide any connection URLs, simply include a build dependency to the embedded database that you want to use.

For example, typical POM dependencies would be:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

For me leaving out the spring-boot-starter-data-jpa dependency and just using the spring-boot-starter-jdbc dependency worked like a charm, as long as I had h2 (or hsqldb) included as dependencies.

Compare object instances for equality by their attributes

I tried the initial example (see 7 above) and it did not work in ipython. Note that cmp(obj1,obj2) returns a "1" when implemented using two identical object instances. Oddly enough when I modify one of the attribute values and recompare, using cmp(obj1,obj2) the object continues to return a "1". (sigh...)

Ok, so what you need to do is iterate two objects and compare each attribute using the == sign.

How can I fetch all items from a DynamoDB table without specifying the primary key?

This C# code is to fetch all items from a dynamodb table using BatchGet or CreateBatchGet

        string tablename = "AnyTableName"; //table whose data you want to fetch

        var BatchRead = ABCContext.Context.CreateBatchGet<ABCTable>(  

            new DynamoDBOperationConfig
            {
                OverrideTableName = tablename; 
            });

        foreach(string Id in IdList) // in case you are taking string from input
        {
            Guid objGuid = Guid.Parse(Id); //parsing string to guid
            BatchRead.AddKey(objGuid);
        }

        await BatchRead.ExecuteAsync();
        var result = BatchRead.Results;

// ABCTable is the table modal which is used to create in dynamodb & data you want to fetch

check if file exists on remote host with ssh

On CentOS machine, the oneliner bash that worked for me was:

if ssh <servername> "stat <filename> > /dev/null 2>&1"; then echo "file exists"; else echo "file doesnt exits"; fi

It needed I/O redirection (as the top answer) as well as quotes around the command to be run on remote.

How to change CSS using jQuery?

_x000D_
_x000D_
$(function(){ _x000D_
$('.bordered').css({_x000D_
"border":"1px solid #EFEFEF",_x000D_
"margin":"0 auto",_x000D_
"width":"80%"_x000D_
});_x000D_
_x000D_
$('h1').css({_x000D_
"margin-left":"10px"_x000D_
});_x000D_
_x000D_
$('#myParagraph').css({_x000D_
"margin-left":"10px",_x000D_
"font-family":"sans-serif"_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<div class="bordered">_x000D_
<h1>Header</h1>_x000D_
<p id="myParagraph">This is some paragraph text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert an enum type variable to a string?

There really is no beautiful way of doing this. Just set up an array of strings indexed by the enum.

If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.

Format the date using Ruby on Rails

Have a look at localize, or l

eg:

l Time.at(1100897479)

Why .NET String is immutable?

Strings and other concrete objects are typically expressed as immutable objects to improve readability and runtime efficiency. Security is another, a process can't change your string and inject code into the string

SQL query to select dates between two dates

select * from test 
     where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'

-- if data type is different

How to check if mod_rewrite is enabled in php?

via command line we in centOs we can do this

httpd -l

console.log timestamps in Chrome?

If you are using Google Chrome browser, you can use chrome console api:

  • console.time: call it at the point in your code where you want to start the timer
  • console.timeEnd: call it to stop the timer

The elapsed time between these two calls is displayed in the console.

For detail info, please see the doc link: https://developers.google.com/chrome-developer-tools/docs/console

What is the difference between server side cookie and client side cookie?

What is the difference between creating cookies on the server and on the client?

What you are referring to are the 2 ways in which cookies can be directed to be set on the client, which are:

  • By server
  • By client ( browser in most cases )

By server: The Set-cookie response header from the server directs the client to set a cookie on that particular domain. The implementation to actually create and store the cookie lies in the browser. For subsequent requests to the same domain, the browser automatically sets the Cookie request header for each request, thereby letting the server have some state to an otherwise stateless HTTP protocol. The Domain and Path cookie attributes are used by the browser to determine which cookies are to be sent to a server. The server only receives name=value pairs, and nothing more.

By Client: One can create a cookie on the browser using document.cookie = cookiename=cookievalue. However, if the server does not intend to respond to any random cookie a user creates, then such a cookie serves no purpose.

Are these called server side cookies and client side cookies?

Cookies always belong to the client. There is no such thing as server side cookie.

Is there a way to create cookies that can only be read on the server or on the client?

Since reading cookie values are upto the server and client, it depends if either one needs to read the cookie at all. On the client side, by setting the HttpOnly attribute of the cookie, it is possible to prevent scripts ( mostly Javscript ) from reading your cookies , thereby acting as a defence mechanism against Cookie theft through XSS, but sends the cookie to the intended server only.

Therefore, in most of the cases since cookies are used to bring 'state' ( memory of past user events ), creating cookies on client side does not add much value, unless one is aware of the cookies the server uses / responds to.

References: Wikipedia

Contain form within a bootstrap popover?

Either replace double quotes around type="text" with single quotes, Like

"<form><input type='text'/></form>"

OR

replace double quotes wrapping data-content with singe quotes, Like

data-content='<form><input type="text"/></form>'

Resize a large bitmap file to scaled output file on Android

Justin answer translated to code (works perfect for me):

private Bitmap getBitmap(String path) {

Uri uri = getImageUri(path);
InputStream in = null;
try {
    final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
    in = mContentResolver.openInputStream(uri);

    // Decode image size
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(in, null, options);
    in.close();



    int scale = 1;
    while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) > 
          IMAGE_MAX_SIZE) {
       scale++;
    }
    Log.d(TAG, "scale = " + scale + ", orig-width: " + options.outWidth + ", 
       orig-height: " + options.outHeight);

    Bitmap resultBitmap = null;
    in = mContentResolver.openInputStream(uri);
    if (scale > 1) {
        scale--;
        // scale to max possible inSampleSize that still yields an image
        // larger than target
        options = new BitmapFactory.Options();
        options.inSampleSize = scale;
        resultBitmap = BitmapFactory.decodeStream(in, null, options);

        // resize to desired dimensions
        int height = resultBitmap.getHeight();
        int width = resultBitmap.getWidth();
        Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
           height: " + height);

        double y = Math.sqrt(IMAGE_MAX_SIZE
                / (((double) width) / height));
        double x = (y / height) * width;

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(resultBitmap, (int) x, 
           (int) y, true);
        resultBitmap.recycle();
        resultBitmap = scaledBitmap;

        System.gc();
    } else {
        resultBitmap = BitmapFactory.decodeStream(in);
    }
    in.close();

    Log.d(TAG, "bitmap size - width: " +resultBitmap.getWidth() + ", height: " + 
       resultBitmap.getHeight());
    return resultBitmap;
} catch (IOException e) {
    Log.e(TAG, e.getMessage(),e);
    return null;
}

Get top n records for each group of grouped results

SELECT
p1.Person,
p1.`GROUP`,
p1.Age  
   FROM
person AS p1 
 WHERE
(
SELECT
    COUNT( DISTINCT ( p2.age ) ) 
FROM
    person AS p2 
WHERE
    p2.`GROUP` = p1.`GROUP` 
    AND p2.Age >= p1.Age 
) < 2 
ORDER BY
p1.`GROUP` ASC,
p1.age DESC

reference leetcode

Transparent ARGB hex value

Just came across this and the short code for transparency is simply #00000000.

How to override a JavaScript function

You can do it like this:

alert(parseFloat("1.1531531414")); // alerts the float
parseFloat = function(input) { return 1; };
alert(parseFloat("1.1531531414")); // alerts '1'

Check out a working example here: http://jsfiddle.net/LtjzW/1/

How to concatenate int values in java?

The easiest (but somewhat dirty) way:

String result = "" + a + b + c + d + e

Edit: I don't recommend this and agree with Jon's comment. Adding those extra empty strings is probably the best compromise between shortness and clarity.

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

If you are using Python 2, the following will be the solution:

import io
for line in io.open("u.item", encoding="ISO-8859-1"):
    # Do something

Because the encoding parameter doesn't work with open(), you will be getting the following error:

TypeError: 'encoding' is an invalid keyword argument for this function

Count how many rows have the same value

SELECT 
   COUNT(NUM) as 'result' 
FROM 
   Table1 
GROUP BY 
   NUM 
HAVING NUM = 1

Please add a @Pipe/@Directive/@Component annotation. Error

I was trying to use BrowserModule in a shared module (import and export). That was not allowed so instead I had to use the CommonModule instead and it worked.

How to get POSTed JSON in Flask?

For reference, here's complete code for how to send json from a Python client:

import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
    print res.json()

The "json=" input will automatically set the content-type, as discussed here: Post JSON using Python Requests

And the above client will work with this server-side code:

from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content['mytext']
    return jsonify({"uuid":uuid})

if __name__ == '__main__':
    app.run(host= '0.0.0.0',debug=True)

Jquery asp.net Button Click Event via ajax

ASP.NET web forms page already have a JavaScript method for handling PostBacks called "__doPostBack".

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

Use the following in your code file to generate the JavaScript that performs the PostBack. Using this method will ensure that the proper ClientID for the control is used.

protected string GetLoginPostBack()
{
    return Page.ClientScript.GetPostBackEventReference(btnLogin, string.Empty);
}

Then in the ASPX page add a javascript block.

<script language="javascript">
function btnLogin_Click() {
  <%= GetLoginPostBack() %>;
}
</script>

The final javascript will be rendered like this.

<script language="javascript">
function btnLogin_Click() {
  __doPostBack('btnLogin','');
}
</script>

Now you can use "btnLogin_Click()" from your javascript to submit the button click to the server.

Deserializing JSON data to C# using JSON.NET

You can try checking some of the class generators online for further information. However, I believe some of the answers have been useful. Here's my approach that may be useful.

The following code was made with a dynamic method in mind.

dynObj = (JArray) JsonConvert.DeserializeObject(nvm);

foreach(JObject item in dynObj) {
 foreach(JObject trend in item["trends"]) {
  Console.WriteLine("{0}-{1}-{2}", trend["query"], trend["name"], trend["url"]);
 }
}

This code basically allows you to access members contained in the Json string. Just a different way without the need of the classes. query, trend and url are the objects contained in the Json string.

You can also use this website. Don't trust the classes a 100% but you get the idea.

Copy tables from one database to another in SQL Server

If it’s one table only then all you need to do is

  • Script table definition
  • Create new table in another database
  • Update rules, indexes, permissions and such
  • Import data (several insert into examples are already shown above)

One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other.

Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using ApexSQL Diff for schema migrations but you can’t go wrong with any other tool out there.

How to get raw text from pdf file using java

For the newer versions of Apache pdfbox. Here is the example from the original source

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pdfbox.examples.util;

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.text.PDFTextStripper;

/**
 * This is a simple text extraction example to get started. For more advance usage, see the
 * ExtractTextByArea and the DrawPrintTextLocations examples in this subproject, as well as the
 * ExtractText tool in the tools subproject.
 *
 * @author Tilman Hausherr
 */
public class ExtractTextSimple
{
    private ExtractTextSimple()
    {
        // example class should not be instantiated
    }

    /**
     * This will print the documents text page by page.
     *
     * @param args The command line arguments.
     *
     * @throws IOException If there is an error parsing or extracting the document.
     */
    public static void main(String[] args) throws IOException
    {
        if (args.length != 1)
        {
            usage();
        }

        try (PDDocument document = PDDocument.load(new File(args[0])))
        {
            AccessPermission ap = document.getCurrentAccessPermission();
            if (!ap.canExtractContent())
            {
                throw new IOException("You do not have permission to extract text");
            }

            PDFTextStripper stripper = new PDFTextStripper();

            // This example uses sorting, but in some cases it is more useful to switch it off,
            // e.g. in some files with columns where the PDF content stream respects the
            // column order.
            stripper.setSortByPosition(true);

            for (int p = 1; p <= document.getNumberOfPages(); ++p)
            {
                // Set the page interval to extract. If you don't, then all pages would be extracted.
                stripper.setStartPage(p);
                stripper.setEndPage(p);

                // let the magic happen
                String text = stripper.getText(document);

                // do some nice output with a header
                String pageStr = String.format("page %d:", p);
                System.out.println(pageStr);
                for (int i = 0; i < pageStr.length(); ++i)
                {
                    System.out.print("-");
                }
                System.out.println();
                System.out.println(text.trim());
                System.out.println();

                // If the extracted text is empty or gibberish, please try extracting text
                // with Adobe Reader first before asking for help. Also read the FAQ
                // on the website: 
                // https://pdfbox.apache.org/2.0/faq.html#text-extraction
            }
        }
    }

    /**
     * This will print the usage for this document.
     */
    private static void usage()
    {
        System.err.println("Usage: java " + ExtractTextSimple.class.getName() + " <input-pdf>");
        System.exit(-1);
    }
}

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

Android: making a fullscreen application

Just add the following attribute to your current theme:

<item name="android:windowFullscreen">true</item>

For example:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/orange</item>
    <item name="colorPrimaryDark">@android:color/holo_orange_dark</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
</style>

Searching for file in directories recursively

You should have the loop over the files either before or after the loop over the directories, but not nested inside it as you have done.

foreach (string f in Directory.GetFiles(d, "*.xml"))
{
    string extension = Path.GetExtension(f);
    if (extension != null && (extension.Equals(".xml")))
    {
        fileList.Add(f);
    }
} 

foreach (string d in Directory.GetDirectories(sDir))
{
    DirSearch(d);
}

How can I make my string property nullable?

string is by default Nullable ,you don't need to do anything to make string Nullable

Multiple Updates in MySQL

UPDATE table1, table2 SET table1.col1='value', table2.col1='value' WHERE table1.col3='567' AND table2.col6='567'

This should work for ya.

There is a reference in the MySQL manual for multiple tables.

Prevent a webpage from navigating away using JavaScript

Use onunload.

For jQuery, I think this works like so:

$(window).unload(function() { 
  alert("Unloading"); 
  return falseIfYouWantToButBeCareful();
});

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

Here is the method in Java

private int ipow(int base, int exp)
{
    int result = 1;
    while (exp != 0)
    {
        if ((exp & 1) == 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }

    return result;
}

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Bootstrap Carousel : Remove auto slide

In Bootstrap v5 use: data-bs-interval="false"

<div id="carouselExampleCaptions" class="carousel" data-bs-ride="carousel" data-bs-interval="false">

You have not concluded your merge (MERGE_HEAD exists)

first,use git pull to merge repository save your change.then retype git commit -m "your commit".

How to avoid annoying error "declared and not used"

According to the FAQ:

Some have asked for a compiler option to turn those checks off or at least reduce them to warnings. Such an option has not been added, though, because compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation.

There are two reasons for having no warnings. First, if it's worth complaining about, it's worth fixing in the code. (And if it's not worth fixing, it's not worth mentioning.) Second, having the compiler generate warnings encourages the implementation to warn about weak cases that can make compilation noisy, masking real errors that should be fixed.

I don't necessarily agree with this for various reasons not worth going into. It is what it is, and it's not likely to change in the near future.

For packages, there's the goimports tool which automatically adds missing packages and removes unused ones. For example:

# Install it
$ go get golang.org/x/tools/cmd/goimports

# -w to write the source file instead of stdout
$ goimports -w my_file.go

You should be able to run this from any half-way decent editor - for example for Vim:

:!goimports -w %

The goimports page lists some commands for other editors, and you typically set it to be run automatically when you save the buffer to disk.

Note that goimports will also run gofmt.


As was already mentioned, for variables the easiest way is to (temporarily) assign them to _ :

// No errors
tasty := "ice cream"
horrible := "marmite"

// Commented out for debugging
//eat(tasty, horrible)

_, _ = tasty, horrible

Start thread with member function

Here is a complete example

#include <thread>
#include <iostream>

class Wrapper {
   public:
      void member1() {
          std::cout << "i am member1" << std::endl;
      }
      void member2(const char *arg1, unsigned arg2) {
          std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
      }
      std::thread member1Thread() {
          return std::thread([=] { member1(); });
      }
      std::thread member2Thread(const char *arg1, unsigned arg2) {
          return std::thread([=] { member2(arg1, arg2); });
      }
};
int main(int argc, char **argv) {
   Wrapper *w = new Wrapper();
   std::thread tw1 = w->member1Thread();
   std::thread tw2 = w->member2Thread("hello", 100);
   tw1.join();
   tw2.join();
   return 0;
}

Compiling with g++ produces the following result

g++ -Wall -std=c++11 hello.cc -o hello -pthread

i am member1
i am member2 and my first arg is (hello) and second arg is (100)

How to loop over directories in Linux?

You can loop through all directories including hidden directrories (beginning with a dot) with:

for file in */ .*/ ; do echo "$file is a directory"; done

note: using the list */ .*/ works in zsh only if there exist at least one hidden directory in the folder. In bash it will show also . and ..


Another possibility for bash to include hidden directories would be to use:

shopt -s dotglob;
for file in */ ; do echo "$file is a directory"; done

If you want to exclude symlinks:

for file in */ ; do 
  if [[ -d "$file" && ! -L "$file" ]]; then
    echo "$file is a directory"; 
  fi; 
done

To output only the trailing directory name (A,B,C as questioned) in each solution use this within the loops:

file="${file%/}"     # strip trailing slash
file="${file##*/}"   # strip path and leading slash
echo "$file is the directoryname without slashes"

Example (this also works with directories which contains spaces):

mkdir /tmp/A /tmp/B /tmp/C "/tmp/ dir with spaces"
for file in /tmp/*/ ; do file="${file%/}"; echo "${file##*/}"; done

Copy entire contents of a directory to another using php

With Symfony this is very easy to accomplish:

$fileSystem = new Symfony\Component\Filesystem\Filesystem();
$fileSystem->mirror($from, $to);

See https://symfony.com/doc/current/components/filesystem.html

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});

how to query child objects in mongodb

If it is exactly null (as opposed to not set):

db.states.find({"cities.name": null})

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

If it's the case that the property is not set:

db.states.find({"cities.name": {"$exists": false}})

I've tested the above with a collection created with these two inserts:

db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or query:

db.states.find({"$or": [
  {"cities.name": null}, 
  {"cities.name": {"$exists": false}}
]})