Programs & Examples On #Keypreview

Simple InputBox function

The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.

$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString

This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:

[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

If the info does not need to be secure at all you can convert it to plain text:

$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))

Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0

Up, Down, Left and Right arrow keys do not trigger KeyDown event

In order to capture keystrokes in a Forms control, you must derive a new class that is based on the class of the control that you want, and you override the ProcessCmdKey().

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //handle your keys here
}

Example :

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //capture up arrow key
    if (keyData == Keys.Up )
    {
        MessageBox.Show("You pressed Up arrow key");
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Full source...Arrow keys in C#

Vayne

Two statements next to curly brace in an equation

Are you looking for

\begin{cases}
  math text
\end{cases}

It wasn't very clear from the description. But may be this is what you are looking for http://en.wikipedia.org/wiki/Help:Displaying_a_formula#Continuation_and_cases

How do I access Configuration in any class in ASP.NET Core?

The right way to do it:

In .NET Core you can inject the IConfiguration as a parameter into your Class constructor, and it will be available.

public class MyClass 
{
    private IConfiguration configuration;
    public MyClass(IConfiguration configuration)
    {
        ConnectionString = new configuration.GetValue<string>("ConnectionString");
    }

Now, when you want to create an instance of your class, since your class gets injected the IConfiguration, you won't be able to just do new MyClass(), because it needs a IConfiguration parameter injected into the constructor, so, you will need to inject your class as well to the injecting chain, which means two simple steps:

1) Add your Class/es - where you want to use the IConfiguration, to the IServiceCollection at the ConfigureServices() method in Startup.cs

services.AddTransient<MyClass>();

2) Define an instance - let's say in the Controller, and inject it using the constructor:

public class MyController : ControllerBase
{
    private MyClass _myClass;
    public MyController(MyClass myClass)
    {
        _myClass = myClass;
    }

Now you should be able to enjoy your _myClass.configuration freely...

Another option:

If you are still looking for a way to have it available without having to inject the classes into the controller, then you can store it in a static class, which you will configure in the Startup.cs, something like:

public static class MyAppData
{
    public static IConfiguration Configuration;
}

And your Startup constructor should look like this:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    MyAppData.Configuration = configuration;
}

Then use MyAppData.Configuration anywhere in your program.

Don't confront me why the first option is the right way, I can just see experienced developers always avoid garbage data along their way, and it's well understood that it's not the best practice to have loads of data available in memory all the time, neither is it good for performance and nor for development, and perhaps it's also more secure to only have with you what you need.

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

How can I deploy an iPhone application from Xcode to a real iPhone device?

