Programs & Examples On #Django piston

A mini-framework for Django for creating RESTful APIs.

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

A duplicate in the database should be a 409 CONFLICT.

I recommend using 422 UNPROCESSABLE ENTITY for validation errors.

I give a longer explanation of 4xx codes here: http://parker0phil.com/2014/10/16/REST_http_4xx_status_codes_syntax_and_sematics/

Does JavaScript have the interface type (such as Java's 'interface')?

Pick up a copy of 'JavaScript design patterns' by Dustin Diaz. There's a few chapters dedicated to implementing JavaScript interfaces through Duck Typing. It's a nice read as well. But no, there's no language native implementation of an interface, you have to Duck Type.

// example duck typing method
var hasMethods = function(obj /*, method list as strings */){
    var i = 1, methodName;
    while((methodName = arguments[i++])){
        if(typeof obj[methodName] != 'function') {
            return false;
        }
    }
    return true;
}

// in your code
if(hasMethods(obj, 'quak', 'flapWings','waggle')) {
    //  IT'S A DUCK, do your duck thang
}

How to make a jquery function call after "X" seconds

You can just use the normal setTimeout method in JavaScript.

ie...

setTimeout( function(){ 
    // Do something after 1 second 
  }  , 1000 );

In your example, you might want to use showStickySuccessToast directly.

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

Check play state of AVPlayer

To get notification for reaching the end of an item (via Apple):

[[NSNotificationCenter defaultCenter] 
      addObserver:<self>
      selector:@selector(<#The selector name#>)
      name:AVPlayerItemDidPlayToEndTimeNotification 
      object:<#A player item#>];

And to track playing you can:

"track changes in the position of the playhead in an AVPlayer object" by using addPeriodicTimeObserverForInterval:queue:usingBlock: or addBoundaryTimeObserverForTimes:queue:usingBlock:.

Example is from Apple:

// Assume a property: @property (retain) id playerObserver;

Float64 durationSeconds = CMTimeGetSeconds([<#An asset#> duration]);
CMTime firstThird = CMTimeMakeWithSeconds(durationSeconds/3.0, 1);
CMTime secondThird = CMTimeMakeWithSeconds(durationSeconds*2.0/3.0, 1);
NSArray *times = [NSArray arrayWithObjects:[NSValue valueWithCMTime:firstThird], [NSValue valueWithCMTime:secondThird], nil];

self.playerObserver = [<#A player#> addBoundaryTimeObserverForTimes:times queue:NULL usingBlock:^{
    // Passing NULL for the queue specifies the main queue.

    NSString *timeDescription = (NSString *)CMTimeCopyDescription(NULL, [self.player currentTime]);
    NSLog(@"Passed a boundary at %@", timeDescription);
    [timeDescription release];
}];

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

Convert string to variable name in JavaScript

As far as eval vs. global variable solutions...

I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.

var tempNamespace = {};
var myString = "myVarProperty";

tempNamespace[myString] = 5;

Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)

POST data with request module on Node.JS

I have to get the data from a POST method of the PHP code. What worked for me was:

const querystring = require('querystring');
const request = require('request');

const link = 'http://your-website-link.com/sample.php';
let params = { 'A': 'a', 'B': 'b' };

params = querystring.stringify(params); // changing into querystring eg 'A=a&B=b'

request.post({
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // important to interect with PHP
  url: link,
  body: params,
}, function(error, response, body){
  console.log(body);
});

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

This can be fixed by changing your URL, example bad:

https://raw.githubusercontent.com/svnpenn/bm/master/yt-dl/yt-dl.js
Content-Type: text/plain; charset=utf-8

Example good:

https://cdn.rawgit.com/svnpenn/bm/master/yt-dl/yt-dl.js
content-type: application/javascript;charset=utf-8

rawgit.com is a caching proxy service for github. You can also go there and interactively derive a corresponding URL for your original raw.githubusercontent.com URL. See its FAQ

jQuery return ajax result into outside variable

'async': false says it's depreciated. I did notice if I run console.log('test1'); on ajax success, then console.log('test2'); in normal js after the ajax function, test2 prints before test1 so the issue is an ajax call has a small delay, but doesn't stop the rest of the function to get results. The variable simply, was not set "yet", so you need to delay the next function.

function runPHP(){
    var input = document.getElementById("input1");
    var result = 'failed to run php';

    $.ajax({ url: '/test.php',
        type: 'POST',
        data: {action: 'test'},
        success: function(data) {
            result = data;
        }
    });

    setTimeout(function(){
        console.log(result);
    }, 1000);
}

on test.php (incase you need to test this function)

function test(){
    print 'ran php';
}

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = htmlentities($_POST['action']);
    switch($action) {
        case 'test' : test();break;
    }
}

AttributeError("'str' object has no attribute 'read'")

You need to open the file first. This doesn't work:

json_file = json.load('test.json')

But this works:

f = open('test.json')
json_file = json.load(f)

Where is svn.exe in my machine?

I installed TortoiseSVN-1.12.2.28653-x64-svn-1.12.2 in Windows 10 with commandline tool enabled. Still it didn't have the svn.exe file inside the bin folder.

So I downloaded Apache Subversion commandline tools from https://www.visualsvn.com/files/Apache-Subversion-1.13.0.zip. After unzipping, I have put the following two locations into my PATH variable:

C:\Program Files\TortoiseSVN\bin
E:\Apache-Subversion-1.13.0\bin

Everything works fine for me after this configuration.I wanted to use SVN in VsCode IDE.

TestNG ERROR Cannot find class in classpath

Just do Eclipse> Project > Clean and then run the test cases again. It should work.

What it does in background is, that it will call mvn eclipse:clean in your project directory which will delete your .project and .classpath files and you can also do a mvn eclipse:eclipse - this regenerates your .project and .classpath files. Thus adding the desired class in the classpath.

How to resolve "local edit, incoming delete upon update" message

So you can just revert the file that you deleted but remember, If you are working on any type of project with a set project file (like iOS), reverting the file will add it to your system folder structure but not your project file structure. additional steps may be required if you are in this case

Codesign error: Provisioning profile cannot be found after deleting expired profile

Unfortunately this approach didn't work out for me. But here's a fix which worked for me (to get this to work you need a working project file on Subversion or so):

I did roll back to an working version of my project file. As it isn't possible to revert with Xcode (Where is the 'Revert' option in Xcode 4's Source Control?) - I used Tortoise, my Windows machine and this Tutorial (http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-howto-rollback.html) to roll back to an older project file.

As the Tutorial didn't work out for me, I just used Tortoise to save the working revision of my project file to an usb stick to port it to my mac. After that I replaced the new broken project file with the old working one, cleaned and it worked like a charm!

Object of class DateTime could not be converted to string

$Date = $row['Received_date']->format('d/m/Y');

then it cast date object from given in database

Difference between using bean id and name in Spring configuration file

From the Spring reference, 3.2.3.1 Naming Beans:

Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.

When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.

So basically the id attribute conforms to the XML id attribute standards whereas name is a little more flexible. Generally speaking, I use name pretty much exclusively. It just seems more "Spring-y".

How to create streams from string in Node.Js?

Just create a new instance of the stream module and customize it according to your needs:

var Stream = require('stream');
var stream = new Stream();

stream.pipe = function(dest) {
  dest.write('your string');
  return dest;
};

stream.pipe(process.stdout); // in this case the terminal, change to ya-csv

or

var Stream = require('stream');
var stream = new Stream();

stream.on('data', function(data) {
  process.stdout.write(data); // change process.stdout to ya-csv
});

stream.emit('data', 'this is my string');

BEGIN - END block atomic transactions in PL/SQL

The default behavior of Commit PL/SQL block:

You should explicitly commit or roll back every transaction. Whether you issue the commit or rollback in your PL/SQL program or from a client program depends on the application logic. If you do not commit or roll back a transaction explicitly, the client environment determines its final state.

For example, in the SQLPlus environment, if your PL/SQL block does not include a COMMIT or ROLLBACK statement, the final state of your transaction depends on what you do after running the block. If you execute a data definition, data control, or COMMIT statement or if you issue the EXIT, DISCONNECT, or QUIT command, Oracle commits the transaction. If you execute a ROLLBACK statement or abort the SQLPlus session, Oracle rolls back the transaction.

https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/sqloperations.htm#i7105

How to connect to MySQL Database?

Install Oracle's MySql.Data NuGet package.

using MySql.Data;
using MySql.Data.MySqlClient;

namespace Data
{
    public class DBConnection
    {
        private DBConnection()
        {
        }

        public string Server { get; set; }
        public string DatabaseName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        private MySqlConnection Connection { get; set;}

        private static DBConnection _instance = null;
        public static DBConnection Instance()
        {
            if (_instance == null)
                _instance = new DBConnection();
           return _instance;
        }
    
        public bool IsConnect()
        {
            if (Connection == null)
            {
                if (String.IsNullOrEmpty(databaseName))
                    return false;
                string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
                Connection = new MySqlConnection(connstring);
                Connection.Open();
            }
    
            return true;
        }
    
        public void Close()
        {
            Connection.Close();
        }        
    }
}

Example:

var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
    //suppose col0 and col1 are defined as VARCHAR in the DB
    string query = "SELECT col0,col1 FROM YourTable";
    var cmd = new MySqlCommand(query, dbCon.Connection);
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        string someStringFromColumnZero = reader.GetString(0);
        string someStringFromColumnOne = reader.GetString(1);
        Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
    }
    dbCon.Close();
}

How to import functions from different js file in a Vue+webpack+vue-loader project

Say I want to import data into a component from src/mylib.js:

var test = {
  foo () { console.log('foo') },
  bar () { console.log('bar') },
  baz () { console.log('baz') }
}

export default test

In my .Vue file I simply imported test from src/mylib.js:

<script> 
  import test from '@/mylib'

  console.log(test.foo())
  ...
</script>

How do I avoid the specification of the username and password at every git push?

1. Generate an SSH key

Linux/Mac

Open terminal to create ssh keys:

cd ~                 #Your home directory
ssh-keygen -t rsa    #Press enter for all values

For Windows

(Only works if the commit program is capable of using certificates/private & public ssh keys)

  1. Use Putty Gen to generate a key
  2. Export the key as an open SSH key

Here is a walkthrough on putty gen for the above steps

2. Associate the SSH key with the remote repository

This step varies, depending on how your remote is set up.

  • If it is a GitHub repository and you have administrative privileges, go to settings and click 'add SSH key'. Copy the contents of your ~/.ssh/id_rsa.pub into the field labeled 'Key'.

  • If your repository is administered by somebody else, give the administrator your id_rsa.pub.

  • If your remote repository is administered by your, you can use this command for example:

    scp ~/.ssh/id_rsa.pub YOUR_USER@YOUR_IP:~/.ssh/authorized_keys/id_rsa.pub

