Programs & Examples On #Usertype

How to set width of mat-table column in angular?

Here's an alternative way of tackling the problem:

Instead of trying to "fix it in post" why don't you truncate the description before the table needs to try and fit it into its columns? I did it like this:

<ng-container matColumnDef="description">
   <th mat-header-cell *matHeaderCellDef> {{ 'Parts.description' | translate }} </th>
            <td mat-cell *matCellDef="let element">
                {{(element.description.length > 80) ? ((element.description).slice(0, 80) + '...') : element.description}}
   </td>
</ng-container>

So I first check if the array is bigger than a certain length, if Yes then truncate and add '...' otherwise pass the value as is. This enables us to still benefit from the auto-spacing the table does :)

enter image description here

ASP.NET MVC Dropdown List From SelectList

Just try this in razor

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem {Text = "Google", Value = "Google"},
            new SelectListItem {Text = "Other", Value = "Other"},
        }, "Value", "Text");
}

and then

@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })

or

@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })

Multiple condition in single IF statement

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

How can I display a messagebox in ASP.NET?

I use this and it works

public void Messagebox(string xMessage)
{
    Response.Write("<script>alert('" + xMessage + "')</script>");
}

And I call like this

    Messagebox("je suis la!");

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

How to remove specific session in asp.net?

There is nothing like session container , so you can set it as null

but rather you can set individual session element as null or ""

like Session["userid"] = null;

Symfony2 : How to get form validation errors after binding the request to the form

For Symfony 2.1:

This is my final solution putting in together many others solutions:

protected function getAllFormErrorMessages($form)
{
    $retval = array();
    foreach ($form->getErrors() as $key => $error) {
        if($error->getMessagePluralization() !== null) {
            $retval['message'] = $this->get('translator')->transChoice(
                $error->getMessage(), 
                $error->getMessagePluralization(), 
                $error->getMessageParameters(), 
                'validators'
            );
        } else {
            $retval['message'] = $this->get('translator')->trans($error->getMessage(), array(), 'validators');
        }
    }
    foreach ($form->all() as $name => $child) {
        $errors = $this->getAllFormErrorMessages($child);
        if (!empty($errors)) {
           $retval[$name] = $errors; 
        }
    }
    return $retval;
}

Is it possible to CONTINUE a loop from an exception?

For this example you really should just use an outer join.

declare
begin
  FOR attr_rec IN ( 
    select attr 
    from USER_TABLE u 
    left outer join attribute_table a 
    on ( u.USERTYPE = 'X' and a.user_id = u.id ) 
  ) LOOP
    <process records> 
    <if primary key of attribute_table is null 
     then the attribute does not exist for this user.>
  END LOOP;
END;

Using json_encode on objects in PHP (regardless of scope)

Following code worked for me:

public function jsonSerialize()
{
    return get_object_vars($this);
}

Map enum in JPA with fixed values?

For versions earlier than JPA 2.1, JPA provides only two ways to deal with enums, by their name or by their ordinal. And the standard JPA doesn't support custom types. So:

  • If you want to do custom type conversions, you'll have to use a provider extension (with Hibernate UserType, EclipseLink Converter, etc). (the second solution). ~or~
  • You'll have to use the @PrePersist and @PostLoad trick (the first solution). ~or~
  • Annotate getter and setter taking and returning the int value ~or~
  • Use an integer attribute at the entity level and perform a translation in getters and setters.

I'll illustrate the latest option (this is a basic implementation, tweak it as required):

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {

    public enum Right {
        READ(100), WRITE(200), EDITOR (300);

        private int value;

        Right(int value) { this.value = value; }    

        public int getValue() { return value; }

        public static Right parse(int id) {
            Right right = null; // Default
            for (Right item : Right.values()) {
                if (item.getValue()==id) {
                    right = item;
                    break;
                }
            }
            return right;
        }

    };

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "AUTHORITY_ID")
    private Long id;

    @Column(name = "RIGHT_ID")
    private int rightId;

    public Right getRight () {
        return Right.parse(this.rightId);
    }

    public void setRight(Right right) {
        this.rightId = right.getValue();
    }

}

Why are unnamed namespaces used and what are their benefits?

Unnamed namespace limits access of class,variable,function and objects to the file in which it is defined. Unnamed namespace functionality is similar to static keyword in C/C++.
static keyword limits access of global variable and function to the file in which they are defined.
There is difference between unnamed namespace and static keyword because of which unnamed namespace has advantage over static. static keyword can be used with variable, function and objects but not with user defined class.
For example:

static int x;  // Correct 

But,

static class xyz {/*Body of class*/} //Wrong
static structure {/*Body of structure*/} //Wrong

But same can be possible with unnamed namespace. For example,

 namespace {
           class xyz {/*Body of class*/}
           static structure {/*Body of structure*/}
  } //Correct

T-SQL: Opposite to string concatenation - how to split string into multiple records

Slight modification of the solution above so it works with variable-length delimiters.

create FUNCTION dbo.fn_Split2 (@sep nvarchar(10), @s nvarchar(4000))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + (datalength(@sep)/2), CHARINDEX(@sep, @s, stop + (datalength(@sep)/2))
      FROM Pieces
      WHERE stop > 0
    )
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS s
    FROM Pieces
  )

NB: I've used datalength() since len() reports incorrectly if there are trailing spaces.

How to resolve Nodejs: Error: ENOENT: no such file or directory

In my case the issue was caused by using a file path starting at the directory where the script was executing rather than at the root of the project.

My directory stucture was like this: projectfolder/ +-- package.json +-- scriptFolder/ ¦ +-- myScript.js

And I was calling fs.createReadStream('users.csv') instead of the correct fs.createReadStream('scriptFolder/users.csv')

How can I execute Shell script in Jenkinsfile?

There's the Managed Script Plugin which provides an easy way of managing user scripts. It also adds a build step action which allows you to select which user script to execute.

How can I safely create a nested directory?

Starting from Python 3.5, pathlib.Path.mkdir has an exist_ok flag:

from pathlib import Path
path = Path('/my/directory/filename.txt')
path.parent.mkdir(parents=True, exist_ok=True) 
# path.parent ~ os.path.dirname(path)

This recursively creates the directory and does not raise an exception if the directory already exists.

(just as os.makedirs got an exist_ok flag starting from python 3.2 e.g os.makedirs(path, exist_ok=True))


Note: when i posted this answer none of the other answers mentioned exist_ok...

How to increase Java heap space for a tomcat app

Your change may well be working. Does your application need a lot of memory - the stack trace shows some Image related features.

I'm guessing that the error either happens right away, with a large file, or happens later after several requests.

If the error happens right away, then you can increase memory still further, or investigate find out why so much memory is needed for one file.

If the error happens after several requests, then you could have a memory leak - where objects are not being reclaimed by the garbage collector. Using a tool like JProfiler can help you monitor how much memory is being used by your VM and can help you see what is using that memory and why objects are not being reclaimed by the garbage collector.

textarea character limit

I believe if you use delegates, it would work..

$("textarea").on('change paste keyup', function () {
    var currText = $(this).val();
    if (currText.length > 500) {
        var text = $(this).text();
        $(this).text(text.substr(0, 500));
        alert("You have reached the maximum length for this field");
    }
});

How to display both icon and title of action inside ActionBar?

You can create actions with text in 2 ways:

1- From XML:

<item android:id="@id/resource_name"
      android:title="text"
      android:icon="@drawable/drawable_resource_name"
      android:showAsAction="withText" />

When inflating the menu, you should call getSupportMenuInflater() since you are using ActionBarSherlock.

2- Programmatically:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
    item.setIcon(R.drawable.drawable_resource_name);
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);

    return true;
}

Make sure you import com.actionbarsherlock.view.Menu and com.actionbarsherlock.view.MenuItem.

SELECT INTO USING UNION QUERY

You have to define a table alias for a derived table in SQL Server:

SELECT x.* 
  INTO [NEW_TABLE]
  FROM (SELECT * FROM TABLE1
        UNION
        SELECT * FROM TABLE2) x

"x" is the table alias in this example.

Change limit for "Mysql Row size too large"

After spending hours I have found the solution: just run the following SQL in your MySQL admin to convert the table to MyISAM:

USE db_name;
ALTER TABLE table_name ENGINE=MYISAM;

MySQL Workbench: How to keep the connection alive

I had a similar problem where CREATE FULLTEXT timed out after 30 seconds:

error

Setting DBMS connection read timeout interval to 0 under Edit -> Preferences -> SQL Editor fixed the issue for me:

fix error

Also, I did not have to restart mysql workbench for this to work.

How can I convert a VBScript to an executable (EXE) file?

There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.

Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.

Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.

In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.

Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.

How do I list all the files in a directory and subdirectories in reverse chronological order?

Try this one:

find . -type f -printf "%T@ %p\n" | sort -nr | cut -d\  -f2-

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

In my case, I was installing a project with MinimumSDK bigger than the Android version of my real device. I used another device and it solved MinSDK -> 24 My Phone -> 21

When and Why to use abstract classes/methods?

Typically one uses an abstract class to provide some incomplete functionality that will be fleshed out by concrete subclasses. It may provide methods that are used by its subclasses; it may also represent an intermediate node in the class hierarchy, to represent a common grouping of concrete subclasses, distinguishing them in some way from other subclasses of its superclass. Since an interface can't derive from a class, this is another situation where a class (abstract or otherwise) would be necessary, versus an interface.

A good rule of thumb is that only leaf nodes of a class hierarchy should ever be instantiated. Making non-leaf nodes abstract is an easy way of ensuring that.

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

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

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

(at the bottom of the right column).


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

Example of EntityFramework's detail page

Random number between 0 and 1 in python

RTM

From the docs for the Python random module:

Functions for integers:

random.randrange(stop)
random.randrange(start, stop[, step])

    Return a randomly selected element from range(start, stop, step).
    This is equivalent to choice(range(start, stop, step)), but doesn’t
    actually build a range object.

That explains why it only gives you 0, doesn't it. range(0,1) is [0]. It is choosing from a list consisting of only that value.

Also from those docs:

random.random()    
    Return the next random floating point number in the range [0.0, 1.0).

But if your inclusion of the numpy tag is intentional, you can generate many random floats in that range with one call using a np.random function.

Django Rest Framework File Upload

I'm using the same stack and was also looking for an example of file upload, but my case is simpler since I use the ModelViewSet instead of APIView. The key turned out to be the pre_save hook. I ended up using it together with the angular-file-upload module like so:

# Django
class ExperimentViewSet(ModelViewSet):
    queryset = Experiment.objects.all()
    serializer_class = ExperimentSerializer

    def pre_save(self, obj):
        obj.samplesheet = self.request.FILES.get('file')

class Experiment(Model):
    notes = TextField(blank=True)
    samplesheet = FileField(blank=True, default='')
    user = ForeignKey(User, related_name='experiments')

class ExperimentSerializer(ModelSerializer):
    class Meta:
        model = Experiment
        fields = ('id', 'notes', 'samplesheet', 'user')

// AngularJS
controller('UploadExperimentCtrl', function($scope, $upload) {
    $scope.submit = function(files, exp) {
        $upload.upload({
            url: '/api/experiments/' + exp.id + '/',
            method: 'PUT',
            data: {user: exp.user.id},
            file: files[0]
        });
    };
});

Docker and securing passwords

There is a new docker command for "secrets" management. But that only works for swarm clusters.

docker service create
--name my-iis
--publish target=8000,port=8000
--secret src=homepage,target="\inetpub\wwwroot\index.html"
microsoft/iis:nanoserver 

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

To get the whole adress add

s.nextLine();//read the rest of the line as input

before

System.out.println("Enter Your Address: ");
String address = s.next();

How do I concatenate or merge arrays in Swift?

Swift 3.0

You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array's type is inferred from the type of the two array you add together,

let arr0 = Array(repeating: 1, count: 3) // [1, 1, 1]
let arr1 = Array(repeating: 2, count: 6)//[2, 2, 2, 2, 2, 2]
let arr2 = arr0 + arr1 //[1, 1, 1, 2, 2, 2, 2, 2, 2]

this is the right results of above codes.

How to terminate a process in vbscript

Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.

Multiprocessing: How to use Pool.map on a function defined in a class?

Here is a boilerplate I wrote for using multiprocessing Pool in python3, specifically python3.7.7 was used to run the tests. I got my fastest runs using imap_unordered. Just plug in your scenario and try it out. You can use timeit or just time.time() to figure out which works best for you.

import multiprocessing
import time

NUMBER_OF_PROCESSES = multiprocessing.cpu_count()
MP_FUNCTION = 'starmap'  # 'imap_unordered' or 'starmap' or 'apply_async'

def process_chunk(a_chunk):
    print(f"processig mp chunk {a_chunk}")
    return a_chunk


map_jobs = [1, 2, 3, 4]

result_sum = 0

s = time.time()
if MP_FUNCTION == 'imap_unordered':
    pool = multiprocessing.Pool(processes=NUMBER_OF_PROCESSES)
    for i in pool.imap_unordered(process_chunk, map_jobs):
        result_sum += i
