Programs & Examples On #Genericprincipal

How to update a claim in ASP.NET Identity?

Here you go:

            var user = User as ClaimsPrincipal;
            var identity = user.Identity as ClaimsIdentity;
            var claim = (from c in user.Claims
                         where c.Type == ClaimTypes.UserData
                         select c).Single();
            identity.RemoveClaim(claim);

taken from here.

Using an integer as a key in an associative array in JavaScript

Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:

var test = {}
test[2300] = 20;
console.log(test["2300"]);

How to run shell script on host from docker container?

docker run --detach-keys="ctrl-p" -it -v /:/mnt/rootdir --name testing busybox
# chroot /mnt/rootdir
# 

Error importing SQL dump into MySQL: Unknown database / Can't create database

I create the database myself using the command line. Then try to import again, it works.

nodejs mongodb object id to string

When using mongoose .

A representation of the _id is usually in the form (recieved client side)

{ _id: { _bsontype: 'ObjectID', id: <Buffer 5a f1 8f 4b c7 17 0e 76 9a c0 97 aa> },

As you can see there's a buffer in there. The easiest way to convert it is just doing <obj>.toString() or String(<obj>._id)

So for example

var mongoose = require('mongoose')
mongoose.connect("http://localhost/test")
var personSchema = new mongoose.Schema({ name: String })
var Person = mongoose.model("Person", personSchema)
var guy = new Person({ name: "someguy" })
Person.find().then((people) =>{
  people.forEach(person => {
    console.log(typeof person._id) //outputs object
    typeof person._id == 'string'
      ? null
      : sale._id = String(sale._id)  // all _id s will be converted to strings
  })
}).catch(err=>{ console.log("errored") })

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

A similar issue happened with me today. I also had searched alot about this.No one help. I just made two changes and its get working properly as well.

  1. I had visited Amazon documentation where describe either Verify that there is a rule that allows traffic from your computer to port 22 (SSH) and if not present, create it and edit "Security Group" and add "SSH" to my IP. This will help.
  2. In my case, In putty profile, I have to again authorize with .ppk file. I don't know why it ask again, without any changes made.

Hope it will help you.

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

How do I add a auto_increment primary key in SQL Server database?

It can be done in a single command. You need to set the IDENTITY property for "auto number":

ALTER TABLE MyTable ADD mytableID int NOT NULL IDENTITY (1,1) PRIMARY KEY

More precisely, to set a named table level constraint:

ALTER TABLE MyTable
   ADD MytableID int NOT NULL IDENTITY (1,1),
   CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (MyTableID)

See ALTER TABLE and IDENTITY on MSDN

Conditionally formatting cells if their value equals any value of another column

No formulas required. This works on as many columns as you need, but will only compare columns in the same worksheet:

NOTE: remove any duplicates from the individual columns first!

  1. Select the columns to compare
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red

    • Bonus tip, you can filter each row by colour to either leave the unique values in the column, or leave just the duplicates.

enter image description here enter image description here

How to read a file byte by byte in Python and how to print a bytelist as a binary?

There's a python module especially made for reading and writing to and from binary encoded data called 'struct'. Since versions of Python under 2.6 doesn't support str.format, a custom method needs to be used to create binary formatted strings.

import struct

# binary string
def bstr(n): # n in range 0-255
    return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)])

# read file into an array of binary formatted strings.
def read_binary(path):
    f = open(path,'rb')
    binlist = []
    while True:
        bin = struct.unpack('B',f.read(1))[0] # B stands for unsigned char (8 bits)
        if not bin:
            break
        strBin = bstr(bin)
        binlist.append(strBin)
    return binlist

What does "ulimit -s unlimited" do?

stack size can indeed be unlimited. _STK_LIM is the default, _STK_LIM_MAX is something that differs per architecture, as can be seen from include/asm-generic/resource.h:

/*
 * RLIMIT_STACK default maximum - some architectures override it:
 */
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX           RLIM_INFINITY
#endif

As can be seen from this example generic value is infinite, where RLIM_INFINITY is, again, in generic case defined as:

/*
 * SuS says limits have to be unsigned.
 * Which makes a ton more sense anyway.
 *
 * Some architectures override this (for compatibility reasons):
 */
#ifndef RLIM_INFINITY
# define RLIM_INFINITY          (~0UL)
#endif

So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

PostgreSQL error 'Could not connect to server: No such file or directory'

I encountered this error when running on Mac 10.15.5 using homebrew and seems to be a more updated solution that works where the ones above did not.

There is a file called postmaster.pid which should is automatically deleted when postresql exits.

If it doesn't do the following

  • brew services stop postgresql <--- Failing to exit before rm could corrupt db
  • sudo rm /usr/local/var/postgres/postmaster.pid

Check whether a value is a number in JavaScript or jQuery

there is a function called isNaN it return true if it's (Not-a-number) , so u can check for a number this way

if(!isNaN(miscCharge))
{
   //do some thing if it's a number
}else{
   //do some thing if it's NOT a number
}

hope it works

SQLAlchemy: print the actual query

In the vast majority of cases, the "stringification" of a SQLAlchemy statement or query is as simple as:

print(str(statement))

This applies both to an ORM Query as well as any select() or other statement.

Note: the following detailed answer is being maintained on the sqlalchemy documentation.

To get the statement as compiled to a specific dialect or engine, if the statement itself is not already bound to one you can pass this in to compile():

print(statement.compile(someengine))

or without an engine:

from sqlalchemy.dialects import postgresql
print(statement.compile(dialect=postgresql.dialect()))

When given an ORM Query object, in order to get at the compile() method we only need access the .statement accessor first:

statement = query.statement
print(statement.compile(someengine))

with regards to the original stipulation that bound parameters are to be "inlined" into the final string, the challenge here is that SQLAlchemy normally is not tasked with this, as this is handled appropriately by the Python DBAPI, not to mention bypassing bound parameters is probably the most widely exploited security holes in modern web applications. SQLAlchemy has limited ability to do this stringification in certain circumstances such as that of emitting DDL. In order to access this functionality one can use the 'literal_binds' flag, passed to compile_kwargs:

from sqlalchemy.sql import table, column, select

t = table('t', column('x'))

s = select([t]).where(t.c.x == 5)

print(s.compile(compile_kwargs={"literal_binds": True}))

the above approach has the caveats that it is only supported for basic types, such as ints and strings, and furthermore if a bindparam without a pre-set value is used directly, it won't be able to stringify that either.

To support inline literal rendering for types not supported, implement a TypeDecorator for the target type which includes a TypeDecorator.process_literal_param method:

from sqlalchemy import TypeDecorator, Integer


class MyFancyType(TypeDecorator):
    impl = Integer

    def process_literal_param(self, value, dialect):
        return "my_fancy_formatting(%s)" % value

from sqlalchemy import Table, Column, MetaData

tab = Table('mytable', MetaData(), Column('x', MyFancyType()))

print(
    tab.select().where(tab.c.x > 5).compile(
        compile_kwargs={"literal_binds": True})
)

producing output like:

SELECT mytable.x
FROM mytable
WHERE mytable.x > my_fancy_formatting(5)

How do I get column datatype in Oracle with PL-SQL with low privileges?

select t.data_type 
  from user_tab_columns t 
 where t.TABLE_NAME = 'xxx' 
   and t.COLUMN_NAME='aaa'

Face recognition Library

You can try open MVG library, It can be used for multiple interfaces too.

get basic SQL Server table structure information

Write the table name in the query editor select the name and press Alt+F1 and it will bring all the information of the table.

How to remove the arrow from a select element in Firefox

The other answers didn't seem to work for me, but I found this hack. This worked for me (July 2014)

select {
-moz-appearance: textfield !important;
    }

In my case, I also had a woocommerce input field so I used this

.woocommerce .quantity input.qty {
-moz-appearance: textfield !important;
 }

Updated my answer to show select rather than input

How to set auto increment primary key in PostgreSQL?

Try this command:

ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;

Try it with the same DB-user as the one you have created the table.

Styling an input type="file" button

ONLY CSS

Use this very simple and EASY

_x000D_
_x000D_
.choose::-webkit-file-upload-button {_x000D_
  color: white;_x000D_
  display: inline-block;_x000D_
  background: #1CB6E0;_x000D_
  border: none;_x000D_
  padding: 7px 15px;_x000D_
  font-weight: 700;_x000D_
  border-radius: 3px;_x000D_
  white-space: nowrap;_x000D_
  cursor: pointer;_x000D_
  font-size: 10pt;_x000D_
}
_x000D_
<label>Attach your screenshort</label>_x000D_
<input type="file" multiple class="choose">
_x000D_
_x000D_
_x000D_

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

The problem is that the true y is binary (zeros and ones), while your predictions are not. You probably generated probabilities and not predictions, hence the result :) Try instead to generate class membership, and it should work!

How can I check if a URL exists via PHP?

All above solutions + extra sugar. (Ultimate AIO solution)

/**
 * Check that given URL is valid and exists.
 * @param string $url URL to check
 * @return bool TRUE when valid | FALSE anyway
 */