3. Set your remote URL to a form that supports SSH 1

If you have done the steps above and are still getting the password prompt, make sure your repo URL is in the form

git+ssh://[email protected]/username/reponame.git

as opposed to

https://github.com/username/reponame.git

To see your repo URL, run:

git remote show origin

You can change the URL with:

git remote set-url origin git+ssh://[email protected]/username/reponame.git

[1] This section incorporates the answer from Eric P

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];

How to listen state changes in react.js?

I haven't used Angular, but reading the link above, it seems that you're trying to code for something that you don't need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively 'listening' for changes). If you want to 'listen' from another component in your hierarchy then you have two options:

  1. Pass handlers down (via props) from a common parent and have them update the parent's state, causing the hierarchy below the parent to be re-rendered.
  2. Alternatively, to avoid an explosion of handlers cascading down the hierarchy, you should look at the flux pattern, which moves your state into data stores and allows components to watch them for changes. The Fluxxor plugin is very useful for managing this.

Convert one date format into another in PHP

strtotime will work that out. the dates are just not the same and all in us-format.

<?php
$e1 = strtotime("2013-07-22T12:00:03Z");
echo date('y.m.d H:i', $e1);
echo "2013-07-22T12:00:03Z";

$e2 = strtotime("2013-07-23T18:18:15Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-23T18:18:15Z";

$e1 = strtotime("2013-07-21T23:57:04Z");
echo date ('y.m.d H:i', $e2);
echo "2013-07-21T23:57:04Z";
?>

How to parse JSON Array (Not Json Object) in Android

@Stebra See this example. This may help you.

public class CustomerInfo 
{   
    @SerializedName("customerid")
    public String customerid;
    @SerializedName("picture")
    public String picture;

    @SerializedName("location")
    public String location;

    public CustomerInfo()
    {}
}

And when you get the result; parse like this

List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());

How to cut a string after a specific character in unix

This will also do.

echo $var | cut -f2 -d":"

How can I create an executable JAR with dependencies using Maven?

I compared the tree plugins mentioned in this post. I generated 2 jars and a directory with all the jars. I compared the results and definitely the maven-shade-plugin is the best. My challenge was that I have multiple spring resources that needed to be merged, as well as jax-rs, and JDBC services. They were all merged properly by the shade plugin in comparison with the maven-assembly-plugin. In which case the spring will fail unless you copy them to your own resources folder and merge them manually one time. Both plugins output the correct dependency tree. I had multiple scopes like test,provide, compile, etc the test and provided were skipped by both plugins. They both produced the same manifest but I was able to consolidate licenses with the shade plugin using their transformer. With the maven-dependency-plugin of course you don't have those problems because the jars are not extracted. But like some other have pointed you need to carry one extra file(s) to work properly. Here is a snip of the pom.xml

            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <includeScope>compile</includeScope>
                        <excludeTransitive>true</excludeTransitive>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <mainClass>com.rbccm.itf.cdd.poller.landingzone.LandingZonePoller</mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>make-my-jar-with-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.3</version>
            <configuration>
                <shadedArtifactAttached>false</shadedArtifactAttached>
                <keepDependenciesWithProvidedScope>false</keepDependenciesWithProvidedScope>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/services/javax.ws.rs.ext.Providers</resource>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.factories</resource>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.handlers</resource>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.schemas</resource>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                        <resource>META-INF/spring.tooling</resource>
                    </transformer>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"/>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer">
                    </transformer>
                </transformers>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Python and JSON - TypeError list indices must be integers not str

You can simplify your code down to

url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
    print player['firstName']

You were trying to access a list element using dictionary syntax. the equivalent of

foo = [1, 2, 3, 4]
foo["1"]

It can be confusing when you have lists of dictionaries and keeping the nesting in order.

Android: Unable to add window. Permission denied for this window type

I did manage to finally display a window on the lock screen with the use of TYPE_SYSTEM_OVERLAY instead of TYPE_KEYGUARD_DIALOG. This works as expected and adds the window on the lock screen.

The problem with this is that the window is added on top of everything it possibly can. That is, the window will even appear on top of your keypad/pattern lock in case of secure lock screens. In the case of an unsecured lock screen, it will appear on top of the notification tray if you open it from the lock screen.

For me, that is unacceptable. I hope that this may help anybody else facing this problem.

How to set a maximum execution time for a mysql query?

If you're using the mysql native driver (common since php 5.3), and the mysqli extension, you can accomplish this with an asynchronous query:

<?php

// Here's an example query that will take a long time to execute.
$sql = "
    select *
    from information_schema.tables t1
    join information_schema.tables t2
    join information_schema.tables t3
    join information_schema.tables t4
    join information_schema.tables t5
    join information_schema.tables t6
    join information_schema.tables t7
    join information_schema.tables t8
";

$mysqli = mysqli_connect('localhost', 'root', '');
$mysqli->query($sql, MYSQLI_ASYNC | MYSQLI_USE_RESULT);
$links = $errors = $reject = [];
$links[] = $mysqli;

// wait up to 1.5 seconds
$seconds = 1;
$microseconds = 500000;

$timeStart = microtime(true);

if (mysqli_poll($links, $errors, $reject, $seconds, $microseconds) > 0) {
    echo "query finished executing. now we start fetching the data rows over the network...\n";
    $result = $mysqli->reap_async_query();
    if ($result) {
        while ($row = $result->fetch_row()) {
            // print_r($row);
            if (microtime(true) - $timeStart > 1.5) {
                // we exceeded our time limit in the middle of fetching our result set.
                echo "timed out while fetching results\n";
                var_dump($mysqli->close());
                break;
            }
        }
    }
} else {
    echo "timed out while waiting for query to execute\n";
    var_dump($mysqli->close());
}

The flags I'm giving to mysqli_query accomplish important things. It tells the client driver to enable asynchronous mode, while forces us to use more verbose code, but lets us use a timeout(and also issue concurrent queries if you want!). The other flag tells the client not to buffer the entire result set into memory.

By default, php configures its mysql client libraries to fetch the entire result set of your query into memory before it lets your php code start accessing rows in the result. This can take a long time to transfer a large result. We disable it, otherwise we risk that we might time out while waiting for the buffering to complete.

Note that there's two places where we need to check for exceeding a time limit:

  • The actual query execution
  • while fetching the results(data)

You can accomplish similar in the PDO and regular mysql extension. They don't support asynchronous queries, so you can't set a timeout on the query execution time. However, they do support unbuffered result sets, and so you can at least implement a timeout on the fetching of the data.

For many queries, mysql is able to start streaming the results to you almost immediately, and so unbuffered queries alone will allow you to somewhat effectively implement timeouts on certain queries. For example, a

select * from tbl_with_1billion_rows

can start streaming rows right away, but,

select sum(foo) from tbl_with_1billion_rows

needs to process the entire table before it can start returning the first row to you. This latter case is where the timeout on an asynchronous query will save you. It will also save you from plain old deadlocks and other stuff.

ps - I didn't include any timeout logic on the connection itself.

Regex for allowing alphanumeric,-,_ and space

For me I wanted a regex which supports a strings as preceding. Basically, the motive is to support some foreign countries postal format as it should be an alphanumeric with spaces allowed.

  1. ABC123
  2. ABC 123
  3. ABC123(space)
  4. ABC 123 (space)

So I ended up by writing custom regex as below.

/^([a-z]+[\s]*[0-9]+[\s]*)+$/i

enter image description here

Here, I gave * in [\s]* as it is not mandatory to have a space. A postal code may or may not contains space in my case.

Cannot push to GitHub - keeps saying need merge

I was getting a similar error while pushing the latest changes to a bare Git repository which I use for gitweb. In my case I didn't make any changes in the bare repository, so I simply deleted my bare repository and cloned again:

git clone --bare <source repo path> <target bare repo path>

What is an undefined reference/unresolved external symbol error and how do I fix it?

This is one of most confusing error messages that every VC++ programmers have seen time and time again. Let’s make things clarity first.

A. What is symbol? In short, a symbol is a name. It can be a variable name, a function name, a class name, a typedef name, or anything except those names and signs that belong to C++ language. It is user defined or introduced by a dependency library (another user-defined).

B. What is external? In VC++, every source file (.cpp,.c,etc.) is considered as a translation unit, the compiler compiles one unit at a time, and generate one object file(.obj) for the current translation unit. (Note that every header file that this source file included will be preprocessed and will be considered as part of this translation unit)Everything within a translation unit is considered as internal, everything else is considered as external. In C++, you may reference an external symbol by using keywords like extern, __declspec (dllimport) and so on.

C. What is “resolve”? Resolve is a linking-time term. In linking-time, linker attempts to find the external definition for every symbol in object files that cannot find its definition internally. The scope of this searching process including:

  • All object files that generated in compiling time
  • All libraries (.lib) that are either explicitly or implicitly specified as additional dependencies of this building application.

This searching process is called resolve.

D. Finally, why Unresolved External Symbol? If the linker cannot find the external definition for a symbol that has no definition internally, it reports an Unresolved External Symbol error.

E. Possible causes of LNK2019: Unresolved External Symbol error. We already know that this error is due to the linker failed to find the definition of external symbols, the possible causes can be sorted as:

  1. Definition exists

For example, if we have a function called foo defined in a.cpp:

int foo()
{
    return 0;
}

In b.cpp we want to call function foo, so we add

void foo();

to declare function foo(), and call it in another function body, say bar():

void bar()
{
    foo();
}

Now when you build this code you will get a LNK2019 error complaining that foo is an unresolved symbol. In this case, we know that foo() has its definition in a.cpp, but different from the one we are calling(different return value). This is the case that definition exists.

  1. Definition does not exist

If we want to call some functions in a library, but the import library is not added into the additional dependency list (set from: Project | Properties | Configuration Properties | Linker | Input | Additional Dependency) of your project setting. Now the linker will report a LNK2019 since the definition does not exist in current searching scope.

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.

Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModules basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandlers can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.

Can I have multiple Xcode versions installed?

Can I have multiple Xcode versions installed?

Solution:
Actually as many of the above answers says, it is possible. Even according to the following Oracle Mobile Platform Blog, you can install more than one XCodes in the same Mac. The reason why you need to do that may vary according to you.