elif MP_FUNCTION == 'starmap':
    pool = multiprocessing.Pool(processes=NUMBER_OF_PROCESSES)
    try:
        map_jobs = [(i, ) for i in map_jobs]
        result_sum = pool.starmap(process_chunk, map_jobs)
        result_sum = sum(result_sum)
    finally:
        pool.close()
        pool.join()
elif MP_FUNCTION == 'apply_async':
    with multiprocessing.Pool(processes=NUMBER_OF_PROCESSES) as pool:
        result_sum = [pool.apply_async(process_chunk, [i, ]).get() for i in map_jobs]
    result_sum = sum(result_sum)
print(f"result_sum is {result_sum}, took {time.time() - s}s")

In the above scenario imap_unordered actually seems to perform the worst for me. Try out your case and benchmark it on the machine you plan to run it on. Also read up on Process Pools. Cheers!

How to call external url in jquery?

google the javascript same origin policy

in a nutshell, the url you are trying to use must have the same root and protocol. so http://yoursite.com cannot access https://yoursite.com or http://anothersite.com

is you absolutely MUST bypass this protection (which is at the browser level, as galimy pointed out), consider the ProxyPass module for your favorite web server.

How to insert multiple rows from array using CodeIgniter framework?

mysqli in PHP 5 is an object with some good functions that will allow you to speed up the insertion time for the answer above:

$mysqli->autocommit(FALSE);
$mysqli->multi_query($sqlCombined);
$mysqli->autocommit(TRUE);

Turning off autocommit when inserting many rows greatly speeds up insertion, so turn it off, then execute as mentioned above, or just make a string (sqlCombined) which is many insert statements separated by semi-colons and multi-query will handle them fine.

List vs tuple, when to use each?

Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple is immutable whereas a list is mutable.

  1. You can't add elements to a tuple. Tuples have no append or extend method.
  2. You can't remove elements from a tuple. Tuples have no remove or pop method.
  3. You can find elements in a tuple, since this doesn’t change the tuple.
  4. You can also use the in operator to check if an element exists in the tuple.

  • Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.

  • It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.

  • Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.

Source: Dive into Python 3

failed to load ad : 3

in my case :
I/Ads: Ad failed to load : Account not approved yet.

but you need to implement the listener for knowing the error

First import the listener : import com.google.android.gms.ads.AdListener;
Second create variable : private final String TAG2 = com.ringtones.splash.class.getSimpleName();

            mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {Log.d(TAG2, "google banner ad loaded"); }
            @Override
            public void onAdFailedToLoad(LoadAdError adError) {Log.d(TAG2, "google banner ad failed to load : "+ adError.getMessage());}
            @Override
            public void onAdOpened() {Log.d(TAG2, "google banner ad opened");}
            @Override
            public void onAdClicked() {Log.d(TAG2, "google banner ad clicked");}
            @Override
            public void onAdLeftApplication() {Log.d(TAG2, "google banner ad left application");}
            @Override
            public void onAdClosed() {Log.d(TAG2, "google banner ad closed");}
        });

Maximum concurrent Socket.IO connections

For +300k concurrent connection:

Set these variables in /etc/sysctl.conf:

fs.file-max = 10000000 
fs.nr_open = 10000000

Also, change these variables in /etc/security/limits.conf:

* soft nofile 10000000
* hard nofile 10000000
root soft nofile 10000000
root hard nofile 10000000

And finally, increase TCP buffers in /etc/sysctl.conf, too:

net.ipv4.tcp_mem = 786432 1697152 1945728
net.ipv4.tcp_rmem = 4096 4096 16777216
net.ipv4.tcp_wmem = 4096 4096 16777216

for more information please refer to this.

Split array into chunks of N length

It could be something like that:

_x000D_
_x000D_
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

var arrays = [], size = 3;
    
while (a.length > 0)
  arrays.push(a.splice(0, size));

console.log(arrays);
_x000D_
_x000D_
_x000D_

See splice Array's method.

Media Player called in state 0, error (-38,0)

You need to call mediaPlayer.start() in the onPrepared method by using a listener. You are getting this error because you are calling mediaPlayer.start() before it has reached the prepared state.

Here is how you can do it :

mp.setDataSource(url); 
mp.setOnPreparedListener(this);
mp.prepareAsync();

public void onPrepared(MediaPlayer player) {
    player.start();
}

JavaScript regex for alphanumeric string with length of 3-5 chars

add {3,5} to your expression which means length between 3 to 5

/^([a-zA-Z0-9_-]){3,5}$/

How to get current available GPUs in tensorflow?

I am working on TF-2.1 and torch, so I don't want to specific this automacit choosing in any ML frame. I just use original nvidia-smi and os.environ to get a vacant gpu.

def auto_gpu_selection(usage_max=0.01, mem_max=0.05):
"""Auto set CUDA_VISIBLE_DEVICES for gpu

:param mem_max: max percentage of GPU utility
:param usage_max: max percentage of GPU memory
:return:
"""
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
log = str(subprocess.check_output("nvidia-smi", shell=True)).split(r"\n")[6:-1]
gpu = 0

# Maximum of GPUS, 8 is enough for most
for i in range(8):
    idx = i*3 + 2
    if idx > log.__len__()-1:
        break
    inf = log[idx].split("|")
    if inf.__len__() < 3:
        break
    usage = int(inf[3].split("%")[0].strip())
    mem_now = int(str(inf[2].split("/")[0]).strip()[:-3])
    mem_all = int(str(inf[2].split("/")[1]).strip()[:-3])
    # print("GPU-%d : Usage:[%d%%]" % (gpu, usage))
    if usage < 100*usage_max and mem_now < mem_max*mem_all:
        os.environ["CUDA_VISIBLE_EVICES"] = str(gpu)
        print("\nAuto choosing vacant GPU-%d : Memory:[%dMiB/%dMiB] , GPU-Util:[%d%%]\n" %
              (gpu, mem_now, mem_all, usage))
        return
    print("GPU-%d is busy: Memory:[%dMiB/%dMiB] , GPU-Util:[%d%%]" %
          (gpu, mem_now, mem_all, usage))
    gpu += 1
print("\nNo vacant GPU, use CPU instead\n")
os.environ["CUDA_VISIBLE_EVICES"] = "-1"

If I can get any GPU, it will set CUDA_VISIBLE_EVICES to BUSID of that gpu :

GPU-0 is busy: Memory:[5738MiB/11019MiB] , GPU-Util:[60%]
GPU-1 is busy: Memory:[9688MiB/11019MiB] , GPU-Util:[78%]

Auto choosing vacant GPU-2 : Memory:[1MiB/11019MiB] , GPU-Util:[0%]

else, set to -1 to use CPU:

GPU-0 is busy: Memory:[8900MiB/11019MiB] , GPU-Util:[95%]
GPU-1 is busy: Memory:[4674MiB/11019MiB] , GPU-Util:[35%]
GPU-2 is busy: Memory:[9784MiB/11016MiB] , GPU-Util:[74%]

No vacant GPU, use CPU instead

Note: Use this function before you import any ML frame that require a GPU, then it can automatically choose a gpu. Besides, it's easy for you to set multiple tasks.

NGINX - No input file specified. - php Fast/CGI

server {
    server_name www.test.com test.com;
    access_log /sites/test/logs/access.log;
    error_log /sites/test/logs/error.log;
    root /sites/test;

 location ~ / {

index index.php
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME `$document_root/service/public$fastcgi_script_name`;
}

How to randomize (or permute) a dataframe rowwise and columnwise?

Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations

How to JOIN three tables in Codeigniter

public function getdata(){
        $this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
        $this->db->from('tblmaster t'); 
        $this->db->join('country c', 't.country=c.country_id');
        $this->db->join('state s', 't.state=s.state_id');
        $this->db->join('city ct', 't.city=ct.city_id');
        $this->db->order_by('t.id','desc');
        $query = $this->db->get();      
        return $query->result();
}

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

Press ctrl+v then use ? or ? to select the number of lines to comment. Then press shift+I, press # and then ESC. This will comment out the number of lines you have selected.

The opposite for uncomment lines.

SQL - Create view from multiple tables

Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:

CREATE VIEW V AS (

  SELECT i.country,i.year,p.pop,f.food,i.income FROM
    INCOME i
  LEFT JOIN 
    POP p 
  ON
    i.country=p.country
  LEFT JOIN
    Food f
  ON 
    i.country=f.country
  WHERE 
    i.year=p.year
  AND
    i.year=f.year
);

The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

How do I store data in local storage using Angularjs?

Follow the steps to store data in Angular - local storage:

  1. Add 'ngStorage.js' in your folder.
  2. Inject 'ngStorage' in your angular.module

        eg: angular.module("app", [ 'ngStorage']);
    
  3. Add $localStorage in your app.controller function

4.You can use $localStorage inside your controller

Eg: $localstorage.login= true;

The above will store the localstorage in your browser application

The conversion of the varchar value overflowed an int column

Declare @phoneNumber int

select @phoneNumber=Isnull('08041159620',0);

Give error :

The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)

AS

Integer is defined as :

Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.

Solution

Declare @phoneNumber bigint

Reference

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I think You are using Spring 3.0.5 and you need to use Spring 4.0.* This will resolve your problem. org.springframework.web.bind.annotation.RequestMapping is not available in Spring-web earlier then Spring-web 4.0.*

What does request.getParameter return?

String onevalue;   
if(request.getParameterMap().containsKey("one")!=false) 
{
onevalue=request.getParameter("one").toString();
}

How to start Spyder IDE on Windows

In case if you want the desktop icon

In desktop, create a new shortcut, in Location paste this

%comspec% /k spyder3

then type the name Spyder,

Now you may have Desktop Icon for opening Spyder

How to Select a substring in Oracle SQL up to a specific character?

This can be done using REGEXP_SUBSTR easily.

Please use

REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1) 

where STRING_EXAMPLE is your string.

Try:

SELECT 
REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1) 
from dual

It will solve your problem.

Reshaping data.frame from wide to long format

Three alternative solutions:

1) With :

You can use the same melt function as in the reshape2 package (which is an extended & improved implementation). melt from data.table has also more parameters that the melt-function from reshape2. You can for example also specify the name of the variable-column:

library(data.table)
long <- melt(setDT(wide), id.vars = c("Code","Country"), variable.name = "year")

which gives:

> long
    Code     Country year  value
 1:  AFG Afghanistan 1950 20,249
 2:  ALB     Albania 1950  8,097
 3:  AFG Afghanistan 1951 21,352
 4:  ALB     Albania 1951  8,986
 5:  AFG Afghanistan 1952 22,532
 6:  ALB     Albania 1952 10,058
 7:  AFG Afghanistan 1953 23,557
 8:  ALB     Albania 1953 11,123
 9:  AFG Afghanistan 1954 24,555
10:  ALB     Albania 1954 12,246

Some alternative notations:

melt(setDT(wide), id.vars = 1:2, variable.name = "year")
melt(setDT(wide), measure.vars = 3:7, variable.name = "year")
melt(setDT(wide), measure.vars = as.character(1950:1954), variable.name = "year")

2) With :

library(tidyr)
long <- wide %>% gather(year, value, -c(Code, Country))

Some alternative notations:

wide %>% gather(year, value, -Code, -Country)
wide %>% gather(year, value, -1:-2)
wide %>% gather(year, value, -(1:2))
wide %>% gather(year, value, -1, -2)
wide %>% gather(year, value, 3:7)
wide %>% gather(year, value, `1950`:`1954`)

3) With :

library(reshape2)
long <- melt(wide, id.vars = c("Code", "Country"))

Some alternative notations that give the same result:

# you can also define the id-variables by column number
melt(wide, id.vars = 1:2)

# as an alternative you can also specify the measure-variables
# all other variables will then be used as id-variables
melt(wide, measure.vars = 3:7)
melt(wide, measure.vars = as.character(1950:1954))

NOTES:

  • is retired. Only changes necessary to keep it on CRAN will be made. (source)
  • If you want to exclude NA values, you can add na.rm = TRUE to the melt as well as the gather functions.

Another problem with the data is that the values will be read by R as character-values (as a result of the , in the numbers). You can repair that with gsub and as.numeric:

long$value <- as.numeric(gsub(",", "", long$value))

Or directly with data.table or dplyr:

# data.table
long <- melt(setDT(wide),
             id.vars = c("Code","Country"),
             variable.name = "year")[, value := as.numeric(gsub(",", "", value))]

# tidyr and dplyr
long <- wide %>% gather(year, value, -c(Code,Country)) %>% 
  mutate(value = as.numeric(gsub(",", "", value)))

Data:

wide <- read.table(text="Code Country        1950    1951    1952    1953    1954
AFG  Afghanistan    20,249  21,352  22,532  23,557  24,555
ALB  Albania        8,097   8,986   10,058  11,123  12,246", header=TRUE, check.names=FALSE)

fatal error LNK1169: one or more multiply defined symbols found in game programming

You can't put variable definitions in header files, as these will then be a part of all source file you include the header into.

The #pragma once is just to protect against multiple inclusions in the same source file, not against multiple inclusions in multiple source files.

You could declare the variables as extern in the header file, and then define them in a single source file. Or you could declare the variables as const in the header file and then the compiler and linker will manage it.

Deleting multiple columns based on column names in Pandas

The by far the simplest approach is:

yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)

How do I build a graphical user interface in C++?

It's easy to create a .NET Windows GUI in C++.

See the following tutorial from MSDN. You can download everything you need (Visual C++ Express) for free.

Of course you tie yourself to .NET, but if you're just playing around or only need a Windows application you'll be fine (most people still have Windows...for now).

SQL Add foreign key to existing column

If the table has already been created:

First do:

ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);

Then:

ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

How to run a Command Prompt command with Visual Basic code?

You need to use CreateProcess [ http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx ]

For ex:

LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\Program Files\MyApp\" -L -S")); CreateProcess(NULL, szCmdline, /.../);

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

As for "phone numbers" you should really consider the difference between a "subscriber number" and a "dialling number" and the possible formatting options of them.

A subscriber number is generally defined in the national numbering plans. The question itself shows a relation to a national view by mentioning "area code" which a lot of nations don't have. ITU has assembled an overview of the world's numbering plans publishing recommendation E.164 where the national number was found to have a maximum of 12 digits. With international direct distance calling (DDD) defined by a country code of 1 to 3 digits they added that up to 15 digits ... without formatting.

The dialling number is a different thing as there are network elements that can interpret exta values in a phone number. You may think of an answering machine and a number code that sets the call diversion parameters. As it may contain another subscriber number it must be obviously longer than its base value. RFC 4715 has set aside 20 bcd-encoded bytes for "subaddressing".

If you turn to the technical limitation then it gets even more as the subscriber number has a technical limit in the 10 bcd-encoded bytes in the 3GPP standards (like GSM) and ISDN standards (like DSS1). They have a seperate TON/NPI byte for the prefix (type of number / number plan indicator) which E.164 recommends to be written with a "+" but many number plans define it with up to 4 numbers to be dialled.

So if you want to be future proof (and many software systems run unexpectingly for a few decades) you would need to consider 24 digits for a subscriber number and 64 digits for a dialling number as the limit ... without formatting. Adding formatting may add roughly an extra character for every digit. So as a final thought it may not be a good idea to limit the phone number in the database in any way and leave shorter limits to the UX designers.

What is the best way to repeatedly execute a function every x seconds?

Here's an update to the code from MestreLion that avoids drifiting over time.

The RepeatedTimer class here calls the given function every "interval" seconds as requested by the OP; the schedule doesn't depend on how long the function takes to execute. I like this solution since it doesn't have external library dependencies; this is just pure python.

import threading 
import time

class RepeatedTimer(object):
  def __init__(self, interval, function, *args, **kwargs):
    self._timer = None
    self.interval = interval
    self.function = function
    self.args = args
    self.kwargs = kwargs
    self.is_running = False
    self.next_call = time.time()
    self.start()

  def _run(self):
    self.is_running = False
    self.start()
    self.function(*self.args, **self.kwargs)

  def start(self):
    if not self.is_running:
      self.next_call += self.interval
      self._timer = threading.Timer(self.next_call - time.time(), self._run)
      self._timer.start()
      self.is_running = True

  def stop(self):
    self._timer.cancel()
    self.is_running = False

