Programs & Examples On #Shared primary key

Shared Primary Key is a technique used in relational database design when it is desired to enforce a one-to-one relationship between rows in two or more tables (relations).

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

I noticed this problem recently myself, and I'm not sure how it comes about but it would appear sometimes firefox gets stuck on something loaded in cache. After clearing cache and restarting firefox it appears to function again.

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

The definitive guide to form-based website authentication

I do not think the above answer is "wrong" but there are large areas of authentication that are not touched upon (or rather the emphasis is on "how to implement cookie sessions", not on "what options are available and what are the trade-offs".

My suggested edits/answers are

  • The problem lies more in account setup than in password checking.
  • The use of two-factor authentication is much more secure than more clever means of password encryption
  • Do NOT try to implement your own login form or database storage of passwords, unless the data being stored is valueless at account creation and self-generated (that is, web 2.0 style like Facebook, Flickr, etc.)

    1. Digest Authentication is a standards-based approach supported in all major browsers and servers, that will not send a password even over a secure channel.

This avoids any need to have "sessions" or cookies as the browser itself will re-encrypt the communication each time. It is the most "lightweight" development approach.

However, I do not recommend this, except for public, low-value services. This is an issue with some of the other answers above - do not try an re-implement server-side authentication mechanisms - this problem has been solved and is supported by most major browsers. Do not use cookies. Do not store anything in your own hand-rolled database. Just ask, per request, if the request is authenticated. Everything else should be supported by configuration and third-party trusted software.

So ...

First, we are confusing the initial creation of an account (with a password) with the re-checking of the password subsequently. If I am Flickr and creating your site for the first time, the new user has access to zero value (blank web space). I truly do not care if the person creating the account is lying about their name. If I am creating an account of the hospital intranet/extranet, the value lies in all the medical records, and so I do care about the identity (*) of the account creator.

This is the very very hard part. The only decent solution is a web of trust. For example, you join the hospital as a doctor. You create a web page hosted somewhere with your photo, your passport number, and a public key, and hash them all with the private key. You then visit the hospital and the system administrator looks at your passport, sees if the photo matches you, and then hashes the web page/photo hash with the hospital private key. From now on we can securely exchange keys and tokens. As can anyone who trusts the hospital (there is the secret sauce BTW). The system administrator can also give you an RSA dongle or other two-factor authentication.

But this is a lot of a hassle, and not very web 2.0. However, it is the only secure way to create new accounts that have access to valuable information that is not self-created.

  1. Kerberos and SPNEGO - single sign-on mechanisms with a trusted third party - basically the user verifies against a trusted third party. (NB this is not in any way the not to be trusted OAuth)

  2. SRP - sort of clever password authentication without a trusted third party. But here we are getting into the realms of "it's safer to use two-factor authentication, even if that's costlier"

  3. SSL client side - give the clients a public key certificate (support in all major browsers - but raises questions over client machine security).

In the end, it's a tradeoff - what is the cost of a security breach vs the cost of implementing more secure approaches. One day, we may see a proper PKI widely accepted and so no more own rolled authentication forms and databases. One day...

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.

Python convert tuple to string

here is an easy way to use join.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

Looks like the user account you're using for your app pool doesn't have rights to the web site directory, so it can't read config from there. Check the app pool and see what user it is configured to run as. Check the directory and see if that user has appropriate rights to it. While you're at it, check the event log and see if IIS logged any more detailed diagnostic information there.

How to set image button backgroundimage for different state?

Try this

btn.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        btn.setBackgroundResource(R.drawable.icon);
    }
});

What’s the best way to reload / refresh an iframe?

Because of the same origin policy, this won't work when modifying an iframe pointing to a different domain. If you can target newer browsers, consider using HTML5's Cross-document messaging. You view the browsers that support this feature here: http://caniuse.com/#feat=x-doc-messaging.

If you can't use HTML5 functionality, then you can follow the tricks outlined here: http://softwareas.com/cross-domain-communication-with-iframes. That blog entry also does a good job of defining the problem.

Create tap-able "links" in the NSAttributedString of a UILabel?

I had a hard time dealing with this... UILabel with links on it on attributed text... it is just a headache so I ended up using ZSWTappableLabel.

Nullable type as a generic parameter possible?

The shorter way :

public static T ValueOrDefault<T>(this DataRow reader, string columnName) => 
        reader.IsNull(columnName) ? default : (T) reader[columnName];

return 0 for int, and null for int?

PHP Array to JSON Array using json_encode();

If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.

Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:

Example:

// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
  2 => array("Afghanistan", 32, 13),
  4 => array("Albania", 32, 12)
);

// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]

installing JDK8 on Windows XP - advapi32.dll error

With JRE 8 on XP there is another way - to use MSI to deploy package.

  • Install JRE 8 x86 on a PC with supported OS
  • Copy c:\Users[USER]\AppData\LocalLow\Sun\Java\jre1.8.0\jre1.8.0.msi and Data1.cab to XP PC and run jre1.8.0.msi

or (silent way, usable in batch file etc..)

for %%I in ("*.msi") do if exist "%%I" msiexec.exe /i %%I /qn EULA=0 SKIPLICENSE=1 PROG=0 ENDDIALOG=0

GenyMotion Unable to start the Genymotion virtual device

In my case, the only option was to remove the VM and download it again. No re-configuration of the host-only adapter did not help, I used different addressing of DHCP. Virtual Box I updated to version 4.3.4 and Genymotion to 2.0.2

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

In addition to existing answers:

RUN apt-get update && apt-get install -y gnupg

-y flag agrees to terms during installation process. It is important not to break the build

Can I convert a C# string value to an escaped string literal

Interesting question.

If you can't find a better method, you can always replace.
In case you're opting for it, you could use this C# Escape Sequence List:

  • \' - single quote, needed for character literals
  • \" - double quote, needed for string literals
  • \ - backslash
  • \0 - Unicode character 0
  • \a - Alert (character 7)
  • \b - Backspace (character 8)
  • \f - Form feed (character 12)
  • \n - New line (character 10)
  • \r - Carriage return (character 13)
  • \t - Horizontal tab (character 9)
  • \v - Vertical quote (character 11)
  • \uxxxx - Unicode escape sequence for character with hex value xxxx
  • \xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
  • \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)

This list can be found in the C# Frequently Asked Questions What character escape sequences are available?

Cutting the videos based on start and end time using ffmpeg

feel free to use this tool https://github.com/rooty0/ffmpeg_video_cutter I wrote awhile ago Pretty much that's cli front-end for ffmpeg... you just need to create a yaml what you want to cut out... something like this

cut_method: delete  # we're going to delete following video fragments from a video
timeframe:
  - from: start   # waiting for people to join the conference
    to: 4m
  - from: 10m11s  # awkward silence
    to: 15m50s
  - from: 30m5s   # Off-Topic Discussion
    to: end

and then just run a tool to get result

Random character generator with a range of (A..Z, 0..9) and punctuation

The easiest is to do the following:

  • Create a String alphabet with the chars that you want.
  • Say N = alphabet.length()
  • Then we can ask a java.util.Random for an int x = nextInt(N)
  • alphabet.charAt(x) is a random char from the alphabet

Here's an example:

    final String alphabet = "0123456789ABCDE";
    final int N = alphabet.length();

    Random r = new Random();

    for (int i = 0; i < 50; i++) {
        System.out.print(alphabet.charAt(r.nextInt(N)));
    }

Center the nav in Twitter Bootstrap

http://www.bootply.com/3iSOTAyumP in this example the button for collapse was not clickable because the .navbar-brand was in front.

http://www.bootply.com/RfnEgu45qR there is an updated version where the collapse buttons is actually clickable.

What's the difference between [ and [[ in Bash?