Scenario:
You might have installed only one version of XCode for now. Mostly the one release behind the latest XCode version which is available through App Store (mine I've Xcode 6.3.2 and I needed to keep it and also install Xcode 7 which is available through App Store).

For Ex:-

You have already installed XCode 6.x, and App Store has XCode 7 already given by App Store. For any reason you need to keep that Older XCode 6.x(as you know it is stable for some time now) and also you need to install and try out new XCode 7

So number one question might be, How and Where could you download the Mac OS X installable DMG file for XCode 7 (or may be if you wanna try out an older XCode version)? Ok, here is the direct link apple downloads (you might have to log into Apple Developer account before viewing this link correctly), or else following is a StackOverflow Q&A link which gives the answer to where to download DMG files for XCode IDEs.

So now let's assume that you have obtained any of the DMG file for the XCode version you require to install as secondarily?

Steps:
Follow the steps given bellow which I got from the above given first link of Oracles Mobile Platform Blog.

  1. Close Xcode if running
  2. Rename /Applications/Xcode.app to /Applications/Xcode_6.x.app
  3. Enter the admin password when prompted
  4. Double click the DMG file of your required, pre-downloaded Xcode and install it
  5. Once installed it, before running it, change the new /Applications/Xcode.app that was just installed to (according to my above given example) /Application/Xcode_7.app

Note*:

[Please patiently read this section until the next Note] When you have two versions of Xcode installed, your workstation has two versions of Command Line Tool (xcodebuild) installed too. The question is what your Terminal and Xcode build command will use to when you are building your iOS App. Because along with the Command Line Tool, iOS SDK which is being used to build your app also depends on.

My experience was I've had two Xcode versions. Xcode 10 (Old one with iOS12.0 - iphoneos12.0), and Xcode 10.1 (New one with iOS 12.1 - iphoneos12.1). So obviously the settings for Command Line Tool was selected to use xcodebuild tool from the Old app. I had to manually select it in Xcode preference window.

Where to set Command Line Tool in Xcode Preference Window?

  • Select the Locations tab and there, you can select all the installed versions of Command Line Tools (which is xcodebuild).

How to figure out which version of iOS SDK is being used to build your iOS App?

  • On your Terminal issue following command: $> xcodebuild -showsdks
  • Above command should print out all the SDK details which your current Xcode configuration uses to build your Apps. And by seeing the results you will understand that your iOS/iphoneos SDK version depends on changing Command Line Tool (xcodebuild) setting on your Xcode.

Note**:
Above given Apple Downloads link and Oracles MPF blog post links might change and/or unavailable in the future.

So I hope that my this answer might be helpful to somebody else out there!
Cheers!

Where is the itoa function in Linux?

As Matt J wrote, there is itoa, but it's not standard. Your code will be more portable if you use snprintf.

How to center absolute div horizontally using CSS?

Although above answers are correct but to make it simple for newbies, all you need to do is set margin, left and right. following code will do it provided that width is set and position is absolute:

margin: 0 auto;
left: 0;
right: 0;

Demo:

_x000D_
_x000D_
.centeredBox {_x000D_
    margin: 0 auto;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
   _x000D_
   _x000D_
   /** Position should be absolute */_x000D_
    position: absolute;_x000D_
    /** And box must have a width, any width */_x000D_
    width: 40%;_x000D_
    background: #faebd7;_x000D_
   _x000D_
   }
_x000D_
<div class="centeredBox">Centered Box</div>
_x000D_
_x000D_
_x000D_

jQuery add image inside of div tag

$("#theDiv").append("<img id='theImg' src='theImg.png'/>");

You need to read the documentation here.

Calling a stored procedure in Oracle with IN and OUT parameters

If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!

The code is,

set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;

And then call the function as it is:

DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

How to animate CSS Translate

I too was looking for a good way to do this, I found the best way was to set a transition on the "transform" property and then change the transform and then remove the transition.

I put it all together in a jQuery plugin

https://gist.github.com/dustinpoissant/8a4837c476e3939a5b3d1a2585e8d1b0

You would use the code like this:

$("#myElement").animateTransform("rotate(180deg)", 750, function(){
  console.log("animation completed after 750ms");
});

Setting cursor at the end of any text of a textbox

There are multiple options:

txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);

Find a line in a file and remove it

You want to do something like the following:

  • Open the old file for reading
  • Open a new (temporary) file for writing
  • Iterate over the lines in the old file (probably using a BufferedReader)
    • For each line, check if it matches what you are supposed to remove
    • If it matches, do nothing
    • If it doesn't match, write it to the temporary file
  • When done, close both files
  • Delete the old file
  • Rename the temporary file to the name of the original file

(I won't write the actual code, since this looks like homework, but feel free to post other questions on specific bits that you have trouble with)

How to get the size of a JavaScript object?

Here's a slightly more compact solution to the problem:

const typeSizes = {
  "undefined": () => 0,
  "boolean": () => 4,
  "number": () => 8,
  "string": item => 2 * item.length,
  "object": item => !item ? 0 : Object
    .keys(item)
    .reduce((total, key) => sizeOf(key) + sizeOf(item[key]) + total, 0)
};

const sizeOf = value => typeSizes[typeof value](value);

Removing duplicate rows in Notepad++

You may need a plugin to do this. You can try the command line cc.ddl(delete duplicate lines) of ConyEdit. It is a cross-editor plugin for the text editors, including Notepad++.

With ConyEdit running in background, follow the steps below:

  1. enter the command line cc.ddl at the end of the text.
  2. copy the text and the command line.
  3. paste, then you will see what you want.

Example
enter image description here

Error running android: Gradle project sync failed. Please fix your project and try again

Delete .gradle folder(root directory) and build folder(project directory) and then invalidate caches/restart android studio, run your project again hopefully it will work. It might take some time for the background tasks. In some countries, you may need to turn on the VPN to download.

After updating Entity Framework model, Visual Studio does not see changes

Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.

Add JavaScript object to JavaScript object

// Merge object2 into object1, recursively

$.extend( true, object1, object2 );

// Merge object2 into object1

$.extend( object1, object2 );

https://api.jquery.com/jquery.extend/

Get User Selected Range

This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.

Sub test()
    Dim myString As String
    myString = Selection.Address
End Sub

Simple mediaplayer play mp3 from file path?

It works like this:

mpintro = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/intro.mp3"));
mpintro.setLooping(true);
        mpintro.start();

It did not work properly as string filepath...

How to iterate through a DataTable

You can also use linq extensions for DataSets:

var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
    TextBox1.Text = imgPath;
}

ggplot2: sorting a plot

I've recently been struggling with a related issue, discussed at length here: Order of legend entries in ggplot2 barplots with coord_flip() .

As it happens, the reason I had a hard time explaining my issue clearly, involved the relation between (the order of) factors and coord_flip(), as seems to be the case here.

I get the desired result by adding + xlim(rev(levels(x$variable))) to the ggplot statement:

ggplot(x, aes(x=variable,y=value)) + geom_bar() + 
scale_y_continuous("",formatter="percent") + coord_flip() 
+  xlim(rev(levels(x$variable)))

This reverses the order of factors as found in the original data frame in the x-axis, which will become the y-axis with coord_flip(). Notice that in this particular example, the variable also happen to be in alphabetical order, but specifying an arbitrary order of levels within xlim() should work in general.

How to give the background-image path in CSS?

you can also add inline css for adding image as a background as per below example

<div class="item active" style="background-image: url(../../foo.png);">

Asynchronously wait for Task<T> to complete with timeout

Another way of solving this problem is using Reactive Extensions:

public static Task TimeoutAfter(this Task task, TimeSpan timeout, IScheduler scheduler)
{
        return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}

Test up above using below code in your unit test, it works for me

TestScheduler scheduler = new TestScheduler();
Task task = Task.Run(() =>
                {
                    int i = 0;
                    while (i < 5)
                    {
                        Console.WriteLine(i);
                        i++;
                        Thread.Sleep(1000);
                    }
                })
                .TimeoutAfter(TimeSpan.FromSeconds(5), scheduler)
                .ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);

scheduler.AdvanceBy(TimeSpan.FromSeconds(6).Ticks);

You may need the following namespace:

using System.Threading.Tasks;
using System.Reactive.Subjects;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using Microsoft.Reactive.Testing;
using System.Threading;
using System.Reactive.Concurrency;

Get records of current month

Check the MySQL Datetime Functions:

Try this:

SELECT * 
FROM tableA 
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND 
      MONTH(columnName) = MONTH(CURRENT_DATE());

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

I enabled zlib.output_compression in php.ini and it seemed to fix the issue for me.

How to get json response using system.net.webrequest in c#?

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

How can I find out if I have Xcode commandline tools installed?

/usr/bin/xcodebuild -version

will give you the xcode version, run it via Terminal command

How to set a value for a selectize.js input?

I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.

So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.

I ended up using this hack (which it is probably unsupported):

var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();

Twitter Bootstrap - how to center elements horizontally or vertically

for bootstrap4 vertical center of few items

d-flex for flex rules

flex-column for vertical direction on items

justify-content-center for centering

style='height: 300px;' must have for set points where center be calc or use h-100 class

<div class="d-flex flex-column justify-content-center bg-secondary" style="
    height: 300px;
">
    <div class="p-2 bg-primary">Flex item</div>
    <div class="p-2 bg-primary">Flex item</div>
    <div class="p-2 bg-primary">Flex item</div>
  </div> 

How to run a program in Atom Editor?

You can run specific lines of script by highlighting them and clicking shift + ctrl + b

You can also use command line by going to the root folder and writing: $ node nameOfFile.js

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

How to return a string value from a Bash function

You could have the function take a variable as the first arg and modify the variable with the string you want to return.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "$1='foo bar rab oof'"
}

return_var=''
pass_back_a_string return_var
echo $return_var

Prints "foo bar rab oof".

Edit: added quoting in the appropriate place to allow whitespace in string to address @Luca Borrione's comment.

Edit: As a demonstration, see the following program. This is a general-purpose solution: it even allows you to receive a string into a local variable.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "$1='foo bar rab oof'"
}

return_var=''
pass_back_a_string return_var
echo $return_var

function call_a_string_func() {
     local lvar=''
     pass_back_a_string lvar
     echo "lvar='$lvar' locally"
}

call_a_string_func
echo "lvar='$lvar' globally"

This prints:

+ return_var=
+ pass_back_a_string return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local lvar=
+ pass_back_a_string lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally

Edit: demonstrating that the original variable's value is available in the function, as was incorrectly criticized by @Xichen Li in a comment.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "echo in pass_back_a_string, original $1 is \$$1"
    eval "$1='foo bar rab oof'"
}

return_var='original return_var'
pass_back_a_string return_var
echo $return_var

function call_a_string_func() {
     local lvar='original lvar'
     pass_back_a_string lvar
     echo "lvar='$lvar' locally"
}

call_a_string_func
echo "lvar='$lvar' globally"

This gives output:

+ return_var='original return_var'
+ pass_back_a_string return_var
+ eval 'echo in pass_back_a_string, original return_var is $return_var'
++ echo in pass_back_a_string, original return_var is original return_var
in pass_back_a_string, original return_var is original return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local 'lvar=original lvar'
+ pass_back_a_string lvar
+ eval 'echo in pass_back_a_string, original lvar is $lvar'
++ echo in pass_back_a_string, original lvar is original lvar
in pass_back_a_string, original lvar is original lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally

how to parse JSON file with GSON

You have to fetch the whole data in the list and then do the iteration as it is a file and will become inefficient otherwise.

private static final Type REVIEW_TYPE = new TypeToken<List<Review>>() {
}.getType();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
List<Review> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole reviews list
data.toScreen(); // prints to screen some values

How do I make HttpURLConnection use a proxy?

Proxies are supported through two system properties: http.proxyHost and http.proxyPort. They must be set to the proxy server and port respectively. The following basic example illustrates it:

String url = "http://www.google.com/",
       proxy = "proxy.mydomain.com",
       port = "8080";
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
readResponse(in);

Checking if an object is a number in C#

Take advantage of the IsPrimitive property to make a handy extension method:

public static bool IsNumber(this object obj)
{
    if (Equals(obj, null))
    {
        return false;
    }

    Type objType = obj.GetType();
    objType = Nullable.GetUnderlyingType(objType) ?? objType;

    if (objType.IsPrimitive)
    {
        return objType != typeof(bool) && 
            objType != typeof(char) && 
            objType != typeof(IntPtr) && 
            objType != typeof(UIntPtr);
    }

    return objType == typeof(decimal);
}

EDIT: Fixed as per comments. The generics were removed since .GetType() boxes value types. Also included fix for nullable values.

inserting characters at the start and end of a string

Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:

s = "something about cupcakes"
print(f"L{s}LL")

Using CSS in Laravel views?

Put your assets in the public folder

public/css
public/images
public/fonts
public/js

And them called it using Laravel

{{ HTML::script('js/scrollTo.js'); }}

{{ HTML::style('css/css.css'); }}

JavaScript Infinitely Looping slideshow with delays?

The key is not to schedule all pics at once, but to schedule a next pic each time you have a pic shown.

var current = 0;
var num_slides = 10;
function slide() {
    // here display the current slide, then:

    current = (current + 1) % num_slides;
    setTimeout(slide, 3000);
}

The alternative is to use setInterval, which sets the function to repeat regularly (as opposed to setTimeout, which schedules the next appearance only.

Counting the number of elements with the values of x in a vector

One option could be to use vec_count() function from the vctrs library:

vec_count(numbers)

   key count
1  435     3
2   67     2
3    4     2
4   34     2
5   56     2
6   23     2
7  456     1
8   43     1
9  453     1
10   5     1
11 657     1
12 324     1
13  54     1
14 567     1
15  65     1

The default ordering puts the most frequent values at top. If looking for sorting according keys (a table()-like output):

vec_count(numbers, sort = "key")

   key count
1    4     2
2    5     1
3   23     2
4   34     2
5   43     1
6   54     1
7   56     2
8   65     1
9   67     2
10 324     1
11 435     3
12 453     1
13 456     1
14 567     1
15 657     1

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

Formatting PowerShell Get-Date inside string

"This is my string with date in specified format $($theDate.ToString('u'))"

or

"This is my string with date in specified format $(Get-Date -format 'u')"

The sub-expression ($(...)) can include arbitrary expressions calls.

MSDN Documents both standard and custom DateTime format strings.

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

You may also get this error if you have a name clash of a view and a module. I've got the error when i distribute my view files under views folder, /views/view1.py, /views/view2.py and imported some model named table.py in view2.py which happened to be a name of a view in view1.py. So naming the view functions as v_table(request,id) helped.

How do I correctly clean up a Python object?

I'd recommend using Python's with statement for managing resources that need to be cleaned up. The problem with using an explicit close() statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a finally block to prevent a resource leak when an exception occurs.

To use the with statement, create a class with the following methods:

  def __enter__(self)
  def __exit__(self, exc_type, exc_value, traceback)

In your example above, you'd use

class Package:
    def __init__(self):
        self.files = []

    def __enter__(self):
        return self

    # ...

    def __exit__(self, exc_type, exc_value, traceback):
        for file in self.files:
            os.unlink(file)

Then, when someone wanted to use your class, they'd do the following:

with Package() as package_obj:
    # use package_obj

The variable package_obj will be an instance of type Package (it's the value returned by the __enter__ method). Its __exit__ method will automatically be called, regardless of whether or not an exception occurs.

You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the with clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the __enter__ and __exit__ methods. Then, the Package class would be defined strictly inside the __enter__ method and returned. That way, the caller never could instantiate the Package class without using a with statement:

class PackageResource:
    def __enter__(self):
        class Package:
            ...
        self.package_obj = Package()
        return self.package_obj

    def __exit__(self, exc_type, exc_value, traceback):
        self.package_obj.cleanup()

You'd use this as follows:

with PackageResource() as package_obj:
    # use package_obj

How to Display Selected Item in Bootstrap Button Dropdown Title

Another simple way (Bootstrap 4) to work with multiple dropdowns

    $('.dropdown-item').on('click',  function(){
        var btnObj = $(this).parent().siblings('button');
        $(btnObj).text($(this).text());
        $(btnObj).val($(this).text());
    });

Creating a script for a Telnet session?

Couple of questions:

  1. Can you put stuff on the device that you're telnetting into?
  2. Are the commands executed by the script the same or do they vary by machine/user?
  3. Do you want the person clicking the icon to have to provide a userid and/or password?

That said, I wrote some Java a while ago to talk to a couple of IP-enabled power strips (BayTech RPC3s) which might be of use to you. If you're interested I'll see if I can dig it up and post it someplace.

IIS Express Windows Authentication

This answer may help if: 1) your site used to work with Windows authentication before upgrading to Visual Studio 2015 and 2) and your site is attempting to load /login.aspx (even though there is no such file on your site).

Add the following two lines to the appSettingssection of your site's Web.config.

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>

How to upload a file and JSON data in Postman?

To send image along with json data in postman you just have to follow the below steps .

  • Make your method to post in postman
  • go to the body section and click on form-data
  • provide your field name select file from the dropdown list as shown below
  • you can also provide your other fields .
  • now just write your image storing code in your controller as shown below .

postman : enter image description here

my controller :

public function sendImage(Request $request)
{
    $image=new ImgUpload;  
    if($request->hasfile('image'))  
    {  
        $file=$request->file('image');  
        $extension=$file->getClientOriginalExtension();  
        $filename=time().'.'.$extension;  
        $file->move('public/upload/userimg/',$filename);  
        $image->image=$filename;  
    }  
    else  
    {  
        return $request;  
        $image->image='';  
    }  
    $image->save();
    return response()->json(['response'=>['code'=>'200','message'=>'image uploaded successfull']]);
}

That's it hope it will help you

Why am I seeing "TypeError: string indices must be integers"?

data is a dict object. So, iterate over it like this:

Python 2

for key, value in data.iteritems():
    print key, value

Python 3

for key, value in data.items():
    print(key, value)

Python: TypeError: cannot concatenate 'str' and 'int' objects

If you want to concatenate int or floats to a string you must use this:

i = 123
a = "foobar"
s = a + str(i)

Error related to only_full_group_by when executing a query in MySql

you can turn off the warning message as explained in the other answers or you can understand what's happening and fix it.

As of MySQL 5.7.5, the default SQL mode includes ONLY_FULL_GROUP_BY which means when you are grouping rows and then selecting something out of that groups, you need to explicitly say which row should that selection be made from. Mysql needs to know which row in the group you're looking for, which gives you two options

Mysql needs to know which row in the group you're looking for, which gives you two options

  • You can also add the column you want to the group statement group by rect.color, rect.value which can be what you want in some cases otherwise would return duplicate results with the same color which you may not want
  • you could also use aggregate functions of mysql to indicate which row you are looking for inside the groups like AVG() MIN() MAX() complete list
  • AND finally you can use ANY_VALUE() if you are sure that all the results inside the group are the same. doc

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

Checkout Jenkins Pipeline Git SCM with credentials?

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}

compareTo with primitives -> Integer / int

For pre 1.7 i would say an equivalent to Integer.compare(x, y) is:

Integer.valueOf(x).compareTo(y);

Node.js - use of module.exports as a constructor

In my opinion, some of the node.js examples are quite contrived.

You might expect to see something more like this in the real world

// square.js
function Square(width) {

  if (!(this instanceof Square)) {
    return new Square(width);
  }

  this.width = width;
};

Square.prototype.area = function area() {
  return Math.pow(this.width, 2);
};

module.exports = Square;

Usage

var Square = require("./square");

// you can use `new` keyword
var s = new Square(5);
s.area(); // 25

// or you can skip it!
var s2 = Square(10);
s2.area(); // 100

For the ES6 people

class Square {
  constructor(width) {
    this.width = width;
  }
  area() {
    return Math.pow(this.width, 2);
  }
}

export default Square;

Using it in ES6

import Square from "./square";
// ...

When using a class, you must use the new keyword to instatiate it. Everything else stays the same.

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

How to display items side-by-side without using tables?

You should float them inside a container that is cleared.

Example:

https://jsfiddle.net/W74Z8/504/

enter image description here

A clean implementation is the "clearfix hack". This is Nicolas Gallagher's version:

/**
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    contenteditable attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that are clearfixed.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */
.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/**
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */
.clearfix {
    *zoom: 1;
}
?

How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];
data.push(postdata);

console.log(data);

How can I get city name from a latitude and longitude point?

In case if you don't want to use google geocoding API than you can refer to few other Free APIs for the development purpose. for example i used [mapquest] API in order to get the location name.

you can fetch location name easily by implementing this following function

_x000D_
_x000D_
 const fetchLocationName = async (lat,lng) => {
    await fetch(
      'https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location='+lat+'%2C'+lng+'&outFormat=json&thumbMaps=false',
    )
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(
          'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson),
        );
      });
  };
_x000D_
_x000D_
_x000D_

Git Bash: Could not open a connection to your authentication agent

I was struggling with the problem as well.

After I typed $ eval 'ssh-agent -s' followed by $ssh-add ~/.ssh/id_rsa

I got the same complain: "Could not open a connection to your authentication agent". Then I realize there are two different kind of quotation on my computer's keyboard. So I tried the one at the same position as "~": $ eval ssh-agent -s $ ssh-add ~/.ssh/id_rsa

And bang it worked.

Str_replace for multiple items

Like this:

str_replace(array(':', '\\', '/', '*'), ' ', $string);

Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:

str_replace([':', '\\', '/', '*'], ' ', $string);

Horizontal swipe slider with jQuery and touch devices support?