Sample usage (copied from MestreLion's answer):

from time import sleep

def hello(name):
    print "Hello %s!" % name

print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
    sleep(5) # your long-running job goes here...
finally:
    rt.stop() # better in a try/finally block to make sure the program ends!

Moment.js - how do I get the number of years since a date, not rounded up?

http://jsfiddle.net/xR8t5/27/

if you do not want fraction values:

var years = moment().diff('1981-01-01', 'years',false);
alert( years);

if you want fraction values:

var years = moment().diff('1981-01-01', 'years',true);
alert( years);

Units can be [seconds, minutes, hours, days, weeks, months, years]

How to always show the vertical scrollbar in a browser?

Here is a method. This will not only provide scrollbar container, but will also show the scrollbar even if content isnt enough (as per your requirement). Would also work on Iphone, and android devices as well..

<style>
    .scrollholder {
        position: relative;
        width: 310px; height: 350px;
        overflow: auto;
        z-index: 1;
    }
</style>

<script>
    function isTouchDevice() {
        try {
            document.createEvent("TouchEvent");
            return true;
        } catch (e) {
            return false;
        }
    }

    function touchScroll(id) {
        if (isTouchDevice()) { //if touch events exist...
            var el = document.getElementById(id);
            var scrollStartPos = 0;

            document.getElementById(id).addEventListener("touchstart", function (event) {
                scrollStartPos = this.scrollTop + event.touches[0].pageY;
                event.preventDefault();
            }, false);

            document.getElementById(id).addEventListener("touchmove", function (event) {
                this.scrollTop = scrollStartPos - event.touches[0].pageY;
                event.preventDefault();
            }, false);
        }
    }
</script>

<body onload="touchScroll('scrollMe')">

    <!-- title -->
    <!-- <div class="title" onselectstart="return false">Alarms</div> -->
    <div class="scrollholder" id="scrollMe">

</div>
</body>

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Using Windows Authentication

To connect to the database server is recommended to use Windows Authentication, commonly known as integrated security. To specify the Windows authentication, you can use any of the following two key-value pairs with the data provider. NET Framework for SQL Server:

 Integrated Security = true;
 Integrated Security = SSPI;

However, only the second works with the data provider .NET Framework OleDb. If you set Integrated Security = true for ConnectionString an exception is thrown.

To specify the Windows authentication in the data provider. NET Framework for ODBC, you should use the following key-value pair.

Trusted_Connection = yes;

Source: MSDN: Working with Connection Strings

Random string generation with upper case letters and digits

this is a take on Anurag Uniyal 's response and something that i was working on myself.

import random
import string

oneFile = open('?Numbers.txt', 'w')
userInput = 0
key_count = 0
value_count = 0
chars = string.ascii_uppercase + string.digits + string.punctuation

for userInput in range(int(input('How many 12 digit keys do you want?'))):
    while key_count <= userInput:
        key_count += 1
        number = random.randint(1, 999)
        key = number

        text = str(key) + ": " + str(''.join(random.sample(chars*6, 12)))
        oneFile.write(text + "\n")
oneFile.close()

Sample settings.xml

A standard Maven settings.xml file is as follows:

<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>

  <proxies>
    <proxy>
      <active/>
      <protocol/>
      <username/>
      <password/>
      <port/>
      <host/>
      <nonProxyHosts/>
      <id/>
    </proxy>
  </proxies>

  <servers>
    <server>
      <username/>
      <password/>
      <privateKey/>
      <passphrase/>
      <filePermissions/>
      <directoryPermissions/>
      <configuration/>
      <id/>
    </server>
  </servers>

  <mirrors>
    <mirror>
      <mirrorOf/>
      <name/>
      <url/>
      <layout/>
      <mirrorOfLayouts/>
      <id/>
    </mirror>
  </mirrors>

  <profiles>
    <profile>
      <activation>
        <activeByDefault/>
        <jdk/>
        <os>
          <name/>
          <family/>
          <arch/>
          <version/>
        </os>
        <property>
          <name/>
          <value/>
        </property>
        <file>
          <missing/>
          <exists/>
        </file>
      </activation>
      <properties>
        <key>value</key>
      </properties>

      <repositories>
        <repository>
          <releases>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </releases>
          <snapshots>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </snapshots>
          <id/>
          <name/>
          <url/>
          <layout/>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <releases>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </releases>
          <snapshots>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </snapshots>
          <id/>
          <name/>
          <url/>
          <layout/>
        </pluginRepository>
      </pluginRepositories>
      <id/>
    </profile>
  </profiles>

  <activeProfiles/>
  <pluginGroups/>
</settings>

To access a proxy, you can find detailed information on the official Maven page here:

Maven-Settings - Settings

I hope it helps for someone.

Converting HTML string into DOM elements?

Just give an id to the element and process it normally eg:

<div id="dv">
<a href="#"></a>
<span></span>
</div>

Now you can do like:

var div = document.getElementById('dv');
div.appendChild(......);

Or with jQuery:

$('#dv').get(0).appendChild(........);

How can I center text (horizontally and vertically) inside a div block?

You can try the following methods:

  1. If you have a single word or one line sentence, then the following code can do the trick.

    Have a text inside a div tag and give it an id. Define the following properties for that id.

    id-name {
      height: 90px;
      line-height: 90px;
      text-align: center;
      border: 2px dashed red;
    }
    

    Note: Make sure the line-height property is same as the height of the division.

    Image

    But, if the content is more than one single word or a line then this doesn’t work. Also, there will be times when you cannot specify the size of a division in px or % (when the division is really small and you want the content to be exactly in the middle).

  2. To solve this issue, we can try the following combination of properties.

    id-name {
      display: flex;
      justify-content: center;
      align-items: center;
      border: 2px dashed red;
    }
    

    Image

    These 3 lines of code sets the content exactly in the middle of a division (irrespective of the size of the display). The "align-items: center" helps in vertical centering while "justify-content: center" will make it horizontally centered.

    Note: Flex does not work in all browsers. Make sure you add appropriate vendor prefixes for additional browser support.

Set size on background image with CSS?

background-size is working in Chrome 4.1, but so far I couldn't make it work in Firefox 3.6.

Aligning rotated xticklabels with their respective xticks

You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha='right'

n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(ha[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

How do I check if an object's type is a particular subclass in C++?

In c# you can simply say:

if (myObj is Car) {

}

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

SQL Count for each date

When you cast a DateTime to an int it "truncates" at noon, you might want to strip the day out like so

cast(DATEADD(DAY, DATEDIFF(DAY, 0, created_date), 0) as int) as DayBucket

Fatal error: Call to undefined function curl_init()

$ch = curl_init('http://api.imgur.com/2/upload.xml'); //initialising our url

curl_setopt($ch, CURLOPT_MUTE, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  //used for https headers 

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  //used for https headers

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($pvars));  
//the value we post

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //waiting for reponse, default value in php is zero ie, curls normally do not wait for a response

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0'); 

$output = curl_exec($ch); //the real execution 
curl_close($ch);

echo $output;

Try this code. I am not sure about it. But i used it to send xml data to a remote url.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

To people using Codeigniter (i'm on C3):

The index.php file overwrite php.ini configuration, so on index.php file, line 68:

case 'development':
        error_reporting(-1);
        ini_set('display_errors', 1);
    break;

You can change this option to set what you need. Here's the complete list:

1   E_ERROR
2   E_WARNING
4   E_PARSE
8   E_NOTICE
16  E_CORE_ERROR
32  E_CORE_WARNING
64  E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024    E_USER_NOTICE
6143    E_ALL
2048    E_STRICT
4096    E_RECOVERABLE_ERROR

Hope it helps.

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

How do I set session timeout of greater than 30 minutes

If you want to never expire a session use 0 or negative value -1.

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

or mention 1440 it indicates 1440 minutes [24hours * 60 minutes]

<session-config>
  <session-timeout>1440</session-timeout><!-- 24hours -->
</session-config>

Session will be expire after 24hours.

how to find seconds since 1970 in java

The difference you see is most likely because you don't zero the hour, minute, second and milliseconds fields of your Calendar instances: Calendar.getInstance() gives you the current date and time, just like new Date() or System.currentTimeMillis().

Note that the month field of Calendar is zero-based, i.e. January is 0, not 1.

Also, don't prefix numbers with zero, this might look nice and it even works till you reach 8: 08 isn't a valid numeral in Java. Prefixing numerals with zero makes the compiler assume you're defining them as octal numerals which only works up to 07 (for single digits).

Just drop calendar1 completely (1970-01-01 00:00:00'000 is the begin of the epoch, i.e. zero anyway) and do this:

public long returnSeconds(int year, int month, int date) {
    final Calendar cal = Calendar.getInstance();
    cal.set(year, month, date, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis() / 1000;
}

PHP create key => value pairs within a foreach

In PHP >= 5.3 it can be done like this:

$offerArray = array_map(function($value) {
    return $value[4];
}, $offer);

How to install Guest addition in Mac OS as guest and Windows machine as host

Guest additions are not available for Mac OS X. You can get features like clipboard sync and shared folders by using VNC and SMB. Here's my answer on a similar question.

How to make external HTTP requests with Node.js

node-http-proxy is a great solution as was suggested by @hross above. If you're not deadset on using node, we use NGINX to do the same thing. It works really well with node. We use it for example to process SSL requests before forwarding them to node. It can also handle cacheing and forwarding routes. Yay!

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

How can I change UIButton title color?

With Swift 5, UIButton has a setTitleColor(_:for:) method. setTitleColor(_:for:) has the following declaration:

Sets the color of the title to use for the specified state.

func setTitleColor(_ color: UIColor?, for state: UIControlState)

The following Playground sample code show how to create a UIbutton in a UIViewController and change it's title color using setTitleColor(_:for:):

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white

        // Create button
        let button = UIButton(type: UIButton.ButtonType.system)

        // Set button's attributes
        button.setTitle("Print 0", for: UIControl.State.normal)
        button.setTitleColor(UIColor.orange, for: UIControl.State.normal)

        // Set button's frame
        button.frame.origin = CGPoint(x: 100, y: 100)
        button.sizeToFit()

        // Add action to button
        button.addTarget(self, action: #selector(printZero(_:)), for: UIControl.Event.touchUpInside)

        // Add button to subView
        view.addSubview(button)
    }

    @objc func printZero(_ sender: UIButton) {
        print("0")
    }

}

let controller = ViewController()
PlaygroundPage.current.liveView = controller

Add missing dates to pandas dataframe

An alternative approach is resample, which can handle duplicate dates in addition to missing dates. For example:

df.resample('D').mean()

resample is a deferred operation like groupby so you need to follow it with another operation. In this case mean works well, but you can also use many other pandas methods like max, sum, etc.

Here is the original data, but with an extra entry for '2013-09-03':

             val
date           
2013-09-02     2
2013-09-03    10
2013-09-03    20    <- duplicate date added to OP's data
2013-09-06     5
2013-09-07     1

And here are the results:

             val
date            
2013-09-02   2.0
2013-09-03  15.0    <- mean of original values for 2013-09-03
2013-09-04   NaN    <- NaN b/c date not present in orig
2013-09-05   NaN    <- NaN b/c date not present in orig
2013-09-06   5.0
2013-09-07   1.0

I left the missing dates as NaNs to make it clear how this works, but you can add fillna(0) to replace NaNs with zeroes as requested by the OP or alternatively use something like interpolate() to fill with non-zero values based on the neighboring rows.

Mocking a class: Mock() or patch()?

Key points which explain difference and provide guidance upon working with unittest.mock

  1. Use Mock if you want to replace some interface elements(passing args) of the object under test
  2. Use patch if you want to replace internal call to some objects and imported modules of the object under test
  3. Always provide spec from the object you are mocking
    • With patch you can always provide autospec
    • With Mock you can provide spec
    • Instead of Mock, you can use create_autospec, which intended to create Mock objects with specification.

In the question above the right answer would be to use Mock, or to be more precise create_autospec (because it will add spec to the mock methods of the class you are mocking), the defined spec on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some

from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch


class MyClass:
    
    @staticmethod
    def method(foo, bar):
        print(foo)


def something(some_class: MyClass):
    arg = 1
    # Would fail becuase of wrong parameters passed to methd.
    return some_class.method(arg)


def second(some_class: MyClass):
    arg = 1
    return some_class.unexisted_method(arg)


class TestSomethingTestCase(TestCase):
    def test_something_with_autospec(self):
        mock = create_autospec(MyClass)
        mock.method.return_value = True
        # Fails because of signature misuse.
        result = something(mock)
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
    
    def test_something(self):
        mock = Mock()  # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
        mock.method.return_value = True
        
        result = something(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
        
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)


class TestSecondTestCase(TestCase):
    def test_second_with_autospec(self):
        mock = Mock(spec=MyClass)
        # Fails because of signature misuse.
        result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second(self):
        mock = Mock()
        mock.unexisted_method.return_value = True
        
        result = second(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)

The test cases with defined spec used fail because methods called from something and second functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock will display.

As a side note there is one more option: use patch.object to mock just the class method which is called with.

The good use cases for patch would be the case when the class is used as inner part of function:

def something():
    arg = 1
    return MyClass.method(arg)

Then you will want to use patch as a decorator to mock the MyClass.

Error: Unexpected value 'undefined' imported by the module

This can be caused by multiple scenarios like

  1. Missing commas
imports: [
    BrowserModule
   ,routing <= Missing Comma
   ,FeatureComponentsModule
  ],
  1. Double Commas
imports: [
    BrowserModule, 
   ,routing <=Double Comma
   ,FeatureComponentsModule
  ],
  1. Exporting Nothing from the Module
  2. Syntax errors
  3. Typo Errors
  4. Semicolons inside Objects, Arrays
  5. Incorrect import Statements

why numpy.ndarray is object is not callable in my simple for python loop

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function.

Use

Z=XY[0]+XY[1]

Instead of

Z=XY(i,0)+XY(i,1)

List of all special characters that need to be escaped in a regex

Combining what everyone said, I propose the following, to keep the list of characters special to RegExp clearly listed in their own String, and to avoid having to try to visually parse thousands of "\\"'s. This seems to work pretty well for me:

final String regExSpecialChars = "<([{\\^-=$!|]})?*+.>";
final String regExSpecialCharsRE = regExSpecialChars.replaceAll( ".", "\\\\$0");
final Pattern reCharsREP = Pattern.compile( "[" + regExSpecialCharsRE + "]");

String quoteRegExSpecialChars( String s)
{
    Matcher m = reCharsREP.matcher( s);
    return m.replaceAll( "\\\\$0");
}

Android design support library for API 28 (P) not working

Try this:

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'

Why would an Enum implement an Interface?

There is a case I often use. I have a IdUtil class with static methods to work with objects implementing a very simple Identifiable interface:

public interface Identifiable<K> {
    K getId();
}


public abstract class IdUtil {

    public static <T extends Enum<T> & Identifiable<S>, S> T get(Class<T> type, S id) {
        for (T t : type.getEnumConstants()) {
            if (Util.equals(t.getId(), id)) {
                return t;
            }
        }
        return null;
    }

    public static <T extends Enum<T> & Identifiable<S>, S extends Comparable<? super S>> List<T> getLower(T en) {
        List<T> list = new ArrayList<>();
        for (T t : en.getDeclaringClass().getEnumConstants()) {
             if (t.getId().compareTo(en.getId()) < 0) {
                 list.add(t);
            }
        }
        return list;
    }
}

If I create an Identifiable enum:

    public enum MyEnum implements Identifiable<Integer> {

        FIRST(1), SECOND(2);

        private int id;

        private MyEnum(int id) {
            this.id = id;
        }

        public Integer getId() {
            return id;
        }

    }

Then I can get it by its id this way:

MyEnum e = IdUtil.get(MyEnum.class, 1);

Change the color of cells in one column when they don't match cells in another column

  1. Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:

    enter image description here

  2. Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):

    =$A1<>$B1
    

    enter image description here

  3. Then press OK and that should do it.

    enter image description here

best way to create object

Or you can use a data file to put many person objects in to a list or array. You do need to use the System.IO for this. And you need a data file which contains all the information about the objects.

A method for it would look something like this:

static void ReadFile()
{
    using(StreamWriter writer = new StreamWriter(@"Data.csv"))
    {
        string line = null;
        line = reader.ReadLine();
        while(null!= (line = reader.ReadLine())
                {
                    string[] values = line.Split(',');
                    string name = values[0];
                    int age = int.Parse(values[1]);
                }
        Person person = new Person(name, age);
    }
}

Flutter: Run method on Widget build complete

UPDATE: Flutter v1.8.4

Both mentioned codes are working now:

Working:

WidgetsBinding.instance
        .addPostFrameCallback((_) => yourFunction(context));

Working

import 'package:flutter/scheduler.dart';

SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));

Batch file to copy files from one folder to another folder

You can use esentutl to copy (mainly big) files with a progress bar:

esentutl /y "my.file" /d "another.file" /o

the progress bar looks like this:

enter image description here

What is a Windows Handle?

So at the most basic level a HANDLE of any sort is a pointer to a pointer or

#define HANDLE void **

Now as to why you would want to use it

Lets take a setup:

class Object{
   int Value;
}

class LargeObj{

   char * val;
   LargeObj()
   {
      val = malloc(2048 * 1000);
   }

}

void foo(Object bar){
    LargeObj lo = new LargeObj();
    bar.Value++;
}

void main()
{
   Object obj = new Object();
   obj.val = 1;
   foo(obj);
   printf("%d", obj.val);
}

So because obj was passed by value (make a copy and give that to the function) to foo, the printf will print the original value of 1.

Now if we update foo to:

void foo(Object * bar)
{
    LargeObj lo = new LargeObj();
    bar->val++;
}

There is a chance that the printf will print the updated value of 2. But there is also the possibility that foo will cause some form of memory corruption or exception.

The reason is this while you are now using a pointer to pass obj to the function you are also allocating 2 Megs of memory, this could cause the OS to move the memory around updating the location of obj. Since you have passed the pointer by value, if obj gets moved then the OS updates the pointer but not the copy in the function and potentially causing problems.

A final update to foo of:

void foo(Object **bar){
    LargeObj lo = LargeObj();
    Object * b = &bar;
    b->val++;
}

This will always print the updated value.

See, when the compiler allocates memory for pointers it marks them as immovable, so any re-shuffling of memory caused by the large object being allocated the value passed to the function will point to the correct address to find out the final location in memory to update.

Any particular types of HANDLEs (hWnd, FILE, etc) are domain specific and point to a certain type of structure to protect against memory corruption.

pip install mysql-python fails with EnvironmentError: mysql_config not found

On Mac:

brew install mysql-client

locate mysql

mdfind mysql | grep bin

then add to path

export PATH=$PATH:/usr/local/Cellar/mysql-client/8.0.23/bin/

or permanently

echo "export PATH=$PATH:/usr/local/Cellar/mysql-client/8.0.23/bin/" >> ~/.zshrc
source ~/.zshrc

Temporary tables in stored procedures

Not really and I am talking about SQL Server. The temp table (with single #) exists and is visible within the scope it is created (scope-bound). Each time you call your stored procedure it creates a new scope and therefore that temp table exists only in that scope. I believe the temp tables are also visible to stored procedures and udfs that're called within that scope as well. If you however use double pound (##) then they become global within your session and therefore visible to other executing processes as part of the session that the temp table is created in and you will have to think if the possibility of temp table being accessed concurrently is desirable or not.

How to do scanf for single char in C

neither fgets nor getchar works to solve the problem. the only workaround is keeping a space before %c while using scanf scanf(" %c",ch); // will only work

In the follwing fgets also not work..

char line[256];
char ch;
int i;

printf("Enter a num : ");
scanf("%d",&i);
printf("Enter a char : ");

if (fgets(line, sizeof line, stdin) == NULL) {
    printf("Input error.\n");
    exit(1);
}

ch = line[0];
printf("Character read: %c\n", ch);

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Use Set in Python

>>> a = [2,4]
>>> b = [1,4,3]
>>> set(a) - set(b)
set([2])

Why does "return list.sort()" return None, not the list?

list.sort sorts the list in place, i.e. it doesn't return a new list. Just write

newList.sort()
return newList

Xcode error "Could not find Developer Disk Image"

For iOS 10 beta 7, add the following link on the command line:

sudo ln -s /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0\ \(14A5339a\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

How to print without newline or space?

You can do the same in python3 as follows :

#!usr/bin/python

i = 0
while i<10 :
    print('.',end='')
    i = i+1

and execute it with python filename.py or python3 filename.py

JavaScript global event mechanism

// display error messages for a page, but never more than 3 errors
window.onerror = function(msg, url, line) {
if (onerror.num++ < onerror.max) {
alert("ERROR: " + msg + "\n" + url + ":" + line);
return true;
}
}
onerror.max = 3;
onerror.num = 0;

Optimal way to concatenate/aggregate strings

I found Serge's answer to be very promising, but I also encountered performance issues with it as-written. However, when I restructured it to use temporary tables and not include double CTE tables, the performance went from 1 minute 40 seconds to sub-second for 1000 combined records. Here it is for anyone who needs to do this without FOR XML on older versions of SQL Server:

DECLARE @STRUCTURED_VALUES TABLE (
     ID                 INT
    ,VALUE              VARCHAR(MAX) NULL
    ,VALUENUMBER        BIGINT
    ,VALUECOUNT         INT
);

INSERT INTO @STRUCTURED_VALUES
SELECT   ID
        ,VALUE
        ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY VALUE) AS VALUENUMBER
        ,COUNT(*) OVER (PARTITION BY ID)    AS VALUECOUNT
FROM    RAW_VALUES_TABLE;

WITH CTE AS (
    SELECT   SV.ID
            ,SV.VALUE
            ,SV.VALUENUMBER
            ,SV.VALUECOUNT
    FROM    @STRUCTURED_VALUES SV
    WHERE   VALUENUMBER = 1

    UNION ALL

    SELECT   SV.ID
            ,CTE.VALUE + ' ' + SV.VALUE AS VALUE
            ,SV.VALUENUMBER
            ,SV.VALUECOUNT
    FROM    @STRUCTURED_VALUES SV
    JOIN    CTE 
        ON  SV.ID = CTE.ID
        AND SV.VALUENUMBER = CTE.VALUENUMBER + 1

)
SELECT   ID
        ,VALUE
FROM    CTE
WHERE   VALUENUMBER = VALUECOUNT
ORDER BY ID
;

Parsing time string in Python

Here's a stdlib solution that supports a variable utc offset in the input time string:

>>> from email.utils import parsedate_tz, mktime_tz
>>> from datetime import datetime, timedelta
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2012, 5, 8, 7, 14, 45)

How to split string using delimiter char using T-SQL?

You simply need to do a SUBSTR on the string in col3....

    Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'), 
    (instr(col3, '|', instr(col3, 'Client Name')  -
    instr(col3, 'Client Name'))
    ),
'Client Name = ',
'')
    from Table01 

And yes, that is a bad DB design for the reasons stated in the original issue

How do I attach events to dynamic HTML elements with jQuery?

If your on jQuery 1.3+ then use .live()

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

How to get item's position in a list?

for i in xrange(len(testlist)):
  if testlist[i] == 1:
    print i

xrange instead of range as requested (see comments).

Validate select box

if (select == "") {
    alert("Please select a selection");
    return false;

That should work for you. It just did for me.

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

How can I selectively merge or pick changes from another branch in Git?

When only a few files have changed between the current commits of the two branches, I manually merge the changes by going through the different files.

git difftool <branch-1>..<branch-2>

see also https://sites.google.com/site/icusite/setup/git-difftool

How to track down a "double free or corruption" error

If you're using glibc, you can set the MALLOC_CHECK_ environment variable to 2, this will cause glibc to use an error tolerant version of malloc, which will cause your program to abort at the point where the double free is done.

You can set this from gdb by using the set environment MALLOC_CHECK_ 2 command before running your program; the program should abort, with the free() call visible in the backtrace.

see the man page for malloc() for more information

Why should a Java class implement comparable?

An easy way to implement multiple field comparisons is with Guava's ComparisonChain - then you can say

   public int compareTo(Foo that) {
     return ComparisonChain.start()
         .compare(lastName, that.lastName)
         .compare(firstName, that.firstName)
         .compare(zipCode, that.zipCode)
         .result();
   }

instead of

  public int compareTo(Person other) {
    int cmp = lastName.compareTo(other.lastName);
    if (cmp != 0) {
      return cmp;
    }
    cmp = firstName.compareTo(other.firstName);
    if (cmp != 0) {
      return cmp;
    }
    return Integer.compare(zipCode, other.zipCode);
  }
}

How are software license keys generated?

CD-Keys aren't much of a security for any non-networked stuff, so technically they don't need to be securely generated. If you're on .net, you can almost go with Guid.NewGuid().

Their main use nowadays is for the Multiplayer component, where a server can verify the CD Key. For that, it's unimportant how securely it was generated as it boils down to "Lookup whatever is passed in and check if someone else is already using it".

That being said, you may want to use an algorhithm to achieve two goals:

  • Have a checksum of some sort. That allows your Installer to display "Key doesn't seem valid" message, solely to detect typos (Adding such a check in the installer actually means that writing a Key Generator is trivial as the hacker has all the code he needs. Not having the check and solely relying on server-side validation disables that check, at the risk of annoying your legal customers who don't understand why the server doesn't accept their CD Key as they aren't aware of the typo)
  • Work with a limited subset of characters. Trying to type in a CD Key and guessing "Is this an 8 or a B? a 1 or an I? a Q or an O or a 0?" - by using a subset of non-ambigous chars/digits you eliminate that confusion.

That being said, you still want a large distribution and some randomness to avoid a pirate simply guessing a valid key (that's valid in your database but still in a box on a store shelf) and screwing over a legitimate customer who happens to buy that box.

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

Using number as "index" (JSON)

What about

Game.status[0][0] or Game.status[0]["0"] ?

Does one of these work?

PS: What you have in your question is a Javascript Object, not JSON. JSON is the 'string' version of a Javascript Object.

Why doesn't wireshark detect my interface?

This is usually caused by incorrectly setting up permissions related to running Wireshark correctly. While you can avoid this issue by running Wireshark with elevated privileges (e.g. with sudo), it should generally be avoided (see here, specifically here). This sometimes results from an incomplete or partially successful installation of Wireshark. Since you are running Ubuntu, this can be resolved by following the instructions given in this answer on the Wireshark Q&A site. In summary, after installing Wireshark, execute the following commands:

sudo dpkg-reconfigure wireshark-common 
sudo usermod -a -G wireshark $USER

Then log out and log back in (or reboot), and Wireshark should work correctly without needing additional privileges. Finally, if the problem is still not resolved, it may be that dumpcap was not correctly configured, or there is something else preventing it from operating correctly. In this case, you can set the setuid bit for dumpcap so that it always runs as root.

sudo chmod 4711 `which dumpcap`

One some distros you might get the following error when you execute the command above:

chmod: missing operand after ‘4711’

Try 'chmod --help' for more information.

In this case try running

sudo chmod 4711 `sudo which dumpcap`

Double % formatting question for printf in Java

%d is for integers use %f instead, it works for both float and double types:

double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000

Truncate Decimal number not Round Off

What format are you wanting the output?

If you're happy with a string then consider the following C# code:

double num = 3.12345;
num.ToString("G3");

The result will be "3.12".

This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.

Powershell get ipv4 address into a variable

Here is another solution:

$env:HostIP = (
    Get-NetIPConfiguration |
    Where-Object {
        $_.IPv4DefaultGateway -ne $null -and
        $_.NetAdapter.Status -ne "Disconnected"
    }
).IPv4Address.IPAddress

BLOB to String, SQL Server

Found this...

bcp "SELECT top 1 BlobText FROM TableName" queryout "C:\DesinationFolder\FileName.txt" -T -c'

If you need to know about different options of bcp flags...

http://msdn.microsoft.com/en-us/library/ms162802.aspx

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

You can use

sudo apt-get install php7-mysql

or

sudo apt-get install php5-mysql

or

sudo apt-get install php-mysql

This worked for me.

What are public, private and protected in object oriented programming?

All the three are access modifiers and keywords which are used in a class. Anything declared in public can be used by any object within the class or outside the class,variables in private can only be used by the objects within the class and could not be changed through direct access(as it can change through functions like friend function).Anything defined under protected section can be used by the class and their just derived class.

How to create an empty file at the command line in Windows?

Use copy > your_file_name.extension in command prompt like

P:\excecise> copy > Sample.txt

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

How to stop execution after a certain time in Java?

Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask to schedule a task to set a stopExecution flag, and also .interrupt() your thread.

With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).

ReactJS - How to use comments?

To summarize, JSX doesn't support comments, either html-like or js-like:

<div>
    /* This will be rendered as text */
    // as well as this
    <!-- While this will cause compilation failure -->
</div>

and the only way to add comments "in" JSX is actually to escape into JS and comment in there:

<div>
    {/* This won't be rendered */}
    {// just be sure that your closing bracket is out of comment
    }
</div>

if you don't want to make some nonsense like

<div style={{display:'none'}}>
    actually, there are other stupid ways to add "comments"
    but cluttering your DOM is not a good idea
</div>

Finally, if you do want to create a comment node via React, you have to go much fancier, check out this answer.

How do I read the source code of shell commands?

CoreUtils referred to in other posts does NOT show the real implementation of most of the functionality which I think you seek. In most cases it provides front-ends for the actual functions that retrieve the data, which can be found here:

It is build upon Gnulib with the actual source code in the lib-subdirectory

HTML5 Canvas Rotate Image

You can use canvas’ context.translate & context.rotate to do rotate your image

enter image description here

Here’s a function to draw an image that is rotated by the specified degrees:

function drawRotated(degrees){
    context.clearRect(0,0,canvas.width,canvas.height);

    // save the unrotated context of the canvas so we can restore it later
    // the alternative is to untranslate & unrotate after drawing
    context.save();

    // move to the center of the canvas
    context.translate(canvas.width/2,canvas.height/2);

    // rotate the canvas to the specified degrees
    context.rotate(degrees*Math.PI/180);

    // draw the image
    // since the context is rotated, the image will be rotated also
    context.drawImage(image,-image.width/2,-image.width/2);

    // we’re done with the rotating so restore the unrotated context
    context.restore();
}

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/6ZsCz/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

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

    var angleInDegrees=0;

    var image=document.createElement("img");
    image.onload=function(){
        ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
    }
    image.src="houseicon.png";

    $("#clockwise").click(function(){ 
        angleInDegrees+=30;
        drawRotated(angleInDegrees);
    });

    $("#counterclockwise").click(function(){ 
        angleInDegrees-=30;
        drawRotated(angleInDegrees);
    });

    function drawRotated(degrees){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.save();
        ctx.translate(canvas.width/2,canvas.height/2);
        ctx.rotate(degrees*Math.PI/180);
        ctx.drawImage(image,-image.width/2,-image.width/2);
        ctx.restore();
    }


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas><br>
    <button id="clockwise">Rotate right</button>
    <button id="counterclockwise">Rotate left</button>
</body>
</html>

Sublime Text 2 multiple line edit

It's fine to manually select each number for a small set of numbers like in your example, but for larger collections you can do a regex search which will do the work for you.

Ctrl + F will open the search bar.

Regex searches are enabled by clicking the ".*" button on the far left.

Type in "\d+" to search for all occurrences of 1 or more digits. Clicking the "Find All" button will select each of these numbers separately.

Then you can use Ctrl + Shift + L to convert the selection into multiple cursors. From here you can do as you like.

Can I pass an array as arguments to a method with variable arguments in Java?

The underlying type of a variadic method function(Object... args) is function(Object[] args). Sun added varargs in this manner to preserve backwards compatibility.

So you should just be able to prepend extraVar to args and call String.format(format, args).

Best way to test for a variable's existence in PHP; isset() is clearly broken

THE only way to know if a variable is defined in current scope ($GLOBALS is not trustworthy) is array_key_exists( 'var_name', get_defined_vars() ).

How can I upload files asynchronously?

What if using promises which ajax and checking if the file is valid and well saved in your backend, so you can use some animation in front while user is navigating thought your page.

You can even make it paralel upload or stacking with recursive approach

How can I install a previous version of Python 3 in macOS using homebrew?

To solve this with homebrew, you can temporarily backdate homebrew-core and set the HOMEBREW_NO_AUTO_UPDATE variable to hold it in place:

cd `brew --repo homebrew/core`
git checkout f2a764ef944b1080be64bd88dca9a1d80130c558
export HOMEBREW_NO_AUTO_UPDATE=1
brew install python

I don't recommend permanently backdating homebrew-core, as you will miss out on security patches, but it is useful for testing purposes.

You can also extract old versions of homebrew formulae into your own tap (tap_owner/tap_name) using the brew extract command:

brew extract python tap_owner/tap_name --version=3.6.5

How to export data to an excel file using PHPExcel

I currently use this function in my project after a series of googling to download excel file from sql statement

    // $sql = sql query e.g "select * from mytablename"
    // $filename = name of the file to download 
        function queryToExcel($sql, $fileName = 'name.xlsx') {
                // initialise excel column name
                // currently limited to queries with less than 27 columns
        $columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                // Execute the database query
                $result =  mysql_query($sql) or die(mysql_error());

                // Instantiate a new PHPExcel object
                $objPHPExcel = new PHPExcel();
                // Set the active Excel worksheet to sheet 0
                $objPHPExcel->setActiveSheetIndex(0);
                // Initialise the Excel row number
                $rowCount = 1;
    // fetch result set column information
                $finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter                
$columnlenght = 0;
                foreach ($finfo as $val) {
// set column header values                   
  $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
                }
// make the column headers bold
                $objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);

                $rowCount++;
                // Iterate through each result from the SQL query in turn
                // We fetch each database result row into $row in turn

                while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
                    for ($i = 0; $i < $columnLenght; $i++) {
                        $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
                    }
                    $rowCount++;
                }
// set header information to force download
                header('Content-type: application/vnd.ms-excel');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file        
                // Write the Excel file to filename some_excel_file.xlsx in the current directory                
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                // Write the Excel file to filename some_excel_file.xlsx in the current directory
                $objWriter->save('php://output');
            }

Checking letter case (Upper/Lower) within a string in Java

A loop like this one:

else if (!(Character.isLowerCase(ch)))
            {
                for (int i=1; i<password.length(); i++)
                {
                   ch = password.charAt(i);

                    if (!Character.isLowerCase(ch))
                       {  
                        System.out.println("Invalid password - Must have a Lower Case character.");
                        password = "";
                       }
                     // end if
                } //end for
            }

Has an obvious logical flaw: You enter it if the first character is not lowercase, then test if the second character is not lower case. At that point you throw an error.

Instead, you should do something like this (not full code, just an example):

boolean hasLower = false, hasUpper = false, hasNumber = false, hasSpecial = false; // etc - all the rules
for ( ii = 0; ii < password.length(); ii++ ) {
  ch = password.charAt(ii);
  // check each rule in turn, with code like this:
  if Character.isLowerCase(ch) hasLower = true;
  if Character.isUpperCase(ch) hasUpper = true;
  // ... etc for all the tests you want to do
}

if(hasLower && hasUpper && ...) {
  // password is good
} 
else {
  // password is bad
}

Of course the code snippet you provided, besides the faulty logic, did not have code to test for the other conditions that your "help" option printed out. As was pointed out in one of the other answers, you could consider using regular expressions to help you speed up the process of finding each of these things. For example,

hasNumber  : use regex pattern "\d+" for "find at least one digit"
hasSpecial : use regex pattern "[!@#$%^&*]+" for "find at least one of these characters"

In code:

hasNumber  = password.matches(".*\\d.*");  // "a digit with anything before or after"
hasSpecial = password.matches(".*[!@#$%^&*].*");
hasNoNOT   = !password.matches(".*NOT.*");
hasNoAND   = !password.matches(".*AND.*");

It is possible to combine these things in clever ways - but especially when you are a novice regex user, it is much better to be a little bit "slow and tedious", and get code that works first time (plus you will be able to figure out what you did six months from now).

How can I list ALL grants a user received?

Assuming you want to list grants on all objects a particular user has received:

select * from all_tab_privs_recd where grantee = 'your user'

This will not return objects owned by the user. If you need those, use all_tab_privs view instead.

In VBA get rid of the case sensitivity when comparing words?

It is a bit of hack but will do the task.

Function equalsIgnoreCase(str1 As String, str2 As String) As Boolean
    equalsIgnoreCase = LCase(str1) = LCase(str2)
End Function

Node.js: Python not found exception due to node-sass and node-gyp

After looking at all the answers, i notice this solution might be very helpful. It explains how to configure "npm" to find your installed python version while installing node-sass. Remember, node-sass requires node-gyp (an npm build-tool) which looks for your python path. Or just install python, and follow the same solution given (in the link). Thanks.

Why are arrays of references illegal?

When you store something in an array , its size needs to be known (since array indexing relies on the size). Per the C++ standard It is unspecified whether or not a reference requires storage, as a result indexing an array of references would not be possible.

Android: how to convert whole ImageView to Bitmap?

Just thinking out loud here (with admittedly little expertise working with graphics in Java) maybe something like this would work?:

ImageView iv = (ImageView)findViewById(R.id.imageview);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
iv.draw(canvas);

Out of curiosity, what are you trying to accomplish? There may be a better way to achieve your goal than what you have in mind.

Find the last element of an array while using a foreach loop in PHP

you can do a count().

for ($i=0;$i<count(arr);$i++){
    $i == count(arr)-1 ? true : false;
}

or if you're looking for ONLY the last element, you can use end().

end(arr);

returns only the last element.

and, as it turns out, you CAN index php arrays by integers. It's perfectly happy with

arr[1];

How to do a GitHub pull request

(In addition of the official "GitHub Help 'Using pull requests' page",
see also "Forking vs. Branching in GitHub", "What is the difference between origin and upstream in GitHub")

Couple tips on pull-requests:

Assuming that you have first forked a repo, here is what you should do in that fork that you own:

  • create a branch: isolate your modifications in a branch. Don't create a pull request from master, where you could be tempted to accumulate and mix several modifications at once.
  • rebase that branch: even if you already did a pull request from that branch, rebasing it on top of origin/master (making sure your patch is still working) will update the pull request automagically (no need to click on anything)
  • update that branch: if your pull request is rejected, you simply can add new commits, and/or redo your history completely: it will activate your existing pull request again.
  • "focus" that branch: i.e., make its topic "tight", don't modify thousands of class and the all app, only add or fix a well-defined feature, keeping the changes small.
  • delete that branch: once accepted, you can safely delete that branch on your fork (and git remote prune origin). The GitHub GUI will propose for you to delete your branch in your pull-request page.

Note: to write the Pull-Request itself, see "How to write the perfect pull request" (January 2015, GitHub)


March 2016: New PR merge button option: see "Github squash commits from web interface on pull request after review comments?".

squash

The maintainer of the repo can chose to merge --squash those PR commits.


After a Pull Request

Regarding the last point, since April, 10th 2013, "Redesigned merge button", the branch is deleted for you:

new merge button

Deleting branches after you merge has also been simplified.
Instead of confirming the delete with an extra step, we immediately remove the branch when you delete it and provide a convenient link to restore the branch in the event you need it again.

That confirms the best practice of deleting the branch after merging a pull request.


pull-request vs. request-pull


e-notes for "reposotory" (sic)

<humour>

That (pull request) isn't even defined properly by GitHub!

Fortunately, a true business news organization would know, and there is an e-note in order to replace pull-replace by 'e-note':

https://pbs.twimg.com/media/BT_5S-TCcAA-EF2.jpg:large

So if your reposotory needs a e-note... ask Fox Business. They are in the know.

</humour>

Why does visual studio 2012 not find my tests?

I sometimes get the same symptoms.

What I did is:
1. Closed the Test Explorer window
2. Cleaned the solution
3. Rebuild the solution
4. Relaunched Test Explorer window from Test -> Windows -> Test Explorer.

And I got my test in Test Explorer window.

VideoView Full screen in android application

The below code worked.

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

Add this code before calling videoView.start(). With this the video activity runs in full screen mode in most of the cases. But if the title bar is still displayed then change your theme in your manifest to this.

    android:theme="@style/Theme.AppCompat.NoActionBar">

How to align the checkbox and label in same line in html?

Just place a div around the input and label...

    <li>
      <div>
        <input id="checkid"  type="checkbox" value="test" />
      </div>
      <div>
        <label  style="word-wrap:break-word">testdata</label>
      </div>
    </li>

How can I return the difference between two lists?

I was looking similar but I wanted the difference in either list (uncommon elements between the 2 lists).

Let say I have:

List<String> oldKeys = Arrays.asList("key0","key1","key2","key5");
List<String> newKeys = Arrays.asList("key0","key2","key5", "key6");

And I wanted to know which key has been added and which key is removed i.e I wanted to get (key1, key6)

Using org.apache.commons.collections.CollectionUtils

List<String> list = new ArrayList<>(CollectionUtils.disjunction(newKeys, oldKeys));

Result

["key1", "key6"]

Unexpected end of file error

The line #include "stdafx.h" must be the first line at the top of each source file, before any other header files are included.

If what you've shown is the entire .cxx file, then you did forget to include stdafx.h in that file.

How do I view 'git diff' output with my preferred diff tool/ viewer?

you can use git difftool.

for example if you have meld, you can edit the branchs master and devel by:

git config --global diff.external meld
git difftool master..devel

Getting the last element of a split string array

var title = 'fdfdsg dsgdfh dgdh dsgdh tyu hjuk yjuk uyk hjg fhjg hjj tytutdfsf sdgsdg dsfsdgvf dfgfdhdn dfgilkj,n, jhk jsu wheiu sjldsf dfdsf hfdkdjf dfhdfkd hsfd ,dsfk dfjdf ,yier djsgyi kds';
var shortText = $.trim(title).substring(1000, 150).split(" ").slice(0, -1).join(" ") + "...More >>";

C++ cout hex values?

std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.

Configuration with name 'default' not found. Android Studio

I am facing same problem, I was fixed it by generating gradle project and then adding lib project to android studio

First, See build.gradle file is present in project root directory

if not then, Create gradle project,

  1. export your required lib project from eclipse then (File->Export->Android->generate Gradle build file
  2. Click on Next->Next->Select your lib project from project listing->Next->Next->Finish
  3. See build.gradle file present in your project root directory
  4. Move this project to Android Studio

How do I automatically update a timestamp in PostgreSQL

Using 'now()' as default value automatically generates time-stamp.

What does ||= (or-equals) mean in Ruby?

To be precise, a ||= b means "if a is undefined or falsy (false or nil), set a to b and evaluate to (i.e. return) b, otherwise evaluate to a".

Others often try to illustrate this by saying that a ||= b is equivalent to a || a = b or a = a || b. These equivalencies can be helpful for understanding the concept, but be aware that they are not accurate under all conditions. Allow me to explain:

  • a ||= b ? a || a = b?

    The behavior of these statements differs when a is an undefined local variable. In that case, a ||= b will set a to b (and evaluate to b), whereas a || a = b will raise NameError: undefined local variable or method 'a' for main:Object.

  • a ||= b ? a = a || b?

    The equivalency of these statements are often assumed, since a similar equivalence is true for other abbreviated assignment operators (i.e. +=,-=,*=,/=,%=,**=,&=,|=,^=,<<=, and >>=). However, for ||= the behavior of these statements may differ when a= is a method on an object and a is truthy. In that case, a ||= b will do nothing (other than evaluate to a), whereas a = a || b will call a=(a) on a's receiver. As others have pointed out, this can make a difference when calling a=a has side effects, such as adding keys to a hash.

  • a ||= b ? a = b unless a??

    The behavior of these statements differs only in what they evaluate to when a is truthy. In that case, a = b unless a will evaluate to nil (though a will still not be set, as expected), whereas a ||= b will evaluate to a.

  • a ||= b ? defined?(a) ? (a || a = b) : (a = b)????

    Still no. These statements can differ when a method_missing method exists which returns a truthy value for a. In this case, a ||= b will evaluate to whatever method_missing returns, and not attempt to set a, whereas defined?(a) ? (a || a = b) : (a = b) will set a to b and evaluate to b.

Okay, okay, so what is a ||= b equivalent to? Is there a way to express this in Ruby?

Well, assuming that I'm not overlooking anything, I believe a ||= b is functionally equivalent to... (drumroll)

begin
  a = nil if false
  a || a = b
end

Hold on! Isn't that just the first example with a noop before it? Well, not quite. Remember how I said before that a ||= b is only not equivalent to a || a = b when a is an undefined local variable? Well, a = nil if false ensures that a is never undefined, even though that line is never executed. Local variables in Ruby are lexically scoped.

Pandas: Appending a row to a dataframe and specify its index label

I shall refer to the same sample of data as posted in the question:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))