[[ is bash's improvement to the [ command. It has several enhancements that make it a better choice if you write scripts that target bash. My favorites are:

  1. It is a syntactical feature of the shell, so it has some special behavior that [ doesn't have. You no longer have to quote variables like mad because [[ handles empty strings and strings with whitespace more intuitively. For example, with [ you have to write

    if [ -f "$file" ]
    

    to correctly handle empty strings or file names with spaces in them. With [[ the quotes are unnecessary:

    if [[ -f $file ]]
    
  2. Because it is a syntactical feature, it lets you use && and || operators for boolean tests and < and > for string comparisons. [ cannot do this because it is a regular command and &&, ||, <, and > are not passed to regular commands as command-line arguments.

  3. It has a wonderful =~ operator for doing regular expression matches. With [ you might write

    if [ "$answer" = y -o "$answer" = yes ]
    

    With [[ you can write this as

    if [[ $answer =~ ^y(es)?$ ]]
    

    It even lets you access the captured groups which it stores in BASH_REMATCH. For instance, ${BASH_REMATCH[1]} would be "es" if you typed a full "yes" above.

  4. You get pattern matching aka globbing for free. Maybe you're less strict about how to type yes. Maybe you're okay if the user types y-anything. Got you covered:

    if [[ $ANSWER = y* ]]
    

Keep in mind that it is a bash extension, so if you are writing sh-compatible scripts then you need to stick with [. Make sure you have the #!/bin/bash shebang line for your script if you use double brackets.

See also

how does Request.QueryString work?

The HttpRequest class represents the request made to the server and has various properties associated with it, such as QueryString.

The ASP.NET run-time parses a request to the server and populates this information for you.

Read HttpRequest Properties for a list of all the potential properties that get populated on you behalf by ASP.NET.

Note: not all properties will be populated, for instance if your request has no query string, then the QueryString will be null/empty. So you should check to see if what you expect to be in the query string is actually there before using it like this:

if (!String.IsNullOrEmpty(Request.QueryString["pID"]))
{
    // Query string value is there so now use it
    int thePID = Convert.ToInt32(Request.QueryString["pID"]);
}

Pass parameter to EventHandler

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

But you need to think about where to store your note.

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I used JUG (Java UUID Generator) to generate unique ID. It is unique across JVMs. Pretty good to use. Here is the code for your reference:

private static final SecureRandom secureRandom = new SecureRandom();
private static final UUIDGenerator generator = UUIDGenerator.getInstance();

public synchronized static String generateUniqueId() {
  UUID uuid = generator.generateRandomBasedUUID(secureRandom);

  return uuid.toString().replaceAll("-", "").toUpperCase();
}

You could download the library from: https://github.com/cowtowncoder/java-uuid-generator

Remove directory which is not empty

In the latest version of Node.js (12.10.0 or later), the rmdir style functions fs.rmdir(), fs.rmdirSync(), and fs.promises.rmdir() have a new experimental option recursive that allows deleting non-empty directories, e.g.

fs.rmdir(path, { recursive: true });

The related PR on GitHub: https://github.com/nodejs/node/pull/29168

mysql after insert trigger which updates another table's column

Maybe remove the semi-colon after set because now the where statement doesn't belong to the update statement. Also the idRequest could be a problem, better write BookingRequest.idRequest

Jquery click event not working after append method

Use on :

$('#registered_participants').on('click', '.new_participant_form', function() {

So that the click is delegated to any element in #registered_participants having the class new_participant_form, even if it's added after you bound the event handler.

Why AVD Manager options are not showing in Android Studio

It happens when there is no runnable module for Android App in your project. Creating new project definitely solves this.

You can check this using Run > Edit Configurations > Adding Android App. If there is not runnable Android App module then you can't see "AVD Manager" in the menu.

typeof operator in C

It's a GNU extension. In a nutshell it's a convenient way to declare an object having the same type as another. For example:

int x;         /* Plain old int variable. */
typeof(x) y;   /* Same type as x. Plain old int variable. */

It works entirely at compile-time and it's primarily used in macros. One famous example of macro relying on typeof is container_of.

A CORS POST request works from plain JavaScript, but why not with jQuery?

Modify your Jquery in following way:

$.ajax({
            url: someurl,
            contentType: 'application/json',
            data: JSONObject,
            headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
            dataType: 'json',
            type: 'POST',                
            success: function (Data) {....}
});

Select columns from result set of stored procedure

A quick hack would be to add a new parameter '@Column_Name' and have the calling function define the column name to be retrieved. In the return part of your sproc, you would have if/else statements and return only the specified column, or if empty - return all.

CREATE PROCEDURE [dbo].[MySproc]
        @Column_Name AS VARCHAR(50)
AS
BEGIN
    IF (@Column_Name = 'ColumnName1')
        BEGIN
            SELECT @ColumnItem1 as 'ColumnName1'
        END
    ELSE
        BEGIN
            SELECT @ColumnItem1 as 'ColumnName1', @ColumnItem2 as 'ColumnName2', @ColumnItem3 as 'ColumnName3'
        END
END

Primary key or Unique index?

You can see it like this:

A Primary Key IS Unique

A Unique value doesn't have to be the Representaion of the Element

Meaning?; Well a primary key is used to identify the element, if you have a "Person" you would like to have a Personal Identification Number ( SSN or such ) which is Primary to your Person.

On the other hand, the person might have an e-mail which is unique, but doensn't identify the person.

I always have Primary Keys, even in relationship tables ( the mid-table / connection table ) I might have them. Why? Well I like to follow a standard when coding, if the "Person" has an identifier, the Car has an identifier, well, then the Person -> Car should have an identifier as well!

How do I use a C# Class Library in a project?

There are necessary steps that are missing in the above answers to work for all levels of devs:

  1. compile your class library project
  2. the dll file will be available in the bin folder
  3. in another project, right click ProjectName and select "Add" => "Existing Item"
  4. Browser to the bin folder of the class library project and select the dll file (3 & 4 steps are important if you plan to ship your app to other machines)
  5. as others mentioned, add reference to the dll file you "just" added to your project
  6. as @Adam mentioned, just call the library name from anywhere in your program, you do not need a using statement

How to access custom attributes from event object in React?

// Method inside the component
userClick(event){
 let tag = event.currentTarget.dataset.tag;
 console.log(tag); // should return Tagvalue
}
// when render element
<a data-tag="TagValue" onClick={this.userClick}>Click me</a>

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

You must analyse the actual HTML output, for the hint.

By giving the path like this means "from current location", on the other hand if you start with a / that would mean "from the context".

how to create a list of lists

Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

Can I change the color of Font Awesome's icon color?

To change the font awesome icons color for your entire project use this in your css

.fa {
  color : red;
}

Fill an array with random numbers

People don't see the nice cool Stream producers all over the Java libs.

public static double[] list(){
    return new Random().ints().asDoubleStream().toArray();
}

Controlling fps with requestAnimationFrame?

var time = 0;
var time_framerate = 1000; //in milliseconds

function animate(timestamp) {
  if(timestamp > time + time_framerate) {
    time = timestamp;    

    //your code
  }

  window.requestAnimationFrame(animate);
}

Check if a number is odd or even in python

Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and operator:

if x & 1:
    return 'odd'
else:
    return 'even'

Using Bitwise AND operator

  • The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
  • If a number is odd & (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

Go to C:\wamp\alias. Open the file phpmyadmin.conf and change

<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</Directory>

to

<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Allow,Deny
    Allow from all
</Directory>

problem solved

Python [Errno 98] Address already in use

run the command

fuser -k (port_number_you_are _trying_to_access)/TCP

example for flask: fuser -k 5000/tcp

Also, remember this error arises when you interput by ctrl+z. so to terminate use ctrl+c

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

This is worked for me, Hope to help someone (Using my own button not FB login button )

CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_sign_in_user);



     LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {


            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    try {
                        Log.i("RESAULTS : ", object.getString("email"));
                    }catch (Exception e){

                    }
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "email");
            request.setParameters(parameters);
            request.executeAsync();

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            Log.i("RESAULTS : ", error.getMessage());
        }
    });


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}


boolean isEmailValid(CharSequence email) {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

public void signupwith_facebook(View view) {

    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}

Python - 'ascii' codec can't decode byte

Always encode from unicode to bytes.
In this direction, you get to choose the encoding.

>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
??

The other way is to decode from bytes to unicode.
In this direction, you have to know what the encoding is.

>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
??
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
??

This point can't be stressed enough. If you want to avoid playing unicode "whack-a-mole", it's important to understand what's happening at the data level. Here it is explained another way:

  • A unicode object is decoded already, you never want to call decode on it.
  • A bytestring object is encoded already, you never want to call encode on it.

Now, on seeing .encode on a byte string, Python 2 first tries to implicitly convert it to text (a unicode object). Similarly, on seeing .decode on a unicode string, Python 2 implicitly tries to convert it to bytes (a str object).

These implicit conversions are why you can get UnicodeDecodeError when you've called encode. It's because encoding usually accepts a parameter of type unicode; when receiving a str parameter, there's an implicit decoding into an object of type unicode before re-encoding it with another encoding. This conversion chooses a default 'ascii' decoder, giving you the decoding error inside an encoder.

In fact, in Python 3 the methods str.decode and bytes.encode don't even exist. Their removal was a [controversial] attempt to avoid this common confusion.

...or whatever coding sys.getdefaultencoding() mentions; usually this is 'ascii'

Git: copy all files in a directory from another branch

As you are not trying to move the files around in the tree, you should be able to just checkout the directory:

git checkout master -- dirname

How to validate domain credentials?

Here's how to determine a local user:

    public bool IsLocalUser()
    {
        return windowsIdentity.AuthenticationType == "NTLM";
    }

Edit by Ian Boyd

You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.

Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:

Why the NTLM Plug-in is Needed

NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.

Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.

By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.

How the Plug-in Works

The Verifier plug detects the following errors:

  • The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).

  • The target name in the call to InitializeSecurityContext is NULL.

  • The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.

The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).

The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.

NTLM Stops

5000 – Application Has Explicitly Selected NTLM Package

Severity – Error

The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.

How to Fix this Error

The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.

APIs(parameter) Used by Application    Incorrect Value  Correct Value  
=====================================  ===============  ========================
AcquireCredentialsHandle (pszPackage)  “NTLM”           NEGOSSP_NAME “Negotiate”

Should I use @EJB or @Inject

Injection already existed in Java EE 5 with the @Resource, @PersistentUnit or @EJB annotations, for example. But it was limited to certain resources (datasource, EJB . . .) and into certain components (Servlets, EJBs, JSF backing bean . . .). With CDI you can inject nearly anything anywhere thanks to the @Inject annotation.

Start HTML5 video at a particular position when loading?

Using a #t=10,20 fragment worked for me.

How do I print the content of a .txt file in Python?

Just do this:

>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
...     print f.read()

This will print the file in the terminal.

Want custom title / image / description in facebook share link from a flash app

2016 Update

Use the Sharing Debugger to figure out what your problems are.

Make sure you're following the Facebook Sharing Best Practices.

Make sure you're using the Open Graph Markup correctly.

Original Answer

I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.

Ruby class instance variable vs. class variable

While it may immediately seem useful to utilize class instance variables, since class instance variable are shared among subclasses and they can be referred to within both singleton and instance methods, there is a singificant drawback. They are shared and so subclasses can change the value of the class instance variable, and the base class will also be affected by the change, which is usually undesirable behavior:

class C
  @@c = 'c'
  def self.c_val
    @@c
  end
end

C.c_val
 => "c" 

class D < C
end

D.instance_eval do 
  def change_c_val
    @@c = 'd'
  end
end
 => :change_c_val 

D.change_c_val
(irb):12: warning: class variable access from toplevel
 => "d" 

C.c_val
 => "d" 

Rails introduces a handy method called class_attribute. As the name implies, it declares a class-level attribute whose value is inheritable by subclasses. The class_attribute value can be accessed in both singleton and instance methods, as is the case with the class instance variable. However, the huge benefit with class_attribute in Rails is subclasses can change their own value and it will not impact parent class.

class C
  class_attribute :c
  self.c = 'c'
end

 C.c
 => "c" 

class D < C
end

D.c = 'd'
 => "d" 

 C.c
 => "c" 

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

In order to resolve this issue make all your data flow tasks in one sequence. It means it should not execute parallel. One data flow task sequence should contain only one data flow task and for this another data flow task as sequence.

Ex:-

enter image description here

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

def getAny(dic, keys, default=None):
    return (keys or default) and dic.get(keys[0], 
                                         getAny( dic, keys[1:], default=default))

or even better, without recursion and more clear:

def getAny(dic, keys, default=None):
    for k in keys: 
        if k in dic:
           return dic[k]
    return default

Then that could be used in a way similar to the dict.get method, like:

getAny(myDict, keySet)

and even have a default result in case of no keys found at all:

getAny(myDict, keySet, "not found")

How do I check if file exists in jQuery or pure JavaScript?

I wanted a function that would return a boolean, I encountered problems related to closure and asynchronicity. I solved this way:

checkFileExistence= function (file){
    result=false;
    jQuery.ajaxSetup({async:false});
    $.get(file)
        .done(function() {
           result=true;
        })
        .fail(function() {
           result=false;
        })
    jQuery.ajaxSetup({async:true});
    return(result);
},

Which Android IDE is better - Android Studio or Eclipse?

The use of IDE is your personal preference. But personally if I had to choose, Eclipse is a widely known, trusted and certainly offers more features then Android Studio. Android Studio is a little new right now. May be it's upcoming versions keep up to Eclipse level soon.

Xcode 6 Storyboard the wrong size?

Go to Attributes Inspector(right top corner) In the Simulated Metrics, which has Size, Orientation, Status Bar, Top Bar, Bottom Bar properties. For SIZE, change Inferred --> Freeform.

How to clear APC cache entries?

apc.ini

apc.stat = "1" will force APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version.

If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.

How do I set log4j level on the command line?

Based on @lijat, here is a simplified implementation. In my spring-based application I simply load this as a bean.

public static void configureLog4jFromSystemProperties()
{
  final String LOGGER_PREFIX = "log4j.logger.";

  for(String propertyName : System.getProperties().stringPropertyNames())
  {
    if (propertyName.startsWith(LOGGER_PREFIX)) {
      String loggerName = propertyName.substring(LOGGER_PREFIX.length());
      String levelName = System.getProperty(propertyName, "");
      Level level = Level.toLevel(levelName); // defaults to DEBUG
      if (!"".equals(levelName) && !levelName.toUpperCase().equals(level.toString())) {
        logger.error("Skipping unrecognized log4j log level " + levelName + ": -D" + propertyName + "=" + levelName);
        continue;
      }
      logger.info("Setting " + loggerName + " => " + level.toString());
      Logger.getLogger(loggerName).setLevel(level);
    }
  }
}

Hash function that produces short hashes?

If you need "sub-10-character hash" you could use Fletcher-32 algorithm which produces 8 character hash (32 bits), CRC-32 or Adler-32.

CRC-32 is slower than Adler32 by a factor of 20% - 100%.

Fletcher-32 is slightly more reliable than Adler-32. It has a lower computational cost than the Adler checksum: Fletcher vs Adler comparison.

A sample program with a few Fletcher implementations is given below:

    #include <stdio.h>
    #include <string.h>
    #include <stdint.h> // for uint32_t

    uint32_t fletcher32_1(const uint16_t *data, size_t len)
    {
            uint32_t c0, c1;
            unsigned int i;

            for (c0 = c1 = 0; len >= 360; len -= 360) {
                    for (i = 0; i < 360; ++i) {
                            c0 = c0 + *data++;
                            c1 = c1 + c0;
                    }
                    c0 = c0 % 65535;
                    c1 = c1 % 65535;
            }
            for (i = 0; i < len; ++i) {
                    c0 = c0 + *data++;
                    c1 = c1 + c0;
            }
            c0 = c0 % 65535;
            c1 = c1 % 65535;
            return (c1 << 16 | c0);
    }

    uint32_t fletcher32_2(const uint16_t *data, size_t l)
    {
        uint32_t sum1 = 0xffff, sum2 = 0xffff;

        while (l) {
            unsigned tlen = l > 359 ? 359 : l;
            l -= tlen;
            do {
                sum2 += sum1 += *data++;
            } while (--tlen);
            sum1 = (sum1 & 0xffff) + (sum1 >> 16);
            sum2 = (sum2 & 0xffff) + (sum2 >> 16);
        }
        /* Second reduction step to reduce sums to 16 bits */
        sum1 = (sum1 & 0xffff) + (sum1 >> 16);
        sum2 = (sum2 & 0xffff) + (sum2 >> 16);
        return (sum2 << 16) | sum1;
    }

    int main()
    {
        char *str1 = "abcde";  
        char *str2 = "abcdef";

        size_t len1 = (strlen(str1)+1) / 2; //  '\0' will be used for padding 
        size_t len2 = (strlen(str2)+1) / 2; // 

        uint32_t f1 = fletcher32_1(str1,  len1);
        uint32_t f2 = fletcher32_2(str1,  len1);

        printf("%u %X \n",    f1,f1);
        printf("%u %X \n\n",  f2,f2);

        f1 = fletcher32_1(str2,  len2);
        f2 = fletcher32_2(str2,  len2);

        printf("%u %X \n",f1,f1);
        printf("%u %X \n",f2,f2);

        return 0;
    }

Output:

4031760169 F04FC729                                                                                                                                                                                                                              
4031760169 F04FC729                                                                                                                                                                                                                              

1448095018 56502D2A                                                                                                                                                                                                                              
1448095018 56502D2A                                                                                                                                                                                                                              

Agrees with Test vectors:

"abcde"  -> 4031760169 (0xF04FC729)
"abcdef" -> 1448095018 (0x56502D2A)

Adler-32 has a weakness for short messages with few hundred bytes, because the checksums for these messages have a poor coverage of the 32 available bits. Check this:

The Adler32 algorithm is not complex enough to compete with comparable checksums.

Initializing a static std::map<int, int> in C++

Using C++11:

#include <map>
using namespace std;

map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};

Using Boost.Assign:

#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;

map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');

Cannot deserialize the current JSON array (e.g. [1,2,3])

I think the problem you're having is that your JSON is a list of objects when it comes in and it doesnt directly relate to your root class.

var content would look something like this (i assume):

[
  {
    "id": 3636,
    "is_default": true,
    "name": "Unit",
    "quantity": 1,
    "stock": "100000.00",
    "unit_cost": "0"
  },
  {
    "id": 4592,
    "is_default": false,
    "name": "Bundle",
    "quantity": 5,
    "stock": "100000.00",
    "unit_cost": "0"
  }
]

Note: make use of http://jsonviewer.stack.hu/ to format your JSON.

So if you try the following it should work:

  public static List<RootObject> GetItems(string user, string key, Int32 tid, Int32 pid)
    {
        // Customize URL according to geo location parameters
        var url = string.Format(uniqueItemUrl, user, key, tid, pid);

        // Syncronious Consumption
        var syncClient = new WebClient();

        var content = syncClient.DownloadString(url);

        return JsonConvert.DeserializeObject<List<RootObject>>(content);

    }

You will need to then iterate if you don't wish to return a list of RootObject.


I went ahead and tested this in a Console app, worked fine.

enter image description here

Design DFA accepting binary strings divisible by a number 'n'

I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.

Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.

In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.

Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.

For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :

20/2 = 10 
10/2 = 5

Hence our answer is 5 + 1 + 1 = 7. (The 1 + 1 because we divided the number 20 twice).

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

xmlns:android="http://schemas.android.com/apk/res/android"

This is form of xmlns:android ="@+/id". Now to refernce it we use for example

android:layout_width="wrap_content"
android:text="Hello World!"

Another xmlns is

 xmlns:app="http://schemas.android.com/apk/res-auto"

which is in form of xmlns:app = "@+/id" and its use is given below

 app:layout_constraintBottom_toBottomOf="parent"
 app:layout_constraintLeft_toLeftOf="parent"

How to set HTML5 required attribute in Javascript?

required is a reflected property (like id, name, type, and such), so:

element.required = true;

...where element is the actual input DOM element, e.g.:

document.getElementById("edName").required = true;

(Just for completeness.)

Re:

Then the attribute's value is not the empty string, nor the canonical name of the attribute:

edName.attributes.required = [object Attr]

That's because required in that code is an attribute object, not a string; attributes is a NamedNodeMap whose values are Attr objects. To get the value of one of them, you'd look at its value property. But for a boolean attribute, the value isn't relevant; the attribute is either present in the map (true) or not present (false).

So if required weren't reflected, you'd set it by adding the attribute:

element.setAttribute("required", "");

...which is the equivalent of element.required = true. You'd clear it by removing it entirely:

element.removeAttribute("required");

...which is the equivalent of element.required = false.

But we don't have to do that with required, since it's reflected.

Using Powershell to stop a service remotely without WMI or remoting

This worked for me, but I used it as start. powershell outputs, waiting for service to finshing starting a few times then finishes and then a get-service on the remote server shows the service started.

**start**-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)

Latex - Change margins of only a few pages

I could not find a easy way to set the margin for a single page.

My solution was to use vspace with the number of centimeters of empty space I wanted:

 \vspace*{5cm}                                                             

I put this command at the beginning of the pages that I wanted to have +5cm of margin.

How do I include a Perl module that's in a different directory?

I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.

#!/usr/bin/perl
use FindBin::libs;
use <your lib>;

how to remove new lines and returns from php string?

To remove new lines from string, follow the below code

$newstring = preg_replace("/[\n\r]/","",$subject); 

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

This is a fast way to encode the array, the array shape and the array dtype:

def numpy_to_bytes(arr: np.array) -> str:
    arr_dtype = bytearray(str(arr.dtype), 'utf-8')
    arr_shape = bytearray(','.join([str(a) for a in arr.shape]), 'utf-8')
    sep = bytearray('|', 'utf-8')
    arr_bytes = arr.ravel().tobytes()
    to_return = arr_dtype + sep + arr_shape + sep + arr_bytes
    return to_return

def bytes_to_numpy(serialized_arr: str) -> np.array:
    sep = '|'.encode('utf-8')
    i_0 = serialized_arr.find(sep)
    i_1 = serialized_arr.find(sep, i_0 + 1)
    arr_dtype = serialized_arr[:i_0].decode('utf-8')
    arr_shape = tuple([int(a) for a in serialized_arr[i_0 + 1:i_1].decode('utf-8').split(',')])
    arr_str = serialized_arr[i_1 + 1:]
    arr = np.frombuffer(arr_str, dtype = arr_dtype).reshape(arr_shape)
    return arr

To use the functions:

a = np.ones((23, 23), dtype = 'int')
a_b = numpy_to_bytes(a)
a1 = bytes_to_numpy(a_b)
np.array_equal(a, a1) and a.shape == a1.shape and a.dtype == a1.dtype

How do I configure the proxy settings so that Eclipse can download new plugins?

For me, I go to \eclipse\configuration.settings\org.eclipse.core.net.prefs set the property systemProxiesEnabled to true manually and restart eclipse.

failed to lazily initialize a collection of role

as suggested here solving the famous LazyInitializationException is one of the following methods:

(1) Use Hibernate.initialize

Hibernate.initialize(topics.getComments());

(2) Use JOIN FETCH

You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is somehow like EAGER fetching.

(3) Use OpenSessionInViewFilter

LazyInitializationException often occurs in the view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to a performance issue if not used correctly.

Select parent element of known element in Selenium

Little more about XPath axes

Lets say we have below HTML structure:

<div class="third_level_ancestor">
    <nav class="second_level_ancestor">
        <div class="parent">
            <span>Child</span>
        </div>
    </nav>
</div>
  1. //span/parent::* - returns any element which is direct parent.

In this case output is <div class="parent">

  1. //span/parent::div[@class="parent"] - returns parent element only of exact node type and only if specified predicate is True.

Output: <div class="parent">

  1. //span/ancestor::* - returns all ancestors (including parent).

Output: <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor-or-self::* - returns all ancestors and current element itself.

Output: <span>Child</span>, <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor::div[2] - returns second ancestor (starting from parent) of type div.

Output: <div class="third_level_ancestor">

How to install a private NPM module without my own registry?

Can I just install an NPM package that sits on the local filesystem, or perhaps even from git?

Yes you can! From the docs https://docs.npmjs.com/cli/install

A package is:

  • a) a folder containing a program described by a package.json file
  • b) a gzipped tarball containing (a)
  • c) a url that resolves to (b)
  • d) a <name>@<version> that is published on the registry with (c)
  • e) a <name>@<tag> that points to (d)
  • f) a <name> that has a "latest" tag satisfying (e)
  • g) a <git remote url> that resolves to (b)