function urlExists ( $url ) {
    // Remove all illegal characters from a url
    $url = filter_var($url, FILTER_SANITIZE_URL);

    // Validate URI
    if (filter_var($url, FILTER_VALIDATE_URL) === FALSE
        // check only for http/https schemes.
        || !in_array(strtolower(parse_url($url, PHP_URL_SCHEME)), ['http','https'], true )
    ) {
        return false;
    }

    // Check that URL exists
    $file_headers = @get_headers($url);
    return !(!$file_headers || $file_headers[0] === 'HTTP/1.1 404 Not Found');
}

Example:

var_dump ( urlExists('http://stackoverflow.com/') );
// Output: true;

How to create <input type=“text”/> dynamically

Maybe the method document.createElement(); is what you're looking for.

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

How to resolve "Waiting for Debugger" message?

I solved this issue this way:

Go to Run menu ====> click on Edit Configurations ====> Micellaneous and finaly uncheck the option Skip installation if APK has not changed

enter image description here

enter image description here

How can I pass a list as a command-line argument with argparse?

I want to handle passing multiple lists, integer values and strings.

Helpful link => How to pass a Bash variable to Python?

def main(args):
    my_args = []
    for arg in args:
        if arg.startswith("[") and arg.endswith("]"):
            arg = arg.replace("[", "").replace("]", "")
            my_args.append(arg.split(","))
        else:
            my_args.append(arg)

    print(my_args)


if __name__ == "__main__":
    import sys
    main(sys.argv[1:])

Order is not important. If you want to pass a list just do as in between "[" and "] and seperate them using a comma.

Then,

python test.py my_string 3 "[1,2]" "[3,4,5]"

Output => ['my_string', '3', ['1', '2'], ['3', '4', '5']], my_args variable contains the arguments in order.

Matplotlib legends in subplot

This does what you want and overcomes some of the problems in other answers:

import matplotlib.pyplot as plt

labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]

f,axs = plt.subplots(3, sharex=True, sharey=True)

# ---- loop over axes ----
for i,ax in enumerate(axs):
  axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
  axs[i].legend(loc="upper right")

plt.show()

... produces ... subplots

What is reflection and why is it useful?

Reflection gives you the ability to write more generic code. It allows you to create an object at runtime and call its method at runtime. Hence the program can be made highly parameterized. It also allows introspecting the object and class to detect its variables and method exposed to the outer world.

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

Steps:

  1. Add platform runner in build.gralde
    => testCompile group: 'org.junit.platform', name: 'junit-platform-runner', version: '1.7.0'
  2. Anotate test class with @RunWith => @RunWith(JunitPlatform.class)

Git reset --hard and push to remote repository

To complement Jakub's answer, if you have access to the remote git server in ssh, you can go into the git remote directory and set:

user@remote$ git config receive.denyNonFastforwards false

Then go back to your local repo, try again to do your commit with --force:

user@local$ git push origin +master:master --force

And finally revert the server's setting in the original protected state:

user@remote$ git config receive.denyNonFastforwards true

Change EditText hint color when using TextInputLayout

When I tried to set theme attribute to TextInputLayout, the theme was also getting applied to its child view edittext, which I didn't wanted.

So the solution which worked for me was to add a custom style to the "app:hintTextAppearance" property of the TextInputLayout.

In styles.xml add the following style:

<style name="TextInputLayoutTextAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textColor">@color/text_color</item>
    <item name="android:textSize">@dimen/text_size_12</item>
</style>

And apply this style to the "app:hintTextAppearance" property of the TextInputLayout as below:

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/mobile_num_til"
        android:layout_width="0dp"
        android:layout_height="@dimen/dim_56"
        app:layout_constraintStart_toStartOf="@id/title_tv"
        app:layout_constraintEnd_toEndOf="@id/title_tv"
        app:layout_constraintTop_toBottomOf="@id/sub_title_tv"
        android:layout_marginTop="@dimen/dim_30"
        android:padding="@dimen/dim_8"
        app:hintTextAppearance="@style/TextInputLayoutTextAppearance"
        android:background="@drawable/rect_round_corner_grey_outline">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/mobile_num_et"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:hint="@string/mobile_number"
            android:gravity="center_vertical"
            android:background="@android:color/transparent"/>

    </com.google.android.material.textfield.TextInputLayout>

insert/delete/update trigger in SQL server

the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind

/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
                    EmpID int,
                    Activity varchar(20),
                    DoneBy varchar(50),
                    Date_Time datetime NOT NULL DEFAULT GETDATE()
                   );

select * from Emp_Audit*/

create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
    SET @activity = 'UPDATE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
    SET @activity = 'INSERT';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin 
    SET @activity = 'DELETE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from deleted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

Cannot instantiate the type List<Product>

Use a concrete list type, e.g. ArrayList instead of just List.

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

There is no rule. I find CTEs more readable, and use them unless they exhibit some performance problem, in which case I investigate the actual problem rather than guess that the CTE is the problem and try to re-write it using a different approach. There is usually more to the issue than the way I chose to declaratively state my intentions with the query.

There are certainly cases when you can unravel CTEs or remove subqueries and replace them with a #temp table and reduce duration. This can be due to various things, such as stale stats, the inability to even get accurate stats (e.g. joining to a table-valued function), parallelism, or even the inability to generate an optimal plan because of the complexity of the query (in which case breaking it up may give the optimizer a fighting chance). But there are also cases where the I/O involved with creating a #temp table can outweigh the other performance aspects that may make a particular plan shape using a CTE less attractive.

Quite honestly, there are way too many variables to provide a "correct" answer to your question. There is no predictable way to know when a query may tip in favor of one approach or another - just know that, in theory, the same semantics for a CTE or a single subquery should execute the exact same. I think your question would be more valuable if you present some cases where this is not true - it may be that you have discovered a limitation in the optimizer (or discovered a known one), or it may be that your queries are not semantically equivalent or that one contains an element that thwarts optimization.

So I would suggest writing the query in a way that seems most natural to you, and only deviate when you discover an actual performance problem the optimizer is having. Personally I rank them CTE, then subquery, with #temp table being a last resort.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

It's funny how other answers ignore the fact that you can't write to that file...

There are a few workarounds that come to my mind which could help use an arbitrary C:\redirected\settings.xml and use the mvn command as usual happily ever after.

mvn alias

In a Unix shell (or on Cygwin) you can create

alias mvn='mvn --global-settings "C:\redirected\settings.xml"'

so when you're calling mvn blah blah from anywhere the config is "automatically" picked up.
See How to create alias in cmd? if you want this, but don't have a Unix shell.

mvn wrapper

Configure your environment so that mvn is resolved to a wrapper script when typed in the command line:

  • Remove your MVN_HOME/bin or M2_HOME/bin from your PATH so mvn is not resolved any more.
  • Add a folder to PATH (or use an existing one)
  • In that folder create an mvn.bat file with contents:

    call C:\your\path\to\maven\bin\mvn.bat --global-settings "C:\redirected\settings.xml" %*
    

Note: if you want some projects to behave differently you can just create mvn.bat in the same folder as pom.xml so when you run plain mvn it resolves to the local one.

Use where mvn at any time to check how it is resolved, the first one will be run when you type mvn.

mvn.bat hack

If you have write access to C:\your\path\to\maven\bin\mvn.bat, edit the file and add set MAVEN_CMD_LINE_ARG to the :runm2 part:

@REM Start MAVEN2
:runm2
set MAVEN_CMD_LINE_ARGS=--global-settings "C:\redirected\settings.xml" %MAVEN_CMD_LINE_ARGS%
set CLASSWORLDS_LAUNCHER=...

mvn.sh hack

For completeness, you can change the C:\your\path\to\maven\bin\mvn shell script too by changing the exec "$JAVACMD" command's

${CLASSWORLDS_LAUNCHER} "$@"

part to

${CLASSWORLDS_LAUNCHER} --global-settings "C:\redirected\settings.xml" "$@"

Suggestion/Rant

As a person in IT it's funny that you don't have access to your own home folder, for me this constitutes as incompetence from the company you're working for: this is equivalent of hiring someone to do software development, but not providing even the possibility to use anything other than notepad.exe or Microsoft Word to edit the source files. I'd suggest to contact your help desk or administrator and request write access at least to that particular file so that you can change the path of the local repository.

Disclaimer: None of these are tested for this particular use case, but I successfully used all of them previously for various other software.

Responding with a JSON object in Node.js (converting object/array to JSON string)

Per JamieL's answer to another post:

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.

Example:

res.json({"foo": "bar"});

Select from where field not equal to Mysql Php

You can use like

NOT columnA = 'x'

Or

columnA != 'x'

Or

columnA <> 'x'

And like Jeffly Bake's query, for including null values, you don't have to write like

(NOT columnA = 'x' OR columnA IS NULL)

You can make it simple by

Not columnA <=> 'x'

<=> is the Null Safe equal to Operator, which includes results from even null values.

What is the difference between a process and a thread?

Process: program under execution is known as process

Thread: Thread is a functionality which is executed with the other part of the program based on the concept of "one with other"so thread is a part of process..

What happens if you mount to a non-empty mount point with fuse?

For me the error message goes away if I unmount the old mount before mounting it again:

fusermount -u /mnt/point

If it's not already mounted you get a non-critical error:

$ fusermount -u /mnt/point

fusermount: entry for /mnt/point not found in /etc/mtab

So in my script I just put unmount it before mounting it.

Xcode build failure "Undefined symbols for architecture x86_64"

I got it solved by adding "-lc++" in Other Linker Flags in Build Settings.

ParseError: not well-formed (invalid token) using cElementTree

See this answer to another question and the according part of the XML spec.

The backspace U+0008 is an invalid character in XML documents. It must be represented as escaped entity &#8; and cannot occur plainly.

If you need to process this XML snippet, you must replace \x08 in s before feeding it into an XML parser.

What are the differences between WCF and ASMX web services?

WCF completely replaces ASMX web services. ASMX is the old way to do web services and WCF is the current way to do web services. All new SOAP web service development, on the client or the server, should be done using WCF.

How to schedule a task to run when shutting down windows

What I can suggest doing is creating a shortcut to the .bat file (for example on your desktop) and a when you want to shutdown your computer (and run the .bat file) click on the shortcut you created. After doing this, edit the .bat file and add this line of code to the end or where needed:

c:\windows\system32\shutdown -s -f -t 00

What this does it is

  1. Runs the shutdown process
  2. Displays a alert
  3. Forces all running processes to stop
  4. Executes immediately

MySQL joins and COUNT(*) from another table

MySQL use HAVING statement for this tasks.

Your query would look like this:

SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4

example when references have different names

SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4

Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.

Vim: insert the same characters across multiple lines

I wanted to comment out a lot of lines in some config file on a server that only had vi (no nano), so visual method was cumbersome as well Here's how i did that.

  1. Open file vi file
  2. Display line numbers :set number! or :set number
  3. Then use the line numbers to replace start-of-line with "#", how?

:35,77s/^/#/

Note: the numbers are inclusive, lines from 35 to 77, both included will be modified.

To uncomment/undo that, simply use :35,77s/^#//

If you want to add a text word as a comment after every line of code, you can also use:

:35,77s/$/#test/ (for languages like Python)

:35,77s/;$/;\/\/test/ (for languages like Java)

credits/references:

  1. https://unix.stackexchange.com/questions/84929/uncommenting-multiple-lines-of-code-specified-by-line-numbers-using-vi-or-vim

  2. https://unix.stackexchange.com/questions/120615/how-to-comment-multiple-lines-at-once

What is a Python egg?

Note: Egg packaging has been superseded by Wheel packaging.

Same concept as a .jar file in Java, it is a .zip file with some metadata files renamed .egg, for distributing code as bundles.

Specifically: The Internal Structure of Python Eggs

A "Python egg" is a logical structure embodying the release of a specific version of a Python project, comprising its code, resources, and metadata. There are multiple formats that can be used to physically encode a Python egg, and others can be developed. However, a key principle of Python eggs is that they should be discoverable and importable. That is, it should be possible for a Python application to easily and efficiently find out what eggs are present on a system, and to ensure that the desired eggs' contents are importable.

The .egg format is well-suited to distribution and the easy uninstallation or upgrades of code, since the project is essentially self-contained within a single directory or file, unmingled with any other projects' code or resources. It also makes it possible to have multiple versions of a project simultaneously installed, such that individual programs can select the versions they wish to use.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

What does your configuration file say?

$ grep dbpath /etc/mongodb.conf

If it is not correct, try this, your database files will be present on the list:

$ sudo lsof -p `ps aux | grep mongodb | head -n1 | tr -s ' ' | cut -d' ' -f 2` | grep REG

It's /var/lib/mongodb/* on my default installation (Ubuntu 11.04).

Note that there is also a /var/lib/mongodb/mongod.lock file holding mongod PID for convenience, however it is located in the data directory - which we are looking for...

pip broke. how to fix DistributionNotFound error?

I had this issue when I was using homebrew. Here is the solution from Issue #26900

python -m pip install --upgrade --force pip

Why doesn't JavaScript support multithreading?

I don't know the rationale for this decision, but I know that you can simulate some of the benefits of multi-threaded programming using setTimeout. You can give the illusion of multiple processes doing things at the same time, though in reality, everything happens in one thread.

Just have your function do a little bit of work, and then call something like:

setTimeout(function () {
    ... do the rest of the work...
}, 0);

And any other things that need doing (like UI updates, animated images, etc) will happen when they get a chance.

Difference between static class and singleton pattern?

Static Class:-

  1. You cannot create the instance of static class.

  2. Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

  3. Static Class cannot have constructor.

  4. We cannot pass the static class to method.

  5. We cannot inherit Static class to another Static class in C#.

  6. A class having all static methods.

  7. Better performance (static methods are bonded on compile time)

Singleton:-

  1. You can create one instance of the object and reuse it.

  2. Singleton instance is created for the first time when the user requested.

  3. Singleton class can have constructor.

  4. You can create the object of singleton class and pass it to method.

  5. Singleton class does not say any restriction of Inheritance.

  6. We can dispose the objects of a singleton class but not of static class.

  7. Methods can be overridden.

  8. Can be lazy loaded when need (static classes are always loaded).

  9. We can implement interface(static class can not implement interface).

Concat scripts in order with Gulp

I have my scripts organized in different folders for each package I pull in from bower, plus my own script for my app. Since you are going to list the order of these scripts somewhere, why not just list them in your gulp file? For new developers on your project, it's nice that all your script end-points are listed here. You can do this with gulp-add-src:

gulpfile.js

var gulp = require('gulp'),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    addsrc = require('gulp-add-src'),
    sourcemaps = require('gulp-sourcemaps');

// CSS & Less
gulp.task('css', function(){
    gulp.src('less/all.less')
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(minifyCSS())
        .pipe(sourcemaps.write('source-maps'))
        .pipe(gulp.dest('public/css'));
});