Running this code will give you

The original data frame is:

          A         B         C         D
0  0.494824 -0.328480  0.818117  0.100290
1  0.239037  0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856  0.359811 -0.345560
3 -0.070814 -0.394711  0.081697 -1.178845
4 -1.638063  1.498027 -0.609325  0.882594
5 -0.510217  0.500475  1.039466  0.187076
6  1.116529  0.912380  0.869323  0.119459
7 -1.046507  0.507299 -0.373432 -1.024795

Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append returns a view of the dataframe and does not modify its contents. Following is the code:

row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))

Following would be the new output:

The new data frame is:

           A          B          C          D
0   0.494824  -0.328480   0.818117   0.100290
1   0.239037   0.954912  -0.186825  -0.651935
2  -1.818285  -0.158856   0.359811  -0.345560
3  -0.070814  -0.394711   0.081697  -1.178845
4  -1.638063   1.498027  -0.609325   0.882594
5  -0.510217   0.500475   1.039466   0.187076
6   1.116529   0.912380   0.869323   0.119459
7  -1.046507   0.507299  -0.373432  -1.024795
3  10.000000  20.000000  30.000000  40.000000

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.

Export JAR with Netbeans

You need to enable the option

Project Properties -> Build -> Packaging -> Build JAR after compiling

(but this is enabled by default)