Isn't npm brilliant?

Use grep --exclude/--include syntax to not grep through certain files

In the directories are also many binary files. I can't search only certain directories (the directory structure is a big mess). Is there's a better way of grepping only in certain files?

ripgrep

This is one of the quickest tools designed to recursively search your current directory. It is written in Rust, built on top of Rust's regex engine for maximum efficiency. Check the detailed analysis here.

So you can just run:

rg "some_pattern"

It respect your .gitignore and automatically skip hidden files/directories and binary files.

You can still customize include or exclude files and directories using -g/--glob. Globbing rules match .gitignore globs. Check man rg for help.

For more examples, see: How to exclude some files not matching certain extensions with grep?

On macOS, you can install via brew install ripgrep.

How to check if a network port is open on linux?

Here's a fast multi-threaded port scanner:

from time import sleep
import socket, ipaddress, threading

max_threads = 50
final = {}
def check_port(ip, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
        #sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
        socket.setdefaulttimeout(2.0) # seconds (float)
        result = sock.connect_ex((ip,port))
        if result == 0:
            # print ("Port is open")
            final[ip] = "OPEN"
        else:
            # print ("Port is closed/filtered")
            final[ip] = "CLOSED"
        sock.close()
    except:
        pass
port = 80
for ip in ipaddress.IPv4Network('192.168.1.0/24'): 
    threading.Thread(target=check_port, args=[str(ip), port]).start()
    #sleep(0.1)

# limit the number of threads.
while threading.active_count() > max_threads :
    sleep(1)

print(final)

Live Demo

Random number from a range in a Bash Script

This is how I usually generate random numbers. Then I use "NUM_1" as the variable for the port number I use. Here is a short example script.

#!/bin/bash

clear
echo 'Choose how many digits you want for port# (1-5)'
read PORT

NUM_1="$(tr -dc '0-9' </dev/urandom | head -c $PORT)"

echo "$NUM_1"

if [ "$PORT" -gt "5" ]
then
clear
echo -e "\x1b[31m Choose a number between 1 and 5! \x1b[0m"
sleep 3
clear
exit 0
fi

How do I tar a directory of files and folders without including the directory itself?

 tar -cvzf  tarlearn.tar.gz --remove-files mytemp/*

If the folder is mytemp then if you apply the above it will zip and remove all the files in the folder but leave it alone

 tar -cvzf  tarlearn.tar.gz --remove-files --exclude='*12_2008*' --no-recursion mytemp/*

You can give exclude patterns and also specify not to look into subfolders too

How to execute a shell script on a remote server using Ansible?

You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

Get AVG ignoring Null or Zero values

worked for me:

AVG(CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)

How to convert a char to a String?

I am converting Char Array to String

Char[] CharArray={ 'A', 'B', 'C'};
String text = String.copyValueOf(CharArray);

Raising a number to a power in Java

^ in java does not mean to raise to a power. It means XOR.

You can use java's Math.pow()


And you might want to consider using double instead of int—that is:

double height;
double weight;

Note that 199/100 evaluates to 1.

Combine a list of data frames into one data frame by row

Use bind_rows() from the dplyr package:

bind_rows(list_of_dataframes, .id = "column_label")

What is boilerplate code?

It's code that can be used by many applications/contexts with little or no change.

Boilerplate is derived from the steel industry in the early 1900s.

How to push both value and key into PHP array

Exactly what Pekka said...

Alternatively, you can probably use array_merge like this if you wanted:

array_merge($_GET, array($rule[0] => $rule[1]));

But I'd prefer Pekka's method probably as it is much simpler.

How to do one-liner if else statement?

A very similar construction is available in the language

**if <statement>; <evaluation> {
   [statements ...]
} else {
   [statements ...]
}*

*

i.e.

if path,err := os.Executable(); err != nil {
   log.Println(err)
} else {
   log.Println(path)
}

How to compare two dates?

Other answers using datetime and comparisons also work for time only, without a date.

For example, to check if right now it is more or less than 8:00 a.m., we can use:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

And later compare with:

datetime.datetime.now().time() > eight_am  

which will return True

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

MongoDB: Combine data from multiple collections into one..how?

Doing unions in MongoDB in a 'SQL UNION' fashion is possible using aggregations along with lookups, in a single query. Here is an example I have tested that works with MongoDB 4.0:

// Create employees data for testing the union.
db.getCollection('employees').insert({ name: "John", type: "employee", department: "sales" });
db.getCollection('employees').insert({ name: "Martha", type: "employee", department: "accounting" });
db.getCollection('employees').insert({ name: "Amy", type: "employee", department: "warehouse" });
db.getCollection('employees').insert({ name: "Mike", type: "employee", department: "warehouse"  });

// Create freelancers data for testing the union.
db.getCollection('freelancers').insert({ name: "Stephany", type: "freelancer", department: "accounting" });
db.getCollection('freelancers').insert({ name: "Martin", type: "freelancer", department: "sales" });
db.getCollection('freelancers').insert({ name: "Doug", type: "freelancer", department: "warehouse"  });
db.getCollection('freelancers').insert({ name: "Brenda", type: "freelancer", department: "sales"  });

// Here we do a union of the employees and freelancers using a single aggregation query.
db.getCollection('freelancers').aggregate( // 1. Use any collection containing at least one document.
  [
    { $limit: 1 }, // 2. Keep only one document of the collection.
    { $project: { _id: '$$REMOVE' } }, // 3. Remove everything from the document.

    // 4. Lookup collections to union together.
    { $lookup: { from: 'employees', pipeline: [{ $match: { department: 'sales' } }], as: 'employees' } },
    { $lookup: { from: 'freelancers', pipeline: [{ $match: { department: 'sales' } }], as: 'freelancers' } },

    // 5. Union the collections together with a projection.
    { $project: { union: { $concatArrays: ["$employees", "$freelancers"] } } },

    // 6. Unwind and replace root so you end up with a result set.
    { $unwind: '$union' },
    { $replaceRoot: { newRoot: '$union' } }
  ]);

Here is the explanation of how it works:

  1. Instantiate an aggregate out of any collection of your database that has at least one document in it. If you can't guarantee any collection of your database will not be empty, you can workaround this issue by creating in your database some sort of 'dummy' collection containing a single empty document in it that will be there specifically for doing union queries.

  2. Make the first stage of your pipeline to be { $limit: 1 }. This will strip all the documents of the collection except the first one.

  3. Strip all the fields of the remaining document by using a $project stage:

    { $project: { _id: '$$REMOVE' } }
    
  4. Your aggregate now contains a single, empty document. It's time to add lookups for each collection you want to union together. You may use the pipeline field to do some specific filtering, or leave localField and foreignField as null to match the whole collection.

    { $lookup: { from: 'collectionToUnion1', pipeline: [...], as: 'Collection1' } },
    { $lookup: { from: 'collectionToUnion2', pipeline: [...], as: 'Collection2' } },
    { $lookup: { from: 'collectionToUnion3', pipeline: [...], as: 'Collection3' } }
    
  5. You now have an aggregate containing a single document that contains 3 arrays like this:

    {
        Collection1: [...],
        Collection2: [...],
        Collection3: [...]
    }
    

    You can then merge them together into a single array using a $project stage along with the $concatArrays aggregation operator:

    {
      "$project" :
      {
        "Union" : { $concatArrays: ["$Collection1", "$Collection2", "$Collection3"] }
      }
    }
    
  6. You now have an aggregate containing a single document, into which is located an array that contains your union of collections. What remains to be done is to add an $unwind and a $replaceRoot stage to split your array into separate documents:

    { $unwind: "$Union" },
    { $replaceRoot: { newRoot: "$Union" } }
    
  7. Voilà. You now have a result set containing the collections you wanted to union together. You can then add more stages to filter it further, sort it, apply skip() and limit(). Pretty much anything you want.

Auto increment in MongoDB to store sequence of Unique User ID

First Record should be add

"_id" = 1    in your db

$database = "demo";
$collections ="democollaction";
echo getnextid($database,$collections);

function getnextid($database,$collections){

     $m = new MongoClient();
    $db = $m->selectDB($database);
    $cursor = $collection->find()->sort(array("_id" => -1))->limit(1);
    $array = iterator_to_array($cursor);

    foreach($array as $value){



        return $value["_id"] + 1;

    }
 }

MySQL Select Query - Get only first 10 characters of a value

SELECT SUBSTRING(subject, 1, 10) FROM tbl

String.Format for Hex

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.

colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);

The syntax for the format parameter is described in the documentation:

Format Item Syntax

Each format item takes the following form and consists of the following components:

{ index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

Infinity symbol with HTML

Use the HTML entity &infin; or &#8734;.

How to redirect Valgrind's output to a file?

By default, Valgrind writes its output to stderr. So you need to do something like:

valgrind a.out > log.txt 2>&1

Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).

Array length in angularjs returns undefined

Make it like this:

$scope.users.data.length;

Run a command shell in jenkins

This is happens because Jenkins is not aware about the shell path. In Manage Jenkins -> Configure System -> Shell, set the shell path as

  • C:\Windows\system32\cmd.exe

Display PNG image as response to jQuery AJAX request

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this:

$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');

Sort Array of object by object field in Angular 6

Try this

products.sort(function (a, b) {
  return a.title.rendered - b.title.rendered;
});

OR

You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.

Using underscore: (below one is just an example)

import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title'); 

Jquery validation plugin - TypeError: $(...).validate is not a function

If using VueJS, import all the js dependencies for jQuery extensions first, then import $ second...

import "../assets/js/jquery-2.2.3.min.js"
import "../assets/js/jquery-ui-1.12.1.min.js"
import "../assets/js/jquery.validate.min.js"
import $ from "jquery";

You then need to use jquery from a javascript function called from a custom wrapper defined globally in the VueJS prototype method.

This safeguards use of jQuery and jQuery UI from fighting with VueJS.

Vue.prototype.$fValidateTag = function( sTag, rRules ) 
{
    return ValidateTag( sTag, rRules );
};

function ValidateTag( sTag, rRules )
{
    Var rTagT = $( sTag );
    return rParentTag.validate( sTag, rRules );
}

How to create a multi line body in C# System.Net.Mail.MailMessage

Beginning each new line with two white spaces will avoid the auto-remove perpetrated by Outlook.

var lineString = "  line 1\r\n";
linestring += "  line 2";

Will correctly display:

line 1
line 2

It's a little clumsy feeling to use, but it does the job without a lot of extra effort being spent on it.

Check if EditText is empty.

You can use length() from EditText.

public boolean isEditTextEmpty(EditText mInput){
   return mInput.length() == 0;
}

printing all contents of array in C#

Starting from C# 6.0, when $ - string interpolation has been introduced, there is one more way:

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{string.Join(", ", array}");

//output
A, B, C

Concatenation could be archived using the System.Linq, convert the string[] to char[] and print as a string

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");

//output
ABC

How do I automatically update a timestamp in PostgreSQL

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

Is calculating an MD5 hash less CPU intensive than SHA family functions?

On my 2012 MacBook Air (Intel Core i5-3427U, 2x 1.8 GHz, 2.8 GHz Turbo), SHA-1 is slightly faster than MD5 (using OpenSSL in 64-bit mode):

$ openssl speed md5 sha1
OpenSSL 0.9.8r 8 Feb 2011
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              30055.02k    94158.96k   219602.97k   329008.21k   384150.47k
sha1             31261.12k    95676.48k   224357.36k   332756.21k   396864.62k

Update: 10 months later with OS X 10.9, SHA-1 got slower on the same machine:

$ openssl speed md5 sha1
OpenSSL 0.9.8y 5 Feb 2013
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              36277.35k   106558.04k   234680.17k   334469.33k   381756.70k
sha1             35453.52k    99530.85k   206635.24k   281695.48k   313881.86k

Second update: On OS X 10.10, SHA-1 speed is back to the 10.8 level:

$ openssl speed md5 sha1
OpenSSL 0.9.8zc 15 Oct 2014
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              35391.50k   104905.27k   229872.93k   330506.91k   382791.75k
sha1             38054.09k   110332.44k   238198.72k   340007.12k   387137.77k

Third update: OS X 10.14 with LibreSSL is a lot faster (still on the same machine). SHA-1 still comes out on top:

$ openssl speed md5 sha1
LibreSSL 2.6.5
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              43128.00k   131797.91k   304661.16k   453120.00k   526789.29k
sha1             55598.35k   157916.03k   343214.08k   489092.34k   570668.37k

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

I am facing the same issue. I am using 'Lumen' microservice framework. I recently resolved the same issue by installing two packages:-

  1. sudo apt-get install php7.0-mbstring,
  2. sudo apt-get install php7.0-xml or sudo apt-get install php-xml

After installing this, you need to execute this command:- composer update

Hope, it will resolve the issue. I work on my system.

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

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.

Is there a way to instantiate a class by name in Java?

Using newInstance() directly is deprecated as of Java 8. You need to use Class.getDeclaredConstructor(...).newInstance(...) with the corresponding exceptions.

How to force deletion of a python object?

Perhaps you are looking for a context manager?

>>> class Foo(object):
...   def __init__(self):
...     self.bar = None
...   def __enter__(self):
...     if self.bar != 'open':
...       print 'opening the bar'
...       self.bar = 'open'
...   def __exit__(self, type_, value, traceback):
...     if self.bar != 'closed':
...       print 'closing the bar', type_, value, traceback
...       self.bar = 'close'
... 
>>> 
>>> with Foo() as f:
...     # oh no something crashes the program
...     sys.exit(0)
... 
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>

How to call a View Controller programmatically?

Import the view controller class which you want to show and use the following code

KartViewController *viewKart = [[KartViewController alloc]initWithNibName:@"KartViewController" bundle:nil];
[self presentViewController:viewKart animated:YES completion:nil];

Best way to get application folder path

Root directory:

DriveInfo cDrive = new DriveInfo(System.Environment.CurrentDirectory);
var driverPath = cDrive.RootDirectory;

SQL Server: combining multiple rows into one row

CREATE VIEW  [dbo].[ret_vwSalariedForReport]
AS
     WITH temp1 AS (SELECT
     salaried.*,
     operationalUnits.Title as OperationalUnitTitle
FROM
    ret_vwSalaried salaried LEFT JOIN
    prs_operationalUnitFeatures operationalUnitFeatures on salaried.[Guid] = operationalUnitFeatures.[FeatureGuid] LEFT JOIN 
    prs_operationalUnits operationalUnits ON operationalUnits.id = operationalUnitFeatures.OperationalUnitID 
    ), 
temp2 AS (SELECT
    t2.*,
    STUFF ((SELECT ' - ' + t1.OperationalUnitTitle
        FROM
            temp1 t1 
        WHERE t1.[ID] = t2.[ID]  
        For XML PATH('')), 2, 2, '') OperationalUnitTitles from temp1 t2) 
SELECT 
    [Guid],
    ID,
    Title,
    PersonnelNo,
    FirstName,
    LastName,
    FullName,
    Active,
    SSN,
    DeathDate,
    SalariedType,
    OperationalUnitTitles
FROM 
    temp2
GROUP BY 
    [Guid],
    ID,
    Title,
    PersonnelNo,
    FirstName,
    LastName,
    FullName,
    Active,
    SSN,
    DeathDate,
    SalariedType,
    OperationalUnitTitles

Android TextView padding between lines

If you want padding between text try LineSpacingExtra="10dp"

<TextView
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:lineSpacingExtra="10dp"/>

Git list of staged files

You can Try using :- git ls-files -s

ASP.NET MVC get textbox input value

you can do it so simple:

First: For Example in Models you have User.cs with this implementation

public class User
 {
   public string username { get; set; }
   public string age { get; set; }
 } 

We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this

public ActionResult Add()
{
  var model = new User();
  return View(model);
}

When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:

@model MyApp.Models.Student
@using (Html.BeginForm()) 
 {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.username, htmlAttributes: new { 
                           @class = "control-label col-md-2" })
            <div class="col-md-10">
                 @Html.EditorFor(model => model.username, new { 
                                 htmlAttributes = new { @class = "form-
                                 control" } })
                 @Html.ValidationMessageFor(model => model.userame, "", 
                                            new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.age, htmlAttributes: new { @class 
                           = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.age, new { htmlAttributes = 
                                new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { 
                                           @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" 
                 />
            </div>
        </div>
   </div>
}

So on button submit you will use it like this

[HttpPost]
public ActionResult Add(User user)
 {
   // now user.username has the value that user entered on form
 }

Git Pull While Ignoring Local Changes?

shortest way to do it is:

git pull --rebase --autostash

What are the proper permissions for an upload folder with PHP/Apache?

Remember also CHOWN or chgrp your website folder. Try myusername# chown -R myusername:_www uploads

Update records in table from CTE

WITH CTE_DocTotal (DocTotal, InvoiceNumber)
AS
(
    SELECT  InvoiceNumber,
            SUM(Sale + VAT) AS DocTotal
    FROM    PEDI_InvoiceDetail
    GROUP BY InvoiceNumber
)    
UPDATE PEDI_InvoiceDetail
SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal
FROM CTE_DocTotal
INNER JOIN PEDI_InvoiceDetail ON ...

Automatically enter SSH password with script

In linux/ubuntu

ssh username@server_ip_address -p port_number

Press enter and then enter your server password

if you are not a root user then add sudo in starting of command

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

For SQL Reporting Services 2012 - SP1 and SharePoint 2013.

I got the same issue: The permissions granted to user '[AppPoolAccount]' are insufficient for performing this operation.

I went into the service application settings, clicked Key Management, then Change key and had it regenerate the key.

Using CSS in Laravel views?

Put them in public folder and call it in the view with something like href="{{ asset('public/css/style.css') }}". Note that the public should be included when you call the assets.

How do I create and store md5 passwords in mysql

you have to reason in terms of hased password:

store the password as md5('bob123'); when bob is register to your app

$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');

then, when bob is logging-in:

$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';

obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql

Initializing a struct to 0

See §6.7.9 Initialization:

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

So, yes both of them work. Note that in C99 a new way of initialization, called designated initialization can be used too:

myStruct _m1 = {.c2 = 0, .c1 = 1};

Remove last character from string. Swift language

Swift 4

var welcome = "Hello World!"
welcome = String(welcome[..<welcome.index(before:welcome.endIndex)])

or

welcome.remove(at: welcome.index(before: welcome.endIndex))

or

welcome = String(welcome.dropLast())

Is it possible to disable scrolling on a ViewPager

A simple solution is to create your own subclass of ViewPager that has a private boolean flag, isPagingEnabled. Then override the onTouchEvent and onInterceptTouchEvent methods. If isPagingEnabled equals true invoke the super method, otherwise return.

public class CustomViewPager extends ViewPager {

    private boolean isPagingEnabled = true;

    public CustomViewPager(Context context) {
        super(context);
    }

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

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onInterceptTouchEvent(event);
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }
}

Then in your Layout.XML file replace any <com.android.support.V4.ViewPager> tags with <com.yourpackage.CustomViewPager> tags.

This code was adapted from this blog post.

Pass Array Parameter in SqlCommand

I wanted to expand on the answer that Brian contributed to make this easily usable in other places.

/// <summary>
/// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
/// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN (returnValue))
/// </summary>
/// <param name="sqlCommand">The SqlCommand object to add parameters to.</param>
/// <param name="array">The array of strings that need to be added as parameters.</param>
/// <param name="paramName">What the parameter should be named.</param>
protected string AddArrayParameters(SqlCommand sqlCommand, string[] array, string paramName)
{
    /* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually. 
     * Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
     * IN statement in the CommandText.
     */
    var parameters = new string[array.Length];
    for (int i = 0; i < array.Length; i++)
    {
        parameters[i] = string.Format("@{0}{1}", paramName, i);
        sqlCommand.Parameters.AddWithValue(parameters[i], array[i]);
    }

    return string.Join(", ", parameters);
}