Take a look at iScroll v4 here: http://cubiq.org/iscroll-4

It may not be jQuery, but it works on Desktop Mobile, and iPad quite well; I've used it on many projects and combined it with jQuery.

Good Luck!

Sorting std::map using value

If you want to present the values in a map in sorted order, then copy the values from the map to vector and sort the vector.

How do I find the location of Python module sources?

Another way to check if you have multiple python versions installed, from the terminal.

-MBP:~python3 -m pip show pyperclip

Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-

MBP:~ python -m pip show pyperclip

Location: /Users/umeshvuyyuru/Library/Python/2.7/lib/python/site-packages

How does one remove a Docker image?

docker rmi  91c95931e552

Error response from daemon: Conflict, cannot delete 91c95931e552 because the container 76068d66b290 is using it, use -f to force FATA[0000] Error: failed to remove one or more images

Find container ID,

# docker ps -a

# docker rm  daf644660736 

how can the textbox width be reduced?

<input type="text" style="width:50px;"/>

Check if an object exists

Since filter returns a QuerySet, you can use count to check how many results were returned. This is assuming you don't actually need the results.

num_results = User.objects.filter(email = cleaned_info['username']).count()

After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:

A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).

num_results = len(user_object)

HTML entity for the middle dot

This can be done easily using &middot;. You can color or size the dot according to the tags you wrap it with. For example, try and run this

<h2> I &middot; love &middot; Coding </h2>

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Text file in VBA: Open/Find Replace/SaveAs/Close File

I have had the same problem and came acrosse this site.

the solution to just set another "filename" in the

... for output as ... command was very simple and useful.

in addition (beyond the Application.GetSaveAsFilename() Dialog)

it is very simple to set a** new filename** just using

the replace command, so you may change the filename/extension

eg. (as from the first post)

sFileName = "C:\filelocation"
iFileNum = FreeFile

Open sFileName For Input As iFileNum
content = (...edit the content) 

Close iFileNum

now just set:

newFilename = replace(sFilename, ".txt", ".csv") to change the extension

or

newFilename = replace(sFilename, ".", "_edit.") for a differrent filename

and then just as before

iFileNum = FreeFile
Open newFileName For Output As iFileNum

Print #iFileNum, content
Close iFileNum 

I surfed over an hour to find out how to rename a txt-file,

with many different solutions, but it could be sooo easy :)

Read a text file using Node.js?

Usign fs with node.

var fs = require('fs');

try {  
    var data = fs.readFileSync('file.txt', 'utf8');
    console.log(data.toString());    
} catch(e) {
    console.log('Error:', e.stack);
}

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

How to schedule a task to run when shutting down windows

I had to also enable "Specify maximum wait time for group policy scripts" and "Display instructions in shutdown scripts as they run" to make it work for me as I explain here.

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

How do you tell if caps lock is on using JavaScript?

You can detect caps lock using "is letter uppercase and no shift pressed" using a keypress capture on the document. But then you better be sure that no other keypress handler pops the event bubble before it gets to the handler on the document.

document.onkeypress = function ( e ) {
  e = e || window.event;
  var s = String.fromCharCode( e.keyCode || e.which );
  if ( (s.toUpperCase() === s) !== e.shiftKey ) {
    // alert('caps is on')
  }
}

You could grab the event during the capturing phase in browsers that support that, but it seems somewhat pointless to as it won't work on all browsers.

I can't think of any other way of actually detecting caps lock status. The check is simple anyway and if non detectable characters were typed, well... then detecting wasn't necessary.

There was an article on 24 ways on this last year. Quite good, but lacks international character support (use toUpperCase() to get around that).

What are projection and selection?

Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).

In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.

Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:

SQL Order By Count

SELECT group, COUNT(*) FROM table GROUP BY group ORDER BY group

or to order by the count

SELECT group, COUNT(*) AS count FROM table GROUP BY group ORDER BY count DESC

How can I trigger a JavaScript event click

IE9+

function triggerEvent(el, type){
    var e = document.createEvent('HTMLEvents');
    e.initEvent(type, false, true);
    el.dispatchEvent(e);
}

Usage example:

var el = document.querySelector('input[type="text"]');
triggerEvent(el, 'mousedown');

Source: https://plainjs.com/javascript/events/trigger-an-event-11/

Tar error: Unexpected EOF in archive

In my case, I had started untar before the uploading of the tar file was complete.

java.util.Date to XMLGregorianCalendar

Here is a method for converting from a GregorianCalendar to XMLGregorianCalendar; I'll leave the part of converting from a java.util.Date to GregorianCalendar as an exercise for you:

import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class DateTest {

   public static void main(final String[] args) throws Exception {
      GregorianCalendar gcal = new GregorianCalendar();
      XMLGregorianCalendar xgcal = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(gcal);
      System.out.println(xgcal);
   }

}

EDIT: Slooow :-)

How to hide the keyboard when I press return key in a UITextField?

Define this class and then set your text field to use the class and this automates the whole hiding keyboard when return is pressed automatically.

class TextFieldWithReturn: UITextField, UITextFieldDelegate
{

    required init?(coder aDecoder: NSCoder) 
    {
        super.init(coder: aDecoder)
        self.delegate = self
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool
    {
        textField.resignFirstResponder()
        return true
    }

}

Then all you need to do in the storyboard is set the fields to use the class:

enter image description here

Setting top and left CSS attributes

Your problem is that the top and left properties require a unit of measure, not just a bare number:

div.style.top = "200px";
div.style.left = "200px";

Splitting a string into chunks of a certain size

Why not loops? Here's something that would do it quite well:

        string str = "111122223333444455";
        int chunkSize = 4;
        int stringLength = str.Length;
        for (int i = 0; i < stringLength ; i += chunkSize)
        {
            if (i + chunkSize > stringLength) chunkSize = stringLength  - i;
            Console.WriteLine(str.Substring(i, chunkSize));

        }
        Console.ReadLine();

I don't know how you'd deal with case where the string is not factor of 4, but not saying you're idea is not possible, just wondering the motivation for it if a simple for loop does it very well? Obviously the above could be cleaned and even put in as an extension method.

Or as mentioned in comments, you know it's /4 then

str = "1111222233334444";
for (int i = 0; i < stringLength; i += chunkSize) 
  {Console.WriteLine(str.Substring(i, chunkSize));} 

Removing special characters VBA Excel

In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.

For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:

Function cleanString(text As String) As String
    Dim output As String
    Dim c 'since char type does not exist in vba, we have to use variant type.
    For i = 1 To Len(text)
        c = Mid(text, i, 1) 'Select the character at the i position
        If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
            output = output & c 'add the character to your output.
        Else
            output = output & " " 'add the replacement character (space) to your output
        End If
    Next
    cleanString = output
End Function

The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.

This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.

What is the best way to convert an array to a hash in Ruby

if you have array that looks like this -

data = [["foo",1,2,3,4],["bar",1,2],["foobar",1,"*",3,5,:foo]]

and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -

data_hash = Hash[data.map { |key| [key.shift, key] }]

#=>{"foo"=>[1, 2, 3, 4], "bar"=>[1, 2], "foobar"=>[1, "*", 3, 5, :foo]}

Eclipse won't compile/run java file

This worked for me:

  1. Create a new project
  2. Create a class in it
  3. Add erroneous code, let error come
  4. Now go to your project
  5. Go to Problems window
  6. Double click on a error

It starts showing compilation errors in the code.

How can I check if a JSON is empty in NodeJS?

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.

Find the item with maximum occurrences in a list

Simple and best code:

def max_occ(lst,x):
    count=0
    for i in lst:
        if (i==x):
            count=count+1
    return count

lst=[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
x=max(lst,key=lst.count)
print(x,"occurs ",max_occ(lst,x),"times")

Output: 4 occurs 6 times

Laravel 5: Retrieve JSON array from $request

As of Laravel 5.2+, you can fetch it directly with $request->input('item') as well.

Retrieving JSON Input Values

When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig deeper into JSON arrays:

$name = $request->input('user.name');

https://laravel.com/docs/5.2/requests

As noted above, the content-type header must be set to application/json so the jQuery ajax call would need to include contentType: "application/json",

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    dataType: "json",
    contentType: "application/json",
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

By fixing the AJAX call, $request->all() should work.

How can I get the number of days between 2 dates in Oracle 11g?

I figured it out myself. I need

select extract(day from sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) from dual

How do you connect to a MySQL database using Oracle SQL Developer?

In fact you should do both :


  1. Add driver

  2. Add Oracle SQL developper connector

    • In Oracle SQL Developper > Help > Check for updates > Next
    • Check All > Next
    • Filter on "mysql"
    • Check All > Finish
  3. Next time you will add a connection, MySQL new tab is available !

How to enumerate a range of numbers starting at 1

I don't know how these posts could possibly be made more complicated then the following:

# Just pass the start argument to enumerate ...
for i,word in enumerate(allWords, 1):
    word2idx[word]=i
    idx2word[i]=word

EPPlus - Read Excel Table

This is my working version. Note that the resolvers code is not shown but are a spin on my implementation which allows columns to be resolved even though they are named slightly differently in each worksheet.

public static IEnumerable<T> ToArray<T>(this ExcelWorksheet worksheet, List<PropertyNameResolver> resolvers) where T : new()
{

  // List of all the column names
  var header = worksheet.Cells.GroupBy(cell => cell.Start.Row).First();

  // Get the properties from the type your are populating
  var properties = typeof(T).GetProperties().ToList();


  var start = worksheet.Dimension.Start;
  var end = worksheet.Dimension.End;

  // Resulting list
  var list = new List<T>();

  // Iterate the rows starting at row 2 (ie start.Row + 1)
  for (int row = start.Row + 1; row <= end.Row; row++)
  {
    var instance = new T();
    for (int col = start.Column; col <= end.Column; col++)
    {
      object value = worksheet.Cells[row, col].Text;

      // Get the column name zero based (ie col -1)
      var column = (string)header.Skip(col - 1).First().Value;

      // Gets the corresponding property to set
      var property = properties.Property(resolvers, column);

      try
      {
        var propertyName = property.PropertyType.IsGenericType
          ? property.PropertyType.GetGenericArguments().First().FullName
          : property.PropertyType.FullName;


        // Implement setter code as needed. 
        switch (propertyName)
        {
          case "System.String":
            property.SetValue(instance, Convert.ToString(value));
            break;
          case "System.Int32":
            property.SetValue(instance, Convert.ToInt32(value));
            break;
          case "System.DateTime":
            if (DateTime.TryParse((string) value, out var date))
            {
              property.SetValue(instance, date);
            }
            property.SetValue(instance, FromExcelSerialDate(Convert.ToInt32(value)));
            break;
          case "System.Boolean":
            property.SetValue(instance, (int)value == 1);
            break;
        }
      }
      catch (Exception e)
      {
        // instance property is empty because there was a problem.
      }

    } 
    list.Add(instance);
  }
  return list;
}

// Utility function taken from the above post's inline function.
public static DateTime FromExcelSerialDate(int excelDate)
{
  if (excelDate < 1)
    throw new ArgumentException("Excel dates cannot be smaller than 0.");

  var dateOfReference = new DateTime(1900, 1, 1);

  if (excelDate > 60d)
    excelDate = excelDate - 2;
  else
    excelDate = excelDate - 1;
  return dateOfReference.AddDays(excelDate);
}

Postgres: check if array field contains value?

Instead of IN we can use ANY with arrays casted to enum array, for example:

create type example_enum as enum (
  'ENUM1', 'ENUM2'
);

create table example_table (
  id integer,
  enum_field example_enum
);

select 
  * 
from 
  example_table t
where
  t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);

Or we can still use 'IN' clause, but first, we should 'unnest' it:

select 
  * 
from 
  example_table t
where
  t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));

Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0