static function in C

C programmers use the static attribute to hide variable and function declarations inside modules, much as you would use public and private declarations in Java and C++. C source files play the role of modules. Any global variable or function declared with the static attribute is private to that module. Similarly, any global variable or function declared without the static attribute is public and can be accessed by any other module. It is good programming practice to protect your variables and functions with the static attribute wherever possible.

Why are elementwise additions much faster in separate loops than in a combined loop?

I cannot replicate the results discussed here.

I don't know if poor benchmark code is to blame, or what, but the two methods are within 10% of each other on my machine using the following code, and one loop is usually just slightly faster than two - as you'd expect.

Array sizes ranged from 2^16 to 2^24, using eight loops. I was careful to initialize the source arrays so the += assignment wasn't asking the FPU to add memory garbage interpreted as a double.

I played around with various schemes, such as putting the assignment of b[j], d[j] to InitToZero[j] inside the loops, and also with using += b[j] = 1 and += d[j] = 1, and I got fairly consistent results.

As you might expect, initializing b and d inside the loop using InitToZero[j] gave the combined approach an advantage, as they were done back-to-back before the assignments to a and c, but still within 10%. Go figure.

Hardware is Dell XPS 8500 with generation 3 Core i7 @ 3.4 GHz and 8 GB memory. For 2^16 to 2^24, using eight loops, the cumulative time was 44.987 and 40.965 respectively. Visual C++ 2010, fully optimized.

PS: I changed the loops to count down to zero, and the combined method was marginally faster. Scratching my head. Note the new array sizing and loop counts.

// MemBufferMystery.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <time.h>

#define  dbl    double
#define  MAX_ARRAY_SZ    262145    //16777216    // AKA (2^24)
#define  STEP_SZ           1024    //   65536    // AKA (2^16)