// JS
gulp.task('js', function() {
    gulp.src('resources/assets/bower/jquery/dist/jquery.js')
    .pipe(addsrc.append('resources/assets/bower/bootstrap/dist/js/bootstrap.js'))
    .pipe(addsrc.append('resources/assets/bower/blahblah/dist/js/blah.js'))
    .pipe(addsrc.append('resources/assets/js/my-script.js'))
    .pipe(sourcemaps.init())
    .pipe(concat('all.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write('source-maps'))
    .pipe(gulp.dest('public/js'));
});

gulp.task('default',['css','js']);

Note: jQuery and Bootstrap added for demonstration purposes of order. Probably better to use CDNs for those since they are so widely used and browsers could have them cached from other sites already.

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

How to check if IsNumeric

You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

How can I find my Apple Developer Team id and Team Agent Apple ID?

Apple has changed the interface.

The team ID could be found via this link: https://developer.apple.com/account/#/membership

SQL Server SELECT INTO @variable?

you can do this:

SELECT 
    CustomerId, 
    FirstName, 
    LastName, 
    Email
INTO #tempCustomer 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId

then later

SELECT CustomerId FROM #tempCustomer

you doesn't need to declare the structure of #tempCustomer

Download File Using jQuery

If you don't want search engines to index certain files, you can use robots.txt to tell web spiders not to access certain parts of your website.

If you rely only on javascript, then some users who browse without it won't be able to click your links.

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

This worked for me:

$ sudo apt-get install php-gd php-mysql

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

JsonMappingException: out of START_ARRAY token exception is thrown by Jackson object mapper as it's expecting an Object {} whereas it found an Array [{}] in response.

This can be solved by replacing Object with Object[] in the argument for geForObject("url",Object[].class). References:

  1. Ref.1
  2. Ref.2
  3. Ref.3

C++ error: "Array must be initialized with a brace enclosed initializer"

You can't initialize arrays like this:

int cipher[Array_size][Array_size]=0;

The syntax for 2D arrays is:

int cipher[Array_size][Array_size]={{0}};

Note the curly braces on the right hand side of the initialization statement.

for 1D arrays:

int tomultiply[Array_size]={0};

Using G++ to compile multiple .cpp and .h files

To compile separately without linking you need to add -c option:

g++ -c myclass.cpp
g++ -c main.cpp
g++ myclass.o main.o
./a.out

How do I upload a file with the JS fetch API?

An important note for sending Files with Fetch API

One needs to omit content-type header for the Fetch request. Then the browser will automatically add the Content type header including the Form Boundary which looks like

Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD

Form boundary is the delimiter for the form data

Corrupted Access .accdb file: "Unrecognized Database Format"

WE had this problem on one machine and not another...the solution is to look in control panel at the VERSION of the Access Database Engine 2007 component. If it is version 12.0.45, you need to run the service pack 3 http://www.microsoft.com/en-us/download/confirmation.aspx?id=27835

The above link will install version 12.0.66...and this fixes the problem...thought I would post it since I haven't seen this solution on any other forum.

JWT refresh token flow

Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:

  1. just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens

  2. that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)

  3. an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

You also can use

start /MIN notepad.exe

PS: Unfortunatly, minimized window status depends on command to run. V.G. doen't work

start /MIN calc.exe

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

What's the difference between a mock & stub?

Stub

A stub is an object used to fake a method that has pre-programmed behavior. You may want to use this instead of an existing method in order to avoid unwanted side-effects (e.g. a stub could make a fake fetch call that returns a pre-programmed response without actually making a request to a server).

Mock

A mock is an object used to fake a method that has pre-programmed behavior as well as pre-programmed expectations. If these expectations are not met then the mock will cause the test to fail (e.g. a mock could make a fake fetch call that returns a pre-programmed response without actually making a request to a server which would expect e.g. the first argument to be http://localhost:3008/ otherwise the test would fail.)

Difference

Unlike mocks, stubs do not have pre-programmed expectations that could fail your test.

JavaScript replace \n with <br />

Use a regular expression for .replace().:

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

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

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

Turn off deprecated errors in PHP 5.3

All the previous answers are correct. Since no one have hinted out how to turn off all errors in PHP, I would like to mention it here:

error_reporting(0); // Turn off warning, deprecated,
                    // notice everything except error

Somebody might find it useful...

Comparing two dictionaries and checking how many (key, value) pairs are equal

Here is my answer, use a recursize way:

def dict_equals(da, db):
    if not isinstance(da, dict) or not isinstance(db, dict):
        return False
    if len(da) != len(db):
        return False
    for da_key in da:
        if da_key not in db:
            return False
        if not isinstance(db[da_key], type(da[da_key])):
            return False
        if isinstance(da[da_key], dict):
            res = dict_equals(da[da_key], db[da_key])
            if res is False:
                return False
        elif da[da_key] != db[da_key]:
            return False
    return True

a = {1:{2:3, 'name': 'cc', "dd": {3:4, 21:"nm"}}}
b = {1:{2:3, 'name': 'cc', "dd": {3:4, 21:"nm"}}}
print dict_equals(a, b)

Hope that helps!

Set a cookie to never expire

My privilege prevents me making my comment on the first post so it will have to go here.

Consideration should be taken into account of 2038 unix bug when setting 20 years in advance from the current date which is suggest as the correct answer above.

Your cookie on January 19, 2018 + (20 years) could well hit 2038 problem depending on the browser and or versions you end up running on.

How do I use $rootScope in Angular to store variables?

angular.module('myApp').controller('myCtrl', function($scope, $rootScope) {
   var a = //something in the scope
   //put it in the root scope
    $rootScope.test = "TEST";
 });

angular.module('myApp').controller('myCtrl2', function($scope, $rootScope) {
   var b = //get var a from root scope somehow
   //use var b

   $scope.value = $rootScope.test;
   alert($scope.value);

 //    var b = $rootScope.test;
 //  alert(b);
 });

DEMO

How to get week numbers from dates?

Base package

Using the function strftime passing the argument %V to obtain the week of the year as decimal number (01–53) as defined in ISO 8601. (More details in the documentarion: ?strftime)

strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%V")

Output:

[1] "11" "12" "12" "01"

Vertical rulers in Visual Studio Code

With Visual Studio Code 1.27.2:

  1. When I go to File > Preference > Settings, I get the following tab

    Screenshot

  2. I type rulers in Search settings and I get the following list of settings

    screenshot

  3. Clicking on the first Edit in settings.json, I can edit the user settings

    screenshot

  4. Clicking on the pen icon that appears to the left of the setting in Default user settings I can copy it on the user settings and edit it

With Visual Studio Code 1.38.1, the screenshot shown on the third point changes to the following one.

enter image description here

The panel for selecting the default user setting values isn't shown anymore.

ESRI : Failed to parse source map

Chrome recently added support for source maps in the developer tools. If you go under settings on the chrome developer toolbar you can see the following two options:

Chrome Developer Tools Source Maps

If you disable those two options, and refresh the browser, it should no longer ask for source maps.

These settings can be found here:

Chrome Developer Tools Source Maps

gcc warning" 'will be initialized after'

If you're seeing errors from library headers and you're using GCC, then you can disable warnings by including the headers using -isystem instead of -I.

Similar features exist in clang.

If you're using CMake, you can specify SYSTEM for include_directories.

How can I access "static" class variables within class methods in Python?

class Foo(object):    
    bar = 1

    def bah(object_reference):
        object_reference.var = Foo.bar
        return object_reference.var


f = Foo() 
print 'var=', f.bah()

sql select with column name like

You need to use view INFORMATION_SCHEMA.COLUMNS

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = my_table_name AND COLUMN_NAME like 'a%'

TO inline rows you can use PIVOT and for execution EXEC() function.

Java dynamic array sizes?

You set the number of elements to anything you want at the time you create it:

xClass[] mysclass = new xClass[n];

Then you can initialize the elements in a loop. I am guessing that this is what you need.

If you need to add or remove elements to the array after you create it, then you would have to use an ArrayList.

How to add reference to a method parameter in javadoc?

I guess you could write your own doclet or taglet to support this behaviour.

Taglet Overview

Doclet Overview

Do I cast the result of malloc?

Casting the value returned by malloc() is not necessary now, but I'd like to add one point that seems no one has pointed out:

In the ancient days, that is, before ANSI C provides the void * as the generic type of pointers, char * is the type for such usage. In that case, the cast can shut down the compiler warnings.

Reference: C FAQ

How can I inspect element in an Android browser?

Chrome on Android makes it possible to use the Chrome developer tools on the desktop to inspect the HTML that was loaded from the Chrome application on the Android device.

See: https://developers.google.com/chrome-developer-tools/docs/remote-debugging

html button to send email

You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.

The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.

When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)

How to make div go behind another div?

container can not come front to inner container. but try this below :

Css :
----------------------
.container { position:relative; }
    .div1 { width:100px; height:100px; background:#9C3; position:absolute; 
            z-index:1000; left:50px; top:50px; }
    .div2 { width:200px; height:200px; background:#900; }

HTMl : 
-----------------------
<div class="container">
    <div class="div1">
       Div1 content here .........
    </div>
    <div class="div2">
       Div2 contenet here .........
    </div>
</div>

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

How to check if a string "StartsWith" another string?

Best solution:

function startsWith(str, word) {
    return str.lastIndexOf(word, 0) === 0;
}

And here is endsWith if you need that too:

function endsWith(str, word) {
    return str.indexOf(word, str.length - word.length) !== -1;
}

For those that prefer to prototype it into String:

String.prototype.startsWith || (String.prototype.startsWith = function(word) {
    return this.lastIndexOf(word, 0) === 0;
});

String.prototype.endsWith   || (String.prototype.endsWith = function(word) {
    return this.indexOf(word, this.length - word.length) !== -1;
});

Usage:

"abc".startsWith("ab")
true
"c".ensdWith("c") 
true

With method:

startsWith("aaa", "a")
true
startsWith("aaa", "ab")
false
startsWith("abc", "abc")
true
startsWith("abc", "c")
false
startsWith("abc", "a")
true
startsWith("abc", "ba")
false
startsWith("abc", "ab")
true

Delete specific line from a text file?

  1. Read and remember each line

  2. Identify the one you want to get rid of

  3. Forget that one

  4. Write the rest back over the top of the file

Specifying maxlength for multiline textbox

Roll your own:

function Count(text) 
{
    //asp.net textarea maxlength doesnt work; do it by hand
    var maxlength = 2000; //set your value here (or add a parm and pass it in)
    var object = document.getElementById(text.id)  //get your object
    if (object.value.length > maxlength) 
    {
        object.focus(); //set focus to prevent jumping
        object.value = text.value.substring(0, maxlength); //truncate the value
        object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
        return false;
    }
    return true;
}

Call like this:

<asp:TextBox ID="foo" runat="server" Rows="3" TextMode="MultiLine" onKeyUp="javascript:Count(this);" onChange="javascript:Count(this);" ></asp:TextBox>

What is the use of GO in SQL Server Management Studio & Transact SQL?

Use herDatabase
GO ; 

Code says to execute the instructions above the GO marker. My default database is myDatabase, so instead of using myDatabase GO and makes current query to use herDatabase

Language Books/Tutorials for popular languages

For Java EE 5 there's a separate tutorial JEE tutorial. That's useful, as people often ask about persistence and xml binding in java.

How do I view / replay a chrome network debugger har file saved with content?

There are a couple of online, offline tools how to do this:

But the one that I liked the most, is a browser extension (tried it in chrome, hopefully it works in other browsers). After installation, it appears in your apps as HAR viewer. Then you can upload you HAR file and see something like this:

enter image description here

Total size of the contents of all the files in a directory

Just an alternative:

ls -lAR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'

grep -v '^d' will exclude the directories.

Adding an identity to an existing column

There is cool solution described here: SQL SERVER – Add or Remove Identity Property on Column

In short edit manually your table in SQL Manager, switch the identity, DO NOT SAVE changes, just show the script which will be created for the changes, copy it and use it later.

It is huge time saver, because it (the script) contains all the foreign keys, indices, etc. related to the table you change. Writting this manually... God forbid.

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

Access event to call preventdefault from custom function originating from onclick attribute of tag

Add a unique class to the links and a javascript that prevents default on links with this class:

<a href="#" class="prevent-default" 
   onclick="$('.comment .hidden').toggle();">Show comments</a>

<script>
  $(document).ready(function(){

    $("a.prevent-default").click(function(event) {
         event.preventDefault(); 
          });
  });
</script>

How do you make a deep copy of an object?

You can do a serialization-based deep clone using org.apache.commons.lang3.SerializationUtils.clone(T) in Apache Commons Lang, but be careful—the performance is abysmal.

In general, it is best practice to write your own clone methods for each class of an object in the object graph needing cloning.

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I generally install Apache + PHP + MySQL by-hand, not using any package like those you're talking about.

It's a bit more work, yes; but knowing how to install and configure your environment is great -- and useful.

The first time, you'll need maybe half a day or a day to configure those. But, at least, you'll know how to do so.

And the next times, things will be far more easy, and you'll need less time.

Else, you might want to take a look at Zend Server -- which is another package that bundles Apache + PHP + MySQL.

Or, as an alternative, don't use Windows.

If your production servers are running Linux, why not run Linux on your development machine?

And if you don't want to (or cannot) install Linux on your computer, use a Virtual Machine.

Find oldest/youngest datetime object in a list

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

How to set up a cron job to run an executable every hour?

If you're using Ubuntu, you can put a shell script in one of these folders: /etc/cron.daily, /etc/cron.hourly, /etc/cron.monthly or /etc/cron.weekly.

For more detail, check out this post: https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job

Get PostGIS version

Did you try using SELECT PostGIS_version();

How to do a num_rows() on COUNT query in codeigniter?

num_rows on your COUNT() query will literally ALWAYS be 1. It is an aggregate function without a GROUP BY clause, so all rows are grouped together into one. If you want the value of the count, you should give it an identifier SELECT COUNT(*) as myCount ..., then use your normal method of accessing a result (the first, only result) and get it's 'myCount' property.

Launch Pycharm from command line (terminal)

Update: My answer no longer works as of PyCharm 2018.X

On MacOS, I have this alias in my bashrc:

alias pycharm="open -a /Applications/PyCharm*.app"

I can use it like this: pycharm <project dir or file>

The advantage of launching PyCharm this way is that you can open the current dir in PyCharm using pycharm . (unlike /Applications/PyCharm*.app/Contents/MacOS/pycharm . which opens the PyCharm application dir instead)


Update: I switched to JetBrains Toolbox to install PyCharm. Finding PyCharm has gotten a bit more complex, but so far I was lucky with this monster:

alias pycharm="open -a \"\$(ls -r  /Applications/apps/PyCharm*/*/*/PyCharm*.app | head -n 1 | sed 's/:$//')\""

In C#, what's the difference between \n and \r\n?

The Difference

There are a few characters which can indicate a new line. The usual ones are these two:

* '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF).
* '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).

Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:

* DOS and Windows

They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).

* Unix (and hence Linux as well)

Unix uses a single '\n' to indicate a new line.

* Mac

Macs use a single '\r'.

Taken from Here

Convert month name to month number in SQL Server

I think you may even have a separate table like a monthdetails (Monthno int, monthnames char(15)) and include values:

1 January
2 February 

.... and so on, and then join this table with your existing table in the monthnames column

SELECT t1.*,t2.Monthno from table1 
left outer join monthdetails t2
on t1.monthname=t2.monthnames
order by t2.Monthno 

Spool Command: Do not output SQL statement to file

Exec the query in TOAD or SQL DEVELOPER

---select /*csv*/ username, user_id, created from all_users;

Save in .SQL format in "C" drive

--- x.sql

execute command

---- set serveroutput on
     spool y.csv
     @c:\x.sql
     spool off;

Filter rows which contain a certain string

Solution

It is possible to use str_detect of the stringr package included in the tidyverse package. str_detect returns True or False as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr package.

library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1     ? purrr   0.2.4
# ? tibble  1.4.2     ? dplyr   0.7.4
# ? tidyr   0.7.2     ? stringr 1.2.0
# ? readr   1.1.1     ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag()    masks stats::lag()

mtcars$type <- rownames(mtcars)
mtcars %>%
  filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
# 1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
# 2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
# 3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
# 4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

The good things about Stringr

We should use rather stringr::str_detect() than base::grepl(). This is because there are the following reasons.

  • The functions provided by the stringr package start with the prefix str_, which makes the code easier to read.
  • The first argument of the functions of stringr package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)