How to print binary number via printf

Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:

  char buffer [33];
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);

Here's the origin:

itoa in cplusplus reference

It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

Regex to extract substring, returning 2 results for some reason

Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)

var source = "afskfsd33j"
var result = source.match(/a(.*)j/);

result: ["afskfsd33j", "fskfsd33"]

The reason why you received this exact result is following:

First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".

Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".

If you want to get rid of second value in array you may define pattern like this:

/a(?:.*)j/

where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.

Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:

/a.*j/

If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:

var result = /a.*j/.test(source);

The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml

How to change the text color of first select option

If the first item is to be used as a placeholder (empty value) and your select is required then you can use the :invalid pseudo-class to target it.

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: menulist-button;_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
select:invalid {_x000D_
  color: green;_x000D_
}
_x000D_
<select required>_x000D_
  <option value="">Item1</option>_x000D_
  <option value="Item2">Item2</option>_x000D_
  <option value="Item3">Item3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Get user's current location

You may want to take a look at GeoIP Country Whois Locator found at PHPClasses.

Outlets cannot be connected to repeating content iOS

As most people have pointed out that subclassing UITableViewCell solves this issue. But the reason this not allowed because the prototype cell(UITableViewCell) is defined by Apple and you cannot add any of your own outlets to it.

Resetting MySQL Root Password with XAMPP on Localhost

SIMPLE STRAIGHT FORWARD WORKING SOLUTION AND OUT OF THE BOX:

1 - Start the Apache Server and MySQL instances from the XAMPP control panel.

2 - After the server started, open any web browser and give http://localhost/phpmyadmin/. This will open the phpMyAdmin interface. Using this interface we can manage the MySQL server from the web browser.

3 - In the phpMyAdmin window, select SQL tab from the top panel. This will open the SQL tab where we can run the SQL queries.

4 - Now type the following query in the text area and click Go

UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; FLUSH PRIVILEGES;

5 - Now you will see a message saying some thing like: the query has been executed successfully.

6 - If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.

7 - Open the file [XAMPP Installation Path]/phpmyadmin/config.inc.php in your favorite text editor (e.g: C:\xampp\phpMyAdmin\config.inc.php).

8 - Search for the string

$cfg['Servers'][$i]['password'] = '';

and change it to like this,

$cfg['Servers'][$i]['password'] = 'password';

Here the ‘password’ is what we set to the root user using the SQL query.

9 - Now all set to go. Save the config.inc.php file and restart the XAMPP apache and mysql servers. It should work!

Source: https://veerasundar.com/blog/2009/01/how-to-change-the-root-password-for-mysql-in-xampp/

DONE!

Add a auto increment primary key to existing table in oracle

If you have the column and the sequence, you first need to populate a new key for all the existing rows. Assuming you don't care which key is assigned to which row

UPDATE table_name
   SET new_pk_column = sequence_name.nextval;

Once that's done, you can create the primary key constraint (this assumes that either there is no existing primary key constraint or that you have already dropped the existing primary key constraint)

ALTER TABLE table_name
  ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )

If you want to generate the key automatically, you'd need to add a trigger

CREATE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  FOR EACH ROW
BEGIN
  :new.new_pk_column := sequence_name.nextval;
END;

If you are on an older version of Oracle, the syntax is a bit more cumbersome

CREATE TRIGGER trigger_name
  BEFORE INSERT ON table_name
  FOR EACH ROW
BEGIN
  SELECT sequence_name.nextval
    INTO :new.new_pk_column
    FROM dual;
END;

What is the optimal algorithm for the game 2048?

I think I found an algorithm which works quite well, as I often reach scores over 10000, my personal best being around 16000. My solution does not aim at keeping biggest numbers in a corner, but to keep it in the top row.

Please see the code below:

while( !game_over ) {
    move_direction=up;
    if( !move_is_possible(up) ) {
        if( move_is_possible(right) && move_is_possible(left) ){
            if( number_of_empty_cells_after_moves(left,up) > number_of_empty_cells_after_moves(right,up) ) 
                move_direction = left;
            else
                move_direction = right;
        } else if ( move_is_possible(left) ){
            move_direction = left;
        } else if ( move_is_possible(right) ){
            move_direction = right;
        } else {
            move_direction = down;
        }
    }
    do_move(move_direction);
}

What is a software framework?

Technically, you don't need a framework. If you're making a really really simple site (think of the web back in 1992), you can just do it all with hard-coded HTML and some CSS.

And if you want to make a modern webapp, you don't actually need to use a framework for that, either.

You can instead choose to write all of the logic you need yourself, every time. You can write your own data-persistence/storage layer, or - if you're too busy - just write custom SQL for every single database access. You can write your own authentication and session handling layers. And your own template rending logic. And your own exception-handling logic. And your own security functions. And your own unit test framework to make sure it all works fine. And your own... [goes on for quite a long time]

Then again, if you do use a framework, you'll be able to benefit from the good, usually peer-reviewed and very well tested work of dozens if not hundreds of other developers, who may well be better than you. You'll get to build what you want rapidly, without having to spend time building or worrying too much about the infrastructure items listed above.

You can get more done in less time, and know that the framework code you're using or extending is very likely to be done better than you doing it all yourself.

And the cost of this? Investing some time learning the framework. But - as virtually every web dev out there will attest - it's definitely worth the time spent learning to get massive (really, massive) benefits from using whatever framework you choose.

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

My solution was slightly more complicated. After verifying the user the service was running as, running MSSMS as local and domain administrator, and checking folder permissions, I was still getting this error. My solution?

Folder ownership was still maintained by local account.

Properties > Security > Advanced > Owner > (domain/local user/group SQL services are running as)

This resolved the issue for me.

Location of my.cnf file on macOS

For MAMP 3.5 Mac El Capitan, create a separate empty config file and write your additional settings for mysql

sudo vim /Applications/MAMP/Library/my.cnf

And Add like this

[mysqld]
max_allowed_packet = 256M

Regular expression to find URLs within a string

This is the one I use

(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?

Works for me, should work for you too.

Escape double quote in VB string

Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.

Option Explicit

Private Const SEE_MASK_DEFAULT = &H0

Public Enum EShellShowConstants
        essSW_HIDE = 0
        essSW_SHOWNORMAL = 1
        essSW_SHOWMINIMIZED = 2
        essSW_MAXIMIZE = 3
        essSW_SHOWMAXIMIZED = 3
        essSW_SHOWNOACTIVATE = 4
        essSW_SHOW = 5
        essSW_MINIMIZE = 6
        essSW_SHOWMINNOACTIVE = 7
        essSW_SHOWNA = 8
        essSW_RESTORE = 9
        essSW_SHOWDEFAULT = 10
End Enum

Private Type SHELLEXECUTEINFO
        cbSize        As Long
        fMask         As Long
        hwnd          As Long
        lpVerb        As String
        lpFile        As String
        lpParameters  As String
        lpDirectory   As String
        nShow         As Long
        hInstApp      As Long
        lpIDList      As Long     'Optional
        lpClass       As String   'Optional
        hkeyClass     As Long     'Optional
        dwHotKey      As Long     'Optional
        hIcon         As Long     'Optional
        hProcess      As Long     'Optional
End Type

Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long

Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
    Dim SEI As SHELLEXECUTEINFO

    On Error GoTo Err

    'Fill the SEI structure
    With SEI
        .cbSize = Len(SEI)                  ' Bytes of the structure
        .fMask = SEE_MASK_DEFAULT           ' Check MSDN for more info on Mask
        .lpFile = FilePath                  ' Program Path
        .nShow = ShellShowType              ' How the program will be displayed
        .lpDirectory = PathGetFolder(FilePath)
        .lpParameters = EXEParameters       ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
        .hwnd = hWndOwner                   ' Owner window handle

        ' Determine launch type (would recommend checking for Vista or greater here also)
        If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
            .lpVerb = "runas"
        Else
            .lpVerb = "Open"
        End If
    End With

     ExecuteProcess = ShellExecuteEx(SEI)   ' Execute the program, return success or failure

    Exit Function
Err:
    ' TODO: Log Error
    ExecuteProcess = False
End Function

Private Function PathGetFolder(psPath As String) As String
    On Error Resume Next
    Dim lPos As Long
    lPos = InStrRev(psPath, "\")
    PathGetFolder = Left$(psPath, lPos - 1)
End Function

Correct way to detach from a container without stopping it

You can simply kill docker cli process by sending SEGKILL. If you started the container with

docker run -it some/container

You can get it's pid

ps -aux | grep docker

user   1234  0.3  0.6 1357948 54684 pts/2   Sl+  15:09   0:00 docker run -it some/container

let's say it's 1234, you can "detach" it with

kill -9 1234

It's somewhat of a hack but it works!

Error: request entity too large

I too faced that issue, I was making a silly mistake by repeating the app.use(bodyParser.json()) like below:

app.use(bodyParser.json())
app.use(bodyParser.json({ limit: '50mb' }))

by removing app.use(bodyParser.json()), solved the problem.

how to display employee names starting with a and then b in sql

We can also use REGEXP

select employee_name 
from employees
where employee_name REGEXP '[ab].*'
order by employee_name

Simple way to query connected USB devices info in Python?

If you just need the name of the device here is a little hack which i wrote in bash. To run it in python you need the following snippet. Just replace $1 and $2 with Bus number and Device number eg 001 or 002.

import os
os.system("lsusb | grep \"Bus $1 Device $2\" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}'")

Alternately you can save it as a bash script and run it from there too. Just save it as a bash script like foo.sh make it executable.

#!/bin/bash
myvar=$(lsusb | grep "Bus $1 Device $2" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}')
echo $myvar

Then call it in python script as

import os
os.system('foo.sh')

How to find a string inside a entire database?

In oracle you can use the following sql command to generate the sql commands you need:

select 
     "select * "
     " from "||table_name||
     " where "||column_name||" like '%123abcd%' ;" as sql_command
from user_tab_columns
where data_type='VARCHAR2';

Java SimpleDateFormat for time zone with a colon separator?

JodaTime's DateTimeFormat to rescue:

String dateString = "2010-03-01T00:00:00-08:00";
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(dateString);
System.out.println(dateTime); // 2010-03-01T04:00:00.000-04:00

(time and timezone difference in toString() is just because I'm at GMT-4 and didn't set locale explicitly)

If you want to end up with java.util.Date just use DateTime#toDate():

Date date = dateTime.toDate();

Wait for JDK7 (JSR-310) JSR-310, the referrence implementation is called ThreeTen (hopefully it will make it into Java 8) if you want a better formatter in the standard Java SE API. The current SimpleDateFormat indeed doesn't eat the colon in the timezone notation.

Update: as per the update, you apparently don't need the timezone. This should work with SimpleDateFormat. Just omit it (the Z) in the pattern.

String dateString = "2010-03-01T00:00:00-08:00";
String pattern = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = sdf.parse(dateString);
System.out.println(date); // Mon Mar 01 00:00:00 BOT 2010

(which is correct as per my timezone)

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

Differences

  • KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.

  • UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.

    Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

  • PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.

    Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.

  • FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).

    Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

Similarities

  • All of these indexes may have more than one column in them.

  • With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)