You can use this new function as follows:

SqlCommand cmd = new SqlCommand();

string ageParameters = AddArrayParameters(cmd, agesArray, "Age");
sql = string.Format("SELECT * FROM TableA WHERE Age IN ({0})", ageParameters);

cmd.CommandText = sql;


Edit: Here is a generic variation that works with an array of values of any type and is usable as an extension method:

public static class Extensions
{
    public static void AddArrayParameters<T>(this SqlCommand cmd, string name, IEnumerable<T> values) 
    { 
        name = name.StartsWith("@") ? name : "@" + name;
        var names = string.Join(", ", values.Select((value, i) => { 
            var paramName = name + i; 
            cmd.Parameters.AddWithValue(paramName, value); 
            return paramName; 
        })); 
        cmd.CommandText = cmd.CommandText.Replace(name, names); 
    }
}

You can then use this extension method as follows:

var ageList = new List<int> { 1, 3, 5, 7, 9, 11 };
var cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM MyTable WHERE Age IN (@Age)";    
cmd.AddArrayParameters("Age", ageList);

Make sure you set the CommandText before calling AddArrayParameters.

Also make sure your parameter name won't partially match anything else in your statement (i.e. @AgeOfChild)

Complexities of binary tree traversals

T(n) = 2T(n/2)+ c