object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"

Benchmark

The results of the benchmark test are as follows. For large dataframe, str_detect is faster.

library(rbenchmark)
library(tidyverse)

# The data. Data expo 09. ASA Statistics Computing and Graphics 
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728      29

benchmark(
  "str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
  "grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
  replications = 10,
  columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2      grepl           10  16.480    1.513    16.195    0.248
# 1 str_detect           10  10.891    1.000     9.594    1.281

Trigger an action after selection select2

//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
    console.log("Action Before Selected");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

//when a Department removing
$('#department_id').on('select2-removing', function (e) {
    console.log("Action Before Deleted");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

How to print a single backslash?

You should escape it with another backslash \:

print('\\')

Calculate age given the birth date in the format YYYYMMDD

I just had to write this function for myself - the accepted answer is fairly good but IMO could use some cleanup. This takes a unix timestamp for dob because that was my requirement but could be quickly adapted to use a string:

var getAge = function(dob) {
    var measureDays = function(dateObj) {
            return 31*dateObj.getMonth()+dateObj.getDate();
        },
        d = new Date(dob*1000),
        now = new Date();

    return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}

Notice I've used a flat value of 31 in my measureDays function. All the calculation cares about is that the "day-of-year" be a monotonically increasing measure of the timestamp.

If using a javascript timestamp or string, obviously you'll want to remove the factor of 1000.

Can you test google analytics on a localhost address?

For those using google tag manager to integrate with google analytics events you can do what the guys mentioned about to set the cookies flag to none from GTM it self

enter image description here

open GTM > variables > google analytics variables > and set the cookies tag to none

Bash script to check running process

I was wondering if it would be a good idea to have progressive attempts at a process, so you pass this func a process name func_terminate_process "firefox" and it tires things more nicely first, then moves on to kill.

# -- NICE: try to use killall to stop process(s)
killall ${1} > /dev/null 2>&1 ;sleep 10

# -- if we do not see the process, just end the function
pgrep ${1} > /dev/null 2>&1 || return

# -- UGLY: Step trough every pid and use kill -9 on them individually
for PID in $(pidof ${1}) ;do

    echo "Terminating Process: [${1}], PID [${PID}]" 
    kill -9 ${PID} ;sleep 10

    # -- NASTY: If kill -9 fails, try SIGTERM on PID
    if ps -p ${PID} > /dev/null ;then
        echo "${PID} is still running, forcefully terminating with SIGTERM"
        kill -SIGTERM ${PID}  ;sleep 10
    fi

done

# -- If after all that, we still see the process, report that to the screen.
pgrep ${1} > /dev/null 2>&1 && echo "Error, unable to terminate all or any of [${1}]" || echo "Terminate process [${1}] : SUCCESSFUL"

How to compute the sum and average of elements in an array?

Calculating average (mean) using reduce and ES6:

const average = list => list.reduce((prev, curr) => prev + curr) / list.length;

const list = [0, 10, 20, 30]
average(list) // 15

Regular expression for excluding special characters

I strongly suspect it's going to be easier to come up with a list of the characters that ARE allowed vs. the ones that aren't -- and once you have that list, the regex syntax becomes quite straightforward. So put me down as another vote for "whitelist".

C Macro definition to determine big endian or little endian machine?

#include <stdint.h>
#define IS_LITTLE_ENDIAN (*(uint16_t*)"\0\1">>8)
#define IS_BIG_ENDIAN (*(uint16_t*)"\1\0">>8)

Linear Layout and weight in Android

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="#008">

            <RelativeLayout
                android:id="@+id/paneltamrin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"

                >
                <Button
                    android:id="@+id/BtnT1"
                    android:layout_width="wrap_content"
                    android:layout_height="150dp"
                    android:drawableTop="@android:drawable/ic_menu_edit"
                    android:drawablePadding="6dp"
                    android:padding="15dp"
                    android:text="AndroidDhina"
                    android:textColor="#000"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/paneltamrin2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                >
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="150dp"
                     android:drawableTop="@android:drawable/ic_menu_edit"
                    android:drawablePadding="6dp"
                    android:padding="15dp"
                    android:text="AndroidDhina"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </RelativeLayout>
        </LinearLayout>

enter image description here

Differences between unique_ptr and shared_ptr

When wrapping a pointer in a unique_ptr you cannot have multiple copies of unique_ptr. The shared_ptr holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr is copied, this counter is incremented. Each time a shared_ptr is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

Removing Spaces from a String in C?

Here's a very compact, but entirely correct version:

do while(isspace(*s)) s++; while(*d++ = *s++);

And here, just for my amusement, are code-golfed versions that aren't entirely correct, and get commenters upset.

If you can risk some undefined behavior, and never have empty strings, you can get rid of the body:

while(*(d+=!isspace(*s++)) = *s);

Heck, if by space you mean just space character:

while(*(d+=*s++!=' ')=*s);

Don't use that in production :)

What is the correct wget command syntax for HTTPS with username and password?

By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.

wget --user=username --ask-password https://xyz.com/changelog-6.40.txt

Why use 'virtual' for class properties in Entity Framework model definitions?

It allows the Entity Framework to create a proxy around the virtual property so that the property can support lazy loading and more efficient change tracking. See What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First? for a more thorough discussion.

Edit to clarify "create a proxy around": By "create a proxy around" I'm referring specifically to what the Entity Framework does. The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported. See Requirements for Creating POCO Proxies.
The Entity Framework uses inheritance to support this functionality, which is why it requires certain properties to be marked virtual in your base class POCOs. It literally creates new types that derive from your POCO types. So your POCO is acting as a base type for the Entity Framework's dynamically created subclasses. That's what I meant by "create a proxy around".

The dynamically created subclasses that the Entity Framework creates become apparent when using the Entity Framework at runtime, not at static compilation time. And only if you enable the Entity Framework's lazy loading or change tracking features. If you opt to never use the lazy loading or change tracking features of the Entity Framework (which is not the default) then you needn't declare any of your navigation properties as virtual. You are then responsible for loading those navigation properties yourself, either using what the Entity Framework refers to as "eager loading", or manually retrieving related types across multiple database queries. You can and should use lazy loading and change tracking features for your navigation properties in many scenarios though.

If you were to create a standalone class and mark properties as virtual, and simply construct and use instances of those classes in your own application, completely outside of the scope of the Entity Framework, then your virtual properties wouldn't gain you anything on their own.

Edit to describe why properties would be marked as virtual

Properties such as:

 public ICollection<RSVP> RSVPs { get; set; }

Are not fields and should not be thought of as such. These are called getters and setters and at compilation time, they are converted into methods.

//Internally the code looks more like this:
public ICollection<RSVP> get_RSVPs()
{
    return _RSVPs;
}

public void set_RSVPs(RSVP value)
{
    _RSVPs = value;
}

private RSVP _RSVPs;

That's why they're marked as virtual for use in the Entity Framework, it allows the dynamically created classes to override the internally generated get and set functions. If your navigation property getter/setters are working for you in your Entity Framework usage, try revising them to just properties, recompile, and see if the Entity Framework is able to still function properly:

 public virtual ICollection<RSVP> RSVPs;

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

Get Mouse Position

PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX();
int y = (int) b.getY();
System.out.print(y + "jjjjjjjjj");
System.out.print(x);
Robot r = new Robot();
r.mouseMove(x, y - 50);

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

How to change port number in vue-cli project

Go to node_modules/@vue/cli-service/lib/options.js
At the bottom inside the "devServer" unblock the codes
Now give your desired port number in the "port" :)

devServer: {
   open: process.platform === 'darwin',
   host: '0.0.0.0',
   port: 3000,  // default port 8080
   https: false,
   hotOnly: false,
   proxy: null, // string | Object
   before: app => {}
}

Delimiter must not be alphanumeric or backslash and preg_match

Please try with this

 $pattern = "/My name is '\(.*\)' and im fine/"; 

Git log out user from command line

I am in a corporate setting and was attempting a simple git pull after a recent change in password.

I got: remote: Invalid username or password.

Interestingly, the following did not work: git config --global --unset credential.helper

I use Windows-7, so, I went to control panel -> Credential Manager -> Generic Credentials.

From the credential manager list, delete the line items corresponding to git.

After the deletion, come back to gitbash and git pull should prompt the dialog for you to enter your credentials.

jquery change class name

So you want to change it WHEN it's clicked...let me go through the whole process. Let's assume that your "External DOM Object" is an input, like a select:

Let's start with this HTML:

<body>
  <div>
    <select id="test">
      <option>Bob</option>
      <option>Sam</option>
      <option>Sue</option>
      <option>Jen</option>
    </select>
  </div>

  <table id="theTable">
    <tr><td id="cellToChange">Bob</td><td>Sam</td></tr>
    <tr><td>Sue</td><td>Jen</td></tr>
  </table>
</body>

Some very basic CSS:

?#theTable td {
    border:1px solid #555;
}
.activeCell {
    background-color:#F00;
}

And set up a jQuery event:

function highlightCell(useVal){
  $("#theTable td").removeClass("activeCell")
      .filter(":contains('"+useVal+"')").addClass("activeCell");
}

$(document).ready(function(){
    $("#test").change(function(e){highlightCell($(this).val())});
});

Now, whenever you pick something from the select, it will automatically find a cell with the matching text, allowing you to subvert the whole id-based process. Of course, if you wanted to do it that way, you could easily modify the script to use IDs rather than values by saying

.filter("#"+useVal)

and make sure to add the ids appropriately. Hope this helps!

jQuery Clone table row

The code below will clone last row and add after last row in table:

var $tableBody = $('#tbl').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();

$trLast.after($trNew);

Working example : http://jsfiddle.net/kQpfE/2/

How to execute shell command in Javascript

This depends entirely on the JavaScript environment. Please elaborate.

For example, in Windows Scripting, you do things like:

var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");

How do I delete multiple rows with different IDs?

Delete from BA_CITY_MASTER where CITY_NAME in (select CITY_NAME from BA_CITY_MASTER group by CITY_NAME having count(CITY_NAME)>1);

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

Set CFLAGS and CXXFLAGS options using CMake

You need to set the flags after the project command in your CMakeLists.txt.

Also, if you're calling include(${QT_USE_FILE}) or add_definitions(${QT_DEFINITIONS}), you should include these set commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g.

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb")

Why do I get permission denied when I try use "make" to install something?

I had a very similar error message as you, although listing a particular file:

$ make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127

$ sudo make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127

In my case, I forgot to add a trailing slash to indicate continuation of the line as shown:

${LINEDETECTOR_OBJECTS}:\
    ../HoughLineAccumulator/houghlineaccumulator.hh  # <-- missing slash!!
    ../HoughLineExtractor/houghlineextractor.hh

Hope that helps someone else who lands here from a search engine.

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

How to use EOF to run through a text file in C?

How you detect EOF depends on what you're using to read the stream:

function                  result on EOF or error                    
--------                  ----------------------
fgets()                   NULL
fscanf()                  number of succesful conversions
                            less than expected
fgetc()                   EOF
fread()                   number of elements read
                            less than expected

Check the result of the input call for the appropriate condition above, then call feof() to determine if the result was due to hitting EOF or some other error.

Using fgets():

 char buffer[BUFFER_SIZE];
 while (fgets(buffer, sizeof buffer, stream) != NULL)
 {
   // process buffer
 }
 if (feof(stream))
 {
   // hit end of file
 }
 else
 {
   // some other error interrupted the read
 }

Using fscanf():

char buffer[BUFFER_SIZE];
while (fscanf(stream, "%s", buffer) == 1) // expect 1 successful conversion
{
  // process buffer
}
if (feof(stream)) 
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}

