Programs & Examples On #Illegal characters

No visible cause for "Unexpected token ILLEGAL"

I am going to add one more answer to the pile. THis problem could happen also because of encoding. You want utf8 encoding to be on safe side. Some editors by default use utf16 which can cause issue. One quick way to test this, is, for example in VS code, simply recreate the same content but use the local editor of vscode to create the file. Hope this helps some.

Copy a file in a sane, safe and efficient way

I want to make the very important note that the LINUX method using sendfile() has a major problem in that it can not copy files more than 2GB in size! I had implemented it following this question and was hitting problems because I was using it to copy HDF5 files that were many GB in size.

http://man7.org/linux/man-pages/man2/sendfile.2.html

sendfile() will transfer at most 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes actually transferred. (This is true on both 32-bit and 64-bit systems.)

Laravel Mail::send() sending to multiple to or bcc addresses

If you want to send emails simultaneously to all the admins, you can do something like this:

In your .env file add all the emails as comma separated values:

[email protected],[email protected],[email protected]

so when you going to send the email just do this (yes! the 'to' method of message builder instance accepts an array):

So,

$to = explode(',', env('ADMIN_EMAILS'));

and...

$message->to($to);

will now send the mail to all the admins.

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

This warning generated for default ASP.NET MVC 4 beta see here

In, any cast this Warning can be eliminated by manually editing the .csproj file for your project.

modify........: Reference Include="System.Net.Http"

to read ......: Reference Include="System.Net.Http, Version=4.0.0.0"

How to make overlay control above all other controls?

<Canvas Panel.ZIndex="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="570">
  <!-- YOUR XAML CODE -->
</Canvas>

Ignoring SSL certificate in Apache HttpClient 4.3

If you are using HttpClient 4.5.x, your code can be similar to the following:

SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
        TrustSelfSignedStrategy.INSTANCE).build();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
        sslContext, NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom()
                                   .setDefaultCookieStore(new BasicCookieStore())
                                   .setSSLSocketFactory(sslSocketFactory)
                                   .build();

PHP - Check if two arrays are equal

Syntax problem on your arrays

$array1 = array(
    'a' => 'value1',
    'b' => 'value2',
    'c' => 'value3',
 );

$array2 = array(
    'a' => 'value1',
    'b' => 'value2',
    'c' => 'value3',
 );

$diff = array_diff($array1, $array2);

var_dump($diff); 

How to submit an HTML form without redirection

Place a hidden iFrame at the bottom of your page and target it in your form:

<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>

<form action="/Car/Edit/17" id="myForm" method="post" name="myForm" target="hiddenFrame"> ... </form>

Quick and easy. Keep in mind that while the target attribute is still widely supported (and supported in HTML5), it was deprecated in HTML 4.01.

So you really should be using Ajax to future-proof.

java.lang.IllegalStateException: Fragment not attached to Activity

I adopted the following approach for handling this issue. Created a new class which act as a wrapper for activity methods like this

public class ContextWrapper {
    public static String getString(Activity activity, int resourceId, String defaultValue) {
        if (activity != null) {
            return activity.getString(resourceId);
        } else {
            return defaultValue;
        }
    }

    //similar methods like getDrawable(), getResources() etc

}

Now wherever I need to access resources from fragments or activities, instead of directly calling the method, I use this class. In case the activity context is not null it returns the value of the asset and in case the context is null, it passes a default value (which is also specified by the caller of the function).

Important This is not a solution, this is an effective way where you can handle this crash gracefully. You would want to add some logs in cases where you are getting activity instance as null and try to fix that, if possible.

javax.websocket client simple example

Have a look at this Java EE 7 examples from Arun Gupta.

I forked it on github.

Main

/**
 * @author Arun Gupta
 */
public class Client {

    final static CountDownLatch messageLatch = new CountDownLatch(1);

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            String uri = "ws://echo.websocket.org:80/";
            System.out.println("Connecting to " + uri);
            container.connectToServer(MyClientEndpoint.class, URI.create(uri));
            messageLatch.await(100, TimeUnit.SECONDS);
        } catch (DeploymentException | InterruptedException | IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

ClientEndpoint

/**
 * @author Arun Gupta
 */
@ClientEndpoint
public class MyClientEndpoint {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to endpoint: " + session.getBasicRemote());
        try {
            String name = "Duke";
            System.out.println("Sending message to endpoint: " + name);
            session.getBasicRemote().sendText(name);
        } catch (IOException ex) {
            Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @OnMessage
    public void processMessage(String message) {
        System.out.println("Received message in client: " + message);
        Client.messageLatch.countDown();
    }

    @OnError
    public void processError(Throwable t) {
        t.printStackTrace();
    }
}

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

NSString property: copy or retain?

Copy should be used for NSString. If it's Mutable, then it gets copied. If it's not, then it just gets retained. Exactly the semantics that you want in an app (let the type do what's best).

Seeking useful Eclipse Java code templates

Spring Injection

I know this is sort of late to the game, but here is one I use for Spring Injection in a class:

${:import(org.springframework.beans.factory.annotation.Autowired)}
private ${class_to_inject} ${var_name};

@Autowired
public void set${class_to_inject}(${class_to_inject} ${var_name}) {
  this.${var_name} = ${var_name};
}

public ${class_to_inject} get${class_to_inject}() {
  return this.${var_name};
}

Find current directory and file's directory

To get the current directory full path:

os.path.realpath('.')

Programmatically add new column to DataGridView

Keep it simple

dataGridView1.Columns.Add("newColumnName", "Column Name in Text");

To add rows

dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]

How to get next/previous record in MySQL?

next:

select * from foo where id = (select min(id) from foo where id > 4)

previous:

select * from foo where id = (select max(id) from foo where id < 4)

Calculating powers of integers

import java.util.*;

public class Power {

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int num = 0;
        int pow = 0;
        int power = 0;

        System.out.print("Enter number: ");
        num = sc.nextInt();

        System.out.print("Enter power: ");
        pow = sc.nextInt();

        System.out.print(power(num,pow));
    }

    public static int power(int a, int b)
    {
        int power = 1;

        for(int c = 0; c < b; c++)
            power *= a;

        return power;
    }

}

How to add a footer in ListView?

I know this is a very old question, but I googled my way here and found the answer provided not 100% satisfying, because as gcl1 mentioned - this way the footer is not really a footer to the screen - it's just an "add-on" to the list.

Bottom line - for others who may google their way here - I found the following suggestion here: Fixed and always visible footer below ListFragment

Try doing as follows, where the emphasis is on the button (or any footer element) listed first in the XML - and then the list is added as "layout_above":

<RelativeLayout>

<Button android:id="@+id/footer" android:layout_alignParentBottom="true"/> 
<ListView android:id="@android:id/list" **android:layout_above**="@id/footer"> <!-- the list -->

</RelativeLayout>

Check free disk space for current partition in bash

To know the usage of the specific directory in GB's or TB's in linux the command is,

df -h /dir/inner_dir/

 or

df -sh /dir/inner_dir/

and to know the usage of the specific directory in bits in linux the command is,

df-k /dir/inner_dir/

Refresh Excel VBA Function Results

You should use Application.Volatile in the top of your function:

Function doubleMe(d)
    Application.Volatile
    doubleMe = d * 2
End Function

It will then reevaluate whenever the workbook changes (if your calculation is set to automatic).

Display all post meta keys and meta values of the same post ID in wordpress

$myvals = get_post_meta( get_the_ID());
foreach($myvals as $key=>$val){
  foreach($val as $vals){
    if ($key=='Youtube'){
       echo $vals 
    }
   }
 }

Key = Youtube videos all meta keys for youtube videos and value

How to use Console.WriteLine in ASP.NET (C#) during debug?

Console.Write will not work in ASP.NET as it is called using the browser. Use Response.Write instead.

See Stack Overflow question Where does Console.WriteLine go in ASP.NET?.

If you want to write something to Output window during debugging, you can use

System.Diagnostics.Debug.WriteLine("SomeText");

but this will work only during debug.

See Stack Overflow question Debug.WriteLine not working.

Dynamically load a function from a DLL

LoadLibrary does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary is called at runtime (remember that C++ is a statically typed language).

You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress.

Example

#include <windows.h>
#include <iostream>

/* Define a function pointer for our imported
 * function.
 * This reads as "introduce the new type f_funci as the type: 
 *                pointer to a function returning an int and 
 *                taking no arguments.
 *
 * Make sure to use matching calling convention (__cdecl, __stdcall, ...)
 * with the exported function. __stdcall is the convention used by the WinAPI
 */
typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  // resolve function address here
  f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
  if (!funci) {
    std::cout << "could not locate the function" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "funci() returned " << funci() << std::endl;

  return EXIT_SUCCESS;
}

Also, you should export your function from the DLL correctly. This can be done like this:

int __declspec(dllexport) __stdcall funci() {
   // ...
}

As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.

MySQL Data Source not appearing in Visual Studio

I was having the same problem just now. I solved it by uninstalling the latest Connector/NET drivers (6.7.4) and then installed the older drivers (6.6.5) and it works.

I am using Visual Studio 2010. I uninstalled the latest ones because I figured they were somehow related to .NET4.5, which I'm not able to use.


Update #1:

Supposedly another way is to register the MySql Connector with various Visual Studio versions (2010/2012/2013/2015...) during installation: Go to Modify Product Features and select all the relevant Visual Studio versions.

see Image


Update #2 - Visual Studio 2019 Update:

When I installed MySQL Community with the ConnectorNET and VisualStudio Plugin options included - MySQL didn't show up as a data provider in Visual Studio.

The installer I used included the VS Plugin version 1.2.9, which had supposedly fixed installation issues from 1.2.8, but still didn't work for me...

The solution for me was to uninstall the Connector and the Visual Studio Plugin, download them as individual components, and then install them separately (not as part of the MySQLServer Installer). Install the Connector first, then VS plugin after.

I found the solution here, Thanks to @LambertHeenan.


NOTE about Visual Studio Express

The OP asks whether MySQL is supported with Visual Studio Express (which as far as I can tell has been renamed to Visual Studio Community). In the past MySQL officially didn't support Visual Studio Express, as per @Paul's answer below, but they do officially support Visual Studio Community 2017 and 2019, according to this page.

Reset textbox value in javascript

First, select the element. You can usually use the ID like this:

$("#searchField"); // select element by using "#someid"

Then, to set the value, use .val("something") as in:

$("#searchField").val("something"); // set the value

Note that you should only run this code when the element is available. The usual way to do this is:

$(document).ready(function() { // execute when everything is loaded
    $("#searchField").val("something"); // set the value
});

Reading input files by line using read command in shell scripting skips last line

Below code with Redirected "while-read" loop works fine for me

while read LINE
do
      let count++
      echo "$count $LINE"

done < $FILENAME

echo -e "\nTotal $count Lines read"

How To Add An "a href" Link To A "div"?

I'd say:

 <a href="#"id="buttonOne">
            <div id="linkedinB">
                <img src="img/linkedinB.png" width="40" height="40">
            </div>
      </div> 

However, it will still be a link. If you want to change your link into a button, you should rename the #buttonone to #buttonone a { your css here }.

Opening database file from within SQLite command-line shell

I wonder why no one was able to get what the question actually asked. It stated What is the command within the SQLite shell tool to specify a database file?

A sqlite db is on my hard disk E:\ABCD\efg\mydb.db. How do I access it with sqlite3 command line interface? .open E:\ABCD\efg\mydb.db does not work. This is what question asked.

I found the best way to do the work is

  • copy-paste all your db files in 1 directory (say E:\ABCD\efg\mydbs)
  • switch to that directory in your command line
  • now open sqlite3 and then .open mydb.db

This way you can do the join operation on different tables belonging to different databases as well.

Jquery in React is not defined

I just want to receive ajax request, but the problem is that jQuery is not defined in React.

Then don't use it. Use Fetch and have a look at Fetch polyfill in React not completely working in IE 11 to see example of alternative ways to get it running

Something like this

const that = this; 
fetch('http://jsonplaceholder.typicode.com/posts') 
  .then(function(response) { return response.json(); }) 
  .then(function(myJson) { 
     that.setState({data: myJson}); // for example
  });

JBoss default password

The default credentials are:

login: admin
password: admin

But if you use EAP these credentials are turned off by default and there is no active user (security reasons :)). If you want to turn on these users, you have to edit the following file in your current profile: ./deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-users.properties. It should be enough to remove the # sign from the line with the user.

If you want to create a new user, don't forget to set up the correct groups in web-console-roles.properties file.

You can easily find information where these information are stored: just open the ./conf/login-config.xml file and find the proper security domain definition. In the case of the Web Console application, it will be web-console policy.

Also if you want to have access to JMX, you have unlock JMX Console. Just check the following files in the conf/props/ directory (in your profile): jmx-console-users.properties and jmx-console-roles.properties.

Modal width (increase)

Set max-width:80%; as an inline stylesheet

<div class="modal-dialog modal-lg" role="document" style="max-width: 80%;">

How to get current time and date in Android

You should use Calender class according to new API. Date class is deprecated now.

Calendar cal = Calendar.getInstance();

String date = ""+cal.get(Calendar.DATE)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR);