int _tmain(int argc, _TCHAR* argv[]) {
    long i, j, ArraySz = 0,  LoopKnt = 1024;
    time_t start, Cumulative_Combined = 0, Cumulative_Separate = 0;
    dbl *a = NULL, *b = NULL, *c = NULL, *d = NULL, *InitToOnes = NULL;

    a = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    b = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    c = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    d = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    InitToOnes = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    // Initialize array to 1.0 second.
    for(j = 0; j< MAX_ARRAY_SZ; j++) {
        InitToOnes[j] = 1.0;
    }

    // Increase size of arrays and time
    for(ArraySz = STEP_SZ; ArraySz<MAX_ARRAY_SZ; ArraySz += STEP_SZ) {
        a = (dbl *)realloc(a, ArraySz * sizeof(dbl));
        b = (dbl *)realloc(b, ArraySz * sizeof(dbl));
        c = (dbl *)realloc(c, ArraySz * sizeof(dbl));
        d = (dbl *)realloc(d, ArraySz * sizeof(dbl));
        // Outside the timing loop, initialize
        // b and d arrays to 1.0 sec for consistent += performance.
        memcpy((void *)b, (void *)InitToOnes, ArraySz * sizeof(dbl));
        memcpy((void *)d, (void *)InitToOnes, ArraySz * sizeof(dbl));

        start = clock();
        for(i = LoopKnt; i; i--) {
            for(j = ArraySz; j; j--) {
                a[j] += b[j];
                c[j] += d[j];
            }
        }
        Cumulative_Combined += (clock()-start);
        printf("\n %6i miliseconds for combined array sizes %i and %i loops",
                (int)(clock()-start), ArraySz, LoopKnt);
        start = clock();
        for(i = LoopKnt; i; i--) {
            for(j = ArraySz; j; j--) {
                a[j] += b[j];
            }
            for(j = ArraySz; j; j--) {
                c[j] += d[j];
            }
        }
        Cumulative_Separate += (clock()-start);
        printf("\n %6i miliseconds for separate array sizes %i and %i loops \n",
                (int)(clock()-start), ArraySz, LoopKnt);
    }
    printf("\n Cumulative combined array processing took %10.3f seconds",
            (dbl)(Cumulative_Combined/(dbl)CLOCKS_PER_SEC));
    printf("\n Cumulative seperate array processing took %10.3f seconds",
        (dbl)(Cumulative_Separate/(dbl)CLOCKS_PER_SEC));
    getchar();

    free(a); free(b); free(c); free(d); free(InitToOnes);
    return 0;
}

I'm not sure why it was decided that MFLOPS was a relevant metric. I though the idea was to focus on memory accesses, so I tried to minimize the amount of floating point computation time. I left in the +=, but I am not sure why.

A straight assignment with no computation would be a cleaner test of memory access time and would create a test that is uniform irrespective of the loop count. Maybe I missed something in the conversation, but it is worth thinking twice about. If the plus is left out of the assignment, the cumulative time is almost identical at 31 seconds each.

Where is database .bak file saved from SQL Server Management Studio?

I dont think default backup location is stored within the SQL server itself. The settings are stored in Registry. Look for "BackupDirectory" key and you'll find the default backup.

The "msdb.dbo.backupset" table consists of list of backups taken, if no backup is taken for a database, it won't show you anything

Wavy shape with css

My pure CSS implementation based on above with 100% width. Hope it helps!

_x000D_
_x000D_
#wave-container {_x000D_
  width: 100%;_x000D_
  height: 100px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#wave {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  height: 40px;_x000D_
  background: black;_x000D_
}_x000D_
_x000D_
#wave:before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  right: -25%;_x000D_
  top: 20px_x000D_
}_x000D_
_x000D_
#wave:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: black;_x000D_
  left: -25%;_x000D_
  top: -240px;_x000D_
}
_x000D_
<div id="wave-container">_x000D_
  <div id="wave">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert R Markdown to PDF?

Only two steps:

  1. Install the latest release "pandoc" from here:

    https://github.com/jgm/pandoc/releases

  2. Call the function pandoc in the library(knitr)

    library(knitr)
    pandoc('input.md', format = 'latex')
    

Thus, you can convert your "input.md" into "input.pdf".

How to get max value of a column using Entity Framework?

Try this int maxAge = context.Persons.Max(p => p.Age);

And make sure you have using System.Linq; at the top of your file

Laravel Pagination links not including other GET parameters

In Laravel 7.x you can use it like this:

{{ $results->withQueryString()->links() }}

How can I make setInterval also work when a tab is inactive in Chrome?

I was able to call my callback function at minimum of 250ms using audio tag and handling its ontimeupdate event. Its called 3-4 times in a second. Its better than one second lagging setTimeout

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

In my case I had inherited from the IdentityDbContext correctly (with my own custom types and key defined) but had inadvertantly removed the call to the base class's OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder); // I had removed this
    /// Rest of on model creating here.
}

Which then fixed up my missing indexes from the identity classes and I could then generate migrations and enable migrations appropriately.

Center content in responsive bootstrap navbar

For Bootstrap 4:

Just use

<ul class="navbar-nav mx-auto">

mx-auto will do the job

How to control border height?

I want to control the height of the border. How could I do this?

You can't. CSS borders will always span across the full height / width of the element.

One workaround idea would be to use absolute positioning (which can accept percent values) to place the border-carrying element inside one of the two divs. For that, you would have to make the element position: relative.

Decompile .smali files on an APK

dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Should use Entity class name for em.createQuery method or Should use em.createNativeQuery method for native query without entity class

With Entity class:

em.createQuery("select first_name from CUSTOMERV")

Without Entity class or Native query:

em.createNativeQuery("select c.first_name from CUSTOMERV c")

How do I rotate the Android emulator display?

For Mac you can use fn + Left control + F12.

How to check if any value is NaN in a Pandas DataFrame

I've been using the following and type casting it to a string and checking for the nan value

   (str(df.at[index, 'column']) == 'nan')

This allows me to check specific value in a series and not just return if this is contained somewhere within the series.

What does $1 [QSA,L] mean in my .htaccess file?

If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,

RewriteCond %{REQUEST_FILENAME} !-d

and if the requested filename is not a regular file that exists,

RewriteCond %{REQUEST_FILENAME} !-f

and if the requested filename is not a symbolic link,

RewriteCond %{REQUEST_FILENAME} !-l

then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Apache docs #flag_qsa

Another Example:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for

/pages/123?one=two

will be mapped to

/page.php?page=123&one=two

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

How big can a MySQL database get before performance starts to degrade

I would focus first on your indexes, than have a server admin look at your OS, and if all that doesn't help it might be time for a master/slave configuration.

That's true. Another thing that usually works is to just reduce the quantity of data that's repeatedly worked with. If you have "old data" and "new data" and 99% of your queries work with new data, just move all the old data to another table - and don't look at it ;)

-> Have a look at partitioning.

How do I check if a string is a number (float)?

Updated after Alfe pointed out you don't need to check for float separately as complex handles both:

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True

Previously said: Is some rare cases you might also need to check for complex numbers (e.g. 1+2i), which can not be represented by a float:

def is_number(s):
    try:
        float(s) # for int, long and float
    except ValueError:
        try:
            complex(s) # for complex
        except ValueError:
            return False

    return True

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() don't give formatted output. The latter one allows you to write formatted output.

Response.write - it writes the text stream Response.output.write - it writes the HTTP Output Stream.

reactjs - how to set inline style of backgroundcolor?

https://facebook.github.io/react/tips/inline-styles.html

You don't need the quotes.

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>

how to avoid a new line with p tag?

The <p> paragraph tag is meant for specifying paragraphs of text. If you don't want the text to start on a new line, I would suggest you're using the <p> tag incorrectly. Perhaps the <span> tag more closely fits what you want to achieve...?

AttributeError: 'module' object has no attribute 'model'

I realized that by looking at the stack trace it was trying to load my own script in place of another module called the same way,i.e., my script was called random.py and when a module i used was trying to import the "random" package, it was loading my script causing a circular reference and so i renamed it and deleted a .pyc file it had created from the working folder and things worked just fine.

How to split a comma-separated string?

There is a function called replaceAll() that can remove all whitespaces by replacing them with whatever you want. As an example

String str="  15. 9 4;16.0 1"
String firstAndSecond[]=str.replaceAll("\\s","").split(";");
System.out.println("First:"+firstAndSecond[0]+", Second:"+firstAndSecond[1]);

will give you:

First:15.94, Second:16.01

Oracle SQL Developer spool output?

You can export the query results to a text file (or insert statements, or even pdf) by right-clicking on Query Result row (any row) and choose Export

using Sql Developer 3.0

See SQL Developer downloads for latest versions

Maximum number of rows in an MS Access database engine table?

We're not necessarily talking theoretical limits here, we're talking about real world limits of the 2GB max file size AND database schema.

  • Is your db a single table or multiple?
  • How many columns does each table have?
  • What are the datatypes?

The schema is on even footing with the row count in determining how many rows you can have.

We have used Access MDBs to store exports of MS-SQL data for statistical analysis by some of our corporate users. In those cases we've exported our core table structure, typically four tables with 20 to 150 columns varying from a hundred bytes per row to upwards of 8000 bytes per row. In these cases, we would bump up against a few hundred thousand rows of data were permissible PER MDB that we would ship them.

So, I just don't think that this question has an answer in absence of your schema.

intellij incorrectly saying no beans of type found for autowired repository

in my Case, the Directory I was trying to @Autowired was not at the same level,

after setting it up at the same structure level, the error disappeared

hope it can helps some one!

Undefined index error PHP

Apparently the index 'productid' is missing from your html form. Inspect your html inputs first. eg <input type="text" name="productid" value=""> But this will handle the current error PHP is raising.

  $rowID = isset($_POST['rowID']) ? $_POST['rowID'] : '';
  $productid = isset($_POST['productid']) ? $_POST['productid'] : '';
  $name = isset($_POST['name']) ? $_POST['name'] : '';
  $price = isset($_POST['price']) ? $_POST['price'] : '';
  $description = isset($_POST['description']) ? $_POST['description'] : '';

package javax.servlet.http does not exist

Your CLASSPATH variable does not point to the directory containing the javax classes. The CLASSPATH variable specifies where the java compiler should look for java class file resources. If it does not know to look in the javax directory, then it will never find the file(s) you are after.

What does "exited with code 9009" mean during this build?

I fixed this by simply restarting Visual Studio - I had just run dotnet tool install xxx in a console window and VS hadn't yet picked up the new environment variables and/or path settings that were changed, so a quick restart fixed the issue.

How to randomly select rows in SQL?

This is an old question, but attempting to apply a new field (either NEWID() or ORDER BY rand()) to a table with a large number of rows would be prohibitively expensive. If you have incremental, unique IDs (and do not have any holes) it will be more efficient to calculate the X # of IDs to be selected instead of applying a GUID or similar to every single row and then taking the top X # of.

DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];

DECLARE @randomId1 int, @randomId2 int, @randomId3 int, @randomId4 int, @randomId5 int
SET @randomId1 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId2 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId3 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId4 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId5 = ((@maxValue + 1) - @minValue) * Rand() + @minValue

--select @maxValue as MaxValue, @minValue as MinValue
--  , @randomId1 as SelectedId1
--  , @randomId2 as SelectedId2
--  , @randomId3 as SelectedId3
--  , @randomId4 as SelectedId4
--  , @randomId5 as SelectedId5

select * from [TABLE] el
where el.id in (@randomId1, @randomId2, @randomId3, @randomId4, @randomId5)

If you wanted to select many more rows I would look into populating a #tempTable with an ID and a bunch of rand() values then using each rand() value to scale to the min-max values. That way you do not have to define all of the @randomId1...n parameters. I've included an example below using a CTE to populate the initial table.

DECLARE @NumItems int = 100;

DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];
DECLARE @range int = @maxValue+1 - @minValue;

with cte (n) as (
   select 1 union all
   select n+1 from cte
   where n < @NumItems
)
select cast( @range * rand(cast(newid() as varbinary(100))) + @minValue as int) tp
into #Nt
from cte;

select * from #Nt ntt
inner join [TABLE] i on i.id = ntt.tp;

drop table #Nt;

Hiding and Showing TabPages in tabControl

TabPanel1.Visible = true; // Show Tabpage 1
TabPanel1.Visible = false; //Hide Tabpage 1

Which HTTP methods match up to which CRUD methods?

Create = PUT with a new URI
         POST to a base URI returning a newly created URI
Read   = GET
Update = PUT with an existing URI
Delete = DELETE

PUT can map to both Create and Update depending on the existence of the URI used with the PUT.

POST maps to Create.

Correction: POST can also map to Update although it's typically used for Create. POST can also be a partial update so we don't need the proposed PATCH method.

How do I write to a Python subprocess' stdin?

It might be better to use communicate:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

"Better", because of this warning:

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

Sass - Converting Hex to RGBa for background opacity

SASS has a built-in rgba() function to evaluate values.

rgba($color, $alpha)

E.g.

rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)

An example using your own variables:

$my-color: #00aaff;
$my-opacity: 0.5;

.my-element {
  color: rgba($my-color, $my-opacity);
}

Outputs:

.my-element {
  color: rgba(0, 170, 255, 0.5);
}

In SQL how to compare date values?

Your problem may be that you are dealing with DATETIME data, not just dates. If a row has a mydate that is '2008-11-25 09:30 AM', then your WHERE mydate<='2008-11-25'; is not going to return that row. '2008-11-25' has an implied time of 00:00 (midnight), so even though the date part is the same, they are not equal, and mydate is larger.

If you use < '2008-11-26' instead of <= '2008-11-25', that would work. The Datediff method works because it compares just the date portion, and ignores the times.

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

Android Use Done button on Keyboard to click button

Use this class in your layout :

public class ActionEditText extends EditText
{
    public ActionEditText(Context context)
    {
        super(context);
    }

    public ActionEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public ActionEditText(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs)
    {
        InputConnection conn = super.onCreateInputConnection(outAttrs);
        outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
        return conn;
    }

}

In xml:

<com.test.custom.ActionEditText
                android:id="@+id/postED"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@android:color/transparent"
                android:gravity="top|left"
                android:hint="@string/msg_type_message_here"
                android:imeOptions="actionSend"
                android:inputType="textMultiLine"
                android:maxLines="5"
                android:padding="5dip"
                android:scrollbarAlwaysDrawVerticalTrack="true"
                android:textColor="@color/white"
                android:textSize="20sp" />

git ahead/behind info between master and branch?

You can also use awk to make it a little bit prettier:

git rev-list --left-right --count  origin/develop...feature-branch | awk '{print "Behind "$1" - Ahead "$2""}'

You can even make an alias that always fetches origin first and then compares the branches

commit-diff = !"git fetch &> /dev/null && git rev-list --left-right --count"

phonegap open link in browser

Like this :

<a href="#" onclick="window.open('https://www.nbatou.com', '_system'); return false;">https://www.nbatou.com</a>

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

I think the reason that this is happening could be because TextBox1 is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".

EDIT

It looks like you may be able to use the GetObject function to pull the textbox from the workbook.

Convert Date format into DD/MMM/YYYY format in SQL Server

Try this :

select replace ( convert(varchar,getdate(),106),' ','/')

Add line break to 'git commit -m' from the command line

I don't see anyone mentioning that if you don't provide a message it will open nano for you (at least in Linux) where you can write multiple lines...

Only this is needed:

git commit

How does C compute sin() and other math functions?

Chebyshev polynomials, as mentioned in another answer, are the polynomials where the largest difference between the function and the polynomial is as small as possible. That is an excellent start.

In some cases, the maximum error is not what you are interested in, but the maximum relative error. For example for the sine function, the error near x = 0 should be much smaller than for larger values; you want a small relative error. So you would calculate the Chebyshev polynomial for sin x / x, and multiply that polynomial by x.

Next you have to figure out how to evaluate the polynomial. You want to evaluate it in such a way that the intermediate values are small and therefore rounding errors are small. Otherwise the rounding errors might become a lot larger than errors in the polynomial. And with functions like the sine function, if you are careless then it may be possible that the result that you calculate for sin x is greater than the result for sin y even when x < y. So careful choice of the calculation order and calculation of upper bounds for the rounding error are needed.

For example, sin x = x - x^3/6 + x^5 / 120 - x^7 / 5040... If you calculate naively sin x = x * (1 - x^2/6 + x^4/120 - x^6/5040...), then that function in parentheses is decreasing, and it will happen that if y is the next larger number to x, then sometimes sin y will be smaller than sin x. Instead, calculate sin x = x - x^3 * (1/6 - x^2 / 120 + x^4/5040...) where this cannot happen.

When calculating Chebyshev polynomials, you usually need to round the coefficients to double precision, for example. But while a Chebyshev polynomial is optimal, the Chebyshev polynomial with coefficients rounded to double precision is not the optimal polynomial with double precision coefficients!

For example for sin (x), where you need coefficients for x, x^3, x^5, x^7 etc. you do the following: Calculate the best approximation of sin x with a polynomial (ax + bx^3 + cx^5 + dx^7) with higher than double precision, then round a to double precision, giving A. The difference between a and A would be quite large. Now calculate the best approximation of (sin x - Ax) with a polynomial (b x^3 + cx^5 + dx^7). You get different coefficients, because they adapt to the difference between a and A. Round b to double precision B. Then approximate (sin x - Ax - Bx^3) with a polynomial cx^5 + dx^7 and so on. You will get a polynomial that is almost as good as the original Chebyshev polynomial, but much better than Chebyshev rounded to double precision.

Next you should take into account the rounding errors in the choice of polynomial. You found a polynomial with minimum error in the polynomial ignoring rounding error, but you want to optimise polynomial plus rounding error. Once you have the Chebyshev polynomial, you can calculate bounds for the rounding error. Say f (x) is your function, P (x) is the polynomial, and E (x) is the rounding error. You don't want to optimise | f (x) - P (x) |, you want to optimise | f (x) - P (x) +/- E (x) |. You will get a slightly different polynomial that tries to keep the polynomial errors down where the rounding error is large, and relaxes the polynomial errors a bit where the rounding error is small.

All this will get you easily rounding errors of at most 0.55 times the last bit, where +,-,*,/ have rounding errors of at most 0.50 times the last bit.

Convert string to ASCII value python

If you want your result concatenated, as you show in your question, you could try something like:

>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world"))
'10410110810811132119111114108100'

How to split one string into multiple variables in bash shell?

If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:

var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)

I chose cut here because you could simply extend the code for a few more variables...

jQuery autocomplete with callback ajax json

My issue was that end users would start typing in a textbox and receive autocomplete (ACP) suggestions and update the calling control if a suggestion was selected as the ACP is designed by default. However, I also needed to update multiple other controls (textboxes, DropDowns, etc...) with data specific to the end user's selection. I have been trying to figure out an elegant solution to the issue and I feel the one I developed is worth sharing and hopefully will save you at least some time.

WebMethod (SampleWM.aspx):

  • PURPOSE:

    • To capture SQL Server Stored Procedure results and return them as a JSON String to the AJAX Caller
  • NOTES:

    • Data.GetDataTableFromSP() - Is a custom function that returns a DataTable from the results of a Stored Procedure
    • < System.Web.Services.WebMethod(EnableSession:=True) > _
    • Public Shared Function GetAutoCompleteData(ByVal QueryFilterAs String) As String

 //Call to custom function to return SP results as a DataTable
 // DataTable will consist of Field0 - Field5
 Dim params As ArrayList = New ArrayList
 params.Add("@QueryFilter|" & QueryFilter)
 Dim dt As DataTable = Data.GetDataTableFromSP("AutoComplete", params, [ConnStr])

 //Create a StringBuilder Obj to hold the JSON 
 //IE: [{"Field0":"0","Field1":"Test","Field2":"Jason","Field3":"Smith","Field4":"32","Field5":"888-555-1212"},{"Field0":"1","Field1":"Test2","Field2":"Jane","Field3":"Doe","Field4":"25","Field5":"888-555-1414"}]
 Dim jStr As StringBuilder = New StringBuilder

 //Loop the DataTable and convert row into JSON String
 If dt.Rows.Count > 0 Then
      jStr.Append("[")
      Dim RowCnt As Integer = 1
      For Each r As DataRow In dt.Rows
           jStr.Append("{")
           Dim ColCnt As Integer = 0
           For Each c As DataColumn In dt.Columns
               If ColCnt = 0 Then
                   jStr.Append("""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
               Else
                   jStr.Append(",""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
                End If
                ColCnt += 1
            Next

            If Not RowCnt = dt.Rows.Count Then
                jStr.Append("},")
            Else
                jStr.Append("}")
            End If

            RowCnt += 1
        Next

        jStr.Append("]")
    End If

    //Return JSON to WebMethod Caller
    Return jStr.ToString

AutoComplete jQuery (AutoComplete.aspx):

  • PURPOSE:
    • Perform the Ajax Request to the WebMethod and then handle the response

    $(function() {
      $("#LookUp").autocomplete({                
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "SampleWM.aspx/GetAutoCompleteData",
                    dataType: "json",
                    data:'{QueryFilter: "' + request.term  + '"}',
                    success: function (data) {
                        response($.map($.parseJSON(data.d), function (item) {                                
                            var AC = new Object();

                            //autocomplete default values REQUIRED
                            AC.label = item.Field0;
                            AC.value = item.Field1;

                            //extend values
                            AC.FirstName = item.Field2;
                            AC.LastName = item.Field3;
                            AC.Age = item.Field4;
                            AC.Phone = item.Field5;

                            return AC
                        }));       
                    }                                             
                });
            },
            minLength: 3,
            select: function (event, ui) {                    
                $("#txtFirstName").val(ui.item.FirstName);
                $("#txtLastName").val(ui.item.LastName);
                $("#ddlAge").val(ui.item.Age);
                $("#txtPhone").val(ui.item.Phone);
             }                    
        });
     });

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

Converting string to double in C#

There are 3 problems.

1) Incorrect decimal separator

Different cultures use different decimal separators (namely , and .).

If you replace . with , it should work as expected:

Console.WriteLine(Convert.ToDouble("52,8725945"));

You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:

double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);

You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.

2) You have an incorrect double

One of your values is incorrect, because it contains two dots:

15.5859949000000662452.23862099999999

3) Your array has an empty value at the end, which is an incorrect double

You can use overloaded Split which removes empty values:

string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

Angularjs how to upload multipart form data and a file?

First of all

  1. You don't need any special changes in the structure. I mean: html input tags.

_x000D_
_x000D_
<input accept="image/*" name="file" ng-value="fileToUpload"_x000D_
       value="{{fileToUpload}}" file-model="fileToUpload"_x000D_
       set-file-data="fileToUpload = value;" _x000D_
       type="file" id="my_file" />
_x000D_
_x000D_
_x000D_

1.2 create own directive,

_x000D_
_x000D_
.directive("fileModel",function() {_x000D_
 return {_x000D_
  restrict: 'EA',_x000D_
  scope: {_x000D_
   setFileData: "&"_x000D_
  },_x000D_
  link: function(scope, ele, attrs) {_x000D_
   ele.on('change', function() {_x000D_
    scope.$apply(function() {_x000D_
     var val = ele[0].files[0];_x000D_
     scope.setFileData({ value: val });_x000D_
    });_x000D_
   });_x000D_
  }_x000D_
 }_x000D_
})
_x000D_
_x000D_
_x000D_

  1. In module with $httpProvider add dependency like ( Accept, Content-Type etc) with multipart/form-data. (Suggestion would be, accept response in json format) For e.g:

$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';

  1. Then create separate function in controller to handle form submit call. like for e.g below code:

  2. In service function handle "responseType" param purposely so that server should not throw "byteerror".

  3. transformRequest, to modify request format with attached identity.

  4. withCredentials : false, for HTTP authentication information.

_x000D_
_x000D_
in controller:_x000D_
_x000D_
  // code this accordingly, so that your file object _x000D_
  // will be picked up in service call below._x000D_
  fileUpload.uploadFileToUrl(file); _x000D_
_x000D_
_x000D_
in service:_x000D_
_x000D_
  .service('fileUpload', ['$http', 'ajaxService',_x000D_
    function($http, ajaxService) {_x000D_
_x000D_
      this.uploadFileToUrl = function(data) {_x000D_
        var data = {}; //file object _x000D_
_x000D_
        var fd = new FormData();_x000D_
        fd.append('file', data.file);_x000D_
_x000D_
        $http.post("endpoint server path to whom sending file", fd, {_x000D_
            withCredentials: false,_x000D_
            headers: {_x000D_
              'Content-Type': undefined_x000D_
            },_x000D_
            transformRequest: angular.identity,_x000D_
            params: {_x000D_
              fd_x000D_
            },_x000D_
            responseType: "arraybuffer"_x000D_
          })_x000D_
          .then(function(response) {_x000D_
            var data = response.data;_x000D_
            var status = response.status;_x000D_
            console.log(data);_x000D_
_x000D_
            if (status == 200 || status == 202) //do whatever in success_x000D_
            else // handle error in  else if needed _x000D_
          })_x000D_
          .catch(function(error) {_x000D_
            console.log(error.status);_x000D_
_x000D_
            // handle else calls_x000D_
          });_x000D_
      }_x000D_
    }_x000D_
  }])
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
_x000D_
_x000D_
_x000D_

How do I setup the dotenv file in Node.js?

i had similar problem. i solved it by trim. Please check, path.resolve may add additional space to end of path.

var path = require('path');
const envPath = path.resolve(process.cwd()+'/config','.env.'+process.env.NODE_ENV).trim()
require('dotenv').config({ path: envPath })

my package script is like this to use multiple .env:

 "scripts": {
    "start": "set NODE_ENV=development && nodemon ./bin/www",
    "prod": "set NODE_ENV=production && node ./bin/www"
  },