Using fgetc():

int c;
while ((c = fgetc(stream)) != EOF)
{
  // process c
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted the read
}

Using fread():

char buffer[BUFFER_SIZE];
while (fread(buffer, sizeof buffer, 1, stream) == 1) // expecting 1 
                                                     // element of size
                                                     // BUFFER_SIZE
{
   // process buffer
}
if (feof(stream))
{
  // hit end of file
}
else
{
  // some other error interrupted read
}

Note that the form is the same for all of them: check the result of the read operation; if it failed, then check for EOF. You'll see a lot of examples like:

while(!feof(stream))
{
  fscanf(stream, "%s", buffer);
  ...
}

This form doesn't work the way people think it does, because feof() won't return true until after you've attempted to read past the end of the file. As a result, the loop executes one time too many, which may or may not cause you some grief.

How to execute .sql script file using JDBC

Another option, this DOESN'T support comments, very useful with AmaterasERD DDL export for Apache Derby:

public void executeSqlScript(Connection conn, File inputFile) {

    // Delimiter
    String delimiter = ";";

    // Create scanner
    Scanner scanner;
    try {
        scanner = new Scanner(inputFile).useDelimiter(delimiter);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    // Loop through the SQL file statements 
    Statement currentStatement = null;
    while(scanner.hasNext()) {

        // Get statement 
        String rawStatement = scanner.next() + delimiter;
        try {
            // Execute statement
            currentStatement = conn.createStatement();
            currentStatement.execute(rawStatement);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // Release resources
            if (currentStatement != null) {
                try {
                    currentStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            currentStatement = null;
        }
    }
scanner.close();
}

Laravel: Get Object From Collection By Attribute

As from Laravel 5.5 you can use firstWhere()

In you case:

$green_foods = $foods->firstWhere('color', 'green');

How to pop an alert message box using PHP?

Create function for alert

<?php
alert("Hello World");

function alert($msg) {
    echo "<script type='text/javascript'>alert('$msg');</script>";
}
?>

How do I make a text go onto the next line if it overflows?

word-wrap: break-word; 

add this to your container that should do the trick

How to convert a color integer to a hex String in Android?

You can use this for color without alpha:

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

or this with alpha:

String hexColor = String.format("#%08X", (0xFFFFFFFF & intColor));

How to remove square brackets from list in Python?

You could convert it to a string instead of printing the list directly:

print(", ".join(LIST))

If the elements in the list aren't strings, you can convert them to string using either repr (if you want quotes around strings) or str (if you don't), like so:

LIST = [1, "foo", 3.5, { "hello": "bye" }]
print( ", ".join( repr(e) for e in LIST ) )

Which gives the output:

1, 'foo', 3.5, {'hello': 'bye'}

How to clear the canvas for redrawing

This is what I use, regardless boundaries and matrix transformations:

function clearCanvas(canvas) {
  const ctx = canvas.getContext('2d');
  ctx.save();
  ctx.globalCompositeOperation = 'copy';
  ctx.strokeStyle = 'transparent';
  ctx.beginPath();
  ctx.lineTo(0, 0);
  ctx.stroke();
  ctx.restore();
}

Basically, it saves the current state of the context, and draws a transparent pixel with copy as globalCompositeOperation. Then, restores the previous context state.

Eclipse: How do you change the highlight color of the currently selected method/expression?

After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:

General -> Editors -> Text Editors -> Annotations

Look for Occurences from the Annotation types list.

Then, be sure that Text as highlighted is selected, then choose the desired color.


And, a picture is worth a thousand words...

Preferences dialog
(source: coobird.net)

Image showing occurences highlighted in orange.
(source: coobird.net)

iPhone keyboard, Done button and resignFirstResponder

In Xcode 5.1

Enable Done Button

  • In Attributes Inspector for the UITextField in Storyboard find the field "Return Key" and select "Done"

Hide Keyboard when Done is pressed

  • In Storyboard make your ViewController the delegate for the UITextField
  • Add this method to your ViewController

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }
    

How to encrypt and decrypt file in Android?

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

how to find 2d array size in c++

Here is one possible solution of first part

#include<iostream>

using namespace std;
int main()
{
    int marks[][4] = {
                      10, 20, 30, 50,
                      40, 50, 60, 60,
                      10, 20, 10, 70
                     };

int rows =  sizeof(marks)/sizeof(marks[0]);
int cols = sizeof(marks)/(sizeof(int)*rows);


    for(int i=0; i<rows; i++)
    {
        for(int j=0; j<cols; j++)
        {
            cout<<marks[i][j]<<" ";
        }
        cout<<endl;
    }



    return 0;
}

How do I make a PHP form that submits to self?

  1. change
    <input type="submit" value="Submit" />
    to
    <input type="submit" value="Submit" name='submit'/>

  2. change
    <form method="post" action="<?php echo $PHP_SELF;?>">
    to
    <form method="post" action="">

  3. It will perform the code in if only when it is submitted.
  4. It will always show the form (html code).
  5. what exactly is your question?

How do I change an HTML selected option using JavaScript?

Your own answer technically wasn't incorrect, but you got the index wrong since indexes start at 0, not 1. That's why you got the wrong selection.

document.getElementById('personlist').getElementsByTagName('option')[**10**].selected = 'selected';

Also, your answer is actually a good one for cases where the tags aren't entirely English or numeric.

If they use, for example, Asian characters, the other solutions telling you to use .value() may not always function and will just not do anything. Selecting by tag is a good way to ignore the actual text and select by the element itself.

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

Use this to get your current time in specified format :

 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 System.out.print(dateFormat.format(System.currentTimeMillis()));  }