String time = ""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);

Correct way to write loops for promise.

I don't think it guarantees the order of calling logger.log(res);

Actually, it does. That statement is executed before the resolve call.

Any suggestions?

Lots. The most important is your use of the create-promise-manually antipattern - just do only

promiseWhile(…, function() {
    return db.getUser(email)
             .then(function(res) { 
                 logger.log(res); 
                 count++;
             });
})…

Second, that while function could be simplified a lot:

var promiseWhile = Promise.method(function(condition, action) {
    if (!condition()) return;
    return action().then(promiseWhile.bind(null, condition, action));
});

Third, I would not use a while loop (with a closure variable) but a for loop:

var promiseFor = Promise.method(function(condition, action, value) {
    if (!condition(value)) return value;
    return action(value).then(promiseFor.bind(null, condition, action));
});

promiseFor(function(count) {
    return count < 10;
}, function(count) {
    return db.getUser(email)
             .then(function(res) { 
                 logger.log(res); 
                 return ++count;
             });
}, 0).then(console.log.bind(console, 'all done'));

find vs find_by vs where

Apart from accepted answer, following is also valid

Model.find() can accept array of ids, and will return all records which matches. Model.find_by_id(123) also accept array but will only process first id value present in array

Model.find([1,2,3])
Model.find_by_id([1,2,3])

MySQL, update multiple tables with one query

That's usually what stored procedures are for: to implement several SQL statements in a sequence. Using rollbacks, you can ensure that they are treated as one unit of work, ie either they are all executed or none of them are, to keep data consistent.

Colors in JavaScript console

I've discovered that you can make logs with colors using ANSI color codes, what makes easier to find specific messages in debug. Try it:

console.log( "\u001b[1;31m Red message" );
console.log( "\u001b[1;32m Green message" );
console.log( "\u001b[1;33m Yellow message" );
console.log( "\u001b[1;34m Blue message" );
console.log( "\u001b[1;35m Purple message" );
console.log( "\u001b[1;36m Cyan message" );

How do I show the number keyboard on an EditText in android?

I found this implementation useful, shows a better keyboard and limits input chars.

<EditText
    android:inputType="phone"
    android:digits="1234567890"
    ...
/>

Additionally, you could use android:maxLength to limit the max amount of numbers.

To do this programmatically:

editText.setInputType(InputType.TYPE_CLASS_PHONE);

KeyListener keyListener = DigitsKeyListener.getInstance("1234567890");
editText.setKeyListener(keyListener);

Missing visible-** and hidden-** in Bootstrap v4

Unfortunately all classes hidden-*-up and hidden-*-down were removed from Bootstrap (as of Bootstrap Version 4 Beta, in Version 4 Alpha and Version 3 these classes still existed).

Instead, new classes d-* should be used, as mentioned here: https://getbootstrap.com/docs/4.0/migration/#utilities

I found out that the new approach is less useful under some circumstances. The old approach was to HIDE elements while the new approach is to SHOW elements. Showing elements is not that easy with CSS since you need to know if the element is displayed as block, inline, inline-block, table etc.

You might want to restore the former "hidden-*" styles known from Bootstrap 3 with this CSS:

/*\
 * Restore Bootstrap 3 "hidden" utility classes.
\*/

/* Breakpoint XS */
@media (max-width: 575px)
{
    .hidden-xs-down, .hidden-sm-down, .hidden-md-down, .hidden-lg-down, .hidden-xl-down, 
    .hidden-xs-up, 
    .hidden-unless-sm, .hidden-unless-md, .hidden-unless-lg, .hidden-unless-xl
    {
        display: none !important;
    }

}

/* Breakpoint SM */
@media (min-width: 576px) and (max-width: 767px)
{
    .hidden-sm-down, .hidden-md-down, .hidden-lg-down, .hidden-xl-down, 
    .hidden-xs-up, .hidden-sm-up, 
    .hidden-unless-xs, .hidden-unless-md, .hidden-unless-lg, .hidden-unless-xl
    {
        display: none !important;
    } 
}

/* Breakpoint MD */
@media (min-width: 768px) and (max-width: 991px)
{
    .hidden-md-down, .hidden-lg-down, .hidden-xl-down, 
    .hidden-xs-up, .hidden-sm-up, .hidden-md-up, 
    .hidden-unless-xs, .hidden-unless-sm, .hidden-unless-lg, .hidden-unless-xl
    {
        display: none !important;
    } 
}

/* Breakpoint LG */
@media (min-width: 992px) and (max-width: 1199px)
{
    .hidden-lg-down, .hidden-xl-down, 
    .hidden-xs-up, .hidden-sm-up, .hidden-md-up, .hidden-lg-up, 
    .hidden-unless-xs, .hidden-unless-sm, .hidden-unless-md, .hidden-unless-xl
    {
        display: none !important;
    } 
}

/* Breakpoint XL */
@media (min-width: 1200px)
{
    .hidden-xl-down, 
    .hidden-xs-up, .hidden-sm-up, .hidden-md-up, .hidden-lg-up, .hidden-xl-up, 
    .hidden-unless-xs, .hidden-unless-sm, .hidden-unless-md, .hidden-unless-lg
    {
        display: none !important;
    } 
}

The classes hidden-unless-* were not included in Bootstrap 3, but they are useful as well and should be self-explanatory.

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

Git "error: The branch 'x' is not fully merged"

I tried sehe's answer and it did not work.

To find the commits that have not been merged simply use:

git log feature-branch ^master --no-merges

How to recover closed output window in netbeans?

Go to window tab - reset windows - run your program. - then right click on bottom of the tab where program running

wildcard * in CSS for classes

If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes

Configuring Hibernate logging using Log4j XML config file?

From http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging

Here's the list of logger categories:

Category                    Function

org.hibernate.SQL           Log all SQL DML statements as they are executed
org.hibernate.type          Log all JDBC parameters
org.hibernate.tool.hbm2ddl  Log all SQL DDL statements as they are executed
org.hibernate.pretty        Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache         Log all second-level cache activity
org.hibernate.transaction   Log transaction related activity
org.hibernate.jdbc          Log all JDBC resource acquisition
org.hibernate.hql.ast.AST   Log HQL and SQL ASTs during query parsing
org.hibernate.secure        Log all JAAS authorization requests
org.hibernate               Log everything (a lot of information, but very useful for troubleshooting) 

Formatted for pasting into a log4j XML configuration file:

<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />

NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.

And a category is specified as such:

<logger name="org.hibernate">
    <level value="ALL" />
    <appender-ref ref="FILE"/>
</logger>

It must be placed before the root element.

Wait .5 seconds before continuing code VB.net

I've had better results by checking the browsers readystate before continuing to the next step. This will do nothing until the browser is has a "complete" readystate