Windows CMD command for accessing usb?

firstly you have to change the drive, which is allocated to your usb.

follow these step to access your pendrive using CMD. 1- type drivename follow by the colon just like k: 2- type dir it will show all the files and directory in your usb 3- now you can access any file or directory of your usb.

How can I lock a file using java (if possible)

Use this for unix if you are transferring using winscp or ftp:

public static void isFileReady(File entry) throws Exception {
        long realFileSize = entry.length();
        long currentFileSize = 0;
        do {
            try (FileInputStream fis = new FileInputStream(entry);) {
                currentFileSize = 0;
                while (fis.available() > 0) {
                    byte[] b = new byte[1024];
                    int nResult = fis.read(b);
                    currentFileSize += nResult;
                    if (nResult == -1)
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("currentFileSize=" + currentFileSize + ", realFileSize=" + realFileSize);
        } while (currentFileSize != realFileSize);
    }

How to use an arraylist as a prepared statement parameter

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

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

Create another list :

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

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

Step 2 : Make 'listWithQuotes' comma separated.

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

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

How to calculate the running time of my program?

At the beginning of your main method, add this line of code :

final long startTime = System.nanoTime();

And then, at the last line of your main method, you can add :

final long duration = System.nanoTime() - startTime;

duration now contains the time in nanoseconds that your program ran. You can for example print this value like this:

System.out.println(duration);

If you want to show duration time in seconds, you must divide the value by 1'000'000'000. Or if you want a Date object: Date myTime = new Date(duration / 1000); You can then access the various methods of Date to print number of minutes, hours, etc.

Get the length of a String

In swift4 I have always used string.count till today I have found that

string.endIndex.encodedOffset

is the better substitution because it is faster - for 50 000 characters string is about 6 time faster than .count. The .count depends on the string length but .endIndex.encodedOffset doesn't.

But there is one NO. It is not good for strings with emojis, it will give wrong result, so only .count is correct.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

How can I easily convert DataReader to List<T>?

You cant simply (directly) convert the datareader to list.

You have to loop through all the elements in datareader and insert into list

below the sample code

using (drOutput)   
{
            System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();        
            int customerId = drOutput.GetOrdinal("customerId ");
            int CustomerName = drOutput.GetOrdinal("CustomerName ");

        while (drOutput.Read())        
        {
            CustomerEntity obj=new CustomerEntity ();
            obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
            obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
            arrObjects .Add(obj);
        }

}

What's the best way to select the minimum value from several columns?

You could also do this with a union query. As the number of columns increase, you would need to modify the query, but at least it would be a straight forward modification.

Select T.Id, T.Col1, T.Col2, T.Col3, A.TheMin
From   YourTable T
       Inner Join (
         Select A.Id, Min(A.Col1) As TheMin
         From   (
                Select Id, Col1
                From   YourTable

                Union All

                Select Id, Col2
                From   YourTable

                Union All

                Select Id, Col3
                From   YourTable
                ) As A
         Group By A.Id
       ) As A
       On T.Id = A.Id

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

Send data from a textbox into Flask?

Assuming you already know how to write a view in Flask that responds to a url, create one that reads the request.post data. To add the input box to this post data create a form on your page with the text box. You can then use jquery to do

var data = $('#<form-id>').serialize()

and then post to your view asynchronously using something like the below.

$.post('<your view url>', function(data) {
  $('.result').html(data);
});

Ignore duplicates when producing map using streams

This is possible using the mergeFunction parameter of Collectors.toMap(keyMapper, valueMapper, mergeFunction):

Map<String, String> phoneBook = 
    people.stream()
          .collect(Collectors.toMap(
             Person::getName,
             Person::getAddress,
             (address1, address2) -> {
                 System.out.println("duplicate key found!");
                 return address1;
             }
          ));

mergeFunction is a function that operates on two values associated with the same key. adress1 corresponds to the first address that was encountered when collecting elements and adress2 corresponds to the second address encountered: this lambda just tells to keep the first address and ignores the second.

Matching an optional substring in a regex

(\d+)\s+(\(.*?\))?\s?Z

Note the escaped parentheses, and the ? (zero or once) quantifiers. Any of the groups you don't want to capture can be (?: non-capture groups).

I agree about the spaces. \s is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^ at the front and a $ at the end).

How to remove unused imports in Intellij IDEA on commit?

You can check checkbox in the commit dialog.

enter image description here

You can use settings to automatically optimize imports since 11.1 and above.

enter image description here

How to get text and a variable in a messagebox

MsgBox("Variable {0} " , variable)

asp.net mvc @Html.CheckBoxFor

CheckBoxFor takes a bool, you're passing a List<CheckBoxes> to it. You'd need to do:

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

Notice I've added a HiddenFor for the Text property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.

Edit, as shown in your comments, your EmploymentType list is null when the view is served. You'll need to populate that too, by doing this in your action method:

public ActionResult YourActionMethod()
{
    CareerForm model = new CareerForm();

    model.EmploymentType = new List<CheckBox>
    {
        new CheckBox { Text = "Fulltime" },
        new CheckBox { Text = "Partly" },
        new CheckBox { Text = "Contract" }
    };

    return View(model);
}

How to determine day of week by passing specific date?

Calendar cal = Calendar.getInstance(desired date);
cal.setTimeInMillis(System.currentTimeMillis());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

Get the day value by providing the current time stamp.

Java - Getting Data from MySQL database

  • First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].

  • Add the Jar file to your workspace [build path].

  • Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.

  • Define the database name, userName, and Password for your connection.

  • Use the resultSet to get the data based one the column name from your database table.

Sample code is here:

public class JdbcMySQLExample{

public static void main(String[] args) {

    String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
    String user = "root";
    String password = "root";
    
    String query = "SELECT * from YOUR_TABLE_NAME";

    try (Connection con = DriverManager.getConnection(url, user, password);
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(query)) {

        if (rs.next()) {
            
            System.out.println(rs.getString(1));
        }

    } catch (SQLException ex) {
          System.out.println(ex);
       
    } 
}

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

How does the "this" keyword work?

Since this thread has bumped up, I have compiled few points for readers new to this topic.

How is the value of this determined?

We use this similar to the way we use pronouns in natural languages like English: “John is running fast because he is trying to catch the train.” Instead we could have written “… John is trying to catch the train”.

var person = {    
    firstName: "Penelope",
    lastName: "Barrymore",
    fullName: function () {

    // We use "this" just as in the sentence above:
       console.log(this.firstName + " " + this.lastName);

    // We could have also written:
       console.log(person.firstName + " " + person.lastName);
    }
}

this is not assigned a value until an object invokes the function where it is defined. In the global scope, all global variables and functions are defined on the window object. Therefore, this in a global function refers to (and has the value of) the global window object.

When use strict, this in global and in anonymous functions that are not bound to any object holds a value of undefined.

The this keyword is most misunderstood when: 1) we borrow a method that uses this, 2) we assign a method that uses this to a variable, 3) a function that uses this is passed as a callback function, and 4) this is used inside a closure — an inner function. (2)

table

What holds the future

Defined in ECMA Script 6, arrow-functions adopt the this binding from the enclosing (function or global) scope.

function foo() {
     // return an arrow function
     return (a) => {
     // `this` here is lexically inherited from `foo()`
     console.log(this.a);
  };
}
var obj1 = { a: 2 };
var obj2 = { a: 3 };

var bar = foo.call(obj1);
bar.call( obj2 ); // 2, not 3!

While arrow-functions provide an alternative to using bind(), it’s important to note that they essentially are disabling the traditional this mechanism in favor of more widely understood lexical scoping. (1)


References:

  1. this & Object Prototypes, by Kyle Simpson. © 2014 Getify Solutions.
  2. javascriptissexy.com - http://goo.gl/pvl0GX
  3. Angus Croll - http://goo.gl/Z2RacU

Preferred way of getting the selected item of a JComboBox

The first method is right.

The second method kills kittens if you attempt to do anything with x after the fact other than Object methods.

How to use a decimal range() step value?

Best Solution: no rounding error

>>> step = .1
>>> N = 10     # number of data points
>>> [ x / pow(step, -1) for x in range(0, N + 1) ]