I've used a mix of two howtos: Jason's and alex's. With the second we have the advantage of being able to debug. I'll mostly just copy both below (and simplify alex's):

Update Jan 2012: this still works on SDK 4.2.1 and iOS 5.0.1 - I've just tested it all on a new computer and device!


1. Create Self-Signed Certificate

Patch your iPhone SDK to allow the use of this certificate:

  1. Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate.

    • Name: iPhone Developer
    • Certificate Type: Code Signing
    • Let me override defaults: Yes
  2. Click Continue

    • Validity: 3650 days
  3. Click Continue

  4. Blank out the Email address field.

  5. Click Continue until complete.

    You should see "This root certificate is not trusted". This is expected.

  6. Set the iPhone SDK to allow the self-signed certificate to be used:

    sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist
    

    If you have Xcode open, restart it for this change to take effect.

And if you're on iOS 5, that's it! Try it now! It may not allow debugging, but the app will be there!

I was very surprised by this because, as you should know, I've got no idea on what all those hackings are all about! All I did was improving a little bit what I found elsewhere, as I pointed.

So yeah, the whole method doesn't work the same way anymore and I couldn't bother to find a new one... Except for this, which uses a tool called Theos but I couldn't go through the whole process.

Finally, if you need to uninstall it for whatever reason, check the end of this post. In my case, I had to because I couldn't figure out why all of the blue this whole method stopped working, and I couldn't care anymore since we've already got the long waited license. (Freaking DUNS number takes so long...)

.

.


.

.

.

2. Enable Xcode's to Build on Jailbroken Device

  1. On your jailbroken iPhone, install the app AppSync by adding source ** http://repo.hackyouriphone.org**

  2. Remove SDK requirements for code sign and entitlements (I'm loving sed!):

    sudo /usr/bin/sed -i .bak '/_REQUIRED/N;s/YES/NO/' /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/SDKSettings.plist
    
  3. Pay attention to the iPhoneOS5.0.sdk part. If you're, for instance, using iOS 4.2 SDK, just replace it accordingly:

    sudo /usr/bin/sed -i .bak '/_REQUIRED/N;s/YES/NO/' /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/SDKSettings.plist
    
  4. Conclude the requirement removal through patching Xcode. This means binary editing:

    cd /Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Plug-ins/iPhoneOS\ Build\ System\ Support.xcplugin/Contents/MacOS/
    dd if=iPhoneOS\ Build\ System\ Support of=working bs=500 count=255
    printf "\xc3\x26\x00\x00" >> working
    /bin/mv -n iPhoneOS\ Build\ System\ Support iPhoneOS\ Build\ System\ Support.original
    /bin/mv working iPhoneOS\ Build\ System\ Support
    chmod a+x iPhoneOS\ Build\ System\ Support
    

    If you have Xcode open, restart it for this change (and last one) to take effect.

  5. Open "Project>Edit Project Settings" (from the menu). Click on the "Build" tab. Find "Code Signing Identity" and its child "Any iPhoneOS Device" in the list, and set both to the entry "Don't Code Sign":

    alt text

    After this feel free to undo step 3. At least in my case it went just fine.

  6. Setting Xcode to code sign with our custom made self-signed certificate (the first how-to). This step can probably be skipped if you don't want to be able to debug:

    mkdir /Developer/iphoneentitlements401
    cd /Developer/iphoneentitlements401
    curl -O http://www.alexwhittemore.com/iphone/gen_entitlements.txt
    mv gen_entitlements.txt gen_entitlements.py
    chmod 777 gen_entitlements.py
    

    Plug your iPhone in and open Xcode. Open Window>Organizer. Select the device from the list on the left hand side, and click "Use for development." You'll be prompted for a provisioning website login, click cancel. It's there to make legitimate provisioning easier, but doesn't make illegitimate not-provisioning more difficult.

    Now You have to do this last part for every new project you make. Go to the menu Project > New Build Phase > New Run Script Build Phase. In the window, copy/paste this:

    export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate
    if [ "${PLATFORM_NAME}" == "iphoneos" ]; then
    /Developer/iphoneentitlements401/gen_entitlements.py "my.company.${PROJECT_NAME}" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent";
    codesign -f -s "iPhone Developer" --entitlements "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/"
    fi
    

.

.


.

.

Uninstalling

For the 1st part:

sudo mv -f /Developer/Platforms/iPhoneOS.platform/Info.plist.bak /Developer/Platforms/iPhoneOS.platform/Info.plist

For the 2nd part:

sudo mv -f /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/SDKSettings.plist.bak /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/SDKSettings.plist
sudo mv -f iPhoneOS\ Build\ System\ Support.original iPhoneOS\ Build\ System\ Support

in case you did do the step 3 instead of 2, simply modify it accordingly as well:

sudo mv -f /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/SDKSettings.plist.bak /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/SDKSettings.plist

for the rest, is just reverting what you did on XCode and deleting /Developer/iphoneentitlements401/gen_entitlements.py if you want:

sudo rm -f /Developer/iphoneentitlements401/gen_entitlements.py

Simple way to transpose columns and rows in SQL?

This way Convert all Data From Filelds(Columns) In Table To Record (Row).

Declare @TableName  [nvarchar](128)
Declare @ExecStr    nvarchar(max)
Declare @Where      nvarchar(max)
Set @TableName = 'myTableName'
--Enter Filtering If Exists
Set @Where = ''

--Set @ExecStr = N'Select * From '+quotename(@TableName)+@Where
--Exec(@ExecStr)

Drop Table If Exists #tmp_Col2Row

Create Table #tmp_Col2Row
(Field_Name nvarchar(128) Not Null
,Field_Value nvarchar(max) Null
)

Set @ExecStr = N' Insert Into #tmp_Col2Row (Field_Name , Field_Value) '
Select @ExecStr += (Select N'Select '''+C.name+''' ,Convert(nvarchar(max),'+quotename(C.name) + ') From ' + quotename(@TableName)+@Where+Char(10)+' Union All '
         from sys.columns as C
         where (C.object_id = object_id(@TableName)) 
         for xml path(''))
Select @ExecStr = Left(@ExecStr,Len(@ExecStr)-Len(' Union All '))
--Print @ExecStr
Exec (@ExecStr)

Select * From #tmp_Col2Row
Go

The real difference between "int" and "unsigned int"

The binary representation is the key. An Example: Unsigned int in HEX

 0XFFFFFFF = translates to = 1111 1111 1111 1111 1111 1111 1111 1111 

Which represents 4,294,967,295 in a base-ten positive number. But we also need a way to represent negative numbers. So the brains decided on twos complement. In short, they took the leftmost bit and decided that when it is a 1 (followed by at least one other bit set to one) the number will be negative. And the leftmost bit is set to 0 the number is positive. Now let's look at what happens

0000 0000 0000 0000 0000 0000 0000 0011 = 3

Adding to the number we finally reach.

0111 1111 1111 1111 1111 1111 1111 1111 = 2,147,483,645

the highest positive number with a signed integer. Let's add 1 more bit (binary addition carries the overflow to the left, in this case, all bits are set to one, so we land on the leftmost bit)

1111 1111 1111 1111 1111 1111 1111 1111 = -1

So I guess in short we could say the difference is the one allows for negative numbers the other does not. Because of the sign bit or leftmost bit or most significant bit.

How can I rename a field for all documents in MongoDB?

If you are using MongoMapper, this works:

Access.collection.update( {}, { '$rename' => { 'location' => 'location_info' } }, :multi => true )

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

I want to calculate the distance between two points in Java

Math.sqrt returns a double so you'll have to cast it to int as well

distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

Adding asterisk to required fields in Bootstrap 3

This CSS worked for me:

.form-group.required.control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -10px;
}

and this HTML:

<div class="form-group required control-label">
  <label for="emailField">Email</label>
  <input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
</div>

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

Using angular-google-maps

$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
    $scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};    
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());

Search all of Git history for a string?

Git can search diffs with the -S option (it's called pickaxe in the docs)

git log -S password

This will find any commit that added or removed the string password. Here a few options:

  • -p: will show the diffs. If you provide a file (-p file), it will generate a patch for you.
  • -G: looks for differences whose added or removed line matches the given regexp, as opposed to -S, which "looks for differences that introduce or remove an instance of string".
  • --all: searches over all branches and tags; alternatively, use --branches[=<pattern>] or --tags[=<pattern>]

What is the purpose of global.asax in asp.net

MSDN has an outline of the purpose of the global.asax file.

Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.

You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):

  • Application_Start
  • Application_End
  • Session_Start
  • Session_End
  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_Error

There are other events that you can also hook into, such as "LogRequest".

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

Check this also:

This problem occurs because the Web site does not have the Directory Browsing feature enabled, and the default document is not configured. To resolve this problem, use one of the following methods:

  • Method 1: Enable the Directory Browsing feature in IIS (Recommended)
  • Method 2: Add a default document Method
  • Method 3: Enable the Directory Browsing feature in IIS Express

LINK : https://support.microsoft.com/en-us/kb/942062

Is nested function a good approach when required by only one function?

>>> def sum(x, y):
...     def do_it():
...             return x + y
...     return do_it
... 
>>> a = sum(1, 3)
>>> a
<function do_it at 0xb772b304>
>>> a()
4

Is this what you were looking for? It's called a closure.

Java path..Error of jvm.cfg

In case you get here and scroll this far down, the newer Oracle versions of Java x86 and probably also x64 are horribly broken. You may find that after removing all versions of Java, and even manually deleting all the versions you find in c:/program files/ and c:/program files (x86)/ that you still can't properly run a fresh install of Java.

I'm here to tell you why, and how to fix it.

Go to C:\Program Files\Common Files\ and DELETE the Oracle directory. It has a version of Java underneath it inside a junction (symlink) that is sequestered away from all your other installs. Bastards.

Now, also go to System Properties -> Advanced -> Environment Variables and edit the PATH under System Variables. Find the place where the Oracle folder is referenced, and delete it. Close all your windows down, reboot to be extra sure if you want.

Install the JRE or JDK. Open a command prompt and type 'java' and if it comes up, you're golden. If not, go back to the PATH variable and add "C:\Program Files (x86)\Java\jdk1.8.0_221\bin" or whatever looks right for your machine.

I hate Oracle.

How to call a method in another class of the same package?

Methods are object methods or class methods.

Object methods: it applies over an object. You have to use an instance:

instance.method(args...);

Class methods: it applies over a class. It doesn't have an implicit instance. You have to use the class itself. It's more like procedural programming.

ClassWithStaticMethod.method(args...);

Reflection

With reflection you have an API to programmatically access methods, be they object or class methods.

Instance methods: methodRef.invoke(instance, args...); Class methods: methodRef.invoke(null, args...);

Can I call a constructor from another constructor (do constructor chaining) in C++?

When calling a constructor it actually allocates memory, either from the stack or from the heap. So calling a constructor in another constructor creates a local copy. So we are modifying another object, not the one we are focusing on.

Nested ifelse statement

If the data set contains many rows it might be more efficient to join with a lookup table using data.table instead of nested ifelse().

Provided the lookup table below

lookup
     idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign

and a sample data set

library(data.table)
n_row <- 10L
set.seed(1L)
DT <- data.table(idnat = "french",
                 idbp = sample(c("mainland", "colony", "overseas", "foreign"), n_row, replace = TRUE))
DT[idbp == "foreign", idnat := "foreign"][]
      idnat     idbp
 1:  french   colony
 2:  french   colony
 3:  french overseas
 4: foreign  foreign
 5:  french mainland
 6: foreign  foreign
 7: foreign  foreign
 8:  french overseas
 9:  french overseas
10:  french mainland

then we can do an update while joining:

DT[lookup, on = .(idnat, idbp), idnat2 := i.idnat2][]
      idnat     idbp   idnat2
 1:  french   colony overseas
 2:  french   colony overseas
 3:  french overseas overseas
 4: foreign  foreign  foreign
 5:  french mainland mainland
 6: foreign  foreign  foreign
 7: foreign  foreign  foreign
 8:  french overseas overseas
 9:  french overseas overseas
10:  french mainland mainland

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Activate a virtualenv with a Python script

If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:

import subprocess

# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"

# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"

subprocess.Popen([python_bin, script_file])

However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py script:

# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

execfile(activate_this_file, dict(__file__=activate_this_file))

How to convert an Array to a Set in Java

new HashSet<Object>(Arrays.asList(Object[] a));

But I think this would be more efficient:

final Set s = new HashSet<Object>();    
for (Object o : a) { s.add(o); }         

Is Unit Testing worth the effort?

Unit Testing is one of the most adopted methodologies for high quality code. Its contribution to a more stable, independent and documented code is well proven . Unit test code is considered and handled as an a integral part of your repository, and as such requires development and maintenance. However, developers often encounter a situation where the resources invested in unit tests where not as fruitful as one would expect. In an ideal world every method we code will have a series of tests covering it’s code and validating it’s correctness. However, usually due to time limitations we either skip some tests or write poor quality ones. In such reality, while keeping in mind the amount of resources invested in unit testing development and maintenance, one must ask himself, given the available time, which code deserve testing the most? And from the existing tests, which tests are actually worth keeping and maintaining? See here

Change package name for Android in React Native

To change package I have searched and tried many methods but some are very hard and some are outdated. While searching I found a website that discuss a very simple method that are tested and personally i have also used this. Link : https://www.geoclassifieds.in/2021/02/change-package-name-react-native.html

DateTimePicker: pick both date and time

I'm afraid the DateTimePicker control doesn't have the ability to do those things. It's a pretty basic (and frustrating!) control. Your best option may be to find a third-party control that does what you want.

For the option of typing the date and time manually, you could build a custom component with a TextBox/DateTimePicker combination to accomplish this, and it might work reasonably well, if third-party controls are not an option.

What is token-based authentication?

From Auth0.com

Token-Based Authentication, relies on a signed token that is sent to the server on each request.

What are the benefits of using a token-based approach?

  • Cross-domain / CORS: cookies + CORS don't play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.

  • Stateless (a.k.a. Server side scalability): there is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side.

  • CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.

  • Decoupling: you are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.

  • Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a token-based approach simplifies this a lot.

  • CSRF: since you are not relying on cookies, you don't need to protect against cross site requests (e.g. it would not be possible to sib your site, generate a POST request and re-use the existing authentication cookie because there will be none).

  • Performance: we are not presenting any hard perf benchmarks here, but a network roundtrip (e.g. finding a session on database) is likely to take more time than calculating an HMACSHA256 to validate a token and parsing its contents.

How many socket connections possible?

I achieved 1600k concurrent idle socket connections, and at the same time 57k req/s on a Linux desktop (16G RAM, I7 2600 CPU). It's a single thread http server written in C with epoll. Source code is on github, a blog here.

Edit:

I did 600k concurrent HTTP connections (client & server) on both the same computer, with JAVA/Clojure . detail info post, HN discussion: http://news.ycombinator.com/item?id=5127251

The cost of a connection(with epoll):

  • application need some RAM per connection
  • TCP buffer 2 * 4k ~ 10k, or more
  • epoll need some memory for a file descriptor, from epoll(7)

Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel, and roughly 160 bytes on a 64-bit kernel.

Create a simple HTTP server with Java?

This is how I would go about this:

  1. Start a ServerSocket listening (probably on port 80).
  2. Once you get a connection request, accept and pass to another thread/process (this leaves your ServerSocket available to keep listening and accept other connections).
  3. Parse the request text (specifically, the headers where you will see if it is a GET or POST, and the parameters passed.
  4. Answer with your own headers (Content-Type, etc.) and the HTML.

I find it useful to use Firebug (in Firefox) to see examples of headers. This is what you want to emulate.

Try this link: - Multithreaded Server in Java

How to properly create an SVN tag from trunk?

Use:

svn copy http://svn.example.com/project/trunk \
      http://svn.example.com/project/tags/1.0 -m "Release 1.0"

Shorthand:

cd /path/to/project
svn copy ^/trunk ^/tags/1.0 -m "Release 1.0"

Using python's eval() vs. ast.literal_eval()?

datamap = eval(input('Provide some data here: ')) means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

Use ast.literal_eval whenever you need eval. You shouldn't usually evaluate literal Python statements.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.

same example

...  ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
...  div collapse="isCollapsed"> ...

with

@media screen and (min-width: 768px) {
    .collapse{
        display: block !important;
    }
}

Output in a table format in Java's System.out

Because most of solutions is bit outdated I could also suggest asciitable which already available in maven (de.vandermeer:asciitable:0.3.2) and may produce very complicated configurations.

Features (by offsite):

  • Text table with some flexibility for rules and content, alignment, format, padding, margins, and frames:
  • add text, as often as required in many different formats (string, text provider, render provider, ST, clusters),
  • removes all excessive white spaces (tabulators, extra blanks, combinations of carriage return and line feed),
  • 6 different text alignments: left, right, centered, justified, justified last line left, justified last line right,
  • flexible width, set for text and calculated in many different ways for rendering
  • padding characters for left and right padding (configurable separately)
  • padding characters for top and bottom padding (configurable separately)
  • several options for drawing grids
  • rules with different styles (as supported by the used grid theme: normal, light, strong, heavy)
  • top/bottom/left/right margins outside a frame
  • character conversion to generated text suitable for further process, e.g. for LaTeX and HTML

And usage still looks easy:

AsciiTable at = new AsciiTable();

at.addRule();
at.addRow("row 1 col 1", "row 1 col 2");
at.addRule();
at.addRow("row 2 col 1", "row 2 col 2");
at.addRule();

System.out.println(at.render()); // Finally, print the table to standard out.

How To Raise Property Changed events on a Dependency Property?

I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example. In the code below, MyControl has two dependency properties - ActiveTabInt and ActiveTabString. When the user clicks the button on the host (MainWindow), ActiveTabString is modified. The PropertyChanged CALLBACK on the dependency property sets the value of ActiveTabInt. The PropertyChanged EVENT is not manually raised by MyControl.

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ActiveTabString = "zero";
    }

    private string _ActiveTabString;
    public string ActiveTabString
    {
        get { return _ActiveTabString; }
        set
        {
            if (_ActiveTabString != value)
            {
                _ActiveTabString = value;
                RaisePropertyChanged("ActiveTabString");
            }
        }
    }

    private int _ActiveTabInt;
    public int ActiveTabInt
    {
        get { return _ActiveTabInt; }
        set
        {
            if (_ActiveTabInt != value)
            {
                _ActiveTabInt = value;
                RaisePropertyChanged("ActiveTabInt");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
    }

}

public class MyControl : Control
{
    public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });


    public string ActiveTabString
    {
        get { return (string)GetValue(ActiveTabStringProperty); }
        set { SetValue(ActiveTabStringProperty, value); }
    }

    public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
        "ActiveTabString",
        typeof(string),
        typeof(MyControl), new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            ActiveTabStringChanged));


    public int ActiveTabInt
    {
        get { return (int)GetValue(ActiveTabIntProperty); }
        set { SetValue(ActiveTabIntProperty, value); }
    }
    public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
        "ActiveTabInt",
        typeof(Int32),
        typeof(MyControl), new FrameworkPropertyMetadata(
            new Int32(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }


    private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyControl thiscontrol = sender as MyControl;

        if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
            thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());

    }
}

MainWindow.xaml

    <StackPanel Orientation="Vertical">
    <Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
    <local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>

App.xaml

<Style TargetType="local:MyControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyControl">
                    <TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
                        <TabItem Header="Tab Zero">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                        <TabItem Header="Tab One">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                    </TabControl>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Getting a directory name from a filename

Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.

What is the difference between Class.getResource() and ClassLoader.getResource()?

Class.getResource can take a "relative" resource name, which is treated relative to the class's package. Alternatively you can specify an "absolute" resource name by using a leading slash. Classloader resource paths are always deemed to be absolute.

So the following are basically equivalent:

foo.bar.Baz.class.getResource("xyz.txt");
foo.bar.Baz.class.getClassLoader().getResource("foo/bar/xyz.txt");

And so are these (but they're different from the above):

foo.bar.Baz.class.getResource("/data/xyz.txt");
foo.bar.Baz.class.getClassLoader().getResource("data/xyz.txt");

<SELECT multiple> - how to allow only one item selected?

I had some dealings with the select \ multi-select this is what did the trick for me

<select name="mySelect" multiple="multiple">
    <option>Foo</option>
    <option>Bar</option>
    <option>Foo Bar</option>
    <option>Bar Foo</option>
</select>

Facebook OAuth "The domain of this URL isn't included in the app's domain"

I had the same problem,

I just added the link of my local adress http://localhost/Facebook%20Login%20Test.html to Site URL in my application setting https://developers.facebook.com/apps.

Now it works fine :) I hope this was useful ;)

Order of items in classes: Fields, Properties, Constructors, Methods

The closest you're likely to find is "Design Guidelines, Managed code and the .NET Framework" (http://blogs.msdn.com/brada/articles/361363.aspx) by Brad Abrams

Many standards are outlined here. The relevant section is 2.8 I think.

CSS file not refreshing in browser

I had this issue, I was scratching my head for the best part of two days.

Turns out I completely forgot I had CloudFlare setup on the domain I was live testing on.

CloudFlare caches your JavaScript and CSS. Turned on development mode and BAM!

Seriously... two whole days.

How to access single elements in a table in R

That is so basic that I am wondering what book you are using to study? Try

data[1, "V1"]  # row first, quoted column name second, and case does matter

Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.

I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html

How do I upgrade PHP in Mac OS X?

Upgrading to Snow Leopard won't solve the your primary problem of keeping PHP up to date. Apple doesn't always keep the third party software that it bundles up to date with OS updates. And relying on Apple to get you the bug fix / security update you need is asking for trouble.

Additionally, I would recommend installing through MacPorts (and doing the config necessary to use it instead of Apple's PHP) rather than try to upgrade the Apple supplied PHP in place. Anything you do to /usr/bin risks being overwritten by some future Apple update.

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

Simple PowerShell commands to set this in the registry;

New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
Set-ItemProperty -Path "HKCR:\Microsoft.PowerShellScript.1\Shell\open\command" -name '(Default)' -Value '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"'

Angular: Cannot find a differ supporting object '[object Object]'

This ridiculous error message merely means there's a binding to an array that doesn't exist.

<option
  *ngFor="let option of setting.options"
  [value]="option"
  >{{ option }}
</option>

In the example above the value of setting.options is undefined. To fix, press F12 and open developer window. When the the get request returns the data look for the values to contain data.

If data exists, then make sure the binding name is correct

//was the property name correct? 
setting.properNamedOptions

If the data exists, is it an Array?

If the data doesn't exist then fix it on the backend.

How can I remove non-ASCII characters but leave periods and spaces using Python?

Your question is ambiguous; the first two sentences taken together imply that you believe that space and "period" are non-ASCII characters. This is incorrect. All chars such that ord(char) <= 127 are ASCII characters. For example, your function excludes these characters !"#$%&\'()*+,-./ but includes several others e.g. []{}.

Please step back, think a bit, and edit your question to tell us what you are trying to do, without mentioning the word ASCII, and why you think that chars such that ord(char) >= 128 are ignorable. Also: which version of Python? What is the encoding of your input data?

Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:

this is line 1
this is line 2

the result would be 'this is line 1this is line 2' ... is that what you really want?

A greater solution would include:

  1. a better name for the filter function than onlyascii
  2. recognition that a filter function merely needs to return a truthy value if the argument is to be retained:

    def filter_func(char):
        return char == '\n' or 32 <= ord(char) <= 126
    # and later:
    filtered_data = filter(filter_func, data).lower()
    

getResourceAsStream returns null

So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently.

The best explanation I have seen is this article from InfoWorld. I'll summarize here, but if you want to know more you should check out the article.

Methods

  1. ClassLoader.getResourceAsStream().

Format: "/"-separated names; no leading "/" (all names are absolute).

Example: this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");

  1. Class.getResourceAsStream()

Format: "/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package

Example: this.getClass().getResourceAsStream("/some/pkg/resource.properties");

Updated Sep 2020: Changed article link. Original article was from Javaworld, it is now hosted on InfoWorld (and has many more ads)

How do I get current URL in Selenium Webdriver 2 Python?

Another way to do it would be to inspect the url bar in chrome to find the id of the element, have your WebDriver click that element, and then send the keys you use to copy and paste using the keys common function from selenium, and then printing it out or storing it as a variable, etc.

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

call javascript function on hyperlink click

Use the onclick HTML attribute.

The onclick event handler captures a click event from the users’ mouse button on the element to which the onclick attribute is applied. This action usually results in a call to a script method such as a JavaScript function [...]

Applying CSS styles to all elements inside a DIV

.yourWrapperClass * {
 /* your styles for ALL */
}

This code will apply styles all elements inside .yourWrapperClass.

"std::endl" vs "\n"

If you intend to run your program on anything else than your own laptop, never ever use the endl statement. Especially if you are writing a lot of short lines or as I have often seen single characters to a file. The use of endl is know to kill networked file systems like NFS.

How to remove jar file from local maven repository which was added with install:install-file?

At least on the current maven version you need to add the switch -DreResolve=false if you intend to remove the dependencies from your local repo without re-downloading them.

mvn dependency:purge-local-repository -DreResolve=false

removes the dependencies without downloading them again.

Have a div cling to top of screen if scrolled down past it

There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:

  1. Page loads and element is position: static
  2. On scroll, the position is measured, and if the element is position: static and it's off the page then the element is flipped to position: fixed.

I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

How to inject a Map using the @Value Spring Annotation?

I believe Spring Boot supports loading properties maps out of the box with @ConfigurationProperties annotation.

According that docs you can load properties:

my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

into bean like this:

@ConfigurationProperties(prefix="my")
public class Config {

    private List<String> servers = new ArrayList<String>();

    public List<String> getServers() {
        return this.servers;
    }
}

I used @ConfigurationProperties feature before, but without loading into map. You need to use @EnableConfigurationProperties annotation to enable this feature.

Cool stuff about this feature is that you can validate your properties.

Resize iframe height according to content height in it

You can do this with JavaScript.

document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";

The pipe ' ' could not be found angular2 custom pipe

Suggesting an alternative answer here:

Making a separate module for the Pipe is not required, but is definitely an alternative. Check the official docs footnote: https://angular.io/guide/pipes#custom-pipes

You use your custom pipe the same way you use built-in pipes.
You must include your pipe in the declarations array of the AppModule . If you choose to inject your pipe into a class, you must provide it in the providers array of your NgModule.

All you have to do is add your pipe to the declarations array, and the providers array in the module where you want to use the Pipe.

declarations: [
...
CustomPipe,
...
],
providers: [
...
CustomPipe,
...
]

Go install fails with error: no install location for directory xxx outside GOPATH

I'm on Windows, and I got it by giving command go help gopath to cmd, and read the bold text in the instruction,

that is if code you wnat to install is at ..BaseDir...\SomeProject\src\basic\set, the GOPATH should not be the same location as code, it should be just Base Project DIR: ..BaseDir...\SomeProject.

The GOPATH environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string. On Plan 9, the value is a list.

If the environment variable is unset, GOPATH defaults to a subdirectory named "go" in the user's home directory ($HOME/go on Unix, %USERPROFILE%\go on Windows), unless that directory holds a Go distribution. Run "go env GOPATH" to see the current GOPATH.

See https://golang.org/wiki/SettingGOPATH to set a custom GOPATH.

Each directory listed in GOPATH must have a prescribed structure:

The src directory holds source code. The path below src determines the import path or executable name.

The pkg directory holds installed package objects. As in the Go tree, each target operating system and architecture pair has its own subdirectory of pkg (pkg/GOOS_GOARCH).

If DIR is a directory listed in the GOPATH, a package with source in DIR/src/foo/bar can be imported as "foo/bar" and has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a".

The bin directory holds compiled commands. Each command is named for its source directory, but only the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The "foo/" prefix is stripped so that you can add DIR/bin to your PATH to get at the installed commands. If the GOBIN environment variable is set, commands are installed to the directory it names instead of DIR/bin. GOBIN must be an absolute path.

Here's an example directory layout:

GOPATH=/home/user/go

/home/user/go/
    src/
        foo/
            bar/               (go code in package bar)
                x.go
            quux/              (go code in package main)
                y.go
    bin/
        quux                   (installed command)
    pkg/
        linux_amd64/
            foo/
                bar.a          (installed package object)

..........

if GOPATH has been set to Base Project DIR and still has this problem, in windows you can try to set GOBIN as Base Project DIR\bin or %GOPATH%\bin.

How to download and save a file from Internet using Java?

It's possible to download the file with with Apache's HttpComponents instead of Commons-IO. This code allows you to download a file in Java according to its URL and save it at the specific destination.

public static boolean saveFile(URL fileURL, String fileSavePath) {

    boolean isSucceed = true;

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet(fileURL.toString());
    httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    httpGet.addHeader("Referer", "https://www.google.com");

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity fileEntity = httpResponse.getEntity();

        if (fileEntity != null) {
            FileUtils.copyInputStreamToFile(fileEntity.getContent(), new File(fileSavePath));
        }

    } catch (IOException e) {
        isSucceed = false;
    }

    httpGet.releaseConnection();

    return isSucceed;
}

In contrast to the single line of code:

FileUtils.copyURLToFile(fileURL, new File(fileSavePath),
                        URLS_FETCH_TIMEOUT, URLS_FETCH_TIMEOUT);

this code will give you more control over a process and let you specify not only time outs but User-Agent and Referer values, which are critical for many web-sites.

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

Unfortunately the link in the exception text, http://go.microsoft.com/fwlink/?LinkId=70353, is broken. However, it used to lead to http://msdn.microsoft.com/en-us/library/ms733768.aspx which explains how to set the permissions.

It basically informs you to use the following command:

netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

You can get more help on the details using the help of netsh

For example: netsh http add ?

Gives help on the http add command.

What is the naming convention in Python for variable and function names?

See Python PEP 8: Function and Variable Names:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

Excel - Combine multiple columns into one column

Not sure if this completely helps, but I had an issue where I needed a "smart" merge. I had two columns, A & B. I wanted to move B over only if A was blank. See below. It is based on a selection Range, which you could use to offset the first row, perhaps.

Private Sub MergeProjectNameColumns()
    Dim rngRowCount As Integer
    Dim i As Integer

    'Loop through column C and simply copy the text over to B if it is not blank
    rngRowCount = Range(dataRange).Rows.Count
    ActiveCell.Offset(0, 0).Select
    ActiveCell.Offset(0, 2).Select
    For i = 1 To rngRowCount
        If (Len(RTrim(ActiveCell.Value)) > 0) Then
            Dim currentValue As String
            currentValue = ActiveCell.Value
            ActiveCell.Offset(0, -1) = currentValue
        End If
        ActiveCell.Offset(1, 0).Select
    Next i

    'Now delete the unused column
    Columns("C").Select

    selection.Delete Shift:=xlToLeft
End Sub

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

is there a tool to create SVG paths from an SVG file?

Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.

  1. First download Gimp: https://www.gimp.org/downloads/
  2. Export your SVG as a .svg file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it up
  3. Import the SVG file into Gimp with File -> Open, and the following (or similar) dialog should show up:

Gimp SVG Open Dialog

Check both the Import Paths and Merge imported paths options

  1. Then go to Windows->Dockable Dialogues->Paths
  2. Right-click on the single path which says Imported Path and you should see the following dialog:

enter image description here

  1. Click Export Path... and save this text file to a location of your choice
  2. Locate and open up this file with a text editor of your choice e.g Notepad, TextEdit
  3. Copy the text within the <path d="copy this text here" />
  4. Since Gimp formats the text with lots of spaces, you may need to re-format it, by removing some of the spaces to paste it into your HTML in a single line

PHP - Notice: Undefined index:

You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

Check if all checkboxes are selected

The search criteria is one of these:

input[type=checkbox].MyClass:not(:checked)
input[type=checkbox].MyClass:checked

You probably want to connect to the change event.

How to drop columns using Rails migration

For removing column from table in just easy 3 steps as follows:

  1. write this command

rails g migration remove_column_from_table_name

after running this command in terminal one file created by this name and time stamp (remove_column from_table_name).

Then go to this file.

  1. inside file you have to write

    remove_column :table_name, :column_name

  2. Finally go to the console and then do

    rake db:migrate

Using SELECT result in another SELECT

What you are looking for is a query with WITH clause, if your dbms supports it. Then

WITH NewScores AS (
    SELECT * 
    FROM Score  
    WHERE InsertedDate >= DATEADD(mm, -3, GETDATE())
)
SELECT 
<and the rest of your query>
;

Note that there is no ; in the first half. HTH.

Creating a UIImage from a UIColor to use as a background image for UIButton

I suppose that 255 in 227./255 is perceived as an integer and divide is always return 0

How do I split a string so I can access item x?

Here is a function that will accomplish the question's goal of splitting a string and accessing item X:

CREATE FUNCTION [dbo].[SplitString]
(
   @List       VARCHAR(MAX),
   @Delimiter  VARCHAR(255),
   @ElementNumber INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN

       DECLARE @inp VARCHAR(MAX)
       SET @inp = (SELECT REPLACE(@List,@Delimiter,'_DELMTR_') FOR XML PATH(''))

       DECLARE @xml XML
       SET @xml = '<split><el>' + REPLACE(@inp,'_DELMTR_','</el><el>') + '</el></split>'

       DECLARE @ret VARCHAR(MAX)
       SET @ret = (SELECT
              el = split.el.value('.','varchar(max)')
       FROM  @xml.nodes('/split/el[string-length(.)>0][position() = sql:variable("@elementnumber")]') split(el))

       RETURN @ret

END

Usage:

SELECT dbo.SplitString('Hello John Smith', ' ', 2)

Result:

John

Replace comma with newline in sed on MacOS?

Use an ANSI-C quoted string $'string'

You need a backslash-escaped literal newline to get to sed. In bash at least, $'' strings will replace \n with a real newline, but then you have to double the backslash that sed will see to escape the newline, e.g.

echo "a,b" | sed -e $'s/,/\\\n/g'

Note this will not work on all shells, but will work on the most common ones.

Why doesn't Python have a sign function?

numpy has a sign function, and gives you a bonus of other functions as well. So:

import numpy as np
x = np.sign(y)

Just be careful that the result is a numpy.float64:

>>> type(np.sign(1.0))
<type 'numpy.float64'>

For things like json, this matters, as json does not know how to serialize numpy.float64 types. In that case, you could do:

float(np.sign(y))

to get a regular float.

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

https://support.google.com/a/answer/3001912?hl=en

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

Clicking URLs opens default browser

The method boolean shouldOverrideUrlLoading(WebView view, String url) was deprecated in API 24. If you are supporting new devices you should use boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request).

You can use both by doing something like this:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }
    });
} else {
    newsItem.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
}

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

HTML :

Enter Your Text : <input type="text" id="text-filed" value="test">

Using JS :

var textFiled = document.getElementById("text-filed");
textFiled.addEventListener("focus", function() { this.select(); });

Using JQuery :

$("#text-filed").focus(function() { $(this).select(); } );

Using React JS :

In the respective component -

<input
  type="text"
  value="test"
  onFocus={e => e.target.select()}
/>

Display number with leading zeros

This is how I do it:

str(1).zfill(len(str(total)))

Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:

Python 3.6.5 (default, May 11 2018, 04:00:52) 
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> total = 100
>>> print(str(1).zfill(len(str(total))))
001
>>> total = 1000
>>> print(str(1).zfill(len(str(total))))
0001
>>> total = 10000
>>> print(str(1).zfill(len(str(total))))
00001
>>> 

how do I initialize a float to its max/min value?

May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?

How to add images to README.md on GitHub?

If you want to show an image hosted at any website (say url is "http:// abc.def.com/folder/image.jpg") then in your README.md file use the below syntax:

![alt text](<http:// abc.def.com/folder/image.jpg>)

  • Just browse to the image in your browser (may be by clicking on the image). It can be any website, including yours or somebody else's github hosted image.
  • Copy the url from the browser address bar, that is your "image_url" to be used in above referred syntax.

For images hosted in your own github repository you can use relative path in addition to the above url format
![alt text](<path_relative_to_current_github_location/image.jpg>)


If the image is located in the same folder as the README.md file (special case of relative path url), then you can use:
![alt text](<image.jpg>)


Note the angular brackets "<" and ">" enclosing the url. Sometimes these are required for the url to work.

How do I properly compare strings in C?

Use strcmp.

This is in string.h library, and is very popular. strcmp return 0 if the strings are equal. See this for an better explanation of what strcmp returns.

Basically, you have to do:

while (strcmp(check,input) != 0)

or

while (!strcmp(check,input))

or

while (strcmp(check,input))

You can check this, a tutorial on strcmp.

How do I speed up the gwt compiler?

  • Split your application into multiple modules or entry points and re-compile then only when needed.
  • Analyse your application using the trunk version - which provides the Story of your compile. This may or may not be relevant to the 1.6 compiler but it can indicate what's going on.

How to create json by JavaScript for loop?

If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.

I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.

Here is example code. Tryout on your FireBug Console

var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];

var json = "{ ";
for(var i = 0; i < key.length; i++) {
    (i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Open Project properties by selecting project then go to

View>Properties Windows

and make sure Anonymous Authentication is Enabled

enter image description here

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

Its in the comments of the answers but nobody has posted this as the actual solution.

You just need to add a using statement at the top:

using Microsoft.AspNet.Identity;

Checking if an object is a number in C#

Assuming your input is a string...

There are 2 ways:

use Double.TryParse()

double temp;
bool isNumber = Double.TryParse(input, out temp);

use Regex

 bool isNumber = Regex.IsMatch(input,@"-?\d+(\.\d+)?");

How can I check what version/edition of Visual Studio is installed programmatically?

Run the path in cmd C:\Program Files (x86)\Microsoft Visual Studio\Installer>vswhere.exe

How to get a JavaScript object's class?

For Javascript Classes in ES6 you can use object.constructor. In the example class below the getClass() method returns the ES6 class as you would expect:

var Cat = class {

    meow() {

        console.log("meow!");

    }

    getClass() {

        return this.constructor;

    }

}

var fluffy = new Cat();

...

var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();

ruffles.meow();    // "meow!"

If you instantiate the class from the getClass method make sure you wrap it in brackets e.g. ruffles = new ( fluffy.getClass() )( args... );

XPath - Difference between node() and text()

text() and node() are node tests, in XPath terminology (compare).

Node tests operate on a set (on an axis, to be exact) of nodes and return the ones that are of a certain type. When no axis is mentioned, the child axis is assumed by default.

There are all kinds of node tests:

  • node() matches any node (the least specific node test of them all)
  • text() matches text nodes only
  • comment() matches comment nodes
  • * matches any element node
  • foo matches any element node named "foo"
  • processing-instruction() matches PI nodes (they look like <?name value?>).
  • Side note: The * also matches attribute nodes, but only along the attribute axis. @* is a shorthand for attribute::*. Attributes are not part of the child axis, that's why a normal * does not select them.

This XML document:

<produce>
    <item>apple</item>
    <item>banana</item>
    <item>pepper</item>
</produce>

represents the following DOM (simplified):

root node
   element node (name="produce")
      text node (value="\n    ")
      element node (name="item")
         text node (value="apple")
      text node (value="\n    ")
      element node (name="item")
         text node (value="banana")
      text node (value="\n    ")
      element node (name="item")
         text node (value="pepper")
      text node (value="\n")

So with XPath:

  • / selects the root node
  • /produce selects a child element of the root node if it has the name "produce" (This is called the document element; it represents the document itself. Document element and root node are often confused, but they are not the same thing.)
  • /produce/node() selects any type of child node beneath /produce/ (i.e. all 7 children)
  • /produce/text() selects the 4 (!) whitespace-only text nodes
  • /produce/item[1] selects the first child element named "item"
  • /produce/item[1]/text() selects all child text nodes (there's only one - "apple" - in this case)

And so on.

So, your questions

  • "Select the text of all items under produce" /produce/item/text() (3 nodes selected)
  • "Select all the manager nodes in all departments" //department/manager (1 node selected)

Notes

  • The default axis in XPath is the child axis. You can change the axis by prefixing a different axis name. For example: //item/ancestor::produce
  • Element nodes have text values. When you evaluate an element node, its textual contents will be returned. In case of this example, /produce/item[1]/text() and string(/produce/item[1]) will be the same.
  • Also see this answer where I outline the individual parts of an XPath expression graphically.

A regex for version number parsing

^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$

Perhaps a more concise one could be :

^(?:(\d+)\.){0,2}(\*|\d+)$

This can then be enhanced to 1.2.3.4.5.* or restricted exactly to X.Y.Z using * or {2} instead of {0,2}

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:

@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
    // ...
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}

Failed to execute 'createObjectURL' on 'URL':

The problem is that the keys provided in the loop do not refer to the index of the file.

for (var i in this.files) {
    console.log(i);
}

The output of the above code is:

0
length
item

But what was expected was:

0
1
2
etc...

Then the error occurs when the browser tries to execute, for example:

window.URL.createObjectURL(this.files["length"])

I suggest implementation based on the following code:

var files = this.files;
for (var i = 0; i < files.length; i++) {
    var file = files[i],
        src = (window.URL || window.webkitURL).createObjectURL(file);
    ...
}

I hope this can help someone.

Greetings!

How to remove illegal characters from path and filenames?

If you remove or replace with a single character the invalid characters, you can have collisions:

<abc -> abc
>abc -> abc

Here is a simple method to avoid this:

public static string ReplaceInvalidFileNameChars(string s)
{
    char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();
    foreach (char c in invalidFileNameChars)
        s = s.Replace(c.ToString(), "[" + Array.IndexOf(invalidFileNameChars, c) + "]");
    return s;
}

The result:

 <abc -> [1]abc
 >abc -> [2]abc

How to Empty Caches and Clean All Targets Xcode 4 and later

You have to be careful about the xib file. I tried all the above and nothing worked for me. I was using custom UIButtons defined in the xib, and realized it might be related to the fact that I had assigned attributes there which were not changing programmatically. If you've defined images or text there, remove them. When I did, my programmatic changes began to take effect.

Is there a way to specify how many characters of a string to print out using printf()?

In C++ it is easy.

std::copy(someStr.c_str(), someStr.c_str()+n, std::ostream_iterator<char>(std::cout, ""));

EDIT: It is also safer to use this with string iterators, so you don't run off the end. I'm not sure what happens with printf and string that are too short, but I'm guess this may be safer.

Finding the max value of an attribute in an array of objects

Well, first you should parse the JSON string, so that you can easily access it's members:

var arr = $.parseJSON(str);

Use the map method to extract the values:

arr = $.map(arr, function(o){ return o.y; });

Then you can use the array in the max method:

var highest = Math.max.apply(this,arr);

Or as a one-liner:

var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));

Finding all objects that have a given property inside a collection

Using Commons Collections:

EqualPredicate nameEqlPredicate = new EqualPredicate(3);
BeanPredicate beanPredicate = new BeanPredicate("age", nameEqlPredicate);
return CollectionUtils.filter(cats, beanPredicate);

What is the common header format of Python files?

Its all metadata for the Foobar module.

The first one is the docstring of the module, that is already explained in Peter's answer.

How do I organize my modules (source files)? (Archive)

The first line of each file shoud be #!/usr/bin/env python. This makes it possible to run the file as a script invoking the interpreter implicitly, e.g. in a CGI context.

Next should be the docstring with a description. If the description is long, the first line should be a short summary that makes sense on its own, separated from the rest by a newline.

All code, including import statements, should follow the docstring. Otherwise, the docstring will not be recognized by the interpreter, and you will not have access to it in interactive sessions (i.e. through obj.__doc__) or when generating documentation with automated tools.

Import built-in modules first, followed by third-party modules, followed by any changes to the path and your own modules. Especially, additions to the path and names of your modules are likely to change rapidly: keeping them in one place makes them easier to find.

Next should be authorship information. This information should follow this format:

__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell"
__copyright__ = "Copyright 2007, The Cogent Project"
__credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley",
                    "Matthew Wakefield"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Rob Knight"
__email__ = "[email protected]"
__status__ = "Production"

Status should typically be one of "Prototype", "Development", or "Production". __maintainer__ should be the person who will fix bugs and make improvements if imported. __credits__ differs from __author__ in that __credits__ includes people who reported bug fixes, made suggestions, etc. but did not actually write the code.

Here you have more information, listing __author__, __authors__, __contact__, __copyright__, __license__, __deprecated__, __date__ and __version__ as recognized metadata.

What is the difference between signed and unsigned int

int and unsigned int are two distinct integer types. (int can also be referred to as signed int, or just signed; unsigned int can also be referred to as unsigned.)

As the names imply, int is a signed integer type, and unsigned int is an unsigned integer type. That means that int is able to represent negative values, and unsigned int can represent only non-negative values.

The C language imposes some requirements on the ranges of these types. The range of int must be at least -32767 .. +32767, and the range of unsigned int must be at least 0 .. 65535. This implies that both types must be at least 16 bits. They're 32 bits on many systems, or even 64 bits on some. int typically has an extra negative value due to the two's-complement representation used by most modern systems.

Perhaps the most important difference is the behavior of signed vs. unsigned arithmetic. For signed int, overflow has undefined behavior. For unsigned int, there is no overflow; any operation that yields a value outside the range of the type wraps around, so for example UINT_MAX + 1U == 0U.

Any integer type, either signed or unsigned, models a subrange of the infinite set of mathematical integers. As long as you're working with values within the range of a type, everything works. When you approach the lower or upper bound of a type, you encounter a discontinuity, and you can get unexpected results. For signed integer types, the problems occur only for very large negative and positive values, exceeding INT_MIN and INT_MAX. For unsigned integer types, problems occur for very large positive values and at zero. This can be a source of bugs. For example, this is an infinite loop:

for (unsigned int i = 10; i >= 0; i --) [
    printf("%u\n", i);
}

because i is always greater than or equal to zero; that's the nature of unsigned types. (Inside the loop, when i is zero, i-- sets its value to UINT_MAX.)

Multiple github accounts on the same computer?

Unlike other answers, where you need to follow few steps to use two different github account from same machine, for me it worked in two steps.

You just need to :

1) generate SSH public and private key pair for each of your account under ~/.ssh location with different names and

2) add the generated public keys to the respective account under Settings >> SSH and GPG keys >> New SSH Key.

To generate the SSH public and private key pairs use following command:

cd ~/.ssh
ssh-keygen -t rsa -C "[email protected]" -f "id_rsa_WORK"
ssh-keygen -t rsa -C "[email protected]" -f "id_rsa_PERSONAL"

As a result of above commands, id_rsa_WORK and id_rsa_WORK.pub files will be created for your work account (ex - git.work.com) and id_rsa_PERSONAL and id_rsa_PERSONAL.pub will be created for your personal account (ex - github.com).

Once created, copy the content from each public (*.pub) file and do Step 2 for the each account.

PS : Its not necessary to make an host entry for each git account under ~/.ssh/config file as mentioned in other answers, if hostname of your two accounts are different.

Converting a PDF to PNG

My solution is much simpler and more direct. At least it works that way on my PC (with the following specs):

me@home: my.folder$ uname -a
Linux home 3.2.0-54-generic-pae #82-Ubuntu SMP Tue Sep 10 20:29:22 UTC 2013 i686 i686 i386 GNU/Linux

with

me@home: my.folder$ convert --version
Version: ImageMagick 6.6.9-7 2012-08-17 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
Features: OpenMP

So, here's what I run on my file.pdf:

me@home: my.folder$ convert -density 300 -quality 100 file.pdf file.png

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR is equivalent to wchar_t const *. It's a pointer to a wide character string that won't be modified by the function call.

You can assign to LPCWSTRs by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";

LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx is defined as FindWindowExA or FindWindowExW depending on this definition.

Get the previous month's first and last day dates in c#

I use this simple one-liner:

public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
{
    return date.AddDays(-date.Day);
}

Be aware, that it retains the time.

Find duplicate records in MySQL

This will select duplicates in one table pass, no subqueries.

SELECT  *
FROM    (
        SELECT  ao.*, (@r := @r + 1) AS rn
        FROM    (
                SELECT  @_address := 'N'
                ) vars,
                (
                SELECT  *
                FROM
                        list a
                ORDER BY
                        address, id
                ) ao
        WHERE   CASE WHEN @_address <> address THEN @r := 0 ELSE 0 END IS NOT NULL
                AND (@_address := address ) IS NOT NULL
        ) aoo
WHERE   rn > 1

This query actially emulates ROW_NUMBER() present in Oracle and SQL Server

See the article in my blog for details:

Parsing JSON in Spring MVC using Jackson JSON

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

Get width in pixels from element with style set with %?

document.getElementById('banner-contenedor').clientWidth

INSERT INTO from two different server database

The answer given by Simon works fine for me but you have to do it in the right sequence: First you have to be in the server that you want to insert data into which is [DATABASE.WINDOWS.NET].[basecampdev] in your case.

You can try to see if you can select some data out of the Invoice table to make sure you have access.

Select top 10 * from [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]

Secondly, execute the query given by Simon in order to link to a different server. This time use the other server:

EXEC sp_addlinkedserver [BC1-PC]; -- this will create a link tempdb that you can access from where you are
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR 
    [BC1-PC].testdabse.dbo.invoice; -- Make a copy of the table and data that you can use
GO

Now just do your insert statement.

INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
       ([InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks])
SELECT [InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks] FROM MyInvoice

Hope this helps!

What causes "Unable to access jarfile" error?

Right click the parent folder of the file > properties > check off Read Only

How to determine an object's class?

Use Object.getClass(). It returns the runtime type of the object.

How to draw in JPanel? (Swing/graphics Java)

When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics object outside the paint()/paintComponent()/etc. methods.

However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics() method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel's paintComponent(), you simply need to draw the BufferedImage instance unto the JPanel. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.

What is Func, how and when is it used

Aforementioned answers are great, just putting few points I see might be helpful:

  • Func is built-in delegate type

  • Func delegate type must return a value. Use Action delegate if no return type needed.

  • Func delegate type can have zero to 16 input parameters.

  • Func delegate does not allow ref and out parameters.

  • Func delegate type can be used with an anonymous method or lambda expression.

    Func<int, int, int> Sum = (x, y) => x + y;

Java equivalent of unsigned long long?

Depending on the operations you intend to perform, the outcome is much the same, signed or unsigned. However, unless you are using trivial operations you will end up using BigInteger.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Just Android studio run 'Run as administrator' it will work

Or verify your package name on google-services.json file

Importing a CSV file into a sqlite3 database table using Python

in the interest of simplicity, you could use the sqlite3 command line tool from the Makefile of your project.

%.sql3: %.csv
    rm -f $@
    sqlite3 $@ -echo -cmd ".mode csv" ".import $< $*"
%.dump: %.sql3
    sqlite3 $< "select * from $*"

make test.sql3 then creates the sqlite database from an existing test.csv file, with a single table "test". you can then make test.dump to verify the contents.

How to recursively find the latest modified file in a directory?

I wrote a pypi/github package for this question because I needed a solution as well.

https://github.com/bucknerns/logtail

Install:

pip install logtail

Usage: tails changed files

logtail <log dir> [<glob match: default=*.log>]

Usage2: Opens latest changed file in editor

editlatest <log dir> [<glob match: default=*.log>]

How can I add 1 day to current date?

currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');

difference between iframe, embed and object elements

Another reason to use object over iframe is that object sub resources (when an <object> performs HTTP requests) are considered as passive/display in terms of Mixed content, which means it's more secure when you must have Mixed content.

Mixed content means that when you have https but your resource is from http.

Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content

Vim delete blank lines

This function only remove two or more blank lines, put the lines below in your vimrc, then use \d to call function

fun! DelBlank()
   let _s=@/
   let l = line(".")
   let c = col(".")
   :g/^\n\{2,}/d
   let @/=_s
   call cursor(l, c)
endfun
map <special> <leader>d :keepjumps call DelBlank()<cr>

ImportError: No module named PyQt4.QtCore

Try this command to solve your problem.

sudo apt install build-essential python3-dev libqt4-dev

This works for me in python3.

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):

onClick=""

OR

The element css needs to have the following declaration:

cursor:pointer

Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working

Swift: Testing optionals for nil

Another approach besides using if or guard statements to do the optional binding is to extend Optional with:

extension Optional {

    func ifValue(_ valueHandler: (Wrapped) -> Void) {
        switch self {
        case .some(let wrapped): valueHandler(wrapped)
        default: break
        }
    }

}

ifValue receives a closure and calls it with the value as an argument when the optional is not nil. It is used this way:

var helloString: String? = "Hello, World!"

helloString.ifValue {
    print($0) // prints "Hello, World!"
}

helloString = nil

helloString.ifValue {
    print($0) // This code never runs
}

You should probably use an if or guard however as those are the most conventional (thus familiar) approaches used by Swift programmers.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

i got the same problem and i verified this may occur because of Auto increment primary key. To solve this problem do not inset auto increment value with data set. Insert data without the primary key.

How to change fontFamily of TextView in Android

An easy way to manage the fonts would be to declare them via resources, as such:

<!--++++++++++++++++++++++++++-->
<!--added on API 16 (JB - 4.1)-->
<!--++++++++++++++++++++++++++-->
<!--the default font-->
<string name="fontFamily__roboto_regular">sans-serif</string>
<string name="fontFamily__roboto_light">sans-serif-light</string>
<string name="fontFamily__roboto_condensed">sans-serif-condensed</string>

<!--+++++++++++++++++++++++++++++-->
<!--added on API 17 (JBMR1 - 4.2)-->
<!--+++++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_thin">sans-serif-thin</string>

<!--+++++++++++++++++++++++++++-->
<!--added on Lollipop (LL- 5.0)-->
<!--+++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_medium">sans-serif-medium</string>
<string name="fontFamily__roboto_black">sans-serif-black</string>
<string name="fontFamily__roboto_condensed_light">sans-serif-condensed-light</string>

This is based on the source code here and here

How can I simulate an anchor click via jquery?

What worked for me was:

$('a.mylink')[0].click()

Adjusting HttpWebRequest Connection Timeout in C#

I believe that the problem is that the WebRequest measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit which by default gets the value from ServicePointManager.DefaultConnectionLimit. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.

I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint limitation.

Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.

And yes, you must code your app around the WebRequest.BeginGetRequestStream (for POSTs with content) and WebRequest.BeginGetResponse (for GETs and POSTSs). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint issue is orthogonal to this: the queueing behavior happens with async calls too.

How do I get textual contents from BLOB in Oracle SQL

In case your text is compressed inside the blob using DEFLATE algorithm and it's quite large, you can use this function to read it

CREATE OR REPLACE PACKAGE read_gzipped_entity_package AS

FUNCTION read_entity(entity_id IN VARCHAR2)
  RETURN VARCHAR2;

END read_gzipped_entity_package;
/

CREATE OR REPLACE PACKAGE BODY read_gzipped_entity_package IS

FUNCTION read_entity(entity_id IN VARCHAR2) RETURN VARCHAR2
IS
    l_blob              BLOB;
    l_blob_length       NUMBER;
    l_amount            BINARY_INTEGER := 10000; -- must be <= ~32765.
    l_offset            INTEGER := 1;
    l_buffer            RAW(20000);
    l_text_buffer       VARCHAR2(32767);
BEGIN
    -- Get uncompressed BLOB
    SELECT UTL_COMPRESS.LZ_UNCOMPRESS(COMPRESSED_BLOB_COLUMN_NAME)
    INTO   l_blob
    FROM   TABLE_NAME
    WHERE  ID = entity_id;

    -- Figure out how long the BLOB is.
    l_blob_length := DBMS_LOB.GETLENGTH(l_blob);

    -- We'll loop through the BLOB as many times as necessary to
    -- get all its data.
    FOR i IN 1..CEIL(l_blob_length/l_amount) LOOP

        -- Read in the given chunk of the BLOB.
        DBMS_LOB.READ(l_blob
        ,             l_amount
        ,             l_offset
        ,             l_buffer);

        -- The DBMS_LOB.READ procedure dictates that its output be RAW.
        -- This next procedure converts that RAW data to character data.
        l_text_buffer := UTL_RAW.CAST_TO_VARCHAR2(l_buffer);

        -- For the next iteration through the BLOB, bump up your offset
        -- location (i.e., where you start reading from).
        l_offset := l_offset + l_amount;
    END LOOP;
    RETURN l_text_buffer;
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('!ERROR: ' || SUBSTR(SQLERRM,1,247));
END;

END read_gzipped_entity_package;
/

Then run select to get text

SELECT read_gzipped_entity_package.read_entity('entity_id') FROM DUAL;

Hope this will help someone.

How do you find out which version of GTK+ is installed on Ubuntu?

This will get the version of the GTK+ libraries for GTK+ 2 and GTK+ 3.

dpkg -l | egrep "libgtk(2.0-0|-3-0)"

As major versions are parallel installable, you may have both on your system, which is my case, so the above command returns this on my Ubuntu Trusty system:

ii  libgtk-3-0:amd64                                      3.10.8-0ubuntu1.6                                   amd64        GTK+ graphical user interface library
ii  libgtk2.0-0:amd64                                     2.24.23-0ubuntu1.4                                  amd64        GTK+ graphical user interface library

This means I have GTK+ 2.24.23 and 3.10.8 installed.

If what you want is the version of the development files, use pkg-config --modversion gtk+-3.0 for example for GTK+ 3. To extend that to the different major versions of GTK+, with some sed magic, this gives:

pkg-config --list-all | sed -ne 's/\(gtk+-[0-9]*.0\).*/\1/p' | xargs pkg-config --modversion

Using ZXing to create an Android barcode scanning app

If you want to include into your code and not use the IntentIntegrator that the ZXing library recommend, you can use some of these ports:

I use the first, and it works perfectly! It has a sample project to try it on.

How to open a new HTML page using jQuery?

Use window.open("file2.html");

Syntax

var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);

Return value and parameters

windowObjectReference 

A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements.

strUrl 

The URL to be loaded in the newly opened window. strUrl can be an HTML document on the web, image file or any resource supported by the browser.

strWindowName 

A string name for the new window. The name can be used as the target of links and forms using the target attribute of an <a> or <form> element. The name should not contain any blank space. Note that strWindowName does not specify the title of the new window.

strWindowFeatures 

Optional parameter listing the features (size, position, scrollbars, etc.) of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma.

jQuery check if Cookie exists, if not create it

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });

Choose File Dialog

Thanx schwiz for idea! Here is modified solution:

public class FileDialog {
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;
    public interface FileSelectedListener {
        void fileSelected(File file);
    }
    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }
    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;    

    /**
    * @param activity 
    * @param initialPath
    */
    public FileDialog(Activity activity, File initialPath) {
        this(activity, initialPath, null);
    }

    public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
        this.activity = activity;
        setFileEndsWith(fileEndsWith);
        if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
            loadFileList(initialPath);
    }

    /**
    * @return file dialog
    */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setTitle(currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d(TAG, currentPath.getPath());
                    fireDirectorySelectedEvent(currentPath);
                }
            });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else fireFileSelectedEvent(chosenFile);
            }
        });

        dialog = builder.show();
        return dialog;
    }


    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
    * Show file dialog
    */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
            public void fireEvent(FileSelectedListener listener) {
                listener.fileSelected(file);
            }
        });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
            public void fireEvent(DirectorySelectedListener listener) {
                listener.directorySelected(directory);
            }
        });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null) r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead()) return false;
                    if (selectDirectoryOption) return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            for (String file : fileList1) {
                r.add(file);
            }
        }
        fileList = (String[]) r.toArray(new String[]{});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
        else return new File(currentPath, fileChosen);
    }

    private void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
    }
}

class ListenerList<L> {
    private List<L> listenerList = new ArrayList<L>();

    public interface FireHandler<L> {
        void fireEvent(L listener);
    }

    public void add(L listener) {
        listenerList.add(listener);
    }

    public void fireEvent(FireHandler<L> fireHandler) {
        List<L> copy = new ArrayList<L>(listenerList);
        for (L l : copy) {
            fireHandler.fireEvent(l);
        }
    }

    public void remove(L listener) {
        listenerList.remove(listener);
    }

    public List<L> getListenerList() {
        return listenerList;
    }
}

Use it on activity onCreate (directory selection option is commented):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
    fileDialog = new FileDialog(this, mPath, ".txt");
    fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
        public void fileSelected(File file) {
            Log.d(getClass().getName(), "selected file " + file.toString());
        }
    });
    //fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
    //  public void directorySelected(File directory) {
    //      Log.d(getClass().getName(), "selected dir " + directory.toString());
    //  }
    //});
    //fileDialog.setSelectDirectoryOption(false);
    fileDialog.showDialog();
}

How to catch an Exception from a thread

It is almost always wrong to extend Thread. I cannot state this strongly enough.

Multithreading Rule #1: Extending Thread is wrong.*

If you implement Runnable instead you will see your expected behaviour.

public class Test implements Runnable {

  public static void main(String[] args) {
    Test t = new Test();
    try {
      new Thread(t).start();
    } catch (RuntimeException e) {
      System.out.println("** RuntimeException from main");
    }

    System.out.println("Main stoped");

  }

  @Override
  public void run() {
    try {
      while (true) {
        System.out.println("** Started");

        Thread.sleep(2000);

        throw new RuntimeException("exception from thread");
      }
    } catch (RuntimeException e) {
      System.out.println("** RuntimeException from thread");
      throw e;
    } catch (InterruptedException e) {

    }
  }
}

produces;

Main stoped
** Started
** RuntimeException from threadException in thread "Thread-0" java.lang.RuntimeException: exception from thread
    at Test.run(Test.java:23)
    at java.lang.Thread.run(Thread.java:619)

* unless you want to change the way your application uses threads, which in 99.9% of cases you don't. If you think you are in the 0.1% of cases, please see rule #1.

Action Bar's onClick listener for the Home button

Best way to customize Action bar onClickListener is onSupportNavigateUp()

This code will be helpful link for helping code

fork() child and parent processes

We control fork() process call by if, else statement. See my code below:

int main()
{
   int forkresult, parent_ID;

   forkresult=fork();
   if(forkresult !=0 )
   {
        printf(" I am the parent my ID is = %d" , getpid());
        printf(" and my child ID is = %d\n" , forkresult);
   }
   parent_ID = getpid();

   if(forkresult ==0)
      printf(" I am the  child ID is = %d",getpid());
   else
      printf(" and my parent ID is = %d", parent_ID);
}

How to prevent sticky hover effects for buttons on touch devices

From 4 ways to deal with sticky hover on mobile: Here's a way to dynamically add or remove a "can touch" class to the document based on the current input type of the user. It works with hybrid devices as well where the user may be switching between touch and a mouse/trackpad:

<script>

;(function(){
    var isTouch = false //var to indicate current input type (is touch versus no touch) 
    var isTouchTimer 
    var curRootClass = '' //var indicating current document root class ("can-touch" or "")

    function addtouchclass(e){
        clearTimeout(isTouchTimer)
        isTouch = true
        if (curRootClass != 'can-touch'){ //add "can-touch' class if it's not already present
            curRootClass = 'can-touch'
            document.documentElement.classList.add(curRootClass)
        }
        isTouchTimer = setTimeout(function(){isTouch = false}, 500) //maintain "istouch" state for 500ms so removetouchclass doesn't get fired immediately following a touch event
    }

    function removetouchclass(e){
        if (!isTouch && curRootClass == 'can-touch'){ //remove 'can-touch' class if not triggered by a touch event and class is present
            isTouch = false
            curRootClass = ''
            document.documentElement.classList.remove('can-touch')
        }
    }

    document.addEventListener('touchstart', addtouchclass, false) //this event only gets called when input type is touch
    document.addEventListener('mouseover', removetouchclass, false) //this event gets called when input type is everything from touch to mouse/ trackpad
})();

</script>

How do I return JSON without using a template in Django?

I think the issue has gotten confused regarding what you want. I imagine you're not actually trying to put the HTML in the JSON response, but rather want to alternatively return either HTML or JSON.

First, you need to understand the core difference between the two. HTML is a presentational format. It deals more with how to display data than the data itself. JSON is the opposite. It's pure data -- basically a JavaScript representation of some Python (in this case) dataset you have. It serves as merely an interchange layer, allowing you to move data from one area of your app (the view) to another area of your app (your JavaScript) which normally don't have access to each other.

With that in mind, you don't "render" JSON, and there's no templates involved. You merely convert whatever data is in play (most likely pretty much what you're passing as the context to your template) to JSON. Which can be done via either Django's JSON library (simplejson), if it's freeform data, or its serialization framework, if it's a queryset.

simplejson

from django.utils import simplejson

some_data_to_dump = {
   'some_var_1': 'foo',
   'some_var_2': 'bar',
}

data = simplejson.dumps(some_data_to_dump)

Serialization

from django.core import serializers

foos = Foo.objects.all()

data = serializers.serialize('json', foos)

Either way, you then pass that data into the response:

return HttpResponse(data, content_type='application/json')

[Edit] In Django 1.6 and earlier, the code to return response was

return HttpResponse(data, mimetype='application/json')

[EDIT]: simplejson was remove from django, you can use:

import json

json.dumps({"foo": "bar"})

Or you can use the django.core.serializers as described above.

Sublime Text 3 how to change the font size of the file sidebar?

The answers are omitting the square brackets, in the case one is creating the file from scratch.

To recap, for the ST3 users who don't have the Default.sublime-theme file (which is actually the default configuration), the simplest procedure is:

  1. Navigate to Sublime Text -> Preferences -> Browse Packages
  2. Open the User directory
  3. Create a file named Default.sublime-theme (if you're using the default theme, otherwise use the theme name, e.g. Material-Theme-Darker.sublime-theme) with the following content (modify font.size as required):

[
    {
        "class": "sidebar_label",
        "color": [0, 0, 0],
        "font.bold": false,
        "font.size": 12
    },
]

For reference, here there is the full file (as found in ST2).

Ubuntu 18.04

Location of theme setting on Ubuntu 18.04, installed via sudo apt install sublime-text:

~/.config/sublime-text-3/Packages/User/Default.sublime-theme

MacOS

Location of theme setting on MacOS, installed via DMG:

~/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/Default.sublime-theme

Delete all objects in a list

Here's how you delete every item from a list.

del c[:]

Here's how you delete the first two items from a list.

del c[:2]

Here's how you delete a single item from a list (a in your case), assuming c is a list.

del c[0]

How to save a BufferedImage as a File

The answer lies within the Java Documentation's Tutorial for Writing/Saving an Image.

The Image I/O class provides the following method for saving an image:

static boolean ImageIO.write(RenderedImage im, String formatName, File output)  throws IOException

The tutorial explains that

The BufferedImage class implements the RenderedImage interface.

so it's able to be used in the method.

For example,

try {
    BufferedImage bi = getMyImage();  // retrieve image
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    // handle exception
}

It's important to surround the write call with a try block because, as per the API, the method throws an IOException "if an error occurs during writing"

Also explained are the method's objective, parameters, returns, and throws, in more detail:

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

Parameters:

im - a RenderedImage to be written.

formatName - a String containg the informal name of the format.

output - a File to be written to.

Returns:

false if no appropriate writer is found.

Throws:

IllegalArgumentException - if any parameter is null.

IOException - if an error occurs during writing.

However, formatName may still seem rather vague and ambiguous; the tutorial clears it up a bit:

The ImageIO.write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.

But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.

For most applications it is sufficient to use one of these standard plugins. They have the advantage of being readily available.

There are, however, additional formats you can use:

The Image I/O class provides a way to plug in support for additional formats which can be used, and many such plug-ins exist. If you are interested in what file formats are available to load or save in your system, you may use the getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These methods return an array of strings listing all of the formats supported in this JRE.

String writerNames[] = ImageIO.getWriterFormatNames();

The returned array of names will include any additional plug-ins that are installed and any of these names may be used as a format name to select an image writer.

For a full and practical example, one can refer to Oracle's SaveImage.java example.

Python extract pattern matches

You can also use a capture group (?P<user>pattern) and access the group like a dictionary match['user'].

string = '''someline abc\n
            someother line\n
            name my_user_name is valid\n
            some more lines\n'''

pattern = r'name (?P<user>.*) is valid'
matches = re.search(pattern, str(string), re.DOTALL)
print(matches['user'])

# my_user_name

Using Thymeleaf when the value is null

You can use 'th:if' together with 'th:text'

<span th:if="${someObject.someProperty != null}" th:text="${someObject.someProperty}">someValue</span>

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

I have met this issue , the error comes out since the error transactions hasn't been ended rightly, I found the postgresql_transactions of Transaction Control command here

Transaction Control

The following commands are used to control transactions

BEGIN TRANSACTION - To start a transaction.

COMMIT - To save the changes, alternatively you can use END TRANSACTION command.

ROLLBACK - To rollback the changes.

so i use the END TRANSACTION to end the error TRANSACTION, code like this:

    for key_of_attribute, command in sql_command.items():
        cursor = connection.cursor()
        g_logger.info("execute command :%s" % (command))
        try:
            cursor.execute(command)
            rows = cursor.fetchall()
            g_logger.info("the command:%s result is :%s" % (command, rows))
            result_list[key_of_attribute] = rows
            g_logger.info("result_list is :%s" % (result_list))
        except Exception as e:
            cursor.execute('END TRANSACTION;')
            g_logger.info("error command :%s and error is :%s" % (command, e))
    return result_list

Changing specific text's color using NSMutableAttributedString in Swift

Based on the answers before I created a string extension

extension String {

func highlightWordsIn(highlightedWords: String, attributes: [[NSAttributedStringKey: Any]]) -> NSMutableAttributedString {
     let range = (self as NSString).range(of: highlightedWords)
     let result = NSMutableAttributedString(string: self)

     for attribute in attributes {
         result.addAttributes(attribute, range: range)
     }

     return result
    }
}

You can pass the attributes for the text to the method

Call like this

  let attributes = [[NSAttributedStringKey.foregroundColor:UIColor.red], [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17)]]
  myLabel.attributedText = "This is a text".highlightWordsIn(highlightedWords: "is a text", attributes: attributes)

javascript: calculate x% of a number

var number = 10000;
var result = .358 * number;

Add quotation at the start and end of each line in Notepad++

  • One simple way is replace \n(newline) with ","(double-quote comma double-quote) after this append double-quote in the start and end of file.

example:

      AliceBlue
      AntiqueWhite
      Aqua
      Aquamarine
      Beige
  • Replcae \n with ","

      AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
    
  • Now append "(double-quote) at the start and end

     "AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
    

If your text contains blank lines in between you can use regular expression \n+ instead of \n

example:

      AliceBlue

      AntiqueWhite
      Aqua


      Aquamarine
      Beige
  • Replcae \n+ with "," (in regex mode)

      AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
    
  • Now append "(double-quote) at the start and end

     "AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
    

C++ floating point to integer type conversions

One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.

int someint = (somedouble+epsilon);

Integer to hex string in C++

I would like to add an answer to enjoy the beauty of C ++ language. Its adaptability to work at high and low levels. Happy programming.

public:template <class T,class U> U* Int2Hex(T lnumber, U* buffer)
{
    const char* ref = "0123456789ABCDEF";
    T hNibbles = (lnumber >> 4);

    unsigned char* b_lNibbles = (unsigned char*)&lnumber;
    unsigned char* b_hNibbles = (unsigned char*)&hNibbles;

    U* pointer = buffer + (sizeof(lnumber) << 1);

    *pointer = 0;
    do {
        *--pointer = ref[(*b_lNibbles++) & 0xF];
        *--pointer = ref[(*b_hNibbles++) & 0xF];
    } while (pointer > buffer);

    return buffer;
}

Examples:

char buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns "0000000012345678"
Int2Hex(305419896UL, buffer);//returns "12345678"
Int2Hex((short)65533, buffer);//returns "FFFD"
Int2Hex((char)18, buffer);//returns "12"

wchar_t buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns L"0000000012345678"
Int2Hex(305419896UL, buffer);//returns L"12345678"
Int2Hex((short)65533, buffer);//returns L"FFFD"
Int2Hex((char)18, buffer);//returns L"12"

How can I print the contents of an array horizontally?

public static void Main(string[] args)
{
    int[] numbers = new int[10];

    Console.Write("index ");

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = i;
        Console.Write(numbers[i] + " ");
    }

    Console.WriteLine("");
    Console.WriteLine("");
    Console.Write("value ");

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = numbers.Length - i;
        Console.Write(numbers[i] + " ");
    }

    Console.ReadKey();
}

How to append something to an array?

Append a value to an array

Since Array.prototype.push adds one or more elements to the end of an array and returns the new length of the array, sometimes we want just to get the new up-to-date array so we can do something like so:

const arr = [1, 2, 3];
const val = 4;

arr.concat([val]); // [1, 2, 3, 4]

Or just:

[...arr, val] // [1, 2, 3, 4]

Get the string value from List<String> through loop for display

List<String> al=new ArrayList<string>();
al.add("One");
al.add("Two");
al.add("Three");

for(String al1:al) //for each construct
{
System.out.println(al1);
}

O/p will be

One
Two
Three

How to delete parent element using jQuery

what about using unwrap()

<div class="parent">
<p class="child">
</p>
</div>

after using - $(".child").unwrap() - it will be;

<p class="child">
</p>

matching query does not exist Error in Django

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return UniversityDetails.objects.get(email__exact=email)
    except UniversityDetails.DoesNotExist:
        return False

Is it better to use NOT or <> when comparing values?

Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.

If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.

Initialize a long in Java

You need to add uppercase L at the end like so

long i = 12345678910L;

Same goes true for float with 3.0f

Which should answer both of your questions

Spring Could not Resolve placeholder

Hopefully it will be still helpful, the application.properties (or application.yml) file must be in both the paths:

  • src/main/resource/config
  • src/test/resource/config

containing the same property you are referring

command/usr/bin/codesign failed with exit code 1- code sign error

In my situation, some pods were out of date after I updated my OS. Here's what fixed it:

In terminal:

cd /Users/quaisafzali/Desktop/AppFolder/Application/
pod install

Then, open your project in Xcode and Clean it (Cmd+Shift+K), then Build/Run.

This worked for me, hope it helps some of you!

Installing PG gem on OS X - failure to build native extension

Try:

gem install pg -- --with-pg-config=`which pg_config`

How to do a redirect to another route with react-router?

For the simple answer, you can use Link component from react-router, instead of button. There is ways to change the route in JS, but seems you don't need that here.

<span className="input-group-btn">
  <Link to="/login" />Click to login</Link>
</span>

To do it programmatically in 1.0.x, you do like this, inside your clickHandler function:

this.history.pushState(null, 'login');

Taken from upgrade doc here

You should have this.history placed on your route handler component by react-router. If it child component beneath that mentioned in routes definition, you may need pass that down further

What is [Serializable] and when should I use it?

Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.

It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.

It has NOTHING to do with XML or JSON serialization.

Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.

Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.

Test class with a new() call in it with Mockito

For the future I would recommend Eran Harel's answer (refactoring moving new to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Real spies should be used carefully and occasionally, for example when dealing with legacy code.

In your case you should write:

TestedClass tc = spy(new TestedClass());
LoginContext lcMock = mock(LoginContext.class);
when(tc.login(anyString(), anyString())).thenReturn(lcMock);

Regular Expression for alphanumeric and underscores

Here is the regex for what you want with a quantifier to specify at least 1 character and no more than 255 characters

[^a-zA-Z0-9 _]{1,255}

MATLAB error: Undefined function or method X for input arguments of type 'double'

The most common cause of this problem is that Matlab cannot find the file on it's search path. Basically, Matlab looks for files in:

  1. The current directory (pwd);
  2. Directly in a directory on the path (to see the path, type path at the command line)
  3. In a directory named @(whatever the class of the first argument is) that is in any directory above.

    As someone else suggested, you can use the command which, but that is often unhelpful in this case - it tells you Matlab can't find the file, which you knew already.

    So the first thing to do is make sure the file is locatable on the path.

    Next thing to do is make sure that the file that matlab is finding (use which) requires the same type as the first argument you are actually passing. I.el, If w is supposed to be different class, and there is a divrat function there, but w is actually empty, [], so matlab is looking for Double/divrat, when there is only a @(yourclass)/divrat. This is just speculation on my part, but this often bites me.

How can I use MS Visual Studio for Android Development?

Yes you can:

http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/

enter image description here

In case you get "Unable to locate tools.jar. Expected to find it in C:\Program Files (x86)\Java\jre6\lib\tools.jar" you can add an environment variable JAVA_HOME that points to your Java JDK path, for example c:\sdks\glassfish3\jdk (restart MSVC afterwards)

An even better solution is using WinGDB Mobile Edition in Visual Studio: it lets you create and debug Android projects all inside Visual Studio:

http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html

Download WinGDC for Android from http://www.wingdb.com/wgMobileEdition.htm

How to specify font attributes for all elements on an html web page?

* {
 font-size: 100%;
 font-family: Arial;
}

The asterisk implies all elements.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

This can occur when Safari is in private mode browsing. While in private browsing, local storage is not available at all.

One solution is to warn the user that the app needs non-private mode to work.

UPDATE: This has been fixed in Safari 11, so the behaviour is now aligned with other browsers.

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

How to convert a huge list-of-vector to a matrix more efficiently?

This should be equivalent to your current code, only a lot faster:

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

How to get element by innerText

Functional approach. Returns array of all matched elements and trims spaces around while checking.

function getElementsByText(str, tag = 'a') {
  return Array.prototype.slice.call(document.getElementsByTagName(tag)).filter(el => el.textContent.trim() === str.trim());
}

Usage

getElementsByText('Text here'); // second parameter is optional tag (default "a")

if you're looking through different tags i.e. span or button

getElementsByText('Text here', 'span');
getElementsByText('Text here', 'button');

The default value tag = 'a' will need Babel for old browsers

How set background drawable programmatically in Android

You can also set the background of any Image:

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

How to split string and push in array using jquery

You don't need jQuery for that, you can do it with normal javascript:

http://www.w3schools.com/jsref/jsref_split.asp

var str = "a,b,c,d";
var res = str.split(","); // this returns an array

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

const http = require('http');
const url = require('url');

http.createServer((req,res)=>{

    const parseObj =  url.parse(req.url,true);
    const users = [{id:1,name:'soura'},{id:2,name:'soumya'}]

    if(parseObj.pathname == '/user-details' && req.method == "GET") {
        let Id = parseObj.query.id;
        let user_details = {};
        users.forEach((data,index)=>{
            if(data.id == Id){
                user_details = data;
            }
        })
        res.writeHead(200,{'x-auth-token':'Auth Token'})
        res.write(JSON.stringify(user_details)) // Json to String Convert
        res.end();
    }
}).listen(8000);

I have used the above code in my existing project.

How do I split a string in Rust?

There is a special method split for struct String:

fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>

Split by char:

let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

Split by string:

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

Split by closure:

let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

How can I convert a dictionary into a list of tuples?

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]

It's not in the order you want, but dicts don't have any specific order anyway.1 Sort it or organize it as necessary.

See: items(), iteritems()


In Python 3.x, you would not use iteritems (which no longer exists), but instead use items, which now returns a "view" into the dictionary items. See the What's New document for Python 3.0, and the new documentation on views.

1: Insertion-order preservation for dicts was added in Python 3.7

How to specify 64 bit integers in c

Use int64_t, that portable C99 code.

int64_t var = 0x0000444400004444LL;

For printing:

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

printf("blabla %" PRIi64 " blabla\n", var);

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

Setting device orientation in Swift iOS

In info.plist file , change the orientations which you want in "supported interface orientation".

In swift the way supporting files->info.plist->supporting interface orientation.

Palindrome check in Javascript

<script>
    function checkForPally() {
        var input = document.getElementById("inputTable").value;
        var input = input.replace(/\s/g, ''); 
        var arrayInput = input.split(); 
        var inputReversed = arrayInput.reverse();
        var stringInputReversed = inputReversed.join("");

        if (input == stringInputReversed) {
            check.value = "The word you enter is a palindrome"
        }
        if (input != stringInputReversed) {
            check.value = "The word you entered is not a palindrome"
        }
    }
</script>

You first use the getElement tag to set the initial variable of the palindrome. Seeing as a palindrome can be multiple words you use the regex entry to remove the whitespaces. You then use the split function to convert the string into an array.

Next up, you use the reverse method to reverse the array when this is done you join the reversed array back into a string. Lastly, you just use a very basic if statement to check for equality, if the reversed value is equall to the initial variable you have yourself a palindrome.

jquery, selector for class within id

I think your asking to select only <span class = "my_class">hello</span> this element, You have do like this, If I am understand your question correctly this is the answer,

$("#my_id [class='my_class']").addClass('test');

DEMO

Check variable equality against a list of values

Using the answers provided, I ended up with the following:

Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}

It can be called like:

if(foo.in(1, 3, 12)) {
    // ...
}

Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

/foo|bar|something/.test(str);

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

/^(foo|bar|something)$/.test(str);

How do I resolve this "ORA-01109: database not open" error?

If your database is down then during login as SYSDBA you can assume this. While login command will be executed like sqlplus sys/sys_password as sysdba that time you will get "connected to idle instance" reply from database. This message indicates your database is down. You should need to check first alert.log file about why database is down. If you found it was downed normally then you can issue "startup" command for starting database and after that execute your create user command. If you found database is having issue like missing datafile or something else then you need to recover database first and open database for executing your create user command.

"alter database open" command only accepted by database while it is on Mount stage. If database is down then it won't accept "alter database open" command.

Show percent % instead of counts in charts of categorical variables

With ggplot2 version 2.1.0 it is

+ scale_y_continuous(labels = scales::percent)

Ruby Hash to array of values

I would use:

hash.map { |key, value| value }

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

$ sudo npm i -g increase-memory-limit

Run from the root location of your project:

$ increase-memory-limit

This tool will append --max-old-space-size=4096 in all node calls inside your node_modules/.bin/* files.


Node.js version >= 8 - DEPRECATION NOTICE

Since NodeJs V8.0.0, it is possible to use the option --max-old-space-size. NODE_OPTIONS=options...

$ export NODE_OPTIONS=--max_old_space_size=4096

How can I pause setInterval() functions?

You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value. So there is no need to pause timer and you will get best possible accuracy in this way.

How to debug "ImagePullBackOff"?

I was facing the similar problem, but instead of one all of my pods were not ready and displaying Ready status 0/1 Something like enter image description here

I tried a lot of things but at last i found that the context was not correctly set. Please use following command and ensure you are in correct context

kubectl config get-contexts

How to clear Route Caching on server: Laravel 5.2.37

If you want to remove the routes cache on your server, remove this file:

bootstrap/cache/routes.php

And if you want to update it just run php artisan route:cache and upload the bootstrap/cache/routes.php to your server.

How to hide a TemplateField column in a GridView

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
         e.Row.Cells[columnIndex].Visible = false;
}


If you don't prefer hard-coded index, the only workaround I can suggest is to provide a HeaderText for the GridViewColumn and then find the column using that HeaderText.

protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
    ((DataControlField)UsersGrid.Columns
            .Cast<DataControlField>()
            .Where(fld => fld.HeaderText == "Email")
            .SingleOrDefault()).Visible = false;
}

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

In my case this error was provoked by a size of a string column. What was weird was when I executed the exact same query in different tool, repeated values nor null values weren't there.

Then I discovered that the size of a string column size was 50 so when I called the fill method the value was chopped, throwing this exception.
I click on the column and set in the properties the size to 200 and the error was gone.

Hope this help

Finding longest string in array

Using Array.prototype - (sort is similar to what was posted by @katsPaugh and @deceze while I was doing a fiddle)

DEMO HERE

var arr = [
    "2 --",
    "3 ---",
    "4 ----",
    "1 -",
    "5 -----"
];

Array.prototype.longest=function() {
    return this.sort(
      function(a,b) {  
        if (a.length > b.length) return -1;
        if (a.length < b.length) return 1;
          return 0
      }
    )[0];
}
alert(arr.longest());    

Angularjs checkbox checked by default on load and disables Select list when checked

Do it in the controller ( controller as syntax below)

controller:

vm.question= {};
vm.question.active = true;

form

<input ng-model="vm.question.active" type="checkbox" id="active" name="active">

Changing three.js background to transparent or other color

In 2020 using r115 it works very good with this:

const renderer = new THREE.WebGLRenderer({ alpha: true }); const scene = new THREE.Scene(); scene.background = null;

Difference between Role and GrantedAuthority in Spring Security

Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.

Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST

These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

@Autowired 
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685

To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions

How to make a transparent HTML button?

**add the icon top button like this **

_x000D_
_x000D_
#copy_btn{_x000D_
 align-items: center;_x000D_
 position: absolute;_x000D_
 width: 30px;_x000D_
  height: 30px;_x000D_
     background-color: Transparent;_x000D_
    background-repeat:no-repeat;_x000D_
    border: none;_x000D_
    cursor:pointer;_x000D_
    overflow: hidden;_x000D_
    outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
 position: absolute;_x000D_
 padding: 0px;_x000D_
 top:0;_x000D_
 left: 0;_x000D_
width: 25px;_x000D_
  height: 35px;_x000D_
  _x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
                        <img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
_x000D_
_x000D_

How to access a preexisting collection with Mongoose?

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

or model mapped:

mongoose.model('Question', 
               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name

Downloading an entire S3 bucket?

Try this command:

aws s3 sync yourBucketnameDirectory yourLocalDirectory

For example, if your bucket name is myBucket and local directory is c:\local, then:

aws s3 sync s3://myBucket c:\local

For more informations about awscli check this aws cli installation

Saving timestamp in mysql table using php

If I know the database is MySQL, I'll use the NOW() function like this:

INSERT INTO table_name
   (id, name, created_at) 
VALUES 
   (1, 'Gordon', NOW()) 

LINQ - Full Outer Join

I don't know if this covers all cases, logically it seems correct. The idea is to take a left outer join and right outer join then take the union of the results.

var firstNames = new[]
{
    new { ID = 1, Name = "John" },
    new { ID = 2, Name = "Sue" },
};
var lastNames = new[]
{
    new { ID = 1, Name = "Doe" },
    new { ID = 3, Name = "Smith" },
};
var leftOuterJoin =
    from first in firstNames
    join last in lastNames on first.ID equals last.ID into temp
    from last in temp.DefaultIfEmpty()
    select new
    {
        first.ID,
        FirstName = first.Name,
        LastName = last?.Name,
    };
var rightOuterJoin =
    from last in lastNames
    join first in firstNames on last.ID equals first.ID into temp
    from first in temp.DefaultIfEmpty()
    select new
    {
        last.ID,
        FirstName = first?.Name,
        LastName = last.Name,
    };
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);

This works as written since it is in LINQ to Objects. If LINQ to SQL or other, the query processor might not support safe navigation or other operations. You'd have to use the conditional operator to conditionally get the values.

i.e.,

var leftOuterJoin =
    from first in firstNames
    join last in lastNames on first.ID equals last.ID into temp
    from last in temp.DefaultIfEmpty()
    select new
    {
        first.ID,
        FirstName = first.Name,
        LastName = last != null ? last.Name : default,
    };

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.