How to add 30 minutes to a JavaScript Date object?

Other solution:

var dateAv = new Date();
var endTime = new Date(dateAv.getFullYear(), dateAv.getMonth(), dateAv.getDate(), dateAv.getHours(), dateAv.getMinutes() + 30);
          

How to compile Tensorflow with SSE4.2 and AVX instructions?

I compiled a small Bash script for Mac (easily can be ported to Linux) to retrieve all CPU features and apply some of them to build TF. Im on TF master and use kinda often (couple times in a month).

https://gist.github.com/venik/9ba962c8b301b0e21f99884cbd35082f

'Access denied for user 'root'@'localhost' (using password: NO)'

This is basically a more detailed version of a previous answer.

In your Terminal, go to the location of your utility program, mysqladmin

For example, if you were doing local development and using an application like M/W/XAMP, you might go to the directory:

/Applications/MAMP/Library/bin

This is where mysqladmin resides.

If you're not using an application like MAMP, you may also be able to find your local installation of mysql at: /usr/local/mysql

And then if you go to: /usr/local/mysql/bin/

You are in the directory where mysqladmin resides.

Then, to change the password, you will do the following:

  1. At your Terminal prompt enter the exact command below (aka copy and paste) and press enter. The word "password" is part of the command, so don't be confused and come to the conclusion that you need to replace this word with some password you created previously or want to use in the future. You will have a chance to enter a new password soon enough, but it's not in this first command that you will do that:

    ./mysqladmin -u root -p password

  2. The Terminal will ask you to enter your original or initial password, not a new one yet. From the above image you provided, it looks like you have one already created, so enter it here:

Enter password: oldpassword

  1. The Terminal will ask you to enter a new password. Type it here and press enter:

New password: newpassword

  1. Then the Terminal will ask you to confirm the new password. Type it here and press enter:

Confirm new password: newpassword

Reset or restart your Terminal.

In some cases, as with M/W/XAMP, you will have to update this new password in various files in order to get your application running properly again.

How do you declare an interface in C++?

There is no concept of "interface" per se in C++. AFAIK, interfaces were first introduced in Java to work around the lack of multiple inheritance. This concept has turned out to be quite useful, and the same effect can be achieved in C++ by using an abstract base class.

An abstract base class is a class in which at least one member function (method in Java lingo) is a pure virtual function declared using the following syntax:

class A
{
  virtual void foo() = 0;
};

An abstract base class cannot be instantiated, i. e. you cannot declare an object of class A. You can only derive classes from A, but any derived class that does not provide an implementation of foo() will also be abstract. In order to stop being abstract, a derived class must provide implementations for all pure virtual functions it inherits.

Note that an abstract base class can be more than an interface, because it can contain data members and member functions that are not pure virtual. An equivalent of an interface would be an abstract base class without any data with only pure virtual functions.

And, as Mark Ransom pointed out, an abstract base class should provide a virtual destructor, just like any base class, for that matter.

How do I find out my MySQL URL, host, port and username?

If you use phpMyAdmin, click on Home, then Variables on the top menu. Look for the port setting on the page. The value it is set to is the port your MySQL server is running on.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How to append rows in a pandas dataframe in a for loop?

I have created a data frame in a for loop with the help of a temporary empty data frame. Because for every iteration of for loop, a new data frame will be created thereby overwriting the contents of previous iteration.

Hence I need to move the contents of the data frame to the empty data frame that was created already. It's as simple as that. We just need to use .append function as shown below :

temp_df = pd.DataFrame() #Temporary empty dataframe
for sent in Sentences:
    New_df = pd.DataFrame({'words': sent.words}) #Creates a new dataframe and contains tokenized words of input sentences
    temp_df = temp_df.append(New_df, ignore_index=True) #Moving the contents of newly created dataframe to the temporary dataframe

Outside the for loop, you can copy the contents of the temporary data frame into the master data frame and then delete the temporary data frame if you don't need it

Android, landscape only orientation?

Yes, in AndroidManifest.xml, declare your Activity like so: <activity ... android:screenOrientation="landscape" .../>

Compare two objects in Java with possible null values

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.

Richtextbox wpf binding

Why not just use a FlowDocumentScrollViewer ?

PHP Fatal error: Class 'PDO' not found

I had the same problem on GoDaddy. I added the extension=pdo.so to php.ini, still didn't work. And then only one thing came to my mind: Permissions

Before uploading the file, kill all PHP processes(cPanel->PHP Processes).

The problem was that with the file permissions, it was set to 0644 and was not executable . You need to set the file permission at least 0755.

Permissions

How do I get an object's unqualified (short) class name?

You may get an unexpected result when the class doesn't have a namespace. I.e. get_class returns Foo, then $baseClass would be oo.

$baseClass = substr(strrchr(get_class($this), '\\'), 1);

This can easily be fixed by prefixing get_class with a backslash:

$baseClass = substr(strrchr('\\'.get_class($this), '\\'), 1);

Now also classes without a namespace will return the right value.

Vertical divider doesn't work in Bootstrap 3

Here is some LESS for you, in case you customize the navbar:

.navbar .divider-vertical {
    height: floor(@navbar-height - @navbar-margin-bottom);
    margin: floor(@navbar-margin-bottom / 2) 9px;
    border-left: 1px solid #f2f2f2;
    border-right: 1px solid #ffffff;
}

Difference between binary semaphore and mutex

Mutex work on blocking critical region, But Semaphore work on count.

How to change the colors of a PNG image easily?

Use Photoshop, Paint.NET or similar software and adjust Hue.

Comparing strings in C# with OR in an if statement

The code provided is correct, I don't see any reason why it wouldn't work. You could also try if (string1.Equals(string2)) as suggested.

To do if (something OR something else), use ||:

if (condition_1 || condition_2) { ... }

Core Data: Quickest way to delete all instances of an entity

Swift 3.X and Swift 4.X , Easy way. Change only YourTable

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "YourTable")
    fetchRequest.returnsObjectsAsFaults = false

    do
    {
        let results = try context.fetch(fetchRequest)
        for managedObject in results
        {
            let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
            context.delete(managedObjectData)
        }
    } catch let error as NSError {
        print("Detele all my data in \(entity) error : \(error) \(error.userInfo)")
    }