T(n/2) = 2T(n/4) + c => T(n) = 4T(n/4) + 2c + c

similarly T(n) = 8T(n/8) + 4c+ 2c + c

....

....

last step ... T(n) = nT(1) + c(sum of powers of 2 from 0 to h(height of tree))

so Complexity is O(2^(h+1) -1)

but h = log(n)

so, O(2n - 1) = O(n)

How can I determine the current CPU utilization from the shell?

Maybe something like this

ps -eo pid,pcpu,comm

And if you like to parse and maybe only look at some processes.

#!/bin/sh
ps -eo pid,pcpu,comm | awk '{if ($2 > 4) print }' >> ~/ps_eo_test.txt

Failed to build gem native extension (installing Compass)

On Mac OS X 10.9, if you try xcode-select --install, you will get the following error :

Can't install the software because it is not currently available from the Software Update server.

The solution is to download Command Line Tools (OS X 10.9) directly from Apple website : https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-

You will then be able to install the last version of Command Line Tools.

How can I replace text with CSS?

I had an issue where I had to replace the text of link, but I couldn't use JavaScript nor could I directly change the text of a hyperlink as it was compiled down from XML. Also, I couldn't use pseudo elements, or they didn't seem to work when I had tried them.

Basically, I put the text I wanted into a span and put the anchor tag underneath it and wrapped both in a div. I basically moved the anchor tag up via CSS and then made the font transparent. Now when you hover over the span, it "acts" like a link. A really hacky way of doing this, but this is how you can have a link with different text...

This is a fiddle of how I got around this issue

My HTML

<div class="field">
    <span>This is your link text</span><br/>
    <a href="//www.google.com" target="_blank">This is your actual link</a>
</div>

My CSS

 div.field a {
     color: transparent;
     position: absolute;
     top:1%;
 }
 div.field span {
     display: inline-block;
 }

The CSS will need to change based off your requirements, but this is a general way of doing what you are asking.

Echo tab characters in bash script

Put your string between double quotes:

echo "[$res]"

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

Is it possible to use "return" in stored procedure?

In Stored procedure, you return the values using OUT parameter ONLY. As you have defined two variables in your example:

   outstaticip OUT VARCHAR2, outcount OUT NUMBER

Just assign the return values to the out parameters i.e. outstaticip and outcount and access them back from calling location. What I mean here is: when you call the stored procedure, you will be passing those two variables as well. After the stored procedure call, the variables will be populated with return values.

If you want to have RETURN value as return from the PL/SQL call, then use FUNCTION. Please note that in case, you would be able to return only one variable as return variable.

CFNetwork SSLHandshake failed iOS 9

In iOS 10+, the TLS string MUST be of the form "TLSv1.0". It can't just be "1.0". (Sigh)


The following combination of the other Answers works.

Let's say you are trying to connect to a host (YOUR_HOST.COM) that only has TLS 1.0.

Add these to your app's Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>YOUR_HOST.COM</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.0</string>
            <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
    </dict>
</dict>

Index inside map() function

Using Ramda:

import {addIndex, map} from 'ramda';

const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return 'X';
}, list);

What is the difference between VFAT and FAT32 file systems?

Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx

What's FAT?

FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.

The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.

What About VFAT?

Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.

When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.

An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.

You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.

FAT32

FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.

The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.

This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.

Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.

Note: This section of the quote/ article (1999) is out of date. Updated info quote below.

As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.

The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.

Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.

Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):

I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.

The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.

The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.

Take screenshots in the iOS simulator

First, run the app on simulator. Then, use command+s, or File -> Save Screenshot in Simulator to take necessary and appropriate shots. The screenshots will appear on your desktop by default.

How to solve static declaration follows non-static declaration in GCC C code?

While gcc 3.2.3 was more forgiving of the issue, gcc 4.1.2 is highlighting a potentially serious issue for the linking of your program later. Rather then trying to suppress the error you should make the forward declaration match the function declaration.

If you intended for the function to be globally available (as per the forward declaration) then don't subsequently declare it as static. Likewise if it's indented to be locally scoped then make the forward declaration static to match.

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