[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

Or, for a set range instead of set data points (e.g. continuous function), use:

>>> step = .1
>>> rnge = 1     # NOTE range = 1, i.e. span of data points
>>> N = int(rnge / step
>>> [ x / pow(step,-1) for x in range(0, N + 1) ]

[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

To implement a function: replace x / pow(step, -1) with f( x / pow(step, -1) ), and define f.
For example:

>>> import math
>>> def f(x):
        return math.sin(x)

>>> step = .1
>>> rnge = 1     # NOTE range = 1, i.e. span of data points
>>> N = int(rnge / step)
>>> [ f( x / pow(step,-1) ) for x in range(0, N + 1) ]

[0.0, 0.09983341664682815, 0.19866933079506122, 0.29552020666133955, 0.3894183423086505, 
 0.479425538604203, 0.5646424733950354, 0.644217687237691, 0.7173560908995228,
 0.7833269096274834, 0.8414709848078965]

Updating state on props change in React Form

From react documentation : https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

Erasing state when props change is an Anti Pattern

Since React 16, componentWillReceiveProps is deprecated. From react documentation, the recommended approach in this case is use

  1. Fully controlled component: the ParentComponent of the ModalBody will own the start_time state. This is not my prefer approach in this case since i think the modal should own this state.
  2. Fully uncontrolled component with a key: this is my prefer approach. An example from react documentation : https://codesandbox.io/s/6v1znlxyxn . You would fully own the start_time state from your ModalBody and use getInitialState just like you have already done. To reset the start_time state, you simply change the key from the ParentComponent

Specify path to node_modules in package.json

I'm not sure if this is what you had in mind, but I ended up on this question because I was unable to install node_modules inside my project dir as it was mounted on a filesystem that did not support symlinks (a VM "shared" folder).

I found the following workaround:

  1. Copy the package.json file to a temp folder on a different filesystem
  2. Run npm install there
  3. Copy the resulting node_modules directory back into the project dir, using cp -r --dereference to expand symlinks into copies.

I hope this helps someone else who ends up on this question when looking for a way to move node_modules to a different filesystem.

Other options

There is another workaround, which I found on the github issue that @Charminbear linked to, but this doesn't work with grunt because it does not support NODE_PATH as per https://github.com/browserify/resolve/issues/136:

lets say you have /media/sf_shared and you can't install symlinks in there, which means you can't actually npm install from /media/sf_shared/myproject because some modules use symlinks.

  • $ mkdir /home/dan/myproject && cd /home/dan/myproject
  • $ ln -s /media/sf_shared/myproject/package.json (you can symlink in this direction, just can't create one inside of /media/sf_shared)
  • $ npm install
  • $ cd /media/sf_shared/myproject
  • $ NODE_PATH=/home/dan/myproject/node_modules node index.js

Can't access object property, even though it shows up in a console log

I've just had the same issue with a document loaded from MongoDB using Mongoose.

Turned out that i'm using the property find() to return just one object, so i changed find() to findOne() and everything worked for me.

Solution (if you're using Mongoose): Make sure to return one object only, so you can parse its object.id or it will be treated as an array so you need to acces it like that object[0].id.

What methods of ‘clearfix’ can I use?

I've found a bug in the official CLEARFIX-Method: The DOT doesn't have a font-size. And if you set the height = 0 and the first Element in your DOM-Tree has the class "clearfix" you'll allways have a margin at the bottom of the page of 12px :)

You have to fix it like this:

/* float clearing for everyone else */
.clearfix:after{
  clear: both;
  content: ".";
  display: block;
  height: 0;
  visibility: hidden;
  font-size: 0;
}

It's now part of the YAML-Layout ... Just take a look at it - it's very interesting! http://www.yaml.de/en/home.html

#define in Java

Simplest Answer is "No Direct method of getting it because there is no pre-compiler" But you can do it by yourself. Use classes and then define variables as final so that it can be assumed as constant throughout the program
Don't forget to use final and variable as public or protected not private otherwise you won't be able to access it from outside that class

How to run server written in js with Node.js

Just go on that directory of your JS file from cmd and write node jsFile.js or even node jsFile; both will work fine.

Attaching click to anchor tag in angular

I have encountered this issue in Angular 5 which still followed the link. The solution was to have the function return false in order to prevent the page being refreshed:

html

<a href="" (click)="openChangePasswordForm()">Change expired password</a>

ts

openChangePasswordForm(): boolean {
  console.log("openChangePasswordForm called!");
  return false;
}

JSON order mixed up

I found a "neat" reflection tweak on "the interwebs" that I like to share. (origin: https://towardsdatascience.com/create-an-ordered-jsonobject-in-java-fb9629247d76)

It is about to change underlying collection in org.json.JSONObject to an un-ordering one (LinkedHashMap) by reflection API.

I tested succesfully:

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;

private static void makeJSONObjLinear(JSONObject jsonObject) {
    try {
            Field changeMap = jsonObject.getClass().getDeclaredField("map");
            changeMap.setAccessible(true);
            changeMap.set(jsonObject, new LinkedHashMap<>());
            changeMap.setAccessible(false);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
}

[...]
JSONObject requestBody = new JSONObject();
makeJSONObjLinear(requestBody);

requestBody.put("username", login);
requestBody.put("password", password);
[...]
// returned   '{"username": "billy_778", "password": "********"}' == unordered
// instead of '{"password": "********", "username": "billy_778"}' == ordered (by key)

Meaning of 'const' last in a function declaration of a class?

when you use const in the method signature (like your said: const char* foo() const;) you are telling the compiler that memory pointed to by this can't be changed by this method (which is foo here).

Adding local .aar files to Gradle build using "flatDirs" is not working

This is my structure, and how I solve this:

MyProject/app/libs/mylib-1.0.0.aar

MyProject/app/myModulesFolder/myLibXYZ

On build.gradle

from Project/app/myModulesFolder/myLibXYZ

I have put this:

repositories {
   flatDir {
    dirs 'libs', '../../libs'
  }
}
compile (name: 'mylib-1.0.0', ext: 'aar')

Done and working fine, my submodule XYZ depends on somelibrary from main module.

How do you change the character encoding of a postgres database?

# dump into file
pg_dump myDB > /tmp/myDB.sql

# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'

# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql

# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";' 
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'

# see the result
psql myDB -c "SHOW LC_COLLATE"   

Using psql to connect to PostgreSQL in SSL mode

psql below 9.2 does not accept this URL-like syntax for options.

The use of SSL can be driven by the sslmode=value option on the command line or the PGSSLMODE environment variable, but the default being prefer, SSL connections will be tried first automatically without specifying anything.

Example with a conninfo string (updated for psql 8.4)

psql "sslmode=require host=localhost dbname=test"

Read the manual page for more options.

New lines (\r\n) are not working in email body

' '   

space was missing in my case, when a blank space added ' \r\n' started to work

How to adjust layout when soft keyboard appears

Just add

android:windowSoftInputMode="adjustResize"

in your AndroidManifest.xml where you declare this particular activity and this will adjust the layout resize option.

enter image description here

some source code below for layout design

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="FaceBook"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:hint="username" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="password" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="20dp"
        android:text="Log In" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="17dp"
        android:gravity="center"
        android:text="Sign up for facebook"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

What is the difference between 'java', 'javaw', and 'javaws'?

java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.

What's the function like sum() but for multiplication? product()?

There isn't one built in, but it's simple to roll your own, as demonstrated here:

import operator
def prod(factors):
    return reduce(operator.mul, factors, 1)

See answers to this question:

Which Python module is suitable for data manipulation in a list?

How to insert table values from one database to another database?

Mostly we need this type of query in migration script

INSERT INTO  db1.table1(col1,col2,col3,col4)
SELECT col5,col6,col7,col8
  FROM db1.table2

In this query column count must be same in both table

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Popup window in winform c#

"But the thing is I also want to be able to add textboxes etc in this popup window thru the form designer."

It's unclear from your description at what stage in the development process you're in. If you haven't already figured it out, to create a new Form you click on Project --> Add Windows Form, then type in a name for the form and hit the "Add" button. Now you can add controls to your form as you'd expect.

When it comes time to display it, follow the advice of the other posts to create an instance and call Show() or ShowDialog() as appropriate.

HTML5 Video autoplay on iPhone

Here is the little hack to overcome all the struggles you have for video autoplay in a website:

  1. Check video is playing or not.
  2. Trigger video play on event like body click or touch.

Note: Some browsers don't let videos to autoplay unless the user interacts with the device.

So scripts to check whether video is playing is:

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function () {
    return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}});

And then you can simply autoplay the video by attaching event listeners to the body:

$('body').on('click touchstart', function () {
        const videoElement = document.getElementById('home_video');
        if (videoElement.playing) {
            // video is already playing so do nothing
        }
        else {
            // video is not playing
            // so play video now
            videoElement.play();
        }
});

Note: autoplay attribute is very basic which needs to be added to the video tag already other than these scripts.

You can see the working example with code here at this link:

How to autoplay video when the device is in low power mode / data saving mode / safari browser issue

What's the difference between Thread start() and Runnable run()

run method : - is an abstract method originally created in the Runnable interface and overridden in the Thread class as well as Thread subclasses (As Thread implements Runnable in its source code) and any other implementing classes of Runnable interface. - It is used to load the thread (runnable object) with the task it is intended to do thus you override it to write that task.

start method : - is defined in Thread class. When start method is called on a Thread object 1- it calls internally native (nonjava) method called start0(); method.

start0(); method: is responsible for low processing (stack creation for a thread and allocating thread in processor queue) at this point we have a thread in Ready/Runnable state.

2- At a time when Thread scheduler decides that a thread enters a processor core acorrding to (thread priority as well as OS scheduling algorithm) run method is invoked on the Runnable object (whether it is the current Runnable thread object or the Runnable object passed to the thread constructor) here a thread enters a Running state and starts executing its task (run method)

How to get today's Date?

Date today = new Date();
today.setHours(0); //same for minutes and seconds

Since the methods are deprecated, you can do this with Calendar:

Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0); // same for minutes and seconds

And if you need a Date object in the end, simply call today.getTime()

MySQL Data - Best way to implement paging?

From the MySQL documentation:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.

How to display a loading screen while site content loads

Typically sites that do this by loading content via ajax and listening to the readystatechanged event to update the DOM with a loading GIF or the content.

How are you currently loading your content?

The code would be similar to this:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Check your JNI/native code. One of my references was null, but it was intermittent, so it wasn't very obvious.

C++ delete vector, objects, free memory

You can call clear, and that will destroy all the objects, but that will not free the memory. Looping through the individual elements will not help either (what action would you even propose to take on the objects?) What you can do is this:

vector<tempObject>().swap(tempVector);

That will create an empty vector with no memory allocated and swap it with tempVector, effectively deallocating the memory.

C++11 also has the function shrink_to_fit, which you could call after the call to clear(), and it would theoretically shrink the capacity to fit the size (which is now 0). This is however, a non-binding request, and your implementation is free to ignore it.

Check if element exists in jQuery

How do I check if an element exists

if ($("#mydiv").length){  }

If it is 0, it will evaluate to false, anything more than that true.

There is no need for a greater than, less than comparison.

Sorting objects by property values

Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :

var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects);   //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
    list_Objects.sort(function(a,b){
        return a["name"].localeCompare(b["name"]); 
    });
Console.log(list_Objects);  //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]

How do I negate a condition in PowerShell?

Powershell also accept the C/C++/C* not operator

if ( !(Test-Path C:\Code) ){ write "it doesn't exist!" }

I use it often because I'm used to C*...
allows code compression/simplification...
I also find it more elegant...

Array of char* should end at '\0' or "\0"?

The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.