Do While WebBrowser1.ReadyState <> 4
''' put anything here. 
Loop

How to add header to a dataset in R?

You can also use colnames instead of names if you have data.frame or matrix

PSEXEC, access denied errors

PsExec has whatever access rights its launcher has. It runs under regular Windows access control. This means whoever launched PsExec (be it either you, the scheduler, a service etc.) does not have sufficient rights on the target machine, or the target machine is not configured correctly. The first things to do are:

  1. Make sure the launcher of PsExec is familiar to the target machine, either via the domain or by having the same user and password defined locally on both machines.
  2. Use command line arguments to specify a user that is known to the target machine (-u user -p password)

If this did not solve your problem, make sure the target machine meets the minimum requirements, specified here.

Positioning background image, adding padding

To add space before background image, one could define the 'width' of element which is using 'background-image' object. And then to define a pixel value in 'background-position' property to create space from left side.

For example, I'd a scenario where I got a navigation menu which had a bullet before link item and the bullet graphic were changeable if corrosponding link turns into an active state. Further, the active link also had a background-color to show, and this background-color had approximate 15px padding both on left and right side of link item (so on left, it includes bullet icon of link too).

While padding-right fulfill the purpose to have background-color stretched upto 15px more on right of link text. The padding-left only added to space between link text and bullet.

So I took the width of background-color object from PSD design (for ex. 82px) and added that to li element (in a class created to show active state) and then I set background-position value to 20px. Which resulted in bullet icon shifted inside from the left edge. And its provided me desired output of having left padding before bullet icon used as background image.

Please note, you may need to adjust your padding / margin values accordingly, which may used either for space between link items or for spacing between bullet icon and link text.

What are the pros and cons of parquet format compared to other formats?

Avro is a row-based storage format for Hadoop.

Parquet is a column-based storage format for Hadoop.

If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.

If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.

Source

QtCreator: No valid kits found

I had a similar problems after installing Qt in Windows.

This could be because only the Qt creator was installed and not any of the Qt libraries during initial installation. When installing from scratch use the online installer and select the following to install:

  1. For starting, select at least one version of Qt libs (ex Qt 5.15.1) and the c++ compiler of choice (ex MinGW 8.1.0 64-bit).

  2. Select Developer and Designer Tools. I kept the selected defaults.

Note: The choice of the Qt libs and Tools can also be changed post initial installation using MaintenanceTool.exe under Qt installation dir C:\Qt. See here.

CSS: Set a background color which is 50% of the width of the window

I have used :after and it is working in all major browsers. please check the link. just need to careful for the z-index as after is having position absolute.

<div class="splitBg">
    <div style="max-width:960px; margin:0 auto; padding:0 15px; box-sizing:border-box;">
        <div style="float:left; width:50%; position:relative; z-index:10;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
        </div>
        <div style="float:left; width:50%; position:relative; z-index:10;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, 
        </div>
        <div style="clear:both;"></div>
    </div>
</div>`
css

    .splitBg{
        background-color:#666;
        position:relative;
        overflow:hidden;
        }
    .splitBg:after{
        width:50%;
        position:absolute;
        right:0;
        top:0;
        content:"";
        display:block;
        height:100%;
        background-color:#06F;
        z-index:1;
        }

fiddle link

Create a rounded button / button with border-radius in Flutter

New Elevate Button-------->

    style --->
    
    customElevatedButton({radius, color}) => ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(radius == null ? 100 : radius),
          ),
          primary: color,
        );



icon--->

    Widget saveIcon() => iconsStyle1(
          Icons.save,
        );

//common icon style

    iconsStyle1(icon) => Icon(
          icon,
          color: white,
          size: 15,
        );

button use---> 
    ElevatedButton.icon(
                            icon: saveIcon(),
                            style:
                                customElevatedButton(color: Colors.green[700]),
                            label: Text('Save',
                                style: TextStyle(color: Colors.white)),
                            onPressed: () {
                            },
                          ),

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

How is a tag different from a branch in Git? Which should I use, here?

What you need to realize, coming from CVS, is that you no longer create directories when setting up a branch.
No more "sticky tag" (which can be applied to just one file), or "branch tag".
Branch and tags are two different objects in Git, and they always apply to the all repo.

You would no longer (with SVN this time) have to explicitly structure your repository with:

branches
   myFirstBranch
     myProject
       mySubDirs
   mySecondBranch
     ...
tags
   myFirstTag
     myProject
       mySubDirs
   mySecondTag
   ...

That structure comes from the fact CVS is a revision system and not a version system (see Source control vs. Revision Control?).
That means branches are emulated through tags for CVS, directory copies for SVN.

Your question makes senses if you are used to checkout a tag, and start working in it.
Which you shouldn't ;)
A tag is supposed to represent an immutable content, used only to access it with the guarantee to get the same content every time.

In Git, the history of revisions is a series of commits, forming a graph.
A branch is one path of that graph

x--x--x--x--x # one branch
    \ 
     --y----y # another branch
       1.1
        ^
        |
        # a tag pointing to a commit
  • If you checkout a tag, you will need to create a branch to start working from it.
  • If you checkout a branch, you will directly see the latest commit it('HEAD') of that branch.

See Jakub Narebski's answer for all the technicalities, but frankly, at this point, you do not need (yet) all the details ;)

The main point is: a tag being a simple pointer to a commit, you will never be able to modify its content. You need a branch.


In your case, each developer working on a specific feature:

  • should create their own branch in their respective repository
  • track branches from their colleague's repositories (the one working on the same feature)
  • pulling/pushing in order to share your work with your peers.

Instead of tracking directly the branches of your colleagues, you could track only the branch of one "official" central repository to which everyone pushes his/her work in order to integrate and share everyone's work for this particular feature.

sql delete statement where date is greater than 30 days

Instead of converting to varchar to get just the day (convert(varchar(8), [Date], 112)), I prefer keeping it a datetime field and making it only the date (without the time).

SELECT * FROM Results 
WHERE CONVERT(date, [Date]) >= CONVERT(date, GETDATE())

No module named setuptools

For Python Run This Command

apt-get install -y python-setuptools

For Python 3.

apt-get install -y python3-setuptools

How to highlight cell if value duplicate in same column for google spreadsheet?

While zolley's answer is perfectly right for the question, here's a more general solution for any range, plus explanation:

    =COUNTIF($A$1:$C$50, INDIRECT(ADDRESS(ROW(), COLUMN(), 4))) > 1

Please note that in this example I will be using the range A1:C50. The first parameter ($A$1:$C$50) should be replaced with the range on which you would like to highlight duplicates!


to highlight duplicates:

  1. Select the whole range on which the duplicate marking is wanted.
  2. On the menu: Format > Conditional formatting...
  3. Under Apply to range, select the range to which the rule should be applied.
  4. In Format cells if, select Custom formula is on the dropdown.
  5. In the textbox insert the given formula, adjusting the range to match step (3).

Why does it work?

COUNTIF(range, criterion), will compare every cell in range to the criterion, which is processed similarly to formulas. If no special operators are provided, it will compare every cell in the range with the given cell, and return the number of cells found to be matching the rule (in this case, the comparison). We are using a fixed range (with $ signs) so that we always view the full range.

The second block, INDIRECT(ADDRESS(ROW(), COLUMN(), 4)), will return current cell's content. If this was placed inside the cell, docs will have cried about circular dependency, but in this case, the formula is evaluated as if it was in the cell, without changing it.

ROW() and COLUMN() will return the row number and column number of the given cell respectively. If no parameter is provided, the current cell will be returned (this is 1-based, for example, B3 will return 3 for ROW(), and 2 for COLUMN()).

Then we use: ADDRESS(row, column, [absolute_relative_mode]) to translate the numeric row and column to a cell reference (like B3. Remember, while we are inside the cell's context, we don't know it's address OR content, and we need the content in order to compare with). The third parameter takes care for the formatting, and 4 returns the formatting INDIRECT() likes.

INDIRECT(), will take a cell reference and return its content. In this case, the current cell's content. Then back to the start, COUNTIF() will test every cell in the range against ours, and return the count.

The last step is making our formula return a boolean, by making it a logical expression: COUNTIF(...) > 1. The > 1 is used because we know there's at least one cell identical to ours. That's our cell, which is in the range, and thus will be compared to itself. So to indicate a duplicate, we need to find 2 or more cells matching ours.


Sources:

How to drop SQL default constraint without knowing its name?

Expanding on Mitch Wheat's code, the following script will generate the command to drop the constraint and dynamically execute it.

declare @schema_name nvarchar(256)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command  nvarchar(1000)

set @schema_name = N'MySchema'
set @table_name = N'Department'
set @col_name = N'ModifiedDate'

select @Command = 'ALTER TABLE ' + @schema_name + '.[' + @table_name + '] DROP CONSTRAINT ' + d.name
 from sys.tables t
  join sys.default_constraints d on d.parent_object_id = t.object_id
  join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
 where t.name = @table_name
  and t.schema_id = schema_id(@schema_name)
  and c.name = @col_name

--print @Command

execute (@Command)

CSS3 Transparency + Gradient

Here is my code:

background: #e8e3e3; /* Old browsers */
  background: -moz-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%, rgba(246, 242, 242, 0.95) 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(232, 227, 227, 0.95)), color-stop(100%,rgba(246, 242, 242, 0.95))); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* IE10+ */
  background: linear-gradient(to bottom,  rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='rgba(232, 227, 227, 0.95)', endColorstr='rgba(246, 242, 242, 0.95)',GradientType=0 ); /* IE6-9 */

Android ACTION_IMAGE_CAPTURE Intent

To follow up on Yenchi's comment above, the OK button will also do nothing if the camera app can't write to the directory in question.

That means that you can't create the file in a place that's only writeable by your application (for instance, something under getCacheDir()) Something under getExternalFilesDir() ought to work, however.

It would be nice if the camera app printed an error message to the logs if it could not write to the specified EXTRA_OUTPUT path, but I didn't find one.

How to remove a package in sublime text 2

Simple steps for remove any package from Sublime as phpfmt, Xdebug etc..

1- Go to Sublime menu-> Preference or press Ctrl+Shift+P .
2- Choose -> Remove package option, after you choosing it will display all   packge installed in your sublime, select one of them.
3. After selection it will remove, or for better you can restart your system.

How can I get file extensions with JavaScript?

"one-liner" to get filename and extension using reduce and array destructuring :

_x000D_
_x000D_
var str = "filename.with_dot.png";_x000D_
var [filename, extension] = str.split('.').reduce((acc, val, i, arr) => (i == arr.length - 1) ? [acc[0].substring(1), val] : [[acc[0], val].join('.')], [])_x000D_
_x000D_
console.log({filename, extension});
_x000D_
_x000D_
_x000D_

with better indentation :

var str = "filename.with_dot.png";
var [filename, extension] = str.split('.')
   .reduce((acc, val, i, arr) => (i == arr.length - 1) 
       ? [acc[0].substring(1), val] 
       : [[acc[0], val].join('.')], [])


console.log({filename, extension});

// {
//   "filename": "filename.with_dot",
//   "extension": "png"
// }

Count number of iterations in a foreach loop

Imagine a counter with an initial value of 0.

For every loop, increment the counter value by 1 using $counter = 0;

The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:

$counter = 0;
foreach ($Contents as $item) {
    $counter++;
    $item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}

Try that.

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

This is resolved. The problem was elsewhere. Another code in cron job was truncating XML to 0 length file. I have taken care of that.

Make an HTTP request with android

With a thread:

private class LoadingThread extends Thread {
    Handler handler;

    LoadingThread(Handler h) {
        handler = h;
    }
    @Override
    public void run() {
        Message m = handler.obtainMessage();
        try {
            BufferedReader in = 
                new BufferedReader(new InputStreamReader(url.openStream()));
            String page = "";
            String inLine;

            while ((inLine = in.readLine()) != null) {
                page += inLine;
            }

            in.close();
            Bundle b = new Bundle();
            b.putString("result", page);
            m.setData(b);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        handler.sendMessage(m);
    }
}

How can I convert JSON to CSV?

This is a modification of @MikeRepass's answer. This version writes the CSV to a file, and works for both Python 2 and Python 3.

import csv,json
input_file="data.json"
output_file="data.csv"
with open(input_file) as f:
    content=json.load(f)
try:
    context=open(output_file,'w',newline='') # Python 3
except TypeError:
    context=open(output_file,'wb') # Python 2
with context as file:
    writer=csv.writer(file)
    writer.writerow(content[0].keys()) # header row
    for row in content:
        writer.writerow(row.values())

Allowed characters in filename

You should start with the Wikipedia Filename page. It has a decent-sized table (Comparison of filename limitations), listing the reserved characters for quite a lot of file systems.

It also has a plethora of other information about each file system, including reserved file names such as CON under MS-DOS. I mention that only because I was bitten by that once when I shortened an include file from const.h to con.h and spent half an hour figuring out why the compiler hung.

Turns out DOS ignored extensions for devices so that con.h was exactly the same as con, the input console (meaning, of course, the compiler was waiting for me to type in the header file before it would continue).

Importing data from a JSON file into R

First install the RJSONIO and RCurl package:

_x000D_
_x000D_
install.packages("RJSONIO")_x000D_
install.packages("(RCurl")
_x000D_
_x000D_
_x000D_

Try below code using RJSONIO in console

_x000D_
_x000D_
library(RJSONIO)_x000D_
library(RCurl)_x000D_
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")_x000D_
json_file2 = RJSONIO::fromJSON(json_file)_x000D_
head(json_file2)
_x000D_
_x000D_
_x000D_

call javascript function on hyperlink click

Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.

Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:

[c# example only probably not the way you're writing out your js]
Response.Write("<a href=\"/link/for/javascriptDisabled/Browsers.aspx\" id=\"uxAncMyLink\">My Link</a>");

[Javascript]  
document.getElementById('uxAncMyLink').onclick = function(e){

// do some stuff here

    return false;
    }

That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.

Hope that is of use.

RegEx: Grabbing values between quotation marks

The RegEx of accepted answer returns the values including their sourrounding quotation marks: "Foo Bar" and "Another Value" as matches.

Here are RegEx which return only the values between quotation marks (as the questioner was asking for):

Double quotes only (use value of capture group #1):

"(.*?[^\\])"

Single quotes only (use value of capture group #1):

'(.*?[^\\])'

Both (use value of capture group #2):

(["'])(.*?[^\\])\1

-

All support escaped and nested quotes.

Oracle SQL query for Date format

you can use this command by getting your data. this will extract your data...

select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

If you're generating your javascript with a php file, add this as the beginning of your file:

<?php Header("Content-Type: application/x-javascript; charset=UTF-8"); ?>

DateTime format to SQL format using C#

Your problem is in the "Date" property that truncates DateTime to date only. You could put the conversion like this:

DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss"); // <- No Date.ToString()!

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Firebug like plugin for Safari browser

Firebug is great, but Safari provides its own built-in development tools.

If you haven't already tried Safari's development kit, go to Safari-->Preferences-->Advanced, and check the box next to "Show Develop menu in menu bar".

Once you have the Develop menu enabled, you can use the Web Inspector to get a lot of the same functionality that Firebug provides.

Applying an ellipsis to multiline text

_x000D_
_x000D_
p {_x000D_
    width:100%;_x000D_
    overflow: hidden;_x000D_
    display: -webkit-box;_x000D_
    -webkit-line-clamp: 2;_x000D_
    -webkit-box-orient: vertical;_x000D_
    background:#fff;_x000D_
    position:absolute;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>
_x000D_
_x000D_
_x000D_

What does mvn install in maven exactly do

As you might be aware of, Maven is a build automation tool provided by Apache which does more than dependency management. We can make it as a peer of Ant and Makefile which downloads all of the dependencies required.

On a mvn install, it frames a dependency tree based on the project configuration pom.xml on all the sub projects under the super pom.xml (the root POM) and downloads/compiles all the needed components in a directory called .m2 under the user's folder. These dependencies will have to be resolved for the project to be built without any errors, and mvn install is one utility that could download most of the dependencies.

Further, there are other utils within Maven like dependency:resolve which can be used separately in any specific cases. The build life cycle of the mvn is as below: LifeCycle Bindings

  1. process-resources
  2. compile
  3. process-test-resources
  4. test-compile
  5. test
  6. package
  7. install
  8. deploy

The test phase of this mvn can be ignored by using a flag -DskipTests=true.

How to convert a char array back to a string?

Try to use java.util.Arrays. This module has a variety of useful methods that could be used related to Arrays.

Arrays.toString(your_array_here[]);

inner join in linq to entities

Not 100% sure about the relationship between these two entities but here goes:

IList<Splitting> res = (from s in [data source]
                        where s.Customer.CompanyID == [companyID] &&
                              s.CustomerID == [customerID]
                        select s).ToList();

IList<Splitting> res = [data source].Splittings.Where(
                           x => x.Customer.CompanyID == [companyID] &&
                                x.CustomerID == [customerID]).ToList();

How to send email to multiple recipients with addresses stored in Excel?

Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :

                Dim Splitter() As String
                Splitter = Split(AddrMail, ";")
                For Each Dest In Splitter
                    .Recipients.Add (Trim(Dest))
                Next

Excel formula to search if all cells in a range read "True", if not, then show "False"

=IF(COUNTIF(A1:D1,FALSE)>0,FALSE,TRUE)

(or you can specify any other range to look in)

Using a Python subprocess call to invoke a Python script

First, check if somescript.py is executable and starts with something along the lines of #!/usr/bin/python. If this is done, then you can use subprocess.call('./somescript.py').

Or as another answer points out, you could do subprocess.call(['python', 'somescript.py']).

Programmatically extract contents of InstallShield setup.exe

There's no supported way to do this, but won't you have to examine the files related to each installer to figure out how to actually install them after extracting them? Assuming you can spend the time to figure out which command-line applies, here are some candidate parameters that normally allow you to extract an installation.

MSI Based (may not result in a usable image for an InstallScript MSI installation):

  • setup.exe /a /s /v"/qn TARGETDIR=\"choose-a-location\""

    or, to also extract prerequisites (for versions where it works),

  • setup.exe /a"choose-another-location" /s /v"/qn TARGETDIR=\"choose-a-location\""

InstallScript based:

  • setup.exe /s /extract_all

Suite based (may not be obvious how to install the resulting files):

  • setup.exe /silent /stage_only ISRootStagePath="choose-a-location"

Webfont Smoothing and Antialiasing in Firefox and Opera

When the color of text is dark, in Safari and Chrome, I have better result with the text-stroke css property.

-webkit-text-stroke: 0.5px #000;

How can I count the numbers of rows that a MySQL query returned?

This is not a direct answer to the question, but in practice I often want to have an estimate of the number of rows that will be in the result set. For most type of queries, MySQL's "EXPLAIN" delivers that.

I for example use that to refuse to run a client query if the explain looks bad enough.

Then also daily run "ANALYZE LOCAL TABLE" (outside of replication, to prevent cluster locks) on your tables, on each involved MySQL server.

TypeError: 'str' object cannot be interpreted as an integer

x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

for i in range(x, y):
    print(i)

This outputs:

i have uploaded the output with the code

Get current time in seconds since the Epoch on Linux, Bash

use this bash script (my ~/bin/epoch):

#!/bin/bash

# get seconds since epoch
test "x$1" == x && date +%s && exit 0

# or convert epoch seconds to date format (see "man date" for options)
EPOCH="$1"
shift
date -d @"$EPOCH" "$@"

How to select the row with the maximum value in each group

I wasn't sure what you wanted to do about the Event column, but if you want to keep that as well, how about

isIDmax <- with(dd, ave(Value, ID, FUN=function(x) seq_along(x)==which.max(x)))==1
group[isIDmax, ]

#   ID Value Event
# 3  1     5     2
# 7  2    17     2
# 9  3     5     2

Here we use ave to look at the "Value" column for each "ID". Then we determine which value is the maximal and then turn that into a logical vector we can use to subset the original data.frame.

How to find longest string in the table column data

You can:

SELECT CR 
FROM table1 
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)

Having just recieved an upvote more than a year after posting this, I'd like to add some information.

  • This query gives all values with the maximum length. With a TOP 1 query you get only one of these, which is usually not desired.
  • This query must probably read the table twice: a full table scan to get the maximum length and another full table scan to get all values of that length. These operations, however, are very simple operations and hence rather fast. With a TOP 1 query a DBMS reads all records from the table and then sorts them. So the table is read only once, but a sort operation on a whole table is quite some task and can be very slow on large tables.
  • One would usually add DISTINCT to my query (SELECT DISTINCT CR FROM ...), so as to get every value just once. That would be a sort operation, but only on the few records already found. Again, no big deal.
  • If the string lengths have to be dealt with quite often, one might think of creating a computed column (calculated field) for it. This is available as of Ms Access 2010. But reading up on this shows that you cannot index calculated fields in MS Access. As long as this holds true, there is hardly any benefit from them. Applying LEN on the strings is usually not what makes such queries slow.

Exposing a port on a live Docker container

You cannot do this via Docker, but you can access the container's un-exposed port from the host machine.

If you have a container with something running on its port 8000, you can run

wget http://container_ip:8000

To get the container's IP address, run the 2 commands:

docker ps
docker inspect container_name | grep IPAddress

Internally, Docker shells out to call iptables when you run an image, so maybe some variation on this will work.

To expose the container's port 8000 on your localhost's port 8001:

iptables -t nat -A  DOCKER -p tcp --dport 8001 -j DNAT --to-destination 172.17.0.19:8000

One way you can work this out is to setup another container with the port mapping you want, and compare the output of the iptables-save command (though, I had to remove some of the other options that force traffic to go via the docker proxy).

NOTE: this is subverting docker, so should be done with the awareness that it may well create blue smoke.

OR

Another alternative is to look at the (new? post 0.6.6?) -P option - which will use random host ports, and then wire those up.

OR

With 0.6.5, you could use the LINKs feature to bring up a new container that talks to the existing one, with some additional relaying to that container's -p flags? (I have not used LINKs yet.)

OR

With docker 0.11? you can use docker run --net host .. to attach your container directly to the host's network interfaces (i.e., net is not namespaced) and thus all ports you open in the container are exposed.

Truncating a table in a stored procedure

try the below code

execute immediate 'truncate table tablename' ;

Convert tabs to spaces in Notepad++

You need to replace \t - make sure you use extended mode!

Replace

Looping through JSON with node.js

Not sure if it helps, but it looks like there might be a library for async iteration in node hosted here:

https://github.com/caolan/async

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with node.js, it can also be used directly in the browser.

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, forEach…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the node.js convention of providing a single callback as the last argument of your async function.

generate days from date range

Shorter than accepted answer, same idea:

(SELECT TRIM('2016-01-05' + INTERVAL a + b DAY) date
FROM
(SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
UNION SELECT 8 UNION SELECT 9 ) d,
(SELECT 0 b UNION SELECT 10 UNION SELECT 20
UNION SELECT 30 UNION SELECT 40) m
WHERE '2016-01-05' + INTERVAL a + b DAY  <=  '2016-01-21')

How to get SQL from Hibernate Criteria API (*not* for logging)

I like this if you want to get just some parts of the query:

new CriteriaQueryTranslator(
    factory,
    executableCriteria,
    executableCriteria.getEntityOrClassName(), 
    CriteriaQueryTranslator.ROOT_SQL_ALIAS)
        .getWhereCondition();

For instance something like this:

String where = new CriteriaQueryTranslator(
    factory,
    executableCriteria,
    executableCriteria.getEntityOrClassName(), 
    CriteriaQueryTranslator.ROOT_SQL_ALIAS)
        .getWhereCondition();

String sql = "update my_table this_ set this_.status = 0 where " + where;

Different color for each bar in a bar chart; ChartJS

If you're not able to use NewChart.js you just need to change the way to set the color using array instead. Find the helper iteration inside Chart.js:

Replace this line:

fillColor : dataset.fillColor,

For this one:

fillColor : dataset.fillColor[index],

The resulting code:

//Iterate through each of the datasets, and build this into a property of the chart
  helpers.each(data.datasets,function(dataset,datasetIndex){

    var datasetObject = {
      label : dataset.label || null,
      fillColor : dataset.fillColor,
      strokeColor : dataset.strokeColor,
      bars : []
    };

    this.datasets.push(datasetObject);

    helpers.each(dataset.data,function(dataPoint,index){
      //Add a new point for each piece of data, passing any required data to draw.
      datasetObject.bars.push(new this.BarClass({
        value : dataPoint,
        label : data.labels[index],
        datasetLabel: dataset.label,
        strokeColor : dataset.strokeColor,
        //Replace this -> fillColor : dataset.fillColor,
        // Whith the following:
        fillColor : dataset.fillColor[index],
        highlightFill : dataset.highlightFill || dataset.fillColor,
        highlightStroke : dataset.highlightStroke || dataset.strokeColor
      }));
    },this);

  },this);

And in your js:

datasets: [
                {
                  label: "My First dataset",
                  fillColor: ["rgba(205,64,64,0.5)", "rgba(220,220,220,0.5)", "rgba(24,178,235,0.5)", "rgba(220,220,220,0.5)"],
                  strokeColor: "rgba(220,220,220,0.8)",
                  highlightFill: "rgba(220,220,220,0.75)",
                  highlightStroke: "rgba(220,220,220,1)",
                  data: [2000, 1500, 1750, 50]
                }
              ]

How to set a CheckBox by default Checked in ASP.Net MVC

You could set your property in the model's constructor

public YourModel()
{
    As = true;
}

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

I just kept it simple. I created a list of items with the enum values in my ViewModel:

public enum InputsOutputsBoth
{
    Inputs,
    Outputs,
    Both
}

private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>() 
{ 
    InputsOutputsBoth.Both, 
    InputsOutputsBoth.Inputs, 
    InputsOutputsBoth.Outputs 
};

public IEnumerable<InputsOutputsBoth> IoTypes
{
    get { return _ioTypes; }
    set { }
}

private InputsOutputsBoth _selectedIoType;

public InputsOutputsBoth SelectedIoType
{
    get { return _selectedIoType; }
    set
    {
        _selectedIoType = value;
        OnPropertyChanged("SelectedIoType");
        OnSelectionChanged();
    }
}

In my xaml code I just need this:

<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">

Adding integers to an int array

you have an array of int which is a primitive type, primitive type doesn't have the method add. You should look for Collections.

Python Timezone conversion

Please note: The first part of this answer is or version 1.x of pendulum. See below for a version 2.x answer.

I hope I'm not too late!

The pendulum library excels at this and other date-time calculations.

>>> import pendulum
>>> some_time_zones = ['Europe/Paris', 'Europe/Moscow', 'America/Toronto', 'UTC', 'Canada/Pacific', 'Asia/Macao']
>>> heres_a_time = '1996-03-25 12:03 -0400'
>>> pendulum_time = pendulum.datetime.strptime(heres_a_time, '%Y-%m-%d %H:%M %z')
>>> for tz in some_time_zones:
...     tz, pendulum_time.astimezone(tz)
...     
('Europe/Paris', <Pendulum [1996-03-25T17:03:00+01:00]>)
('Europe/Moscow', <Pendulum [1996-03-25T19:03:00+03:00]>)
('America/Toronto', <Pendulum [1996-03-25T11:03:00-05:00]>)
('UTC', <Pendulum [1996-03-25T16:03:00+00:00]>)
('Canada/Pacific', <Pendulum [1996-03-25T08:03:00-08:00]>)
('Asia/Macao', <Pendulum [1996-03-26T00:03:00+08:00]>)

Answer lists the names of the time zones that may be used with pendulum. (They're the same as for pytz.)

For version 2:

  • some_time_zones is a list of the names of the time zones that might be used in a program
  • heres_a_time is a sample time, complete with a time zone in the form '-0400'
  • I begin by converting the time to a pendulum time for subsequent processing
  • now I can show what this time is in each of the time zones in show_time_zones

...

>>> import pendulum
>>> some_time_zones = ['Europe/Paris', 'Europe/Moscow', 'America/Toronto', 'UTC', 'Canada/Pacific', 'Asia/Macao']
>>> heres_a_time = '1996-03-25 12:03 -0400'
>>> pendulum_time = pendulum.from_format('1996-03-25 12:03 -0400', 'YYYY-MM-DD hh:mm ZZ')
>>> for tz in some_time_zones:
...     tz, pendulum_time.in_tz(tz)
...     
('Europe/Paris', DateTime(1996, 3, 25, 17, 3, 0, tzinfo=Timezone('Europe/Paris')))
('Europe/Moscow', DateTime(1996, 3, 25, 19, 3, 0, tzinfo=Timezone('Europe/Moscow')))
('America/Toronto', DateTime(1996, 3, 25, 11, 3, 0, tzinfo=Timezone('America/Toronto')))
('UTC', DateTime(1996, 3, 25, 16, 3, 0, tzinfo=Timezone('UTC')))
('Canada/Pacific', DateTime(1996, 3, 25, 8, 3, 0, tzinfo=Timezone('Canada/Pacific')))
('Asia/Macao', DateTime(1996, 3, 26, 0, 3, 0, tzinfo=Timezone('Asia/Macao')))

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I do some quick tests and have the following findings:

1) if using SynchronousQueue:

After the threads reach the maximum size, any new work will be rejected with the exception like below.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)

2) if using LinkedBlockingQueue:

The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.

How to grep a string in a directory and all its subdirectories?

grep -r -e string directory

-r is for recursive; -e is optional but its argument specifies the regex to search for. Interestingly, POSIX grep is not required to support -r (or -R), but I'm practically certain that System V grep did, so in practice they (almost) all do. Some versions of grep support -R as well as (or conceivably instead of) -r; AFAICT, it means the same thing.

Split an NSString to access one particular piece

Either of these 2:

NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];

Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.

The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.

Where can I download IntelliJ IDEA Color Schemes?

Here is a theme I created which was inspired by GitHub's embedded source view. I love how elegant their color scheme is, but lately I prefer a darker theme. This is theme is only for Java. Sorry. Download it here: GitHubInspiredDark.xml

Inspired by GitHub

Delete ActionLink with confirm dialog

Using webgrid you can found it here, the action links could look like the following.

enter image description here

    grid.Column(header: "Action", format: (item) => new HtmlString(
                     Html.ActionLink(" ", "Details", new { Id = item.Id }, new { @class = "glyphicon glyphicon-info-sign" }).ToString() + " | " +
                     Html.ActionLink(" ", "Edit", new { Id = item.Id }, new { @class = "glyphicon glyphicon-edit" }).ToString() + " | " +
                     Html.ActionLink(" ", "Delete", new { Id = item.Id }, new { onclick = "return confirm('Are you sure you wish to delete this property?');", @class = "glyphicon glyphicon-trash" }).ToString()
                )

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

Generating a drop down list of timezones with PHP

$timezone = array(
    'Pacific/Midway' => '(GMT-11:00) Midway Island, Samoa',
    'America/Adak' => '(GMT-10:00) Hawaii-Aleutian',
    'Etc/GMT+10' => '(GMT-10:00) Hawaii',
    'Pacific/Marquesas' => '(GMT-09:30) Marquesas Islands',
    'Pacific/Gambier' => '(GMT-09:00) Gambier Islands',
    'America/Anchorage' => '(GMT-09:00) Alaska',
    'America/Ensenada' => '(GMT-08:00) Tijuana, Baja California',
    'Etc/GMT+8' => '(GMT-08:00) Pitcairn Islands',
    'America/Los_Angeles' => '(GMT-08:00) Pacific Time (US & Canada)',
    'America/Denver' => '(GMT-07:00) Mountain Time (US & Canada)',
    'America/Chihuahua' => '(GMT-07:00) Chihuahua, La Paz, Mazatlan',
    'America/Dawson_Creek' => '(GMT-07:00) Arizona',
    'America/Belize' => '(GMT-06:00) Saskatchewan, Central America',
    'America/Cancun' => '(GMT-06:00) Guadalajara, Mexico City, Monterrey',
    'Chile/EasterIsland' => '(GMT-06:00) Easter Island',
    'America/Chicago' => '(GMT-06:00) Central Time (US & Canada)',
    'America/New_York' => '(GMT-05:00) Eastern Time (US & Canada)',
    'America/Havana' => '(GMT-05:00) Cuba',
    'America/Bogota' => '(GMT-05:00) Bogota, Lima, Quito, Rio Branco',
    'America/Caracas' => '(GMT-04:30) Caracas',
    'America/Santiago' => '(GMT-04:00) Santiago',
    'America/La_Paz' => '(GMT-04:00) La Paz',
    'Atlantic/Stanley' => '(GMT-04:00) Faukland Islands',
    'America/Campo_Grande' => '(GMT-04:00) Brazil',
    'America/Goose_Bay' => '(GMT-04:00) Atlantic Time (Goose Bay)',
    'America/Glace_Bay' => '(GMT-04:00) Atlantic Time (Canada)',
    'America/St_Johns' => '(GMT-03:30) Newfoundland',
    'America/Araguaina' => '(GMT-03:00) UTC-3',
    'America/Montevideo' => '(GMT-03:00) Montevideo',
    'America/Miquelon' => '(GMT-03:00) Miquelon, St. Pierre',
    'America/Godthab' => '(GMT-03:00) Greenland',
    'America/Argentina/Buenos_Aires' => '(GMT-03:00) Buenos Aires',
    'America/Sao_Paulo' => '(GMT-03:00) Brasilia',
    'America/Noronha' => '(GMT-02:00) Mid-Atlantic',
    'Atlantic/Cape_Verde' => '(GMT-01:00) Cape Verde Is.',
    'Atlantic/Azores' => '(GMT-01:00) Azores',
    'Europe/Belfast' => '(GMT) Greenwich Mean Time : Belfast',
    'Europe/Dublin' => '(GMT) Greenwich Mean Time : Dublin',
    'Europe/Lisbon' => '(GMT) Greenwich Mean Time : Lisbon',
    'Europe/London' => '(GMT) Greenwich Mean Time : London',
    'Africa/Abidjan' => '(GMT) Monrovia, Reykjavik',
    'Europe/Amsterdam' => '(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'Europe/Belgrade' => '(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague',
    'Europe/Brussels' => '(GMT+01:00) Brussels, Copenhagen, Madrid, Paris',
    'Africa/Algiers' => '(GMT+01:00) West Central Africa',
    'Africa/Windhoek' => '(GMT+01:00) Windhoek',
    'Asia/Beirut' => '(GMT+02:00) Beirut',
    'Africa/Cairo' => '(GMT+02:00) Cairo',
    'Asia/Gaza' => '(GMT+02:00) Gaza',
    'Africa/Blantyre' => '(GMT+02:00) Harare, Pretoria',
    'Asia/Jerusalem' => '(GMT+02:00) Jerusalem',
    'Europe/Minsk' => '(GMT+02:00) Minsk',
    'Asia/Damascus' => '(GMT+02:00) Syria',
    'Europe/Moscow' => '(GMT+03:00) Moscow, St. Petersburg, Volgograd',
    'Africa/Addis_Ababa' => '(GMT+03:00) Nairobi',
    'Asia/Tehran' => '(GMT+03:30) Tehran',
    'Asia/Dubai' => '(GMT+04:00) Abu Dhabi, Muscat',
    'Asia/Yerevan' => '(GMT+04:00) Yerevan',
    'Asia/Kabul' => '(GMT+04:30) Kabul',
    'Asia/Yekaterinburg' => '(GMT+05:00) Ekaterinburg',
    'Asia/Tashkent' => '(GMT+05:00) Tashkent',
    'Asia/Kolkata' => '(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi',
    'Asia/Katmandu' => '(GMT+05:45) Kathmandu',
    'Asia/Dhaka' => '(GMT+06:00) Astana, Dhaka',
    'Asia/Novosibirsk' => '(GMT+06:00) Novosibirsk',
    'Asia/Rangoon' => '(GMT+06:30) Yangon (Rangoon)',
    'Asia/Bangkok' => '(GMT+07:00) Bangkok, Hanoi, Jakarta',
    'Asia/Krasnoyarsk' => '(GMT+07:00) Krasnoyarsk',
    'Asia/Hong_Kong' => '(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi',
    'Asia/Irkutsk' => '(GMT+08:00) Irkutsk, Ulaan Bataar',
    'Australia/Perth' => '(GMT+08:00) Perth',
    'Australia/Eucla' => '(GMT+08:45) Eucla',
    'Asia/Tokyo' => '(GMT+09:00) Osaka, Sapporo, Tokyo',
    'Asia/Seoul' => '(GMT+09:00) Seoul',
    'Asia/Yakutsk' => '(GMT+09:00) Yakutsk',
    'Australia/Adelaide' => '(GMT+09:30) Adelaide',
    'Australia/Darwin' => '(GMT+09:30) Darwin',
    'Australia/Brisbane' => '(GMT+10:00) Brisbane',
    'Australia/Hobart' => '(GMT+10:00) Hobart',
    'Asia/Vladivostok' => '(GMT+10:00) Vladivostok',
    'Australia/Lord_Howe' => '(GMT+10:30) Lord Howe Island',
    'Etc/GMT-11' => '(GMT+11:00) Solomon Is., New Caledonia',
    'Asia/Magadan' => '(GMT+11:00) Magadan',
    'Pacific/Norfolk' => '(GMT+11:30) Norfolk Island',
    'Asia/Anadyr' => '(GMT+12:00) Anadyr, Kamchatka',
    'Pacific/Auckland' => '(GMT+12:00) Auckland, Wellington',
    'Etc/GMT-12' => '(GMT+12:00) Fiji, Kamchatka, Marshall Is.',
    'Pacific/Chatham' => '(GMT+12:45) Chatham Islands',
    'Pacific/Tongatapu' => '(GMT+13:00) Nukualofa',
    'Pacific/Kiritimati' => '(GMT+14:00) Kiritimati',

date_default_timezone_set($timezone);

jQuery Validation plugin: validate check box

There is the easy way

HTML:

<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]"  />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>

JQUERY:

$("#submit").on("click",function(){
    if (($("input[name*='test']:checked").length)<=0) {
        alert("You must check at least 1 box");
    }
    return true;
});

For this you not need any plugin. Enjoy;)

How do I Merge two Arrays in VBA?

Try this:

arr3 = Split(Join(arr1, ",") & "," & Join(arr2, ","), ",") 

How to remove any URL within a string in Python

I wasn't able to find any that handled my particular situation, which was removing urls in the middle of tweets that also have whitespaces in the middle of urls so I made my own:

(https?:\/\/)(\s)*(www\.)?(\s)*((\w|\s)+\.)*([\w\-\s]+\/)*([\w\-]+)((\?)?[\w\s]*=\s*[\w\%&]*)*

here's an explanation:
(https?:\/\/) matches http:// or https://
(\s)* optional whitespaces
(www\.)? optionally matches www.
(\s)* optionally matches whitespaces
((\w|\s)+\.)* matches 0 or more of one or more word characters followed by a period
([\w\-\s]+\/)* matches 0 or more of one or more words(or a dash or a space) followed by '\'
([\w\-]+) any remaining path at the end of the url followed by an optional ending
((\?)?[\w\s]*=\s*[\w\%&]*)* matches ending query params (even with white spaces,etc)

test this out here:https://regex101.com/r/NmVGOo/8

How do I reference a local image in React?

You have two ways to do it.

First

Import the image on top of the class and then reference it in your <img/> element like this

_x000D_
_x000D_
import React, { Component } from 'react';
import myImg from '../path/myImg.svg';

export default class HelloImage extends Component {
  render() {
    return <img src={myImg} width="100" height="50" /> 
  }
} 
_x000D_
_x000D_
_x000D_

Second

You can directly specify the image path using require('../pathToImh/img') in <img/> element like this

_x000D_
_x000D_
import React, { Component } from 'react'; 

export default class HelloImage extends Component {
  render() {
    return <img src={require(../path/myImg.svg)} width="100" height="50" /> 
  }
}
_x000D_
_x000D_
_x000D_

How to convert object to Dictionary<TKey, TValue> in C#?

Another option is to use NewtonSoft.JSON.

var dictionary = JObject.FromObject(anObject).ToObject<Dictionary<string, object>>();

Write a formula in an Excel Cell using VBA

Treb, Matthieu's problem was caused by using Excel in a non-English language. In many language versions ";" is the correct separator. Even functions are translated (SUM can be SOMMA, SUMME or whatever depending on what language you work in). Excel will generally understand these differences and if a French-created workbook is opened by a Brazilian they will normally not have any problem. But VBA speaks only US English so for those of us working in one (or more) foreign langauges, this can be a headache. You and CharlesB both gave answers that would have been OK for a US user but Mikko understod the REAL problem and gave the correct answer (which was also the correct one for me too - I'm a Brit working in Italy for a German-speaking company).

Split Java String by New Line

In JDK11 the String class has a lines() method:

Returning a stream of lines extracted from this string, separated by line terminators.

Further, the documentation goes on to say:

A line terminator is one of the following: a line feed character "\n" (U+000A), a carriage return character "\r" (U+000D), or a carriage return followed immediately by a line feed "\r\n" (U+000D U+000A). A line is either a sequence of zero or more characters followed by a line terminator, or it is a sequence of one or more characters followed by the end of the string. A line does not include the line terminator.

With this one can simply do:

Stream<String> stream = str.lines();

then if you want an array:

String[] array = str.lines().toArray(String[]::new);

Given this method returns a Stream it upon up a lot of options for you as it enables one to write concise and declarative expression of possibly-parallel operations.

Assigning a function to a variable

You simply don't call the function.

>>>def x():
>>>    print(20)
>>>y = x
>>>y()
20

The brackets tell python that you are calling the function, so when you put them there, it calls the function and assigns y the value returned by x (which in this case is None).

CKEditor automatically strips classes from div

Disabling content filtering

The easiest solution is going to the config.js and setting:

config.allowedContent = true;

(Remember to clear browser's cache). Then CKEditor stops filtering the inputted content at all. However, this will totally disable content filtering which is one of the most important CKEditor features.

Configuring content filtering

You can also configure CKEditor's content filter more precisely to allow only these element, classes, styles and attributes which you need. This solution is much better, because CKEditor will still remove a lot of crappy HTML which browsers produce when copying and pasting content, but it will not strip the content you want.

For example, you can extend the default CKEditor's configuration to accept all div classes:

config.extraAllowedContent = 'div(*)';

Or some Bootstrap stuff:

config.extraAllowedContent = 'div(col-md-*,container-fluid,row)';

Or you can allow description lists with optional dir attributes for dt and dd elements:

config.extraAllowedContent = 'dl; dt dd[dir]';

These were just very basic examples. You can write all kind of rules - requiring attributes, classes or styles, matching only special elements, matching all elements. You can also disallow stuff and totally redefine CKEditor's rules. Read more about:

Cannot add or update a child row: a foreign key constraint fails

Delete indexes of the UserID field of table2. Its suits for me

Casting interfaces for deserialization in JSON.NET

To enable deserialization of multiple implementations of interfaces, you can use JsonConverter, but not through an attribute:

Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Converters.Add(new DTOJsonConverter());
Interfaces.IEntity entity = serializer.Deserialize(jsonReader);

DTOJsonConverter maps each interface with a concrete implementation:

class DTOJsonConverter : Newtonsoft.Json.JsonConverter
{
    private static readonly string ISCALAR_FULLNAME = typeof(Interfaces.IScalar).FullName;
    private static readonly string IENTITY_FULLNAME = typeof(Interfaces.IEntity).FullName;


    public override bool CanConvert(Type objectType)
    {
        if (objectType.FullName == ISCALAR_FULLNAME
            || objectType.FullName == IENTITY_FULLNAME)
        {
            return true;
        }
        return false;
    }

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
    {
        if (objectType.FullName == ISCALAR_FULLNAME)
            return serializer.Deserialize(reader, typeof(DTO.ClientScalar));
        else if (objectType.FullName == IENTITY_FULLNAME)
            return serializer.Deserialize(reader, typeof(DTO.ClientEntity));

        throw new NotSupportedException(string.Format("Type {0} unexpected.", objectType));
    }

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

DTOJsonConverter is required only for the deserializer. The serialization process is unchanged. The Json object do not need to embed concrete types names.

This SO post offers the same solution one step further with a generic JsonConverter.

What is the "Temporary ASP.NET Files" folder for?

The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

DECLARE @table_name varchar(max)='tableName'--which needs to be exported
DECLARE @fileName varchar(max)='file Name'--What would be file name

DECLARE @query varchar(8000)
DECLARE @columnHeader VARCHAR(max)
SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+ ''''+column_name +''''  FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name

DECLARE @ColumnList VARCHAR(max)
SELECT @ColumnList = COALESCE(@ColumnList+',' ,'')+ 'CAST('+column_name +' AS VARCHAR)' +column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name

DECLARE @tempRaw_sql nvarchar(max)
SELECT @tempRaw_sql = 'SELECT ' + @ColumnList + ' into ##temp11 FROM ' + @table_name 
PRINT @tempRaw_sql
EXECUTE sp_executesql  @tempRaw_sql


DECLARE @raw_sql nvarchar(max)
SELECT @raw_sql = 'SELECT  '+ @columnHeader +' UNION ALL SELECT * FROM ##temp11'
PRINT @raw_SQL
SET @query='bcp "'+@raw_SQL+'" queryout "C:\data\'+@fileName+'.txt" -T -c -t,'
EXEC xp_cmdshell @query


DROP TABLE ##temp11

Writing a dict to txt file and reading it back?

Have you tried the json module? JSON format is very similar to python dictionary. And it's human readable/writable:

>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))

This code dumps to a text file

$ cat text.txt 
{"two": 2, "one": 1}

Also you can load from a JSON file:

>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}

CSS - center two images in css side by side

Try changing

#fblogo {
    display: block;
    margin-left: auto;
    margin-right: auto;
    height: 30px; 
}

to

.fblogo {
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    height: 30px; 
}

#images{
    text-align:center;
}

HTML

<div id="images">
    <a href="mailto:[email protected]">
    <img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/07/email-icon-e1343123697991.jpg"/></a>
    <a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
    <img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>
</div>?

DEMO.

Where does Hive store files in HDFS?

Hive tables are stored in the Hive warehouse directory. By default, MapR configures the Hive warehouse directory to be /user/hive/warehouse under the root volume. This default is defined in the $HIVE_HOME/conf/hive-default.xml.

How do I import other TypeScript files?

If you're using AMD modules, the other answers won't work in TypeScript 1.0 (the newest at the time of writing.)

You have different approaches available to you, depending upon how many things you wish to export from each .ts file.

Multiple exports

Foo.ts

export class Foo {}
export interface IFoo {}

Bar.ts

import fooModule = require("Foo");

var foo1 = new fooModule.Foo();
var foo2: fooModule.IFoo = {};

Single export

Foo.ts

class Foo
{}

export = Foo;

Bar.ts

import Foo = require("Foo");

var foo = new Foo();

Looping over arrays, printing both index and value

you can always use iteration param:

ITER=0
for I in ${FOO[@]}
do  
    echo ${I} ${ITER}
    ITER=$(expr $ITER + 1)
done

Getting datarow values into a string?

You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]

Share application "link" in Android

Call this method:

public static void shareApp(Context context)
{
    final String appPackageName = context.getPackageName();
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out the App at: https://play.google.com/store/apps/details?id=" + appPackageName);
    sendIntent.setType("text/plain");
    context.startActivity(sendIntent);
}

Access Control Origin Header error using Axios in React Web throwing error in Chrome

try it proxy package.json add code:

"proxy":"https://localhost:port"

and restart npm enjoy

same code

const instance = axios.create({
  baseURL: "/api/list", 
 
});

How to increase the gap between text and underlining in CSS

@last-child's answer is a great answer!

However, adding a border to my H2 produced an underline longer than the text.

If you're dynamically writing your CSS, or if like me you're lucky and know what the text will be, you can do the following:

  1. change the content to something the right length (ie the same

  2. text) set the font color to transparent (or rgba(0,0,0,0) )

to underline <h2>Processing</h2> (for example), change last-child's code to be:

a {
    text-decoration: none;
    position: relative;
}
a:after {
    content: 'Processing';
    color: transparent;

    width: 100%;
    position: absolute;
    left: 0;
    bottom: 1px;

    border-width: 0 0 1px;
    border-style: solid;
}

how to get program files x86 env variable?

On a 64-bit Windows system, the reading of the various environment variables and some Windows Registry keys is redirected to different sources, depending whether the process doing the reading is 32-bit or 64-bit.

The table below lists these data sources:

X = HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion
Y = HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion
Z = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
     
READING ENVIRONMENT VARIABLES:    Source for 64-bit process               Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
                %ProgramFiles% :  X\ProgramW6432Dir                       X\ProgramFilesDir (x86)
           %ProgramFiles(x86)% :  X\ProgramFilesDir (x86)                 X\ProgramFilesDir (x86)
                %ProgramW6432% :  X\ProgramW6432Dir                       X\ProgramW6432Dir
     
          %CommonProgramFiles% :  X\CommonW6432Dir                        X\CommonFilesDir (x86)
     %CommonProgramFiles(x86)% :  X\CommonFilesDir (x86)                  X\CommonFilesDir (x86)
          %CommonProgramW6432% :  X\CommonW6432Dir                        X\CommonW6432Dir
     
                 %ProgramData% :  Z\ProgramData                           Z\ProgramData


      READING REGISTRY VALUES:    Source for 64-bit process               Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
             X\ProgramFilesDir :  X\ProgramFilesDir                       Y\ProgramFilesDir
       X\ProgramFilesDir (x86) :  X\ProgramFilesDir (x86)                 Y\ProgramFilesDir (x86)
            X\ProgramFilesPath :  X\ProgramFilesPath = %ProgramFiles%     Y\ProgramFilesPath = %ProgramFiles(x86)%
             X\ProgramW6432Dir :  X\ProgramW6432Dir                       Y\ProgramW6432Dir
     
              X\CommonFilesDir :  X\CommonFilesDir                        Y\CommonFilesDir
        X\CommonFilesDir (x86) :  X\CommonFilesDir (x86)                  Y\CommonFilesDir (x86)
              X\CommonW6432Dir :  X\CommonW6432Dir                        Y\CommonW6432Dir
     

So for example, for a 32-bit process, the source of the data for the %ProgramFiles% and %ProgramFiles(x86)% environment variables is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86).

However, for a 64-bit process, the source of the data for the %ProgramFiles% environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir ...and the source of the data for the %ProgramFiles(x86)% environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)

Most default Windows installation put a string like C:\Program Files (x86) into the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86) but this (and others) can be changed.

Whatever is entered into these Windows Registry values will be read by Windows Explorer into respective Environment Variables upon login and then copied to any child process that it subsequently spawns.

The registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesPath is especially noteworthy because most Windows installations put the string %ProgramFiles% into it, to be read by 64-bit processes. This string refers to the environment variable %ProgramFiles% which in turn, takes its data from the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir ...unless some program changes the value of this environment variable apriori.

I have written a small utility, which displays these environment variables for 64-bit and 32-bit processes. You can download it here.
The source code for VisualStudio 2017 is included and the compiled 64-bit and 32-bit binary executables are in the directories ..\x64\Release and ..\x86\Release, respectively.

Difference between /res and /assets directories

Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as "resources", Android will process them into its resource system and you will not be able to get the raw data. If you want to access data untouched, Assets are one way to do it.

How to use a Java8 lambda to sort a stream in reverse order?

You can adapt the solution you linked in How to sort ArrayList<Long> in Java in decreasing order? by wrapping it in a lambda:

.sorted((f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified())

note that f2 is the first argument of Long.compare, not the second, so the result will be reversed.

How to print variables in Perl

How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids, but Perl complains.

Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open returned an error, and make sure you are using use strict; use warnings;.

my ($ids, $nIds) is a list, right? With two elements?

It's a (very special) function call. $ids,$nIds is a list with two elements.

Table Height 100% inside Div element

Had a similar problem. My solution was to give the inner table a fixed height of 1px and set the height of the td in the inner table to 100%. Against all odds, it works fine, tested in IE, Chrome and FF!

CodeIgniter removing index.php from url

Step:-1 Open the folder “application/config” and open the file “config.php“. find and replace the below code in config.php file.

//find the below code   
$config['index_page'] = "index.php" 
//replace with the below code
$config['index_page'] = ""

Step:-2 Go to your CodeIgniter folder and create .htaccess

Path:
Your_website_folder/
application/
assets/
system/
.htaccess <——— this file
index.php

Step:-3 Write below code in .htaccess file

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L] 
</IfModule>

Step:-4 In some case the default setting for uri_protocol does not work properly. To solve this problem just open the file “application/config/config.php“, then find and replace the below code

//Not needed for CodeIgniter 3 its already there.
//find the below code
$config['uri_protocol'] = "AUTO"
//replace with the below code
$config['uri_protocol'] = "REQUEST_URI" 

Thats all but in wamp server it does not work because rewrite_module by default disabled so we have need to enable it. for this do the following

  1. Left click WAMP icon
  2. Apache
  3. Apache Modules
  4. Left click rewrite_module

Original Documentation

Example Link

Ruby: What is the easiest way to remove the first element from an array?

This is pretty neat:

head, *tail = [1, 2, 3, 4, 5]
#==> head = 1, tail = [2, 3, 4, 5]

As written in the comments, there's an advantage of not mutating the original list.

Various ways to remove local Git changes

For discard all i like to stash and drop that stash, it's the fastest way to discard all, especially if you work between multiple repos.

This will stash all changes in {0} key and instantly drop it from {0}

git stash && git stash drop

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

How does one make random number between range for arc4random_uniform()?

That's because arc4random_uniform() is defined as follows:

func arc4random_uniform(_: UInt32) -> UInt32

It takes a UInt32 as input, and spits out a UInt32. You're attempting to pass it a range of values. arc4random_uniform gives you a random number in between 0 and and the number you pass it (exclusively), so if for example, you wanted to find a random number between -50 and 50, as in [-50, 50] you could use arc4random_uniform(101) - 50

Why is my toFixed() function not working?

Example simple (worked):

var a=Number.parseFloat($("#budget_project").val()); // from input field
var b=Number.parseFloat(html); // from ajax
var c=a-b;
$("#result").html(c.toFixed(2)); // put to id='result' (div or others)

Remove all special characters from a string

This should do what you're looking for:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

Usage:

echo clean('a|"bc!@£de^&$f g');

Will output: abcdef-g

Edit:

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

How to dynamically load a Python class

If you don't want to roll your own, there is a function available in the pydoc module that does exactly this:

from pydoc import locate
my_class = locate('my_package.my_module.MyClass')

The advantage of this approach over the others listed here is that locate will find any python object at the provided dotted path, not just an object directly within a module. e.g. my_package.my_module.MyClass.attr.

If you're curious what their recipe is, here's the function:

def locate(path, forceload=0):
    """Locate an object by name or dotted path, importing as necessary."""
    parts = [part for part in split(path, '.') if part]
    module, n = None, 0
    while n < len(parts):
        nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
        if nextmodule: module, n = nextmodule, n + 1
        else: break
    if module:
        object = module
    else:
        object = __builtin__
    for part in parts[n:]:
        try:
            object = getattr(object, part)
        except AttributeError:
            return None
    return object

It relies on pydoc.safeimport function. Here are the docs for that:

"""Import a module; handle errors; return None if the module isn't found.

If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised.  Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning.  If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""

Pause in Python

There's no need to wait for input before closing, just change your command like so:

cmd /K python <script>

The /K switch will execute the command that follows, but leave the command interpreter window open, in contrast to /C, which executes and then closes.

Check if input is number or letter javascript

you can use isNaN(). it returns true when data is not number.

var data = 'hello there';
if(isNaN(data)){
  alert("it is not number");
}else {
  alert("its a valid number");
}

How to get complete month name from DateTime

You can do as mservidio suggested, or even better, keep track of your culture using this overload:

DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);

how to fix groovy.lang.MissingMethodException: No signature of method:

This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.

class name - User is accepted but user is not.

An Authentication object was not found in the SecurityContext - Spring 3.2.2

This could also happens if you put a @PreAuthorize or @PostAuthorize in a Bean in creation. I would recommend to move such annotations to methods of interest.

How to find and replace all occurrences of a string recursively in a directory tree?

For me works the next command:

find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'

if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.

For example: 's@string/to/replace@new/string@g'

Abort a git cherry-pick?

Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.

--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.

--abort Cancel the operation and return to the pre-sequence state.

use help to see the original doc with more details, $ git help cherry-pick

I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.

How to specify the default error page in web.xml?

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Where is body in a nodejs http.get response?

A portion of Coffee here:

# My little helper
read_buffer = (buffer, callback) ->
  data = ''
  buffer.on 'readable', -> data += buffer.read().toString()
  buffer.on 'end', -> callback data

# So request looks like
http.get 'http://i.want.some/stuff', (res) ->
  read_buffer res, (response) ->
    # Do some things with your response
    # but don't do that exactly :D
    eval(CoffeeScript.compile response, bare: true)

And compiled

var read_buffer;

read_buffer = function(buffer, callback) {
  var data;
  data = '';
  buffer.on('readable', function() {
    return data += buffer.read().toString();
  });
  return buffer.on('end', function() {
    return callback(data);
  });
};

http.get('http://i.want.some/stuff', function(res) {
  return read_buffer(res, function(response) {
    return eval(CoffeeScript.compile(response, {
      bare: true
    }));
  });
});

Git asks for username every time I push

The proper way to solve it is to change the http to ssh.

You can use this git remote rm origin to remove your remote repo.

And then you can add it again with the ssh sintax (which you can copy from github): git remote add origin [email protected]:username/reponame.git .

Check this article. https://www.freecodecamp.org/news/how-to-fix-git-always-asking-for-user-credentials/

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

Get string after character

${word:$(expr index "$word" "="):1}

that gets the 7. Assuming you mean the entire rest of the string, just leave off the :1.

C++11 reverse range-based for-loop

You could simply use BOOST_REVERSE_FOREACH which iterates backwards. For example, the code

#include <iostream>
#include <boost\foreach.hpp>

int main()
{
    int integers[] = { 0, 1, 2, 3, 4 };
    BOOST_REVERSE_FOREACH(auto i, integers)
    {
        std::cout << i << std::endl;
    }
    return 0;
}

generates the following output:

4

3

2

1

0

Python: Finding differences between elements of a list

A functional approach:

>>> import operator
>>> a = [1,3,5,7,11,13,17,21]
>>> map(operator.sub, a[1:], a[:-1])
[2, 2, 2, 4, 2, 4, 4]

Using generator:

>>> import operator, itertools
>>> g1,g2 = itertools.tee((x*x for x in xrange(5)),2)
>>> list(itertools.imap(operator.sub, itertools.islice(g1,1,None), g2))
[1, 3, 5, 7]

Using indices:

>>> [a[i+1]-a[i] for i in xrange(len(a)-1)]
[2, 2, 2, 4, 2, 4, 4]

How do I detect a click outside an element?

You can listen for a click event on document and then make sure #menucontainer is not an ancestor or the target of the clicked element by using .closest().

If it is not, then the clicked element is outside of the #menucontainer and you can safely hide it.

$(document).click(function(event) { 
  var $target = $(event.target);
  if(!$target.closest('#menucontainer').length && 
  $('#menucontainer').is(":visible")) {
    $('#menucontainer').hide();
  }        
});

Edit – 2017-06-23

You can also clean up after the event listener if you plan to dismiss the menu and want to stop listening for events. This function will clean up only the newly created listener, preserving any other click listeners on document. With ES2015 syntax:

export function hideOnClickOutside(selector) {
  const outsideClickListener = (event) => {
    const $target = $(event.target);
    if (!$target.closest(selector).length && $(selector).is(':visible')) {
        $(selector).hide();
        removeClickListener();
    }
  }

  const removeClickListener = () => {
    document.removeEventListener('click', outsideClickListener)
  }

  document.addEventListener('click', outsideClickListener)
}

Edit – 2018-03-11

For those who don't want to use jQuery. Here's the above code in plain vanillaJS (ECMAScript6).

function hideOnClickOutside(element) {
    const outsideClickListener = event => {
        if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
          element.style.display = 'none'
          removeClickListener()
        }
    }

    const removeClickListener = () => {
        document.removeEventListener('click', outsideClickListener)
    }

    document.addEventListener('click', outsideClickListener)
}

const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ) // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js 

NOTE: This is based on Alex comment to just use !element.contains(event.target) instead of the jQuery part.

But element.closest() is now also available in all major browsers (the W3C version differs a bit from the jQuery one). Polyfills can be found here: Element.closest()

Edit – 2020-05-21

In the case where you want the user to be able to click-and-drag inside the element, then release the mouse outside the element, without closing the element:

      ...
      let lastMouseDownX = 0;
      let lastMouseDownY = 0;
      let lastMouseDownWasOutside = false;

      const mouseDownListener = (event: MouseEvent) => {
        lastMouseDownX = event.offsetX
        lastMouseDownY = event.offsetY
        lastMouseDownWasOutside = !$(event.target).closest(element).length
      }
      document.addEventListener('mousedown', mouseDownListener);

And in outsideClickListener:

const outsideClickListener = event => {
        const deltaX = event.offsetX - lastMouseDownX
        const deltaY = event.offsetY - lastMouseDownY
        const distSq = (deltaX * deltaX) + (deltaY * deltaY)
        const isDrag = distSq > 3
        const isDragException = isDrag && !lastMouseDownWasOutside

        if (!element.contains(event.target) && isVisible(element) && !isDragException) { // or use: event.target.closest(selector) === null
          element.style.display = 'none'
          removeClickListener()
          document.removeEventListener('mousedown', mouseDownListener); // Or add this line to removeClickListener()
        }
    }

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

Visual Studio 2010 shortcut to find classes and methods?

Use the "Go To Find Combo Box" with the ">of" command. CTRL+/ or CTRL+D are the standard hotkeys.

For example, go to the combo box (CTRL+/) and type: >of MyClassName. As you type, intellisense will refine the options in the dropdown.

In my experience, this is faster than Navigate To and doesn't bring up another dialog to deal with. Also, this combo box has a lot of other nifty little shortcut commands:

Using the Go To Find Combo Box

This textbox used to be the default on the Standard toolbar in Visual Studio. It was removed in Visual Studio 2012, so you have to add it back using menu Tools ? Customize. The hotkeys may have changed too: I'm not sure since mine are all customized.

SQL 'like' vs '=' performance

Maybe you are looking about Full Text Search.

In contrast to full-text search, the LIKE Transact-SQL predicate works on character patterns only. Also, you cannot use the LIKE predicate to query formatted binary data. Furthermore, a LIKE query against a large amount of unstructured text data is much slower than an equivalent full-text query against the same data. A LIKE query against millions of rows of text data can take minutes to return; whereas a full-text query can take only seconds or less against the same data, depending on the number of rows that are returned.

Printing reverse of any String without using any predefined function?

import java.util.*;
public class Restring {

public static void main(String[] args) {
  String input,output;
  Scanner kbd=new Scanner(System.in);
  System.out.println("Please Enter a String");
  input=kbd.nextLine();
  int n=input.length();

  char tmp[]=new char[n];
  char nxt[]=new char[n];

  tmp=input.toCharArray();
  int m=0;
  for(int i=n-1;i>=0;i--)
  {
      nxt[m]=tmp[i];
      m++;
  }

  System.out.print("Reversed String is   ");
  for(int i=0;i<n;i++)
  {
      System.out.print(nxt[i]);
  }

}

Getting last month's date in php

$time = mktime(0, 0, 0, date("m"),date("d")-date("t"), date("Y"));
$lastMonth = date("d-m-Y", $time);

OR

$lastMonth = date("m-Y", mktime() - 31*3600*24);

works on 30.03.2012

axios post request to send form data

2020 ES6 way of doing

Having the form in html I binded in data like so:

DATA:

form: {
   name: 'Joan Cap de porc',
   email: '[email protected]',
   phone: 2323,
   query: 'cap d\ou'
   file: null,
   legal: false
},

onSubmit:

async submitForm() {
  const formData = new FormData()
  Object.keys(this.form).forEach((key) => {
    formData.append(key, this.form[key])
  })

  try {
    await this.$axios.post('/ajax/contact/contact-us', formData)
    this.$emit('formSent')
  } catch (err) {
    this.errors.push('form_error')
  }
}

M_PI works with math.h but not with cmath in Visual Studio

With CMake it would just be

add_compile_definitions(_USE_MATH_DEFINES)

in CMakeLists.txt.

Run all SQL files in a directory

You could use ApexSQL Propagate. It is a free tool which executes multiple scripts on multiple databases. You can select as many scripts as you need and execute them against one or multiple databases (even multiple servers). You can create scripts list and save it, then just select that list each time you want to execute those same scripts in the created order (multiple script lists can be added also):

Select scripts

When scripts and databases are selected, they will be shown in the main window and all you have to do is to click the “Execute” button and all scripts will be executed on selected databases in the given order:

Scripts execution

How to programmatically disable page scrolling with jQuery

The only way I've found to do this is similar to what you described:

  1. Grab current scroll position (don't forget horizontal axis!).
  2. Set overflow to hidden (probably want to retain previous overflow value).
  3. Scroll document to stored scroll position with scrollTo().

Then when you're ready to allow scrolling again, undo all that.

Edit: no reason I can't give you the code since I went to the trouble to dig it up...

// lock scroll position, but retain settings for later
var scrollPosition = [
  self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
  self.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
];
var html = jQuery('html'); // it would make more sense to apply this to body, but IE7 won't have that
html.data('scroll-position', scrollPosition);
html.data('previous-overflow', html.css('overflow'));
html.css('overflow', 'hidden');
window.scrollTo(scrollPosition[0], scrollPosition[1]);


// un-lock scroll position
var html = jQuery('html');
var scrollPosition = html.data('scroll-position');
html.css('overflow', html.data('previous-overflow'));
window.scrollTo(scrollPosition[0], scrollPosition[1])

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

It works for me. See this solution - https://alvarotrigo.com/blog/firing-resize-event-only-once-when-resizing-is-finished/

_x000D_
_x000D_
var resizeId;_x000D_
$(window).resize(function() {_x000D_
    clearTimeout(resizeId);_x000D_
    resizeId = setTimeout(doneResizing, 500);_x000D_
});_x000D_
function doneResizing(){_x000D_
    //whatever we want to do _x000D_
}
_x000D_
_x000D_
_x000D_

Spring Security exclude url patterns in security annotation configurartion

specifying the "antMatcher" before "authorizeRequests()" like below will restrict the authenticaiton to only those URLs specified in "antMatcher"

http.csrf().disable() .antMatcher("/apiurlneedsauth/**").authorizeRequests().

HTML table: keep the same width for columns

well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

I still remember the first weeks of my programming courses and I totally understand how you feel. Here is the code that solves your problem. In order to learn from this answer, try to run it adding several 'print' in the loop, so you can see the progress of the variables.

import java.util.*;
import java.lang.*;

public class foo
{

   public static void main(String[] args)
   { 
      double[] alpha = new double[50];
      int count = 0;

      for (int i=0; i<50; i++)
      {
          // System.out.print("variable i = " + i + "\n");
          if (i < 25)
          {
                alpha[i] = i*i;
          }
          else {
                alpha[i] = 3*i;
          }

          if (count < 10)
          {
            System.out.print(alpha[i]+ " "); 
          }  
          else {
            System.out.print("\n"); 
            System.out.print(alpha[i]+ " "); 
            count = 0;
          }

          count++;
      }

      System.out.print("\n"); 

    }
}

Base64 PNG data to HTML5 canvas

Jerryf's answer is fine, except for one flaw.

The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.

(Like Totty.js pointed out.)

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.onload = function() {
    ctx.drawImage(image, 0, 0);
};
image.src = "data:image/  png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";

How to develop Desktop Apps using HTML/CSS/JavaScript?

Awesomium makes it easy to use HTML UI in your C++ or .NET app

Update

My previous answer is now outdated. These days you would be crazy not to look into using Electron for this. Many popular desktop apps have been developed on top of it.

Closing Applications

System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit() method is typically called from within a message loop, and forces Run() to return. To exit a message loop for the current thread only, call ExitThread(). This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run().

System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.

I hope it is best to use Application.Exit

See also these links:

Converting bytes to megabytes

The answer is that #1 is technically correct based on the real meaning of the Mega prefix, however (and in life there is always a however) the math for that doesn't come out so nice in base 2, which is how computers count, so #2 is what people really use.

Node.js - EJS - including a partial

Express 3.x no longer support partial. According to the post ejs 'partial is not defined', you can use "include" keyword in EJS to replace the removed partial functionality.

Django MEDIA_URL and MEDIA_ROOT

This is what I did to achieve image rendering in DEBUG = False mode in Python 3.6 with Django 1.11

from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]

dropdownlist set selected value in MVC3 Razor

You should use view models and forget about ViewBag Think of it as if it didn't exist. You will see how easier things will become. So define a view model:

public class MyViewModel
{
    public int SelectedCategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; } 
}

and then populate this view model from the controller:

public ActionResult NewsEdit(int ID, dms_New dsn)
{
    var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
    var categories = (from b in dc.dms_NewsCategories select b).ToList();

    var model = new MyViewModel
    {
        SelectedCategoryId = dsn.NewsCategoriesID,
        Categories = categories.Select(x => new SelectListItem
        {
            Value = x.NewsCategoriesID.ToString(),
            Text = x.NewsCategoriesName
        })
    };
    return View(model);
}

and finally in your view use the strongly typed DropDownListFor helper:

@model MyViewModel

@Html.DropDownListFor(
    x => x.SelectedCategoryId,
    Model.Categories
)

Case Statement Equivalent in R

Mixing plyr::mutate and dplyr::case_when works for me and is readable.

iris %>%
plyr::mutate(coolness =
     dplyr::case_when(Species  == "setosa"     ~ "not cool",
                      Species  == "versicolor" ~ "not cool",
                      Species  == "virginica"  ~ "super awesome",
                      TRUE                     ~ "undetermined"
       )) -> testIris
head(testIris)
levels(testIris$coolness)  ## NULL
testIris$coolness <- as.factor(testIris$coolness)
levels(testIris$coolness)  ## ok now
testIris[97:103,4:6]

Bonus points if the column can come out of mutate as a factor instead of char! The last line of the case_when statement, which catches all un-matched rows is very important.

     Petal.Width    Species      coolness
 97         1.3  versicolor      not cool
 98         1.3  versicolor      not cool  
 99         1.1  versicolor      not cool
100         1.3  versicolor      not cool
101         2.5  virginica     super awesome
102         1.9  virginica     super awesome
103         2.1  virginica     super awesome

How to use WinForms progress bar?

There is Task exists, It is unnesscery using BackgroundWorker, Task is more simple. for example:

ProgressDialog.cs:

   public partial class ProgressDialog : Form
    {
        public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }

        public ProgressDialog()
        {
            InitializeComponent();
        }

        public void RunAsync(Action action)
        {
            Task.Run(action);
        }
    }

Done! Then you can reuse ProgressDialog anywhere:

var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;

progressDialog.RunAsync(() =>
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000)
        this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
            this.progressDialog.Progressbar.Value += 1;
        }));
    }
});

progressDialog.ShowDialog();

What's the best practice to round a float to 2 decimals?

Here is a shorter implementation comparing to @Jav_Rock's

   /**
     * Round to certain number of decimals
     * 
     * @param d
     * @param decimalPlace the numbers of decimals
     * @return
     */

    public static float round(float d, int decimalPlace) {
         return BigDecimal.valueOf(d).setScale(decimalPlace,BigDecimal.ROUND_HALF_UP).floatValue();
    }



    System.out.println(round(2.345f,2));//two decimal digits, //2.35

Is there a way to force npm to generate package-lock.json?

If your npm version is lower than version 5 then install the higher version for getting the automatic generation of package-lock.json.

Example: Upgrade your current npm to version 6.14.0

npm i -g [email protected]

You could view the latest npm version list by

npm view npm versions

How can I convert a string to upper- or lower-case with XSLT?

For ANSI character encoding:

 translate(//variable, 'ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞŸŽŠŒ', 'abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿžšœ')

Eclipse: The declared package does not match the expected package

I get this problem in Eclipse sometimes when importing an Android project that does not have a .classpath file. The one that Eclipse creates is not exactly the same one that Android expects. But, the Android .classpath files are usually all relative, so I just copy a correct .classpath file from another project over the incorrect .classpath. I've created a video that shows how I do this: https://www.youtube.com/watch?v=IVIhgeahS1Ynto

What does %s and %d mean in printf in the C language?

%d is print as an int %s is print as a string %f is print as floating point

It should be noted that it is incorrect to say that this is different from Java. Printf stands for print format, if you do a formatted print in Java, this is exactly the same usage. This may allow you to solve interesting and new problems in both C and Java!

How to get detailed list of connections to database in sql server 2005?

As @Hutch pointed out, one of the major limitations of sp_who2 is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE).

Instead, you can just go directly to the source on master.dbo.sysprocesses

I've constructed this to output almost exactly the same thing that sp_who2 generates, except that you can easily add ORDER BY and WHERE clauses to get meaningful output.

SELECT  spid,
        sp.[status],
        loginame [Login],
        hostname, 
        blocked BlkBy,
        sd.name DBName, 
        cmd Command,
        cpu CPUTime,
        physical_io DiskIO,
        last_batch LastBatch,
        [program_name] ProgramName   
FROM master.dbo.sysprocesses sp 
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid 

How does strtok() split the string into tokens in C?

For those who are still having hard time understanding this strtok() function, take a look at this pythontutor example, it is a great tool to visualize your C (or C++, Python ...) code.

In case the link got broken, paste in:

#include <stdio.h>
#include <string.h>

int main()
{
    char s[] = "Hello, my name is? Matthew! Hey.";
    char* p;
    for (char *p = strtok(s," ,?!."); p != NULL; p = strtok(NULL, " ,?!.")) {
      puts(p);
    }
    return 0;
}

Credits go to Anders K.

Android. Fragment getActivity() sometimes returns null

I know this is a old question but i think i must provide my answer to it because my problem was not solved by others.

first of all : i was dynamically adding fragments using fragmentTransactions. Second: my fragments were modified using AsyncTasks (DB queries on a server). Third: my fragment was not instantiated at activity start Fourth: i used a custom fragment instantiation "create or load it" in order to get the fragment variable. Fourth: activity was recreated because of orientation change

The problem was that i wanted to "remove" the fragment because of the query answer, but the fragment was incorrectly created just before. I don't know why, probably because of the "commit" be done later, the fragment was not added yet when it was time to remove it. Therefore getActivity() was returning null.

Solution : 1)I had to check that i was correctly trying to find the first instance of the fragment before creating a new one 2)I had to put serRetainInstance(true) on that fragment in order to keep it through orientation change (no backstack needed therefore no problem) 3)Instead of "recreating or getting old fragment" just before "remove it", I directly put the fragment at activity start. Instantiating it at activity start instead of "loading" (or instantiating) the fragment variable before removing it prevented getActivity problems.

How to cut first n and last n columns?

Try the following:

echo a#b#c | awk -F"#" '{$1 = ""; $NF = ""; print}' OFS=""

How to hide columns in HTML table?

you can also use:

<td style="visibility:hidden;">
or
<td style="visibility:collapse;">

The difference between them that "hidden" hides the cell but it holds the space but with "collapse" the space is not held like display:none. This is significant when hidding a whole column or row.

Programmatically change the height and width of a UIImageView Xcode Swift

Using autoview

image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true

Which is faster: Stack allocation or Heap allocation

Concerns Specific to the C++ Language

First of all, there is no so-called "stack" or "heap" allocation mandated by C++. If you are talking about automatic objects in block scopes, they are even not "allocated". (BTW, automatic storage duration in C is definitely NOT the same to "allocated"; the latter is "dynamic" in the C++ parlance.) The dynamically allocated memory is on the free store, not necessarily on "the heap", though the latter is often the (default) implementation.

Although as per the abstract machine semantic rules, automatic objects still occupy memory, a conforming C++ implementation is allowed to ignore this fact when it can prove this does not matter (when it does not change the observable behavior of the program). This permission is granted by the as-if rule in ISO C++, which is also the general clause enabling the usual optimizations (and there is also an almost same rule in ISO C). Besides the as-if rule, ISO C++ also has copy elision rules to allow omission of specific creations of objects. The constructor and destructor calls involved are thereby omitted. As a result, the automatic objects (if any) in these constructors and destructors are also eliminated, compared to naive abstract semantics implied by the source code.

On the other hand, free store allocation is definitely "allocation" by design. Under ISO C++ rules, such an allocation can be achieved by a call of an allocation function. However, since ISO C++14, there is a new (non-as-if) rule to allow merging global allocation function (i.e. ::operator new) calls in specific cases. So parts of dynamic allocation operations can also be no-op like the case of automatic objects.

Allocation functions allocate resources of memory. Objects can be further allocated based on allocation using allocators. For automatic objects, they are directly presented - although the underlying memory can be accessed and be used to provide memory to other objects (by placement new), but this does not make great sense as the free store, because there is no way to move the resources elsewhere.

All other concerns are out of the scope of C++. Nevertheless, they can be still significant.

About Implementations of C++

C++ does not expose reified activation records or some sorts of first-class continuations (e.g. by the famous call/cc), there is no way to directly manipulate the activation record frames - where the implementation need to place the automatic objects to. Once there is no (non-portable) interoperations with the underlying implementation ("native" non-portable code, such as inline assembly code), an omission of the underlying allocation of the frames can be quite trivial. For example, when the called function is inlined, the frames can be effectively merged into others, so there is no way to show what is the "allocation".

However, once interops are respected, things are getting complex. A typical implementation of C++ will expose the ability of interop on ISA (instruction-set architecture) with some calling conventions as the binary boundary shared with the native (ISA-level machine) code. This would be explicitly costly, notably, when maintaining the stack pointer, which is often directly held by an ISA-level register (with probably specific machine instructions to access). The stack pointer indicates the boundary of the top frame of the (currently active) function call. When a function call is entered, a new frame is needed and the stack pointer is added or subtracted (depending on the convention of ISA) by a value not less than the required frame size. The frame is then said allocated when the stack pointer after the operations. Parameters of functions may be passed onto the stack frame as well, depending on the calling convention used for the call. The frame can hold the memory of automatic objects (probably including the parameters) specified by the C++ source code. In the sense of such implementations, these objects are "allocated". When the control exits the function call, the frame is no longer needed, it is usually released by restoring the stack pointer back to the state before the call (saved previously according to the calling convention). This can be viewed as "deallocation". These operations make the activation record effectively a LIFO data structure, so it is often called "the (call) stack". The stack pointer effectively indicates the top position of the stack.

Because most C++ implementations (particularly the ones targeting ISA-level native code and using the assembly language as its immediate output) use similar strategies like this, such a confusing "allocation" scheme is popular. Such allocations (as well as deallocations) do spend machine cycles, and it can be expensive when the (non-optimized) calls occur frequently, even though modern CPU microarchitectures can have complex optimizations implemented by hardware for the common code pattern (like using a stack engine in implementing PUSH/POP instructions).

But anyway, in general, it is true that the cost of stack frame allocation is significantly less than a call to an allocation function operating the free store (unless it is totally optimized away), which itself can have hundreds of (if not millions of :-) operations to maintain the stack pointer and other states. Allocation functions are typically based on API provided by the hosted environment (e.g. runtime provided by the OS). Different to the purpose of holding automatic objects for functions calls, such allocations are general-purposed, so they will not have frame structure like a stack. Traditionally, they allocate space from the pool storage called heap (or several heaps). Different from the "stack", the concept "heap" here does not indicate the data structure being used; it is derived from early language implementations decades ago. (BTW, the call stack is usually allocated with fixed or user-specified size from the heap by the environment in program or thread startup.) The nature of use cases makes allocations and deallocations from a heap far more complicated (than push or pop of stack frames), and hardly possible to be directly optimized by hardware.

Effects on Memory Access

The usual stack allocation always puts the new frame on the top, so it has a quite good locality. This is friendly to the cache. OTOH, memory allocated randomly in the free store has no such property. Since ISO C++17, there are pool resource templates provided by <memory>. The direct purpose of such an interface is to allow the results of consecutive allocations being close together in memory. This acknowledges the fact that this strategy is generally good for performance with contemporary implementations, e.g. being friendly to cache in modern architectures. This is about the performance of access rather than allocation, though.

Concurrency

Expectation of concurrent access to memory can have different effects between the stack and heaps. A call stack is usually exclusively owned by one thread of execution in a C++ implementation. OTOH, heaps are often shared among the threads in a process. For such heaps, the allocation and deallocation functions have to protect the shared internal administrative data structure from the data race. As a result, heap allocations and deallocations may have additional overhead due to internal synchronization operations.

Space Efficiency

Due to the nature of the use cases and internal data structures, heaps may suffer from internal memory fragmentation, while the stack does not. This does not have direct impacts on the performance of memory allocation, but in a system with virtual memory, low space efficiency may degenerate overall performance of memory access. This is particularly awful when HDD is used as a swap of physical memory. It can cause quite long latency - sometimes billions of cycles.

Limitations of Stack Allocations

Although stack allocations are often superior in performance than heap allocations in reality, it certainly does not mean stack allocations can always replace heap allocations.

First, there is no way to allocate space on the stack with a size specified at runtime in a portable way with ISO C++. There are extensions provided by implementations like alloca and G++'s VLA (variable-length array), but there are reasons to avoid them. (IIRC, Linux source removes the use of VLA recently.) (Also note ISO C99 does have mandated VLA, but ISO C11 turns the support optional.)

Second, there is no reliable and portable way to detect stack space exhaustion. This is often called stack overflow (hmm, the etymology of this site), but probably more accurately, stack overrun. In reality, this often causes invalid memory access, and the state of the program is then corrupted (... or maybe worse, a security hole). In fact, ISO C++ has no concept of "the stack" and makes it undefined behavior when the resource is exhausted. Be cautious about how much room should be left for automatic objects.

If the stack space runs out, there are too many objects allocated in the stack, which can be caused by too many active calls of functions or improper use of automatic objects. Such cases may suggest the existence of bugs, e.g. a recursive function call without correct exit conditions.

Nevertheless, deep recursive calls are sometimes desired. In implementations of languages requiring support of unbound active calls (where the call depth only limited by total memory), it is impossible to use the (contemporary) native call stack directly as the target language activation record like typical C++ implementations. To work around the problem, alternative ways of the construction of activation records are needed. For example, SML/NJ explicitly allocates frames on the heap and uses cactus stacks. The complicated allocation of such activation record frames is usually not as fast as the call stack frames. However, if such languages are implemented further with the guarantee of proper tail recursion, the direct stack allocation in the object language (that is, the "object" in the language does not stored as references, but native primitive values which can be one-to-one mapped to unshared C++ objects) is even more complicated with more performance penalty in general. When using C++ to implement such languages, it is difficult to estimate the performance impacts.

NSDictionary to NSArray?

+ (NSArray *)getArrayListFromDictionary:(NSDictionary *)dictMain paramName:(NSString *)paramName
{
    if([dictMain isKindOfClass:[NSDictionary class]])
    {
        if ([dictMain objectForKey:paramName])
        {
            if ([[dictMain objectForKey:paramName] isKindOfClass:[NSArray class]])
            {
                NSArray *dataArray = [dictMain objectForKey:paramName];

                return dataArray;
            }
        }
    }
    return [[NSArray alloc] init];
}

Hope this helps!

SQL Server replace, remove all after certain character

Use LEFT combined with CHARINDEX:

UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

Note that the WHERE clause skips updating rows in which there is no semicolon.

Here is some code to verify the SQL above works:

declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself    

UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

select * from @MyTable

I get the following results:

id MyText
-- -------------------------
1  some text
2  text again
3  text without a semicolon
4  NULL
5        (empty string)
6  test 3 semicolons
7        (empty string)