The way that works for me is to

  1. Go to Integration Request
  2. click URL Query String Parameters
  3. click Add query string
  4. in name field put the query name, which is "name" here
  5. in Mapped From field, put "method.request.querystring.name"

How add class='active' to html menu with php

Your index.php code is correct. I am including the updated code for common.php below then I will explain the differences.

<?php 
     $class = ($page == 'one') ? 'class="active"' : '';
     $nav = <<<EOD
        <div id="nav">
            <ul>
               <li><a $class href="index.php">Tab1</a>/</li>
               <li><a href="two.php">Tab2</a></li>
               <li><a href="three.php">Tab3</a></li>
           </ul>
        </div>
 EOD;
 ?>

The first issue is that you need to make sure that the end declaration for your heredoc -- EOD; -- is not indented at all. If it is indented, then you will get errors.

As for your issue with the PHP code not running within the heredoc statement, that is because you are looking at it wrong. Using a heredoc statement is not the same as closing the PHP tags. As such, you do not need to try reopening them. That will do nothing for you. The way the heredoc syntax works is that everything between the opening and closing is displayed exactly as written with the exception of variables. Those are replaced with the associated value. I removed your logic from the heredoc and used a tertiary function to determine the class to make this easier to see (though I don't believe any logical statements will work within the heredoc anyway)

To understand the heredoc syntax, it is the same as including it within double quotes ("), but without the need for escaping. So your code could also be written like this:

<?php 
     $class = ($page == 'one') ? 'class="active"' : '';
     $nav = "<div id=\"nav\">
            <ul>
               <li><a $class href=\"index.php\">Tab1</a>/</li>
               <li><a href=\"two.php\">Tab2</a></li>
               <li><a href=\"three.php\">Tab3</a></li>
           </ul>
        </div>";
 ?>

It will do exactly the same thing, just is written somewhat differently. Another difference between heredoc and the string is that you can escape out of the string in the middle where you can't in the heredoc. Using this logic, you can produce the following code:

<?php 
     $nav = "<div id=\"nav\">
            <ul>
               <li><a ".(($page == 'one') ? 'class="active"' : '')." href=\"index.php\">Tab1</a>/</li>
               <li><a href=\"two.php\">Tab2</a></li>
               <li><a href=\"three.php\">Tab3</a></li>
           </ul>
        </div>";
 ?>

Then you can include the logic directly in the string like you originally intended.

Whichever method you choose makes very little (if any) difference in the performance of the script. It mostly boils down to preference. Either way, you need to make sure you understand how each works.

LINQ - Left Join, Group By, and Count

LATE ANSWER:

You shouldn't need the left join at all if all you're doing is Count(). Note that join...into is actually translated to GroupJoin which returns groupings like new{parent,IEnumerable<child>} so you just need to call Count() on the group:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into g
select new { ParentId = p.Id, Count = g.Count() }

In Extension Method syntax a join into is equivalent to GroupJoin (while a join without an into is Join):

context.ParentTable
    .GroupJoin(
                   inner: context.ChildTable
        outerKeySelector: parent => parent.ParentId,
        innerKeySelector: child => child.ParentId,
          resultSelector: (parent, children) => new { parent.Id, Count = children.Count() }
    );

Get all files and directories in specific path fast

There is a long history of the .NET file enumeration methods being slow. The issue is there is not an instantaneous way of enumerating large directory structures. Even the accepted answer here has its issues with GC allocations.

The best I've been able to do is wrapped up in my library and exposed as the FindFile (source) class in the CSharpTest.Net.IO namespace. This class can enumerate files and folders without unneeded GC allocations and string marshalling.

The usage is simple enough, and the RaiseOnAccessDenied property will skip the directories and files the user does not have access to:

    private static long SizeOf(string directory)
    {
        var fcounter = new CSharpTest.Net.IO.FindFile(directory, "*", true, true, true);
        fcounter.RaiseOnAccessDenied = false;

        long size = 0, total = 0;
        fcounter.FileFound +=
            (o, e) =>
            {
                if (!e.IsDirectory)
                {
                    Interlocked.Increment(ref total);
                    size += e.Length;
                }
            };

        Stopwatch sw = Stopwatch.StartNew();
        fcounter.Find();
        Console.WriteLine("Enumerated {0:n0} files totaling {1:n0} bytes in {2:n3} seconds.",
                          total, size, sw.Elapsed.TotalSeconds);
        return size;
    }

For my local C:\ drive this outputs the following:

Enumerated 810,046 files totaling 307,707,792,662 bytes in 232.876 seconds.

Your mileage may vary by drive speed, but this is the fastest method I've found of enumerating files in managed code. The event parameter is a mutating class of type FindFile.FileFoundEventArgs so be sure you do not keep a reference to it as it's values will change for each event raised.

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

.htaccess - how to force "www." in a generic way?

The following should prefix 'www' to any request that doesn't have one, and redirect the edited request to the new URI.

RewriteCond "%{HTTP_HOST}" "!^www\."         [NC]
RewriteCond "%{HTTP_HOST}" "(.*)"
RewriteRule "(.*)"         "http://www.%1$1" [R=301,L]

How do I make a simple makefile for gcc on Linux?

For example this simple Makefile should be sufficient:

CC=gcc 
CFLAGS=-Wall

all: program
program: program.o
program.o: program.c program.h headers.h

clean:
    rm -f program program.o
run: program
    ./program

Note there must be <tab> on the next line after clean and run, not spaces.

UPDATE Comments below applied

Incorrect integer value: '' for column 'id' at row 1

That probably means that your id is an AUTO_INCREMENT integer and you're trying to send a string. You should specify a column list and omit it from your INSERT.

INSERT INTO workorders (column1, column2) VALUES ($column1, $column2)

Appropriate datatype for holding percent values?

If 2 decimal places is your level of precision, then a "smallint" would handle this in the smallest space (2-bytes). You store the percent multiplied by 100.

EDIT: The decimal type is probably a better match. Then you don't need to manually scale. It takes 5 bytes per value.

How to remove all elements in String array in java?

example = new String[example.length];

If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.

RedirectToAction with parameter

You can pass the id as part of the routeValues parameter of the RedirectToAction() method.

return RedirectToAction("Action", new { id = 99 });

This will cause a redirect to Site/Controller/Action/99. No need for temp or any kind of view data.

How to execute my SQL query in CodeIgniter

$this->db->select('id, name, price, author, category, language, ISBN, publish_date');

       $this->db->from('tbl_books');

finished with non zero exit value

I ran to same problem today and try to clean and rebuild project.

I did not solve my problem. I got it solved with change the compileSdkVersion, buildToolsVersion, targetSdkVersion and com.android.support:appcompat-v7:23.0.1 values instead on my Gradle app file. Then I ran clean and rebuild the project afterwards.

Most Useful Attributes

If I were to do a code coverage crawl, I think these two would be top:

 [Serializable]
 [WebMethod]

Angular ReactiveForms: Producing an array of checkbox values?

With the help of silentsod answer, I wrote a solution to get values instead of states in my formBuilder.

I use a method to add or remove values in the formArray. It may be a bad approch, but it works !

component.html

<div *ngFor="let choice of checks; let i=index" class="col-md-2">
  <label>
    <input type="checkbox" [value]="choice.value" (change)="onCheckChange($event)">
    {{choice.description}}
  </label>
</div>

component.ts

// For example, an array of choices
public checks: Array<ChoiceClass> = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}
];

initModelForm(): FormGroup{
  return this._fb.group({
    otherControls: [''],
    // The formArray, empty 
    myChoices: new FormArray([]),
  }
}

onCheckChange(event) {
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
  if(event.target.checked){
    // Add a new control in the arrayForm
    formArray.push(new FormControl(event.target.value));
  }
  /* unselected */
  else{
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == event.target.value) {
        // Remove the unselected element from the arrayForm
        formArray.removeAt(i);
        return;
      }

      i++;
    });
  }
}

When I submit my form, for example my model looks like:

  otherControls : "foo",
  myChoices : ['value1', 'value2']

Only one thing is missing, a function to fill the formArray if your model already has checked values.

The type or namespace name 'DbContext' could not be found

Right click your reference and go to manage NuGet packages, then choose online all, then NuGet package source in the search textbox type Entity Framework and install it.

MaxLength Attribute not generating client-side validation attributes

I know I am very late to the party, but I finaly found out how we can register the MaxLengthAttribute.

First we need a validator:

public class MaxLengthClientValidator : DataAnnotationsModelValidator<MaxLengthAttribute>
{
    private readonly string _errorMessage;
    private readonly int _length;


    public MaxLengthClientValidator(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute)
    : base(metadata, context, attribute)
    {
        _errorMessage = attribute.FormatErrorMessage(metadata.DisplayName);
        _length = attribute.Length;
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = _errorMessage,
            ValidationType = "length"
        };

        rule.ValidationParameters["max"] = _length;
        yield return rule;
    }
}

Nothing realy special. In the constructor we save some values from the attribute. In the GetClientValidationRules we set a rule. ValidationType = "length" is mapped to data-val-length by the framework. rule.ValidationParameters["max"] is for the data-val-length-max attribute.

Now since you have a validator, you only need to register it in global.asax:

protected void Application_Start()
{
    //...

    //Register Validator
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator));
}

Et voila, it just works.

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

How can I work with command line on synology?

The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.

Launch Powershell or CMD, enter ssh yourAccountName@diskstation

The first time it will cache off your certificate.

EDIT:

Further detailed explanations can be found on the synology docs page:

How to login to DSM with root permission via SSH Telnet

how to remove css property using javascript?

To change all classes for an element:

document.getElementById("ElementID").className = "CssClass";

To add an additional class to an element:

document.getElementById("ElementID").className += " CssClass";

To check if a class is already applied to an element:

if ( document.getElementById("ElementID").className.match(/(?:^|\s)CssClass(?!\S)/) )

Git clone without .git directory

Use

git clone --depth=1 --branch=master git://someserver/somerepo dirformynewrepo
rm -rf ./dirformynewrepo/.git
  • The depth option will make sure to copy the least bit of history possible to get that repo.
  • The branch option is optional and if not specified would get master.
  • The second line will make your directory dirformynewrepo not a Git repository any more.
  • If you're doing recursive submodule clone, the depth and branch parameter don't apply to the submodules.

Check for false

Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.

if(!(borrar() === false))

or

if(borrar() === true)

getaddrinfo: nodename nor servname provided, or not known

I fixed this problem simply by closing and reopening the Terminal.

Pass accepts header parameter to jquery ajax

I use jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] ) for example:

var url="my.php";
$.getJSON( url, myObj )
.done(function( json ) { ... }) /* got JSON from server */
.fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Failed to obtain JSON data from server: " + err );
  }); /* failed to get JSON */

getJSON is shorthand for:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

How to capture a backspace on the onkeydown event

In your function check for the keycode 8 (backspace) or 46 (delete)

Keycode information
Keycode list

What is the difference between primary, unique and foreign key constraints, and indexes?

Primary Key and Unique Key are Entity integrity constraints

Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist and no null values are entered.

Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values. (In oracle one null is not equal to another null).

  • KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any structure on your data so they are used only for speeding up queries.
  • UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to speed up queries, UNIQUE indexes can be used to enforce structure on data, because the database system does not allow this distinct values rule to be broken when inserting or updating data. Your database system may allow a UNIQUE index on columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (NULL is considered not equal to itself), though this is probably undesirable depending on your application.
  • PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a way to uniquely identify any row in the table, so it shouldn't be used on any columns which allow NULL values. Your PRIMARY index should always be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.
  • FULLTEXT indexes are different to all of the above, and their behaviour differs more between database systems. Unlike the above three, which are typically b-tree (allowing for selecting, sorting or ranges starting from left most column) or hash (allowing for selection starting from left most column), FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause.

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