How to upload a file to directory in S3 bucket using boto

from boto3.s3.transfer import S3Transfer
import boto3
#have all the variables populated which are required below
client = boto3.client('s3', aws_access_key_id=access_key,aws_secret_access_key=secret_key)
transfer = S3Transfer(client)
transfer.upload_file(filepath, bucket_name, folder_name+"/"+filename)

Find where java class is loaded from

This is what we use:

public static String getClassResource(Class<?> klass) {
  return klass.getClassLoader().getResource(
     klass.getName().replace('.', '/') + ".class").toString();
}

This will work depending on the ClassLoader implementation: getClass().getProtectionDomain().getCodeSource().getLocation()

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

pip install python-dateutil
>>> a = "2019-06-27T02:14:49.443814497Z"
>>> dateutil.parser.parse(a)
datetime.datetime(2019, 6, 27, 2, 14, 49, 443814, tzinfo=tzutc())

Variable length (Dynamic) Arrays in Java

Arrays in Java are of fixed size. What you'd need is an ArrayList, one of a number of extremely valuable Collections available in Java.

Instead of

Integer[] ints = new Integer[x]

you use

List<Integer> ints = new ArrayList<Integer>();

Then to change the list you use ints.add(y) and ints.remove(z) amongst many other handy methods you can find in the appropriate Javadocs.

I strongly recommend studying the Collections classes available in Java as they are very powerful and give you a lot of builtin functionality that Java-newbies tend to try to rewrite themselves unnecessarily.

IBOutlet and IBAction

You need to use IBOutlet and IBAction if you are using interface builder (hence the IB prefix) for your GUI components. IBOutlet is needed to associate properties in your application with components in IB, and IBAction is used to allow your methods to be associated with actions in IB.

For example, suppose you define a button and label in IB. To dynamically change the value of the label by pushing the button, you will define an action and property in your app similar to:

UILabel IBOutlet *myLabel;
- (IBAction)pushme:(id)sender;

Then in IB you would connect myLabel with the label and connect the pushme method with the button. You need IBAction and IBOutlet for these connections to exist in IB.

How to get root directory in yii2

To get the base URL you can use this (would return "http:// localhost/yiistore2/upload")

Yii::app()->baseUrl

The following Code would return just "localhost/yiistore2/upload" without http[s]://

Yii::app()->getBaseUrl(true)

Or you could get the webroot path (would return "d:\wamp\www\yii2store")

Yii::getPathOfAlias('webroot')

Grab a segment of an array in Java without creating a new array on heap

How about a thin List wrapper?

List<Byte> getSubArrayList(byte[] array, int offset, int size) {
   return new AbstractList<Byte>() {
      Byte get(int index) {
         if (index < 0 || index >= size) 
           throw new IndexOutOfBoundsException();
         return array[offset+index];
      }
      int size() {
         return size;
      }
   };
}

(Untested)

Adding asterisk to required fields in Bootstrap 3

Use .form-group.required without the space.

.form-group.required .control-label:after {
  content:"*";
  color:red;
}

Edit:

For the checkbox you can use the pseudo class :not(). You add the required * after each label unless it is a checkbox

.form-group.required:not(.checkbox) .control-label:after, 
.form-group.required .text:after { /* change .text in whatever class of the text after the checkbox has */
   content:"*";
   color:red;
}

Note: not tested

You should use the .text class or target it otherwise probably, try this html:

<div class="form-group required">
   <label class="col-md-2 control-label">&#160;</label>
   <div class="col-md-4">
      <div class="checkbox">
         <label class='text'> <!-- use this class -->
            <input class="" id="id_tos" name="tos" required="required" type="checkbox" /> I have read and agree to the Terms of Service
         </label>
      </div>
   </div>
</div>

Ok third edit:

CSS back to what is was

.form-group.required .control-label:after { 
   content:"*";
   color:red;
}

HTML:

<div class="form-group required">
   <label class="col-md-2">&#160;</label> <!-- remove class control-label -->
   <div class="col-md-4">
      <div class="checkbox">
         <label class='control-label'> <!-- use this class as the red * will be after control-label -->
            <input class="" id="id_tos" name="tos" required="required" type="checkbox" /> I have read and agree to the Terms of Service
         </label>
      </div>
   </div>
</div>

Convert array of indices to 1-hot encoded numpy array

You can use the following code for converting into a one-hot vector:

let x is the normal class vector having a single column with classes 0 to some number:

import numpy as np
np.eye(x.max()+1)[x]

if 0 is not a class; then remove +1.

Array.sort() doesn't sort numbers correctly

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

Largest and smallest number in an array

If you need to use foreach (for some reason) and don't want to use bult-in functions, here is a code snippet:

int minint = array[0];
int maxint = array[0];
foreach (int value in array) {
  if (value < minint) minint = value;
  if (value > maxint) maxint = value;
}

Check if an array item is set in JS

var is a statement... so it's a reserved word... So just call it another way. And that's a better way of doing it (=== is better than ==)

if(typeof array[name] !== 'undefined') {
    alert("Has var");
} else {
    alert("Doesn't have var");
}

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

Spring Data: "delete by" is supported?

2 ways:-

1st one Custom Query

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

But, the 1st option (custom query),

It's just a single query It will delete wherever the value exists.

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

How do I get the logfile from an Android device?

Often I get the error "logcat read: Invalid argument". I had to clear the log, before reading from the log.

I do like this:

prompt> cd ~/Desktop
prompt> adb logcat -c
prompt> adb logcat | tee log.txt

The server principal is not able to access the database under the current security context in SQL Server MS 2012

SQL Logins are defined at the server level, and must be mapped to Users in specific databases.

In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.

Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.

enter image description here

These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:

USE {database};
ALTER USER {user} WITH login = {login}

You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.

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

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

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

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

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


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


DROP TABLE ##temp11

Sorting a Dictionary in place with respect to keys

By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.

C# switch statement limitations - why?

According to the switch statement documentation if there is an unambiguous way to implicitly convert the the object to an integral type, then it will be allowed. I think you are expecting a behavior where for each case statement it would be replaced with if (t == typeof(int)), but that would open a whole can of worms when you get to overload that operator. The behavior would change when implementation details for the switch statement changed if you wrote your == override incorrectly. By reducing the comparisons to integral types and string and those things that can be reduced to integral types (and are intended to) they avoid potential issues.

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

Pass multiple values with onClick in HTML link

That is because you pass string to the function. Just remove quotes and pass real values:

<a href=# onclick="return ReAssign(valuationId, user)">Re-Assign</a>

Guess the ReAssign function should return true or false.

How to find which columns contain any NaN value in Pandas dataframe

Both of these should work:

df.isnull().sum()
df.isna().sum()

DataFrame methods isna() or isnull() are completely identical.

Note: Empty strings '' is considered as False (not considered NA)

Set colspan dynamically with jquery

I've also found that if you had display:none, then programmatically changed it to be visible, you might also have to set

$tr.css({display:'table-row'});

rather than display:inline or display:block otherwise the cell might only show as taking up 1 cell, no matter how large you have the colspan set to.

How to execute a java .class from the command line

If you have in your java source

package mypackage;

and your class is hello.java with

public class hello {

and in that hello.java you have

 public static void main(String[] args) {

Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

java -cp . mypackage.hello

Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also

Thanks Stack overflow for a wealth of info.

jQuery Loop through each div

You're right that it involves a loop, but this is, at least, made simple by use of the each() method:

$('.target').each(
    function(){
        // iterate through each of the `.target` elements, and do stuff in here
        // `this` and `$(this)` refer to the current `.target` element
        var images = $(this).find('img'),
            imageWidth = images.width(); // returns the width of the _first_ image
            numImages = images.length;
        $(this).css('width', (imageWidth*numImages));

    });

References:

Access a JavaScript variable from PHP

The short answer is you can't.

I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).

You're doing a $_GET, which is used to retrieve form values:

The built-in $_GET function is used to collect values in a form with method="get".

In other words, if on your page you had:

<form method="get" action="blah.php">
    <input name="test"></input>
</form>

Your $_GET call would retrieve the value in that input field.

So how to retrieve a value from JavaScript?

Well, you could stick the javascript value in a hidden form field...

<script type="text/javascript" charset="utf-8">
    var test = "tester";
    // find the 'test' input element and set its value to the above variable
    document.getElementByID("test").value = test;
</script>

... elsewhere on your page ...

<form method="get" action="blah.php">
    <input id="test" name="test" visibility="hidden"></input>
    <input type="submit" value="Click me!"></input>
</form>

Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

How do I best silence a warning about unused variables?

You can put it in "(void)var;" expression (does nothing) so that a compiler sees it is used. This is portable between compilers.

E.g.

void foo(int param1, int param2)
{
    (void)param2;
    bar(param1);
}

Or,

#define UNUSED(expr) do { (void)(expr); } while (0)
...

void foo(int param1, int param2)
{
    UNUSED(param2);
    bar(param1);
}

On localhost, how do I pick a free port number?

If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:

import socketserver

with socketserver.TCPServer(("localhost", 0), None) as s:
    free_port = s.server_address[1]

Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.