How to implement a binary search tree in Python?

I find the solutions a bit clumsy on the insert part. You could return the root reference and simplify it a bit:

def binary_insert(root, node):
    if root is None:
        return node
    if root.data > node.data:
        root.l_child = binary_insert(root.l_child, node)
    else:
        root.r_child = binary_insert(root.r_child, node)
    return root

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Activating Anaconda Environment in VsCode

Simply use

  1. shift + cmd + P
  2. Search Select Interpreter

pyhton : Select Interpreter

  1. Select it and it will show you the list of your virtual environment created via conda and other python versions

Activating conda virtual environment

  1. select the environment and you are ready to go.

Quoting the 'Select and activate an environment' docs

Selecting an interpreter from the list adds an entry for python.pythonPath with
the path to the interpreter inside your Workspace Settings.

Icons missing in jQuery UI

I met a similar error after adding jQuery-ui-tooltip component using bower. It downloads js + css files only, so I had to manually add images.

A good source to find all the images (for all standard themes) is this CDN.

Excel SUMIF between dates

You haven't got your SUMIF in the correct order - it needs to be range, criteria, sum range. Try:

=SUMIF(A:A,">="&DATE(2012,1,1),B:B)

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

How to recover MySQL database from .myd, .myi, .frm files

I found a solution for converting the files to a .sql file (you can then import the .sql file to a server and recover the database), without needing to access the /var directory, therefore you do not need to be a server admin to do this either.

It does require XAMPP or MAMP installed on your computer.

  • After you have installed XAMPP, navigate to the install directory (Usually C:\XAMPP), and the the sub-directory mysql\data. The full path should be C:\XAMPP\mysql\data
  • Inside you will see folders of any other databases you have created. Copy & Paste the folder full of .myd, .myi and .frm files into there. The path to that folder should be

    C:\XAMPP\mysql\data\foldername\.mydfiles

  • Then visit localhost/phpmyadmin in a browser. Select the database you have just pasted into the mysql\data folder, and click on Export in the navigation bar. Chooses the export it as a .sql file. It will then pop up asking where the save the file

And that is it! You (should) now have a .sql file containing the database that was originally .myd, .myi and .frm files. You can then import it to another server through phpMyAdmin by creating a new database and pressing 'Import' in the navigation bar, then following the steps to import it

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

You are somehow using wrong AWS Credentials (AccessKey and SecretKey) of AWS Account. So make sure they are correct else you need to create new and use them - in that case may be @Prakash answer is good for you

What is the best way to prevent session hijacking?

There are many ways to create protection against session hijack, however all of them are either reducing user satisfaction or are not secure.

  • IP and/or X-FORWARDED-FOR checks. These work, and are pretty secure... but imagine the pain of users. They come to an office with WiFi, they get new IP address and lose the session. Got to log-in again.

  • User Agent checks. Same as above, new version of browser is out, and you lose a session. Additionally, these are really easy to "hack". It's trivial for hackers to send fake UA strings.

  • localStorage token. On log-on generate a token, store it in browser storage and store it to encrypted cookie (encrypted on server-side). This has no side-effects for user (localStorage persists through browser upgrades). It's not as secure - as it's just security through obscurity. Additionally you could add some logic (encryption/decryption) to JS to further obscure it.

  • Cookie reissuing. This is probably the right way to do it. The trick is to only allow one client to use a cookie at a time. So, active user will have cookie re-issued every hour or less. Old cookie is invalidated if new one is issued. Hacks are still possible, but much harder to do - either hacker or valid user will get access rejected.

sys.argv[1], IndexError: list index out of range

sys.argv represents the command line options you execute a script with.

sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

You are attempting to open a file that uses sys.argv[1] (the first argument) as what looks to be the directory.

Try running something like this:

python ConcatenateFiles.py /tmp

SVN "Already Locked Error"

Sometimes cleaning the repository with the "break locks"-option still doesn't work if the lock was created by another process. Possible Solution: 1) Acquire a new lock on the folder/file and choose the option "Steal the locks" 2) Release your new lock.

Print a file, skipping the first X lines, in Bash

Use the sed delete command with a range address. For example:

sed 1,100d file.txt # Print file.txt omitting lines 1-100.

Alternatively, if you want to only print a known range, use the print command with the -n flag:

sed -n 201,300p file.txt # Print lines 201-300 from file.txt

This solution should work reliably on all Unix systems, regardless of the presence of GNU utilities.

Specifying number of decimal places in Python

There's a few ways to do this depending on how you want to hold the value.

You can use basic string formatting, e.g

'Your Meal Price is %.2f' %  mealPrice

You can modify the 2 to whatever precision you need.

However, since you're dealing with money you should look into the decimal module which has a cool method named quantize which is exactly for working with monetary applications. You can use it like so:

from decimal import Decimal, ROUND_DOWN
mealPrice = Decimal(str(mealPrice)).quantize(Decimal('.01'), rounding=ROUND_DOWN)

Note that the rounding attribute is purely optional as well.

Where does forever store console.log output?

Help is your best saviour, there is a logs action that you can call to check logs for all running processes.

forever --help

Shows the commands

logs                Lists log files for all forever processes
logs <script|index> Tails the logs for <script|index>

Sample output of the above command, for three processes running. console.log output's are stored in these logs.

info:    Logs for running Forever processes
data:        script    logfile
data:    [0] server.js /root/.forever/79ao.log
data:    [1] server.js /root/.forever/ZcOk.log
data:    [2] server.js /root/.forever/L30K.log

iPad browser WIDTH & HEIGHT standard

The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.

When page has no meta viewport tag:

  • Portrait: 980x1208
  • Landscape: 980x661

When page has either of these two meta tags:

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">

  • Portrait: 768x946
  • Landscape: 1024x690

With <meta name="viewport" content="width=device-width">:

  • Portrait: 768x946
  • Landscape: 768x518

With <meta name="viewport" content="height=device-height">:

  • Portrait: 980x1024
  • Landscape: 980x1024

With <meta name="viewport" content="height=device-height,width=device-width">:

  • Portrait: 768x1024
  • Landscape: 768x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">

  • Portrait: 768x1024
  • Landscape: 1024x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">

  • Portrait: 831x1024
  • Landscape: 1520x1024

Regular expression to return text between parenthesis

No need to use regex .... Just use list slicing ...

string="(tidtkdgkxkxlgxlhxl) ¥£%#_¥#_¥#_¥#"
print(string[string.find("(")+1:string.find(")")])

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

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

Summary & TL;DR:

This answer hopes to be a comprehensive wrap-up of information from other answers.

The very short version, given the data from the question plus a couple extras:

flat_array   = [  apple, 1,   banana, 2  ] # count=4
nested_array = [ [apple, 1], [banana, 2] ] # count=2 of count=2 k,v arrays
incomplete_f = [  apple, 1,   banana     ] # count=3 - missing last value
incomplete_n = [ [apple, 1], [banana   ] ] # count=2 of either k or k,v arrays


# there's one option for flat_array:
h1  = Hash[*flat_array]                     # => {apple=>1, banana=>2}

# two options for nested_array:
h2a = nested_array.to_h # since ruby 2.1.0    => {apple=>1, banana=>2}
h2b = Hash[nested_array]                    # => {apple=>1, banana=>2}

# ok if *only* the last value is missing:
h3  = Hash[incomplete_f.each_slice(2).to_a] # => {apple=>1, banana=>nil}
# always ok for k without v in nested array:
h4  = Hash[incomplete_n] # or .to_h           => {apple=>1, banana=>nil}

# as one might expect:
h1 == h2a # => true
h1 == h2b # => true
h1 == h3  # => false
h3 == h4  # => true

Discussion and details follow.


Setup: variables

In order to show the data we'll be using up front, I'll create some variables to represent various possibilities for the data. They fit into the following categories:

Based on what was directly in the question, as a1 and a2:

(Note: I presume that apple and banana were meant to represent variables. As others have done, I'll be using strings from here on so that input and results can match.)

a1 = [  'apple', 1 ,  'banana', 2  ] # flat input
a2 = [ ['apple', 1], ['banana', 2] ] # key/value paired input

Multi-value keys and/or values, as a3:

In some other answers, another possibility was presented (which I expand on here) – keys and/or values may be arrays on their own:

a3 = [ [ 'apple',                   1   ],
       [ 'banana',                  2   ],
       [ ['orange','seedless'],     3   ],
       [ 'pear',                 [4, 5] ],
     ]

Unbalanced array, as a4:

For good measure, I thought I'd add one for a case where we might have an incomplete input:

a4 = [ [ 'apple',                   1],
       [ 'banana',                  2],
       [ ['orange','seedless'],     3],
       [ 'durian'                    ], # a spiky fruit pricks us: no value!
     ]

Now, to work:

Starting with an initially-flat array, a1:

Some have suggested using #to_h (which showed up in Ruby 2.1.0, and can be backported to earlier versions). For an initially-flat array, this doesn't work:

a1.to_h   # => TypeError: wrong element type String at 0 (expected array)

Using Hash::[] combined with the splat operator does:

Hash[*a1] # => {"apple"=>1, "banana"=>2}

So that's the solution for the simple case represented by a1.

With an array of key/value pair arrays, a2:

With an array of [key,value] type arrays, there are two ways to go.

First, Hash::[] still works (as it did with *a1):

Hash[a2] # => {"apple"=>1, "banana"=>2}

And then also #to_h works now:

a2.to_h  # => {"apple"=>1, "banana"=>2}

So, two easy answers for the simple nested array case.

This remains true even with sub-arrays as keys or values, as with a3:

Hash[a3] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]} 
a3.to_h  # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}

But durians have spikes (anomalous structures give problems):

If we've gotten input data that's not balanced, we'll run into problems with #to_h:

a4.to_h  # => ArgumentError: wrong array length at 3 (expected 2, was 1)

But Hash::[] still works, just setting nil as the value for durian (and any other array element in a4 that's just a 1-value array):

Hash[a4] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}

Flattening - using new variables a5 and a6

A few other answers mentioned flatten, with or without a 1 argument, so let's create some new variables:

a5 = a4.flatten
# => ["apple", 1, "banana", 2,  "orange", "seedless" , 3, "durian"] 
a6 = a4.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian"] 

I chose to use a4 as the base data because of the balance problem we had, which showed up with a4.to_h. I figure calling flatten might be one approach someone might use to try to solve that, which might look like the following.

flatten without arguments (a5):

Hash[*a5]       # => {"apple"=>1, "banana"=>2, "orange"=>"seedless", 3=>"durian"}
# (This is the same as calling `Hash[*a4.flatten]`.)

At a naïve glance, this appears to work – but it got us off on the wrong foot with the seedless oranges, thus also making 3 a key and durian a value.

And this, as with a1, just doesn't work:

a5.to_h # => TypeError: wrong element type String at 0 (expected array)

So a4.flatten isn't useful to us, we'd just want to use Hash[a4]

The flatten(1) case (a6):

But what about only partially flattening? It's worth noting that calling Hash::[] using splat on the partially-flattened array (a6) is not the same as calling Hash[a4]:

Hash[*a6] # => ArgumentError: odd number of arguments for Hash

Pre-flattened array, still nested (alternate way of getting a6):

But what if this was how we'd gotten the array in the first place? (That is, comparably to a1, it was our input data - just this time some of the data can be arrays or other objects.) We've seen that Hash[*a6] doesn't work, but what if we still wanted to get the behavior where the last element (important! see below) acted as a key for a nil value?

In such a situation, there's still a way to do this, using Enumerable#each_slice to get ourselves back to key/value pairs as elements in the outer array:

a7 = a6.each_slice(2).to_a
# => [["apple", 1], ["banana", 2], [["orange", "seedless"], 3], ["durian"]] 

Note that this ends up getting us a new array that isn't "identical" to a4, but does have the same values:

a4.equal?(a7) # => false
a4 == a7      # => true

And thus we can again use Hash::[]:

Hash[a7] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
# or Hash[a6.each_slice(2).to_a]

But there's a problem!

It's important to note that the each_slice(2) solution only gets things back to sanity if the last key was the one missing a value. If we later added an extra key/value pair:

a4_plus = a4.dup # just to have a new-but-related variable name
a4_plus.push(['lychee', 4])
# => [["apple",                1],
#     ["banana",               2],
#     [["orange", "seedless"], 3], # multi-value key
#     ["durian"],              # missing value
#     ["lychee", 4]]           # new well-formed item

a6_plus = a4_plus.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian", "lychee", 4]

a7_plus = a6_plus.each_slice(2).to_a
# => [["apple",                1],
#     ["banana",               2],
#     [["orange", "seedless"], 3], # so far so good
#     ["durian",               "lychee"], # oops! key became value!
#     [4]]                     # and we still have a key without a value

a4_plus == a7_plus # => false, unlike a4 == a7

And the two hashes we'd get from this are different in important ways:

ap Hash[a4_plus] # prints:
{
                     "apple" => 1,
                    "banana" => 2,
    [ "orange", "seedless" ] => 3,
                    "durian" => nil, # correct
                    "lychee" => 4    # correct
}

ap Hash[a7_plus] # prints:
{
                     "apple" => 1,
                    "banana" => 2,
    [ "orange", "seedless" ] => 3,
                    "durian" => "lychee", # incorrect
                           4 => nil       # incorrect
}

(Note: I'm using awesome_print's ap just to make it easier to show the structure here; there's no conceptual requirement for this.)

So the each_slice solution to an unbalanced flat input only works if the unbalanced bit is at the very end.


Take-aways:

  1. Whenever possible, set up input to these things as [key, value] pairs (a sub-array for each item in the outer array).
  2. When you can indeed do that, either #to_h or Hash::[] will both work.
  3. If you're unable to, Hash::[] combined with the splat (*) will work, so long as inputs are balanced.
  4. With an unbalanced and flat array as input, the only way this will work at all reasonably is if the last value item is the only one that's missing.

Side-note: I'm posting this answer because I feel there's value to be added – some of the existing answers have incorrect information, and none (that I read) gave as complete an answer as I'm endeavoring to do here. I hope that it's helpful. I nevertheless give thanks to those who came before me, several of whom provided inspiration for portions of this answer.

Java: parse int value from a char

Try the following:

str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;

if u subtract by char '0', the ASCII value needs not to be known.

How do I explicitly specify a Model's table-name mapping in Rails?

Rails >= 3.2 (including Rails 4+ and 5+):

class Countries < ActiveRecord::Base
  self.table_name = "cc"
end

Rails <= 3.1:

class Countries < ActiveRecord::Base
  self.set_table_name "cc"
  ...
end

Getting a slice of keys from a map

This is an old question, but here's my two cents. PeterSO's answer is slightly more concise, but slightly less efficient. You already know how big it's going to be so you don't even need to use append:

keys := make([]int, len(mymap))

i := 0
for k := range mymap {
    keys[i] = k
    i++
}

In most situations it probably won't make much of a difference, but it's not much more work, and in my tests (using a map with 1,000,000 random int64 keys and then generating the array of keys ten times with each method), it was about 20% faster to assign members of the array directly than to use append.

Although setting the capacity eliminates reallocations, append still has to do extra work to check if you've reached capacity on each append.

Create an application setup in visual studio 2013

Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.

visual-studio-installer-projects-extension

jQuery how to find an element based on a data-attribute value?

I have faced the same issue while fetching elements using jQuery and data-* attribute.

so for your reference the shortest code is here:

This is my HTML Code:

<section data-js="carousel"></section>
<section></section>
<section></section>
<section data-js="carousel"></section>

This is my jQuery selector:

$('section[data-js="carousel"]');
// this will return array of the section elements which has data-js="carousel" attribute.

Group list by values

>>> xs = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> xs.sort(key=lambda x: x[1])
>>> reduce(lambda l, x: (l.append([x]) if l[-1][0][1] != x[1] else l[-1].append(x)) or l, xs[1:], [[xs[0]]]) if xs else []
[[['A', 0], ['C', 0]], [['B', 1]], [['D', 2], ['E', 2]]]

Basically, if the list is sorted, it is possible to reduce by looking at the last group constructed by the previous steps - you can tell if you need to start a new group, or modify an existing group. The ... or l bit is a trick that enables us to use lambda in Python. (append returns None. It is always better to return something more useful than None, but, alas, such is Python.)

Getting Java version at runtime

Here's the implementation in JOSM:

/**
 * Returns the Java version as an int value.
 * @return the Java version as an int value (8, 9, etc.)
 * @since 12130
 */
public static int getJavaVersion() {
    String version = System.getProperty("java.version");
    if (version.startsWith("1.")) {
        version = version.substring(2);
    }
    // Allow these formats:
    // 1.8.0_72-ea
    // 9-ea
    // 9
    // 9.0.1
    int dotPos = version.indexOf('.');
    int dashPos = version.indexOf('-');
    return Integer.parseInt(version.substring(0,
            dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : 1));
}

Use of contains in Java ArrayList<String>

You are right that it should work; perhaps you forgot to instantiate something. Does your code look something like this?

String rssFeedURL = "http://stackoverflow.com";
this.rssFeedURLS = new ArrayList<String>();
this.rssFeedURLS.add(rssFeedURL);
if(this.rssFeedURLs.contains(rssFeedURL)) {
// this code will execute
}

For reference, note that the following conditional will also execute if you append this code to the above:

String copyURL = new String(rssFeedURL);
if(this.rssFeedURLs.contains(copyURL)) {
// code will still execute because contains() checks equals()
}

Even though (rssFeedURL == copyURL) is false, rssFeedURL.equals(copyURL) is true. The contains method cares about the equals method.

Maven: add a dependency to a jar by relative path

I've previously written about a pattern for doing this.

It is very similar to the solution proposed by Pascal, though it moves all such dependencies into a dedicated repository module so that you don't have to repeat it everywhere the dependency is used if it is a multi-module build.

getResourceAsStream() vs FileInputStream

FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process. Usually in a web container, this is something like the bin folder.

getResourceAsStream() will load a file path relative from your application's classpath.

What is the difference between a static method and a non-static method?

Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:

MyClass.myMethod();
this.myMethod();
myMethod();

Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:

MyClass boston = new MyClassConstructor(); 
boston.myMethod("bostonURL");

MyClass miami = new MyClassConstructor(); 
miami.myMethod("miamiURL");

MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");

In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.

If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.

Use of 'prototype' vs. 'this' in JavaScript?

The ultimate problem with using this instead of prototype is that when overriding a method, the constructor of the base class will still refer to the overridden method. Consider this:

BaseClass = function() {
    var text = null;

    this.setText = function(value) {
        text = value + " BaseClass!";
    };

    this.getText = function() {
        return text;
    };

    this.setText("Hello"); // This always calls BaseClass.setText()
};

SubClass = function() {
    // setText is not overridden yet,
    // so the constructor calls the superclass' method
    BaseClass.call(this);

    // Keeping a reference to the superclass' method
    var super_setText = this.setText;
    // Overriding
    this.setText = function(value) {
        super_setText.call(this, "SubClass says: " + value);
    };
};
SubClass.prototype = new BaseClass();

var subClass = new SubClass();
console.log(subClass.getText()); // Hello BaseClass!

subClass.setText("Hello"); // setText is already overridden
console.log(subClass.getText()); // SubClass says: Hello BaseClass!

versus:

BaseClass = function() {
    this.setText("Hello"); // This calls the overridden method
};

BaseClass.prototype.setText = function(value) {
    this.text = value + " BaseClass!";
};

BaseClass.prototype.getText = function() {
    return this.text;
};

SubClass = function() {
    // setText is already overridden, so this works as expected
    BaseClass.call(this);
};
SubClass.prototype = new BaseClass();

SubClass.prototype.setText = function(value) {
    BaseClass.prototype.setText.call(this, "SubClass says: " + value);
};

var subClass = new SubClass();
console.log(subClass.getText()); // SubClass says: Hello BaseClass!

If you think this is not a problem, then it depends on whether you can live without private variables, and whether you are experienced enough to know a leak when you see one. Also, having to put the constructor logic after the method definitions is inconvenient.

var A = function (param1) {
    var privateVar = null; // Private variable

    // Calling this.setPrivateVar(param1) here would be an error

    this.setPrivateVar = function (value) {
        privateVar = value;
        console.log("setPrivateVar value set to: " + value);

        // param1 is still here, possible memory leak
        console.log("setPrivateVar has param1: " + param1);
    };

    // The constructor logic starts here possibly after
    // many lines of code that define methods

    this.setPrivateVar(param1); // This is valid
};

var a = new A(0);
// setPrivateVar value set to: 0
// setPrivateVar has param1: 0

a.setPrivateVar(1);
//setPrivateVar value set to: 1
//setPrivateVar has param1: 0

versus:

var A = function (param1) {
    this.setPublicVar(param1); // This is valid
};
A.prototype.setPublicVar = function (value) {
    this.publicVar = value; // No private variable
};

var a = new A(0);
a.setPublicVar(1);
console.log(a.publicVar); // 1

How do you round a number to two decimal places in C#?

  public double RoundDown(double number, int decimalPlaces)
        {
            return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
        }

Can an Option in a Select tag carry multiple values?

In HTML

<SELECT NAME="Testing" id="Testing">  
  <OPTION VALUE="1,2010"> One  
  <OPTION VALUE="2,2122"> Two  
  <OPTION VALUE="3,0"> Three
</SELECT>

For JS

  var valueOne= $('#Testing').val().split(',')[0];
  var valueTwo =$('#Testing').val().split(',')[1];
  console.log(valueOne); //output 1
  console.log(valueTwo); //output 2010

OR FOR PHP

  $selectedValue= explode(',', $value);
  $valueOne= $exploded_value[0]; //output 1
  $valueTwo= $exploded_value[1]; //output 2010

Find length of 2D array Python

You can use numpy.shape.

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])

Result:

>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.shape(x)
(3, 2)

First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

After using following load balancer setting my problem solved for wss but for ws problem still exists for specific one ISP.

calssic-load-balancer

How to create checkbox inside dropdown?

You can always use multiple or multiple = "true" option with a select tag, but there is one jquery plugin which makes it more beautiful. It is called chosen and can be found here.

This fiddle-example might help you to get started

Thank you.

PHP how to get the base domain/url?

Use parse_url() like this:

function url(){
    if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }
    else{
        $protocol = 'http';
    }
    return $protocol . "://" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_HOST);
}

Here is another shorter option:

function url(){
    $pu = parse_url($_SERVER['REQUEST_URI']);
    return $pu["scheme"] . "://" . $pu["host"];
}

Find provisioning profile in Xcode 5

xCode 6 allows you to right click on the provisioning profile under account -> detail (the screen shot you have there) & shows a popup "show in finder".