Programs & Examples On #Qdockwidget

QDockWidget is a class from the Qt framework which represents a widget which can be docked inside a QMainWindow or floated as a top-level window in the desktop. Instances of this class are also called "dock widgets", "tool palettes" and "utility windows".

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

How to append rows to an R data frame

Update with purrr, tidyr & dplyr

As the question is already dated (6 years), the answers are missing a solution with newer packages tidyr and purrr. So for people working with these packages, I want to add a solution to the previous answers - all quite interesting, especially .

The biggest advantage of purrr and tidyr are better readability IMHO. purrr replaces lapply with the more flexible map() family, tidyr offers the super-intuitive method add_row - just does what it says :)

map_df(1:1000, function(x) { df %>% add_row(x = x, y = toString(x)) })

This solution is short and intuitive to read, and it's relatively fast:

system.time(
   map_df(1:1000, function(x) { df %>% add_row(x = x, y = toString(x)) })
)
   user  system elapsed 
   0.756   0.006   0.766

It scales almost linearly, so for 1e5 rows, the performance is:

system.time(
  map_df(1:100000, function(x) { df %>% add_row(x = x, y = toString(x)) })
)
   user  system elapsed 
 76.035   0.259  76.489 

which would make it rank second right after data.table (if your ignore the placebo) in the benchmark by @Adam Ryczkowski:

nr  function      time
4   data.frame    228.251 
3   sqlite        133.716
2   data.table      3.059
1   rbindlist     169.998 
0   placebo         0.202

Pentaho Data Integration SQL connection

Turns out I will missing a class called mysql-connector-java-5.1.2.jar, I added it this folder (C:\Program Files\pentaho\design-tools\data-integration\lib) and it worked with a MySQL connection and my data and tables appear.

C# - using List<T>.Find() with custom objects

You can use find with a Predicate as follows:

list.Find(x => x.Id == IdToFind);

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).

How do you get the width and height of a multi-dimensional array?

ary.GetLength(0) 
ary.GetLength(1)

for 2 dimensional array

Why is it said that "HTTP is a stateless protocol"?

HTTP is stateless. TCP is stateful. There is no so-called HTTP connection, but only HTTP request and HTTP response. We don't need anything to be maintained to make another HTTP request. A connection header that is "keep-alive" means the TCP will be reused by the subsequent HTTP requests and responses, instead of disconnecting and re-establishing TCP connection all the time.

Stacking DIVs on top of each other?

style="position:absolute"

The type initializer for 'MyClass' threw an exception

My Answer is also related to Config section. If you assign values from Config file at static class of C# or Module.VB of VB, you will get this error at run time.

add key="LogPath" value="~/Error_Log/"

Using Forward slash in Web.Config also leads to this error on Run time. I just resolved this issue by putting BackSlash

add key="LogPath" value="~\Error_Log\"

Android check null or empty string in Android

All you can do is to call equals() method on empty String literal and pass the object you are testing as shown below :

 String nullString = null;
 String empty = new String();
 boolean test = "".equals(empty); // true 
 System.out.println(test); 
 boolean check = "".equals(nullString); // false 
 System.out.println(check);

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

Remove all subviews?

If you want to remove all the subviews on your UIView (here yourView), then write this code at your button click:

[[yourView subviews] makeObjectsPerformSelector: @selector(removeFromSuperview)];

How do you open an SDF file (SQL Server Compact Edition)?

Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.

You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.

If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.

Update: comment from Nick Westgate in nice formatting

The steps are not all that intuitive:

  1. Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
  2. In the Connect to Server dialog change Server type to SQL Server Compact Edition
  3. From the Database file dropdown select < Browse for more...>
  4. Open your SDF file.

LEFT JOIN only first row

@Matt Dodges answer put me on the right track. Thanks again for all the answers, which helped a lot of guys in the mean time. Got it working like this:

SELECT *
FROM feeds f
LEFT JOIN artists a ON a.artist_id = (
    SELECT artist_id
    FROM feeds_artists fa 
    WHERE fa.feed_id = f.id
    LIMIT 1
)
WHERE f.id = '13815'

remove attribute display:none; so the item will be visible

If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.

$("span").toggle();

Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
_x000D_
_x000D_

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

Convert double to BigDecimal and set BigDecimal Precision

The String.format syntax helps us convert doubles and BigDecimals to strings of whatever precision.

This java code:

double dennis = 0.00000008880000d;
System.out.println(dennis);
System.out.println(String.format("%.7f", dennis));
System.out.println(String.format("%.9f", new BigDecimal(dennis)));
System.out.println(String.format("%.19f", new BigDecimal(dennis)));

Prints:

8.88E-8
0.0000001
0.000000089
0.0000000888000000000

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

Paused in debugger in chrome?

Threads > switch "Main" to "app"

In the "Threads" section I changed the context from "Main" > to "app". The "app" should have a blue arrow aside.

How do I enable logging for Spring Security?

Spring security logging for webflux reactive apps is now available starting with version 5.4.0-M2 (as mentionned by @bzhu in comment How do I enable logging for Spring Security?)

Until this gets into a GA release, here is how to get this milestone release in gradle

repositories {
    mavenCentral()
    if (!version.endsWith('RELEASE')) {
        maven { url "https://repo.spring.io/milestone" }
    }
}

// Force earlier milestone release to get securing logging preview
// https://docs.spring.io/spring-security/site/docs/current/reference/html5/#getting-gradle-boot
// https://github.com/spring-projects/spring-security/pull/8504
// https://github.com/spring-projects/spring-security/releases/tag/5.4.0-M2
ext['spring-security.version']='5.4.0-M2'
dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }

}

How to install JSON.NET using NuGet?

I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

enter image description here

What should be in my .gitignore for an Android Studio project?

https://github.com/github/gitignore is awesome collection

Android.gitignore

# Built application files
*.apk
*.ap_

# Files for the ART/Dalvik VM
*.dex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Log Files
*.log

# Android Studio Navigation editor temp files
.navigation/

# Android Studio captures folder
captures/

# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
.idea/caches

# Keystore files
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks

# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild

# Google Services (e.g. APIs or Firebase)
google-services.json

# Freeline
freeline.py
freeline/
freeline_project_description.json

# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md

Cannot find R.layout.activity_main

Thanks to @RubberDuck's comment and @Emil's answer I was able to figure out what the problem was. The IDs of most elements in my XML file were exactly the same. So, I renamed each and every one of them. Also, my XML file contained capital letters. The filename should be in [a-z0-9_] so I renamed my files too and the problem was solved.

How to install and use "make" in Windows?

Another alternative is if you already installed minGW and added the bin folder the to Path environment variable, you can use "mingw32-make" instead of "make".

You can also create a symlink from "make" to "mingw32-make", or copying and changing the name of the file. I would not recommend the options before, they will work until you do changes on the minGW.

Why am I getting Unknown error in line 1 of pom.xml?

For me I changed in the parent tag of the pom.xml and it solved it change 2.1.5 to 2.1.4 then Maven-> Update Project. its worked for me also.

PHP: Possible to automatically get all POSTed data?

To add to the others, var_export might be handy too:

$email_text = var_export($_POST, true);

GitHub README.md center image

Alternatively, if you have control of the css, you could get clever with url parameters and css.

Markdown:

![A cute kitten](http://placekitten.com/200/300?style=centerme)

And CSS:

img[src$="centerme"] {
  display:block;
  margin: 0 auto;
}

You could create a variety of styling options this way and still keep the markdown clean of extra code. Of course you have no control over what happens if someone else uses the markdown somewhere else but thats a general styling issue with all markdown documents one shares.

What is the difference between the operating system and the kernel?

The difference between an operating system and a kernel:

The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:

  1. memory management
  2. network management
  3. device driver
  4. file management
  5. process management

Variable declaration in a header file

You should declare the variable in a header file:

extern int x;

and then define it in one C file:

int x;

In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).

Android: keeping a background service alive (preventing process death)

As Dave already pointed out, you could run your Service with foreground priority. But this practice should only be used when it's absolutely necessary, i.e. when it would cause a bad user experience if the Service got killed by Android. This is what the "foreground" really means: Your app is somehow in the foreground and the user would notice it immediately if it's killed (e.g. because it played a song or a video).

In most cases, requesting foreground priority for your Service is contraproductive!

Why is that? When Android decides to kill a Service, it does so because it's short of resources (usually RAM). Based on the different priority classes, Android decides which running processes, and this included services, to terminate in order to free resources. This is a healthy process that you want to happen so that the user has a smooth experience. If you request foreground priority, without a good reason, just to keep your service from being killed, it will most likely cause a bad user experience. Or can you guarantee that your service stays within a minimal resource consumption and has no memory leaks?1

Android provides sticky services to mark services that should be restarted after some grace period if they got killed. This restart usually happens within a few seconds.

Image you want to write an XMPP client for Android. Should you request foreground priority for the Service which contains your XMPP connection? Definitely no, there is absolutely no reason to do so. But you want to use START_STICKY as return flag for your service's onStartCommand method. So that your service is stopped when there is resource pressure and restarted once the situation is back to normal.

1: I am pretty sure that many Android apps have memory leaks. It something the casual (desktop) programmer doesn't care that much about.

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

How to set Java environment path in Ubuntu

To set up system wide scope you need to use the

/etc/environment file sudo gedit /etc/environment

is the location where you can define any environment variable. It can be visible in the whole system scope. After variable is defined system need to be restarted.

EXAMPLE :

sudo gedit /etc/environment

Add like following :

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"
JAVA_HOME="/opt/jdk1.6.0_45/"

Here is the site you can find more : http://peesquare.com/blogs/environment-variable-setup-on-ubuntu/

What is the difference between the | and || or operators?

|| is the logical OR operator. It sounds like you basically know what that is. It's used in conditional statements such as if, while, etc.

condition1 || condition2

Evaluates to true if either condition1 OR condition2 is true.

| is the bitwise OR operator. It's used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:

A = 01010101
B = 10101010
A | B = 11111111

A = 00000001
B = 00010000
A | B = 00010001

A = 10001011
B = 00101100

A | B = 10101111

Hopefully that makes sense.

So to answer the last two questions, I wouldn't say there are any caveats besides "know the difference between the two operators." They're not interchangeable because they do two completely different things.

Set transparent background of an imageview on Android

In Android Studio it is very simple to adjust color and opacity using a built-in tool:

Android Adjust Color Opacity

Maven error: Not authorized, ReasonPhrase:Unauthorized

I have recently encountered this problem. Here are the steps to resolve

  1. Check the servers section in the settings.xml file.Is username and password correct?

_x000D_
_x000D_
<servers>_x000D_
  <server>_x000D_
    <id>serverId</id>_x000D_
    <username>username</username>_x000D_
    <password>password</password>_x000D_
  </server>_x000D_
</servers>
_x000D_
_x000D_
_x000D_

  1. Check the repository section in the pom.xml file.The id of the server tag should be the same as the id of the repository tag.

_x000D_
_x000D_
<repositories>_x000D_
 <repository>_x000D_
   <id>serverId</id>  _x000D_
   <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
 </repository>_x000D_
</repositories>
_x000D_
_x000D_
_x000D_

  1. If the repository tag is not configured in the pom.xml file, look in the settings.xml file.

_x000D_
_x000D_
<profiles>_x000D_
 <profile>_x000D_
   <repositories>_x000D_
     <repository>_x000D_
      <id>serverId</id>_x000D_
      <name>aliyun</name>_x000D_
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
     </repository>_x000D_
   </repositories>_x000D_
 </profile>_x000D_
</profiles>
_x000D_
_x000D_
_x000D_

Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.

How to include another XHTML in XHTML using JSF 2.0 Facelets?

<ui:include>

Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Include demo</title>
    </h:head>
    <h:body>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />
    </h:body>
</html>

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

<ui:composition 
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>
</ui:composition>
  

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


<ui:define>/<ui:insert>

A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title><ui:insert name="title">Default title</ui:insert></title>
    </h:head>
    <h:body>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>
    </h:body>
</html>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <ui:define name="title">
        New page title here
    </ui:define>

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>
    </ui:define>
</ui:composition>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


<ui:param>

You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
    <ui:param name="foo" value="#{bean.foo}" />
    ...
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

How to delete all instances of a character in a string in python?

>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'

Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1 argument.

Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)

Unable to install packages in latest version of RStudio and R Version.3.1.1

Please check the following to be able to install new packages:

1- In Tools -> Global Options -> Packages, uncheck the "Use Internet Explorer library/proxy for HTTP" option,

2- In Tools -> Global Options -> Packages, change the CRAN mirror to "0- Cloud - Rstudio, automatic redirection to servers worldwide"

3- Restart Rstudio.

4- Have fun!

What is a simple C or C++ TCP server and client example?

Here are some examples for:

1) Simple
2) Fork
3) Threads

based server:

http://www.martinbroadhurst.com/server-examples.html

How to transform numpy.matrix or array to scipy sparse matrix

In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse

The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:

  1. Block Sparse Row matrix
  2. A sparse matrix in COOrdinate format.
  3. Compressed Sparse Column matrix
  4. Compressed Sparse Row matrix
  5. Sparse matrix with DIAgonal storage
  6. Dictionary Of Keys based sparse matrix.
  7. Row-based list of lists sparse matrix
  8. This class provides a base class for all sparse matrices.

CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.

Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:

import sys                 # Return the size of an object in bytes
import numpy as np         # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix 
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix

create a 2-D Numpy matrix

A = np.array([[1, 0, 0, 0, 0, 0],\
              [0, 0, 2, 0, 0, 1],\
              [0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))

Print the matrix & other details:

Dense matrix representation: 
 [[1 0 0 0 0 0]
 [0 0 2 0 0 1]
 [0 0 0 2 0 0]]
Memory utilised (bytes):  184
Type of the object <class 'numpy.ndarray'>

Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:

S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>

Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:

S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>

As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes.

For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/

How to create a string with format?

There is a simple solution I learned with "We <3 Swift" if you can't either import Foundation, use round() and/or does not want a String:

var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0

result: 31.726

Copy Paste Values only( xlPasteValues )

If you are wanting to just copy the whole column, you can simplify the code a lot by doing something like this:

Sub CopyCol()

    Sheets("Sheet1").Columns(1).Copy

    Sheets("Sheet2").Columns(2).PasteSpecial xlPasteValues

End Sub

Or

Sub CopyCol()

    Sheets("Sheet1").Columns("A").Copy

    Sheets("Sheet2").Columns("B").PasteSpecial xlPasteValues

End Sub

Or if you want to keep the loop

Public Sub CopyrangeA()

    Dim firstrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    firstrowDB = 1
    arr1 = Array("BJ", "BK")
    arr2 = Array("A", "B")

    For i = LBound(arr1) To UBound(arr1)

        Sheets("Sheet1").Columns(arr1(i)).Copy

        Sheets("Sheet2").Columns(arr2(i)).PasteSpecial xlPasteValues

    Next
    Application.CutCopyMode = False

End Sub

Push items into mongo array via mongoose

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

Are HTTPS URLs encrypted?

It is now 2019 and the TLS v1.3 has been released. According to Cloudflare, the server name indication (SNI aka the hostname) can be encrypted thanks to TLS v1.3. So, I told myself great! Let's see how it looks within the TCP packets of cloudflare.com So, I caught a "client hello" handshake packet from a response of the cloudflare server using Google Chrome as browser & wireshark as packet sniffer. I still can read the hostname in plain text within the Client hello packet as you can see below. It is not encrypted.

enter image description here

So, beware of what you can read because this is still not an anonymous connection. A middleware application between the client and the server could log every domain that are requested by a client.

So, it looks like the encryption of the SNI requires additional implementations to work along with TLSv1.3

UPDATE June 2020: It looks like the Encrypted SNI is initiated by the browser. Cloudflare has a page for you to check if your browser supports Encrypted SNI:

https://www.cloudflare.com/ssl/encrypted-sni/

At this point, I think Google chrome does not support it. You can activate Encrypted SNI in Firefox manually. When I tried it for some reason, it didn't work instantly. I restarted Firefox twice before it worked:

Type: about:config in the URL field.

Check if network.security.esni.enabled is true. Clear your cache / restart

Go to the website, I mentioned before.

As you can see VPN services are still useful today for people who want to ensure that a coffee shop owner does not log the list of websites that people visit.

Does Android keep the .apk files? if so where?

Preinstalled Apps are typically in /system/app and user installed apps are in /data/app.

You can use "adb pull", but you need to know the full path of the APK file. On the emulator, you can get a directory listing using "adb shell" + "ls". But on an android device, you will not be able to do that in "/data" folder due to security reasons. So how do you figure out the full path of the APK file?

You can get a full list of all apps installed by writing a program that queries the PackageManager. Short code snippet below:

PackageManager  pm = getPackageManager();
List<PackageInfo> pkginfo_list = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES);
List<ApplicationInfo> appinfo_list = pm.getInstalledApplications(0);
for (int x=0; x < pkginfo_list.size(); x++){             
  PackageInfo pkginfo = pkginfo_list.get(x);
  pkg_path[x] = appinfo_list.get(x).publicSourceDir;  //store package path in array
}

You can also find apps that will give such info. There are lots of them. Try this one (AppSender).

Sound effects in JavaScript / HTML5

I would recommend using SoundJS, a library I've help develop. It allows you to write a single code base that works everywhere, with SoundJS picking web audio, html audio, or flash audio as appropriate.

It will allow you to do all of the thing you want:

  • Play and mix multiple sounds,
  • Play the same sample multiple times, possibly overlapping playbacks
  • Interrupt playback of a sample at any point
  • play WAV files containing (depending on browser support)

Hope that helps.

Binding value to input in Angular JS

Use ng-value for set value of input box after clicking on a button:

"input type="email"  class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"

and

Set Value as:

 $scope.myForm.email2 = $scope.names[0].success;

Phonegap + jQuery Mobile, real world sample or tutorial

These may not solve exactly your "real-world problems", but perhaps something useful ...

Our web site includes PhoneGap and jQuery Mobile tutorials for a media player, barcode scanner, google maps, and OAuth.

Also, my github page has code, but no tutorial, for two apps:

  • AppLaudApp - a run-control, debugging enabling, download complementary app to a cloud IDE
  • NameTrendz - an app developed in at Android Dev Camp to do a bunch of queries about popular name data. The PhoneGap and jQuery Mobile versions are from March 2011.

Java 8 stream map to list of keys sorted by values

You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting

countByType.entrySet()
           .stream()
           .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
           .map(e -> e.getKey())
           .collect(Collectors.toList());

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

How to do integer division in javascript (Getting division answer in int not float)?

var x = parseInt(455/10);

The parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)

jQuery - Getting form values for ajax POST

try as this code.

$.ajax({
        type: "POST",
        url: "http://rt.ja.com/includes/register.php?submit=1",
        data: "username="+username+"&email="+email+"&password="+password+"&passconf="+passconf,

        success: function(html)
        {   
            //alert(html);
            $('#userError').html(html);
            $("#userError").html(userChar);
            $("#userError").html(userTaken);
        }
    });

i think this will work definitely..

you can also use .serialize() function for sending data via jquery Ajax..

i.e: data : $("#registerSubmit").serialize()

Thanks.

Read .doc file with python

You can use python-docx2txt library to read text from Microsoft Word documents. It is an improvement over python-docx library as it can, in addition, extract text from links, headers and footers. It can even extract images.

You can install it by running: pip install docx2txt.

Let's download and read the first Microsoft document on here:

import docx2txt
my_text = docx2txt.process("test.docx")
print(my_text)

Here is a screenshot of the Terminal output the above code:

enter image description here

EDIT:

This does NOT work for .doc files. The only reason I am keep this answer is that it seems there are people who find it useful for .docx files.

How to get datetime in JavaScript?

try this:

_x000D_
_x000D_
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours()+':'+today.getMinutes()+':'+today.getSeconds();
console.log(date + ' '+ time);
_x000D_
_x000D_
_x000D_

How do you dynamically allocate a matrix?

 #include <iostream>

    int main(){
        int rows=4;
        int cols=4;
        int **arr;

        arr = new int*[rows];
        for(int i=0;i<rows;i++){
           arr[i]=new int[cols];
        }
        // statements

        for(int i=0;i<rows;i++){
           delete []arr[i];
        }
        delete []arr;
        return 0;
     }

Using SSH keys inside docker container

In later versions of docker (17.05) you can use multi stage builds. Which is the safest option as the previous builds can only ever be used by the subsequent build and are then destroyed

See the answer to my stackoverflow question for more info

Android: remove notification from notification bar

You can try this quick code

public static void cancelNotification(Context ctx, int notifyId) {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
    nMgr.cancel(notifyId);
}

Conversion between UTF-8 ArrayBuffer and String

The latest answers to these type of questions (using nowadays methods) is here: Converting between strings and ArrayBuffers

Is it possible to set the stacking order of pseudo-elements below their parent element?

There are two issues are at play here:

  1. The CSS 2.1 specification states that "The :beforeand :after pseudo-elements elements interact with other boxes, such as run-in boxes, as if they were real elements inserted just inside their associated element." Given the way z-indexes are implemented in most browsers, it's pretty difficult (read, I don't know of a way) to move content lower than the z-index of their parent element in the DOM that works in all browsers.

  2. Number 1 above does not necessarily mean it's impossible, but the second impediment to it is actually worse: Ultimately it's a matter of browser support. Firefox didn't support positioning of generated content at all until FF3.6. Who knows about browsers like IE. So even if you can find a hack to make it work in one browser, it's very likely it will only work in that browser.

The only thing I can think of that's going to work across browsers is to use javascript to insert the element rather than CSS. I know that's not a great solution, but the :before and :after pseudo-selectors just really don't look like they're gonna cut it here.

Commenting code in Notepad++

Yes in Notepad++ you can do that!

Some hotkeys regarding comments:

  • Ctrl+Q Toggle block comment
  • Ctrl+K Block comment
  • Ctrl+Shift+K Block uncomment
  • Ctrl+Shift+Q Stream comment

Source: shortcutworld.com from the Comment / uncomment section.

On the link you will find many other useful shortcuts too.

MongoDB running but can't connect using shell

I don't see this having an accepted answer yet, so I'll just add my 2 cents.

I had the exact same issue just now. After a while I realized I've locked localhost out in my iptables rules. So, check your firewall.

How to convert a private key to an RSA private key?

This may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):

Which Command to Apply When

It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.

Here are the commands again for easier copy-pasting:

openssl rsa                                                -in $FF -out $TF
openssl rsa -aes256                                        -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt                              -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF

and

openssl rsa -check -in $FF
openssl rsa -text  -in $FF

How to Update Date and Time of Raspberry Pi With out Internet

Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)

server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst

3. If you want to make sure that date and time update at startup run this python script in rpi,

import os

try:
    client = ntplib.NTPClient()
    response = client.request('xxx.xxx.xxx.xxx', version=4)
    print "===================================="
    print "Offset : "+str(response.offset)
    print "Version : "+str(response.version)
    print "Date Time : "+str(ctime(response.tx_time))
    print "Leap : "+str(ntplib.leap_to_text(response.leap))
    print "Root Delay : "+str(response.root_delay)
    print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
    os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
    print "===================================="
except:
    os.system("sudo date")
    print "NTP Server Down Date Time NOT Set At The Startup"
    pass

I found more info in raspberry pi forum.

How to upgrade Python version to 3.7?

Try this if you are on ubuntu:

sudo apt-get update
sudo apt-get install build-essential libpq-dev libssl-dev openssl libffi-dev zlib1g-dev
sudo apt-get install python3-pip python3.7-dev
sudo apt-get install python3.7

In case you don't have the repository and so it fires a not-found package you first have to install this:

sudo apt-get install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update

more info here: http://devopspy.com/python/install-python-3-6-ubuntu-lts/

An example of how to use getopts in bash

The problem with the original code is that:

  • h: expects parameter where it shouldn't, so change it into just h (without colon)
  • to expect -p any_string, you need to add p: to the argument list

Basically : after the option means it requires the argument.


The basic syntax of getopts is (see: man bash):

getopts OPTSTRING VARNAME [ARGS...]

where:

  • OPTSTRING is string with list of expected arguments,

    • h - check for option -h without parameters; gives error on unsupported options;
    • h: - check for option -h with parameter; gives errors on unsupported options;
    • abc - check for options -a, -b, -c; gives errors on unsupported options;
    • :abc - check for options -a, -b, -c; silences errors on unsupported options;

      Notes: In other words, colon in front of options allows you handle the errors in your code. Variable will contain ? in the case of unsupported option, : in the case of missing value.

  • OPTARG - is set to current argument value,

  • OPTERR - indicates if Bash should display error messages.

So the code can be:

#!/usr/bin/env bash
usage() { echo "$0 usage:" && grep " .)\ #" $0; exit 0; }
[ $# -eq 0 ] && usage
while getopts ":hs:p:" arg; do
  case $arg in
    p) # Specify p value.
      echo "p is ${OPTARG}"
      ;;
    s) # Specify strength, either 45 or 90.
      strength=${OPTARG}
      [ $strength -eq 45 -o $strength -eq 90 ] \
        && echo "Strength is $strength." \
        || echo "Strength needs to be either 45 or 90, $strength found instead."
      ;;
    h | *) # Display help.
      usage
      exit 0
      ;;
  esac
done

Example usage:

$ ./foo.sh 
./foo.sh usage:
    p) # Specify p value.
    s) # Specify strength, either 45 or 90.
    h | *) # Display help.
$ ./foo.sh -s 123 -p any_string
Strength needs to be either 45 or 90, 123 found instead.
p is any_string
$ ./foo.sh -s 90 -p any_string
Strength is 90.
p is any_string

See: Small getopts tutorial at Bash Hackers Wiki

What is the best collation to use for MySQL with PHP?

For UTF-8 textual information, you should use utf8_general_ci because...

  • utf8_bin: compare strings by the binary value of each character in the string

  • utf8_general_ci: compare strings using general language rules and using case-insensitive comparisons

a.k.a. it will should making searching and indexing the data faster/more efficient/more useful.

How to set session variable in jquery?

You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

sessionStorage.setItem("username", "John");

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

Browser Compatibility https://code.google.com/p/sessionstorage/ compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/

How to change current working directory using a batch file

A simpler syntax might be

pushd %root%

Change the "From:" address in Unix "mail"

It's also possible to set both the From name and from address using something like:

 echo test | mail -s "test" [email protected] -- -F'Some Name<[email protected]>' -t

For some reason passing -F'Some Name' and [email protected] doesn't work, but passing in the -t to sendmail works and is "easy".

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Comparing websocket and webrtc is unfair.

Websocket is based on top of TCP. Packet's boundary can be detected from header information of a websocket packet unlike tcp.

Typically, webrtc makes use of websocket. The signalling for webrtc is not defined, it is upto the service provider what kind of signalling he wants to use. It may be SIP, HTTP, JSON or any text / binary message.

The signalling messages can be send / received using websocket.

How to enable DataGridView sorting when user clicks on the column header?

In my case, the problem was that I had set my DataSource as an object, which is why it didn't get sorted. After changing from object to a DataTable it workd well without any code complement.

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

In My Case, Im trying to pass messages from Salesforce Marketing Cloud Custom Activity(Domain 1) to Heroku(Domain 2) on load.

The Error Appeared in console, when I loaded my original html page from where message is being passed.

Issue I noticed after reading many blogs is that, the receiver page is not loaded yet. i.e

I need to debug from my receiver page not from sender page.

Simple but glad if it helps anyone.

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

JQuery confirm dialog

Have you tried using the official JQueryUI implementation (not jQuery only) : ?

Escape double quotes in parameter

The 2nd document quoted by Peter Mortensen in his comment on the answer of Codesmith made things much clearer for me. That document was written by windowsinspired.com. The link repeated: A Better Way To Understand Quoting and Escaping of Windows Command Line Arguments.

Some further trial and error leads to the following guideline:

Escape every double quote " with a caret ^. If you want other characters with special meaning to the Windows command shell (e.g., <, >, |, &) to be interpreted as regular characters instead, then escape them with a caret, too.

If you want your program foo to receive the command line text "a\"b c" > d and redirect its output to file out.txt, then start your program as follows from the Windows command shell:

foo ^"a\^"b c^" ^> d > out.txt

If foo interprets \" as a literal double quote and expects unescaped double quotes to delimit arguments that include whitespace, then foo interprets the command as specifying one argument a"b c, one argument >, and one argument d.

If instead foo interprets a doubled double quote "" as a literal double quote, then start your program as

foo ^"a^"^"b c^" ^> d > out.txt

The key insight from the quoted document is that, to the Windows command shell, an unescaped double quote triggers switching between two possible states.

Some further trial and error implies that in the initial state, redirection (to a file or pipe) is recognized and a caret ^ escapes a double quote and the caret is removed from the input. In the other state, redirection is not recognized and a caret does not escape a double quote and isn't removed. Let's refer to these states as 'outside' and 'inside', respectively.

If you want to redirect the output of your command, then the command shell must be in the outside state when it reaches the redirection, so there must be an even number of unescaped (by caret) double quotes preceding the redirection. foo "a\"b " > out.txt won't work -- the command shell passes the entire "a\"b " > out.txt to foo as its combined command line arguments, instead of passing only "a\"b " and redirecting the output to out.txt.

foo "a\^"b " > out.txt won't work, either, because the caret ^ is encountered in the inside state where it is an ordinary character and not an escape character, so "a\^"b " > out.txt gets passed to foo.

The only way that (hopefully) always works is to keep the command shell always in the outside state, because then redirection works.

If you don't need redirection (or other characters with special meaning to the command shell), then you can do without the carets. If foo interprets \" as a literal double quote, then you can call it as

foo "a\"b c"

Then foo receives "a\"b c" as its combined arguments text and can interpret it as a single argument equal to a"b c.

Now -- finally -- to the original question. myscript '"test"' called from the Windows command shell passes '"test"' to myscript. Apparently myscript interprets the single and double quotes as argument delimiters and removes them. You need to figure out what myscript accepts as a literal double quote and then specify that in your command, using ^ to escape any characters that have special meaning to the Windows command shell. Given that myscript is also available on Unix, perhaps \" does the trick. Try

myscript \^"test\^"

or, if you don't need redirection,

myscript \"test\"

GetElementByID - Multiple IDs

here is the solution

if (
  document.getElementById('73536573').value != '' &&
  document.getElementById('1081743273').value != '' &&
  document.getElementById('357118391').value != '' &&
  document.getElementById('1238321094').value != '' &&
  document.getElementById('1118122010').value != ''
  ) {
code
  }

Import text file as single character string

I would use the following. It should work just fine, and doesn't seem ugly, at least to me:

singleString <- paste(readLines("foo.txt"), collapse=" ")

How to replace all occurrences of a character in string?

Imagine a large binary blob where all 0x00 bytes shall be replaced by "\1\x30" and all 0x01 bytes by "\1\x31" because the transport protocol allows no \0-bytes.

In cases where:

  • the replacing and the to-replaced string have different lengths,
  • there are many occurences of the to-replaced string within the source string and
  • the source string is large,

the provided solutions cannot be applied (because they replace only single characters) or have a performance problem, because they would call string::replace several times which generates copies of the size of the blob over and over. (I do not know the boost solution, maybe it is OK from that perspective)

This one walks along all occurrences in the source string and builds the new string piece by piece once:

void replaceAll(std::string& source, const std::string& from, const std::string& to)
{
    std::string newString;
    newString.reserve(source.length());  // avoids a few memory allocations

    std::string::size_type lastPos = 0;
    std::string::size_type findPos;

    while(std::string::npos != (findPos = source.find(from, lastPos)))
    {
        newString.append(source, lastPos, findPos - lastPos);
        newString += to;
        lastPos = findPos + from.length();
    }

    // Care for the rest after last occurrence
    newString += source.substr(lastPos);

    source.swap(newString);
}

Get current value when change select option - Angular2

In angular 4, this worked for me

template.html

<select (change)="filterChanged($event.target.value)">
  <option *ngFor="let type of filterTypes" [value]="type.value">{{type.display}}
  </option>
</select>

component.ts

export class FilterComponent implements OnInit {

selectedFilter:string;
   public filterTypes = [
     { value: 'percentage', display: 'percentage' },
     { value: 'amount', display: 'amount' }
  ];

   constructor() { 
     this.selectedFilter = 'percentage';
   }

   filterChanged(selectedValue:string){
     console.log('value is ', selectedValue);
   }

  ngOnInit() {
  }
}

Properly close mongoose's connection once you're done

You can set the connection to a variable then disconnect it when you are done:

var db = mongoose.connect('mongodb://localhost:27017/somedb');

// Do some stuff

db.disconnect();

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Here is another way to reproduce this error in Python2.7 with numpy:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate(a,b)   #note the lack of tuple format for a and b
print(c) 

The np.concatenate method produces an error:

TypeError: only length-1 arrays can be converted to Python scalars

If you read the documentation around numpy.concatenate, then you see it expects a tuple of numpy array objects. So surrounding the variables with parens fixed it:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate((a,b))  #surround a and b with parens, packaging them as a tuple
print(c) 

Then it prints:

[1 2 3 4 5 6]

What's going on here?

That error is a case of bubble-up implementation - it is caused by duck-typing philosophy of python. This is a cryptic low-level error python guts puke up when it receives some unexpected variable types, tries to run off and do something, gets part way through, the pukes, attempts remedial action, fails, then tells you that "you can't reformulate the subspace responders when the wind blows from the east on Tuesday".

In more sensible languages like C++ or Java, it would have told you: "you can't use a TypeA where TypeB was expected". But Python does it's best to soldier on, does something undefined, fails, and then hands you back an unhelpful error. The fact we have to be discussing this is one of the reasons I don't like Python, or its duck-typing philosophy.

WP -- Get posts by category?

You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts

Note: The category_name parameter needs to be a string, in this case, the category name.

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

Really it's interesting. You need just use javax-mail.jar of "com.sun" not "javax.mail".
dwonload com.sun mail jar

Create excel ranges using column numbers in vba?

Here is a condensed replacement for the ConvertToLetter function that in theory should work for all possible positive integers. For example, 1412 produces "BBH" as the result.

Public Function ColumnNumToStr(ColNum As Integer) As String
Dim Value As Integer
Dim Rtn As String
    Rtn = ""
    Value = ColNum - 1
    While Value > 25
        Rtn = Chr(65 + (Value Mod 26)) & Rtn
        Value = Fix(Value / 26) - 1
    Wend
    Rtn = Chr(65 + Value) & Rtn
    ColumnNumToStr = Rtn
End Function

How do you pass a function as a parameter in C?

Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:

void foo(int bar(int, int));

is equivalent to this:

void foo(int (*bar)(int, int));

node.js http 'get' request with query string parameters

If you don't want use external package , Just add the following function in your utilities :

var params=function(req){
  let q=req.url.split('?'),result={};
  if(q.length>=2){
      q[1].split('&').forEach((item)=>{
           try {
             result[item.split('=')[0]]=item.split('=')[1];
           } catch (e) {
             result[item.split('=')[0]]='';
           }
      })
  }
  return result;
}

Then , in createServer call back , add attribute params to request object :

 http.createServer(function(req,res){
     req.params=params(req); // call the function above ;
      /**
       * http://mysite/add?name=Ahmed
       */
     console.log(req.params.name) ; // display : "Ahmed"

})

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

consider it as a raw string. Just simple answer, add r before your windows path.

import csv
data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
data = csv.reader(data)  
print(data)

Java sending and receiving file (byte[]) over sockets

To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];, instead we could do

    byte[] bytearray = new byte[1024*16];
    FileInputStream fis = null;
    try {

        fis = new FileInputStream(file);
        OutputStream output= socket.getOututStream();
        BufferedInputStream bis = new BufferedInputStream(fis);

        int readLength = -1;
        while ((readLength = bis.read(bytearray)) > 0) {
            output.write(bytearray, 0, readLength);

        }
        bis.close();
        output.close();
    }
    catch(Exception ex ){

        ex.printStackTrace();
    } //Excuse the poor exception handling...

npm install hangs

You can try deleting package-lock.json and running npm install afterwards. This worked for me.

Rails 3 execute custom sql query without a model

Maybe try this:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)

How to remove numbers from a string?

You're remarkably close.

Here's the code you wrote in the question:

questionText.replace(/[0-9]/g, '');

The code you've written does indeed look at the questionText variable, and produce output which is the original string, but with the digits replaced with empty string.

However, it doesn't assign it automatically back to the original variable. You need to specify what to assign it to:

questionText = questionText.replace(/[0-9]/g, '');

GROUP BY with MAX(DATE)

As long as there are no duplicates (and trains tend to only arrive at one station at a time)...

select Train, MAX(Time),
      max(Dest) keep (DENSE_RANK LAST ORDER BY Time) max_keep
from TrainTable
GROUP BY Train;

How to open warning/information/error dialog in Swing?

Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:

import static javax.swing.JOptionPane.*;

public class SimpleDialog(){
    public static void main(String argv[]) {
        showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
    }
}

docker error - 'name is already in use by container'

TL:DR;

List all containers:
docker ps -a
Remove the concerned container by id:
docker container rm <container_id>

How can I remove all objects but one from the workspace in R?

To keep all objects whose names match a pattern, you could use grep, like so:

to.remove <- ls()
to.remove <- c(to.remove[!grepl("^obj", to.remove)], "to.remove")
rm(list=to.remove)

How to create an Array with AngularJS's ng-model

This should work.

app = angular.module('plunker', [])

app.controller 'MainCtrl', ($scope) ->
  $scope.users = ['bob', 'sean', 'rocky', 'john']
  $scope.test = ->
    console.log $scope.users

HTML:

<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />

Example plunk here

Can multiple different HTML elements have the same ID if they're different elements?

Even if the elements are of different types it can cause you some serious problems...

Suppose you have 3 buttons with the same id:

<button id="myid" data-mydata="this is button 1">button 1</button>
<button id="myid" data-mydata="this is button 2">button 2</button>
<button id="myid" data-mydata="this is button 3">button 3</button>

Now you setup some jQuery code to do something when myid buttons are clicked:

$(document).ready(function ()
{
    $("#myid").click(function ()
    {
        var buttonData = $(this).data("mydata");

        // Call interesting function...
        interestingFunction();

        $('form').trigger('submit');
    });
});

What would you expect? That every button clicked would execute the click event handler setup with jQuery. Unfortunately it won't happen. ONLY the 1st button calls the click handler. The other 2 when clicked do nothing. It is as if they weren't buttons at all!

So always assign different IDs to HTML elements. This will get you covered against strange things. :)

<button id="button1" class="mybtn" data-mydata="this is button 1">button 1</button>
<button id="button2" class="mybtn" data-mydata="this is button 2">button 2</button>
<button id="button3" class="mybtn" data-mydata="this is button 3">button 3</button>

Now if you want the click event handler to run when any of the buttons get clicked it will work perfectly if you change the selector in the jQuery code to use the CSS class applied to them like this:

$(document).ready(function ()
{
    $(".mybtn").click(function ()
    {
        var buttonData = $(this).data("mydata");

        // Call interesting function...
        interstingFunction();

        $('form').trigger('submit');
    });
});

Vue.js get selected option on @change

@ is a shortcut option for v-on. Use @ only when you want to execute some Vue methods. As you are not executing Vue methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function

<select name="LeaveType" onchange="onChange(this.value)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

function onChange(value) {
  console.log(value);
}

If you want to call Vue methods, do it like this-

<select name="LeaveType" @change="onChange($event)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

new Vue({
  ...
  ...
  methods:{
    onChange:function(event){
       console.log(event.target.value);
    }
  }
})

You can use v-model data attribute on the select element to bind the value.

<select v-model="selectedValue" name="LeaveType" onchange="onChange(this.value)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

new Vue({
    data:{
        selectedValue : 1, // First option will be selected by default
    },
    ...
    ...
    methods:{
        onChange:function(event){
            console.log(this.selectedValue);
        }
    }
})

Hope this Helps :-)

Adding a module (Specifically pymorph) to Spyder (Python IDE)

If you are using Spyder in the Anaconda package...

In the IPython Console, use

!conda install packageName

This works locally too.

!conda install /path/to/package.tar

Note: the ! is required when using IPython console from within Spyder.

Exclude all transitive dependencies of a single dependency

One thing I have found useful:

If you put the dependency with the exclusions in the dependencyManagement section of either the parent POM for your project, or in an importable dependency management POM, then you don't need to repeat the exclusion (or the version).

For example, if your parent POM has:

<dependencyManagement>
    <dependencies>
    ...         
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
     ....
  </dependencies>
</dependencyManagement>

Then the modules in your project can simply declare the dependency as:

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>

The in the parent POM will specify both the version and the exclusions. I use this technique for nearly all of our projects and it eliminates a lot of repetition.

How to do a GitHub pull request

I've started a project to help people making their first GitHub pull request. You can do the hands-on tutorial to make your first PR here

The workflow is simple as

  • Fork the repo in github
  • Get clone url by clicking on clone repo button
  • Go to terminal and run git clone <clone url you copied earlier>
  • Make a branch for changes you're makeing git checkout -b branch-name
  • Make necessary changes
  • Commit your changes git commit
  • Push your changes to your fork on GitHub git push origin branch-name
  • Go to your fork on GitHub to see a Compare and pull request button
  • Click on it and give necessary details

Cleanest Way to Invoke Cross-Thread Events

I made the following 'universal' cross thread call class for my own purpose, but I think it's worth to share it:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace CrossThreadCalls
{
  public static class clsCrossThreadCalls
  {
    private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);
    public static void SetAnyProperty(Control c, string Property, object Value)
    {
      if (c.GetType().GetProperty(Property) != null)
      {
        //The given property exists
        if (c.InvokeRequired)
        {
          SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);
          c.BeginInvoke(d, c, Property, Value);
        }
        else
        {
          c.GetType().GetProperty(Property).SetValue(c, Value, null);
        }
      }
    }

    private delegate void SetTextPropertyCallBack(Control c, string Value);
    public static void SetTextProperty(Control c, string Value)
    {
      if (c.InvokeRequired)
      {
        SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);
        c.BeginInvoke(d, c, Value);
      }
      else
      {
        c.Text = Value;
      }
    }
  }

And you can simply use SetAnyProperty() from another thread:

CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, "Text", KvaserCanReader.GetSpeed.ToString());

In this example the above KvaserCanReader class runs its own thread and makes a call to set the text property of the lb_Speed label on the main form.

How to dismiss keyboard for UITextView with return key?

I used this code to change responder.

 - (BOOL)textView:(UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
    {
        if ([text isEqualToString:@"\n"]) {
            //[textView resignFirstResponder];
            //return YES;
            NSInteger nextTag = textView.tag + 1;
            // Try to find next responder
            UIResponder* nextResponder = [self.view viewWithTag:nextTag];
            if (nextResponder) {
                // Found next responder, so set it.
                [nextResponder becomeFirstResponder];
            } else {
                // Not found, so remove keyboard.
                [textView resignFirstResponder];
            }
            return NO; 


            return NO;
        }
        return YES;

    }

Cannot open Windows.h in Microsoft Visual Studio

Start Visual Studio. Go to Tools->Options and expand Projects and solutions. Select VC++ Directories from the tree and choose Include Files from the combo on the right.

You should see:

$(WindowsSdkDir)\include

If this is missing, you found a problem. If not, search for a file. It should be located in

32 bit systems:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include

64 bit systems:

C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\Include

if VS was installed in the default directory.

Source: http://forums.codeguru.com/showthread.php?465935-quot-windows-h-no-such-file-or-directory-quot-in-Visual-Studio-2008!-Help&p=1786039#post1786039

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

It was pretty odd the trick that worked. The thing is when I have previously read the content of the file, I used BufferedReader. After reading, I closed the buffer.

Meanwhile I switched and now I'm reading the content using FileInputStream. Also after finishing reading I close the stream. And now it's working.

The problem is I don't have the explanation for this.

I don't know BufferedReader and FileOutputStream to be incompatible.

Limit characters displayed in span

Here's an example of using text-overflow:

_x000D_
_x000D_
.text {_x000D_
  display: block;_x000D_
  width: 100px;_x000D_
  overflow: hidden;_x000D_
  white-space: nowrap;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
<span class="text">Hello world this is a long sentence</span>
_x000D_
_x000D_
_x000D_

With ng-bind-html-unsafe removed, how do I inject HTML?

The best solution to this in my opinion is this:

  1. Create a custom filter which can be in a common.module.js file for example - used through out your app:

    var app = angular.module('common.module', []);
    
    // html filter (render text as html)
    app.filter('html', ['$sce', function ($sce) { 
        return function (text) {
            return $sce.trustAsHtml(text);
        };    
    }])
    
  2. Usage:

    <span ng-bind-html="yourDataValue | html"></span>
    

Now - I don't see why the directive ng-bind-html does not trustAsHtml as part of its function - seems a bit daft to me that it doesn't

Anyway - that's the way I do it - 67% of the time, it works ever time.

How to run a shell script in OS X by double-clicking?

Have you tried using the .command filename extension?

How to change Git log date formats

git log -n1 --format="Last committed item in this release was by %an, `git log -n1 --format=%at | awk '{print strftime("%y%m%d%H%M",$1)}'`, message: %s (%h) [%d]"

BeanFactory not initialized or already closed - call 'refresh' before

The issue here is that the version of spring-web that you're using (3.1.1-RELEASE) is not compatible with the version of spring-beans that you're using (3.0.2-RELEASE). At the top of the stack you can see the NoSuchMethodError which in turn triggers the BeanFactory not initialized... exception.

The NoSuchMethodError is caused because the method invocation XmlWebApplicationContext.loadBeanDefinitions() in spring-web is trying to call XmlBeanDefinitionReader.setEnvironment() in spring-beans which doesn't exist in 3.0.2-RELEASE. It does however exist in 3.1.1-RELEASE - as setEnvironment is inherited from the parent AbstractBeanDefinitionReader.

To resolve, you'd probably be best to upgrade the spring-beans jar to 3.1.1-RELEASE. The version for this jar appears to be parameterized in your pom.xml and is controlled by the property org.springframework.version further down in the file.

Android: Bitmaps loaded from gallery are rotated in ImageView

You can just read the path from sd card and do the following code...it'll Replace the existing photo after rotating it..

Not: Exif doesnt work on most of the devices, it gives the wrong data so it's good to hard code the rotating before saving to any degree you want to,You just have to change the angle value in postRotate to any you want to.

    String photopath = tempphoto.getPath().toString();
    Bitmap bmp = BitmapFactory.decodeFile(photopath);

    Matrix matrix = new Matrix();
    matrix.postRotate(90);
    bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);

    FileOutputStream fOut;
    try {
        fOut = new FileOutputStream(tempphoto);
        bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
        fOut.flush();
        fOut.close();

    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

What is PostgreSQL equivalent of SYSDATE from Oracle?

The following functions are available to obtain the current date and/or time in PostgreSQL:

CURRENT_TIME

CURRENT_DATE

CURRENT_TIMESTAMP

Example

SELECT CURRENT_TIME;
08:05:18.864750+05:30

SELECT CURRENT_DATE;
2020-05-14

SELECT CURRENT_TIMESTAMP;
2020-05-14 08:04:51.290498+05:30

postgresql docs

HTML5 Canvas Resize (Downscale) Image High Quality?

This is the improved Hermite resize filter that utilises 1 worker so that the window doesn't freeze.

https://github.com/calvintwr/blitz-hermite-resize

const blitz = Blitz.create()

/* Promise */
blitz({
    source: DOM Image/DOM Canvas/jQuery/DataURL/File,
    width: 400,
    height: 600
}).then(output => {
    // handle output
})catch(error => {
    // handle error
})

/* Await */
let resized = await blizt({...})

/* Old school callback */
const blitz = Blitz.create('callback')
blitz({...}, function(output) {
    // run your callback.
})

NSRange to Range<String.Index>

I've found the cleanest swift2 only solution is to create a category on NSRange:

extension NSRange {
    func stringRangeForText(string: String) -> Range<String.Index> {
        let start = string.startIndex.advancedBy(self.location)
        let end = start.advancedBy(self.length)
        return Range<String.Index>(start: start, end: end)
    }
}

And then call it from for text field delegate function:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let range = range.stringRangeForText(textField.text)
    let output = textField.text.stringByReplacingCharactersInRange(range, withString: string)

    // your code goes here....

    return true
}

Is Visual Studio Community a 30 day trial?

IMPORTANT DISCLAIMER: Information provided below is for educational purposes only! Extending a trial period of Visual Studio Community 2017 might be ILLEGAL!

You have the same effect when You remove all files from HKEY_CLASSES_ROOT\Licenses\5C505A59-E312-4B89-9508-E162F8150517. Run "Visual Studio Installer" and chose option "repair". Now You have new 30 days of trial. But You lost all configuration in Your VS.

How to compile a static library in Linux?

Here a full makefile example:

makefile

TARGET = prog

$(TARGET): main.o lib.a
    gcc $^ -o $@

main.o: main.c
    gcc -c $< -o $@

lib.a: lib1.o lib2.o
    ar rcs $@ $^

lib1.o: lib1.c lib1.h
    gcc -c -o $@ $<

lib2.o: lib2.c lib2.h
    gcc -c -o $@ $<

clean:
    rm -f *.o *.a $(TARGET)

explaining the makefile:

  • target: prerequisites - the rule head
  • $@ - means the target
  • $^ - means all prerequisites
  • $< - means just the first prerequisite
  • ar - a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
    • r - replace files existing inside the archive
    • c - create a archive if not already existent
    • s - create an object-file index into the archive

To conclude: The static library under Linux is nothing more than a archive of object files.

main.c using the lib

#include <stdio.h>

#include "lib.h"

int main ( void )
{
    fun1(10);
    fun2(10);
    return 0;
}

lib.h the libs main header

#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

#include "lib1.h"
#include "lib2.h"

#endif

lib1.c first lib source

#include "lib1.h"

#include <stdio.h>

void fun1 ( int x )
{
    printf("%i\n",x);
}

lib1.h the corresponding header

#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun1 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB1_H_INCLUDED */

lib2.c second lib source

#include "lib2.h"

#include <stdio.h>

void fun2 ( int x )
{
    printf("%i\n",2*x);
}

lib2.h the corresponding header

#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun2 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB2_H_INCLUDED */

How can I create a two dimensional array in JavaScript?

_x000D_
_x000D_
var playList = [_x000D_
  ['I Did It My Way', 'Frank Sinatra'],_x000D_
  ['Respect', 'Aretha Franklin'],_x000D_
  ['Imagine', 'John Lennon'],_x000D_
  ['Born to Run', 'Bruce Springsteen'],_x000D_
  ['Louie Louie', 'The Kingsmen'],_x000D_
  ['Maybellene', 'Chuck Berry']_x000D_
];_x000D_
_x000D_
function print(message) {_x000D_
  document.write(message);_x000D_
}_x000D_
_x000D_
function printSongs( songs ) {_x000D_
  var listHTML;_x000D_
  listHTML = '<ol>';_x000D_
  for ( var i = 0; i < songs.length; i += 1) {_x000D_
    listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + '</li>';_x000D_
  }_x000D_
  listHTML += '</ol>';_x000D_
  print(listHTML);_x000D_
}_x000D_
_x000D_
printSongs(playList);
_x000D_
_x000D_
_x000D_

How can I loop through a List<T> and grab each item?

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}

Is it possible to append Series to rows of DataFrame without making a list first?

Something like this could work...

mydf.loc['newindex'] = myseries

Here is an example where I used it...

stats = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].describe()

stats
Out[32]: 
          bp_prob   ICD9_prob   meds_prob  regex_prob
count  171.000000  171.000000  171.000000  171.000000
mean     0.179946    0.059071    0.067020    0.126812
std      0.271546    0.142681    0.152560    0.207014
min      0.000000    0.000000    0.000000    0.000000
25%      0.000000    0.000000    0.000000    0.000000
50%      0.000000    0.000000    0.000000    0.013116
75%      0.309019    0.065248    0.066667    0.192954
max      1.000000    1.000000    1.000000    1.000000

medians = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].median()

stats.loc['median'] = medians

stats
Out[36]: 
           bp_prob   ICD9_prob   meds_prob  regex_prob
count   171.000000  171.000000  171.000000  171.000000
mean      0.179946    0.059071    0.067020    0.126812
std       0.271546    0.142681    0.152560    0.207014
min       0.000000    0.000000    0.000000    0.000000
25%       0.000000    0.000000    0.000000    0.000000
50%       0.000000    0.000000    0.000000    0.013116
75%       0.309019    0.065248    0.066667    0.192954
max       1.000000    1.000000    1.000000    1.000000
median    0.000000    0.000000    0.000000    0.013116

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

I was having the same problem and everyone was talking about this is related to DNS configuration, which make sense, since your container maybe isn't knowing how to resolve the name of the domain where your database is.

I guess your can configure that at the moment you start your container, but I think it's better to config this once and for all.

I'm using Windows 10 and in this case docker's gui give us some facilities.

Just right click on docker's icon in the tray bar and select "Settings" item.

Docker's options

Then, on the Docker's window, select the "Network" section and change the DNS option from "Automatic" to "Fixed" and hit "Apply". Docker will restart itself after that. I putted the Google's DNS (8.8.8.8) and it worked fine to me.

docker's network section with dns config

Hope it helps.

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I just saw this blog entry: Money vs. Decimal in SQL Server.

Which basically says that money has a precision issue...

declare @m money
declare @d decimal(9,2)

set @m = 19.34
set @d = 19.34

select (@m/1000)*1000
select (@d/1000)*1000

For the money type, you will get 19.30 instead of 19.34. I am not sure if there is an application scenario that divides money into 1000 parts for calculation, but this example does expose some limitations.

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

By default, the classes in the csv module use Windows-style line terminators (\r\n) rather than Unix-style (\n). Could this be what’s causing the apparent double line breaks?

If so, you can override it in the DictWriter constructor:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)

Number format in excel: Showing % value without multiplying with 100

Pretty easy to do this across multiple cells, without having to add '%' to each individually.

Select all the cells you want to change to percent, right Click, then format Cells, choose Custom. Type in 0.0\%.

Bootstrap 4 - Responsive cards in card-columns

I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.

I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:

_x000D_
_x000D_
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
    <!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
    <div class="container mh0 w-100">_x000D_
        <div class="page-header text-center mb5">_x000D_
            <h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
            <p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
            <div class="header-button">_x000D_
                <button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="container pa0 flex justify-center">_x000D_
            <div class="listings card-columns">_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

After trying both the Bootstrap .card-group and .card-deck card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns class a shot. And it worked!

Your results may vary, but .card-columns seems to be the most stable implementation here.

What's the difference between abstraction and encapsulation?

The essential thing about abstraction is that client code operates in terms of a different logical/abstract model. That different model may be more or less complex than the implementation happens to be in any given client usage.

For example, "Iterator" abstracts (aka generalises) sequenced traversal of 0 or more values - in C++ it manifests as begin(), */-> (dereferencing), end(), pre/post ++ and possibly --, then there's +, +=, [], std::advance etc.. That's a lot of baggage if the client could say increment a size_t along an array anyway. The essential thing is that the abstraction allows client code that needs to perform such a traversal to be decoupled from the exact nature of the "container" or data source providing the elements. Iteration is a higher-level notion that sometimes restricts the way the traversal is performed (e.g. a forward iterator can only advance an element at a time), but the data can then be provided by a larger set of sources (e.g. from a keyboard where there's not even a "container" in the sense of concurrently stored values). The client code can generally switch to another data source abstracted through its own iterators with minimal or even no changes, and even polymorphically to other data types - either implicitly or explicitly using something like std::iterator_traits<Iterator>::value_type available.

This is quite a different thing from encapsulation, which is the practice of making some data or functions less accessible, such that you know they're only used indirectly as a result of operations on the public interface. Encapsulation is an essential tool for maintaining invariants on an object, which means things you want to keep true after every public operation - if client code could just reach in and modify your object then you can't enforce any invariants. For example, a class might wrap a string, ensuring that after any operation any lowercase letters were changed to upper case, but if the client code can reach in and put a lowercase letter into the string without the involvement of the class's member functions, then the invariant can't be enforced.

To further highlight the difference, consider say a private std::vector<Timing_Sample> data member that's incidentally populated by operations on the containing object, with a report dumped out on destruction. With the data and destructor side effect not interacting with the object's client code in any way, and the operations on the object not intentionally controlling the time-keeping behaviour, there's no abstraction of that time reporting functionality but there is encapsulation. An example of abstraction would be to move the timing code into a separate class that might encapsulate the vector (make it private) and just provide a interface like add(const Timing_Sample&) and report(std::ostream&) - the necessary logical/abstract operations involved with using such instrumentation, with the highly desirable side effect that the abstracted code will often be reusable for other client code with similar functional needs.

PHP Get Highest Value from Array

Try using asort().

From documentation:

asort - Sort an array and maintain index association

Description:

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

If you are facing this issue and everything looks good, try invalidate cache/restart from your IDE. This will resolve the issue in most of the cases.

how to align img inside the div to the right?

vertical-align:middle; text-align:right;

How to search multiple columns in MySQL?

SELECT * FROM persons WHERE (`LastName` LIKE 'r%') OR (`FirstName` LIKE 'a%');

Please try with above query.

How can I compare two lists in python and return matches

I prefer the set based answers, but here's one that works anyway

[x for x in a if x in b]

How to select first parent DIV using jQuery?

Use .closest() to traverse up the DOM tree up to the specified selector.

var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.

Get all photos from Instagram which have a specific hashtag with PHP

There is the instagram public API's tags section that can help you do this.

Initialize 2D array

Shorter way is do it as follows:

private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

you could also solved it by adding lazy=false into into your *.hbm.xml file or you can init your object in Hibernate.init(Object) when you get object from db

MySQLDump one INSERT statement for each data row

In newer versions change was made to the flags: from the documentation:

--extended-insert, -e

Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.

--opt

This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.

Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.

--skip-extended-insert

Turn off extended-insert

A potentially dangerous Request.Path value was detected from the client (*)

If you're using .NET 4.0 you should be able to allow these urls via the web.config

<system.web>
    <httpRuntime 
            requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?" />
</system.web>

Note, I've just removed the asterisk (*), the original default string is:

<httpRuntime 
          requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

See this question for more details.

How to check if a database exists in SQL Server?

IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'YourDatabaseName')
  Do your thing...

By the way, this came directly from SQL Server Studio, so if you have access to this tool, I recommend you start playing with the various "Script xxxx AS" functions that are available. Will make your life easier! :)

TypeError: unhashable type: 'list' when using built-in set function

Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.

mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
    thing = tuple(thing)
    mylist2.append(thing)
set(mylist2)

Firestore Getting documents id from collection

Since you are using angularFire, it doesn't make any sense if you are going back to default firebase methods for your implementation. AngularFire itself has the proper mechanisms implemented. Just have to use it.

valueChanges() method of angularFire provides an overload for getting the ID of each document of the collection by simply adding a object as a parameter to the method.

valueChanges({ idField: 'id' })

Here 'idField' must be same as it is. 'id' can be anything that you want your document IDs to be called.

Then the each document object on the returned array will look like this.

{
  field1 = <field1 value>,
  field2 = <field2 value>,
  ..
  id = 'whatEverTheDocumentIdWas'
}

Then you can easily get the document ID by referencing to the field that you named.

AngularFire 5.2.0

How to update Xcode from command line

I encountered the same issue when I uninstalled the complete version of Xcode to reinstall the CLI version. My fix was:

sudo xcode-select -s /Library/Developer/CommandLineTools

How to control the line spacing in UILabel

Here is my solution in swift. The subclass should work for both attributedText and text property and for characterSpacing + lineSpacing. It retains the spacing if a new string or attributedString is set.

open class UHBCustomLabel : UILabel {
    @IBInspectable open var characterSpacing:CGFloat = 1 {
        didSet {
            updateWithSpacing()
        }

    }
    @IBInspectable open var lines_spacing:CGFloat = -1 {
        didSet {
            updateWithSpacing()
        }

    }
    open override var text: String? {
        set {
            super.text = newValue
            updateWithSpacing()
        }
        get {
            return super.text
        }
    }
    open override var attributedText: NSAttributedString? {
        set {
            super.attributedText = newValue
            updateWithSpacing() 
        }
        get {
            return super.attributedText
        }
    }
    func updateWithSpacing() {
        let attributedString = self.attributedText == nil ? NSMutableAttributedString(string: self.text ?? "") : NSMutableAttributedString(attributedString: attributedText!)
        attributedString.addAttribute(NSKernAttributeName, value: self.characterSpacing, range: NSRange(location: 0, length: attributedString.length))
        if lines_spacing >= 0 {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = lines_spacing
            paragraphStyle.alignment = textAlignment
            attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
        }
        super.attributedText = attributedString
    }
}

What does it mean when an HTTP request returns status code 0?

Workaround: what we ended up doing

We figured it was to do with firewall issues, and so we came up with a workaround that did the trick. If anyone has this same issue, here's what we did:

  1. We still write the data to a text file on the local hard disk as we previously did, using an HTA.

  2. When the user clicks "send data back to server", the HTA reads in the data and writes out an HTML page that includes that data as an XML data island (actually using a SCRIPT LANGUAGE=XML script block).

  3. The HTA launches a link to the HTML page in the browser.

  4. The HTML page now contains the javascript that posts the data to the server (using Microsoft.XMLHTTP).

Hope this helps anyone with a similar requirement. In this case it was a Flash game used on a laptop at tradeshows. We never had access to the laptop and could only email it to the client as this tradeshow was happening in another country.

SSIS how to set connection string dynamically from a config file

First add a variable to your SSIS package (Package Scope) - I used FileName, OleRootFilePath, OleProperties, OleProvider. The type for each variable is "string". Then I create a Configuration file (Select each variable - value) - populate the values in the configuration file - Eg: for OleProperties - Microsoft.ACE.OLEDB.12.0; for OleProperties - Excel 8.0;HDR=, OleRootFilePath - Your Excel file path, FileName - FileName

In the Connection manager - I then set the Properties-> Expressions-> Connection string expression dynamically eg:

"Provider=" + @[User::OleProvider] + "Data Source=" + @[User::OleRootFilePath]
+ @[User::FileName]  + ";Extended Properties=\"" + @[User::OleProperties] + "NO \""+";"

This way once you set the variables values and change it in your configuration file - the connection string will change dynamically - this helps especially in moving from development to production environments.

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

What is newline character -- '\n'

sed can be put into multi-line search & replace mode to match newline characters \n.

To do so sed first has to read the entire file or string into the hold buffer ("hold space") so that it then can treat the file or string contents as a single line in "pattern space".

To replace a single newline portably (with respect to GNU and FreeBSD sed) you can use an escaped "real" newline.

# cf. http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/
echo 'California
Massachusetts
Arizona' | 
sed -n -e '
# if the first line copy the pattern to the hold buffer
1h
# if not the first line then append the pattern to the hold buffer
1!H
# if the last line then ...
$ {
# copy from the hold to the pattern buffer
g
# double newlines
s/\n/\
\
/g
s/$/\
/
p
}'

# output
# California
#
# Massachusetts
#
# Arizona
#

There is, however, a much more convenient was to achieve the same result:

echo 'California
Massachusetts
Arizona' | 
   sed G

Scroll to the top of the page after render in react.js

I'm using React Hooks and wanted something re-usable but also something I could call at any time (rather than just after render).

// utils.js
export const useScrollToTop = (initialScrollState = false) => {
  const [scrollToTop, setScrollToTop] = useState(initialScrollState);

  useEffect(() => {
    if (scrollToTop) {
      setScrollToTop(false);
      try {
        window.scroll({
          top: 0,
          left: 0,
          behavior: 'smooth',
        });
      } catch (error) {
        window.scrollTo(0, 0);
      }
    }
  }, [scrollToTop, setScrollToTop]);

  return setScrollToTop;
};

Then to use the hook you can do:

import { useScrollToTop } from 'utils';

const MyPage = (props) => {
  // initialise useScrollToTop with true in order to scroll on page load 
  const setScrollToTop = useScrollToTop(true);

  ...

  return <div onClick={() => setScrollToTop(true)}>click me to scroll to top</div>
}

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Well, In Mapreduce there are two important phrases called Mapper and reducer both are too important, but Reducer is mandatory. In some programs reducers are optional. Now come to your question. Shuffling and sorting are two important operations in Mapreduce. First Hadoop framework takes structured/unstructured data and separate the data into Key, Value.

Now Mapper program separate and arrange the data into keys and values to be processed. Generate Key 2 and value 2 values. This values should process and re arrange in proper order to get desired solution. Now this shuffle and sorting done in your local system (Framework take care it) and process in local system after process framework cleanup the data in local system. Ok

Here we use combiner and partition also to optimize this shuffle and sort process. After proper arrangement, those key values passes to Reducer to get desired Client's output. Finally Reducer get desired output.

K1, V1 -> K2, V2 (we will write program Mapper), -> K2, V' (here shuffle and soft the data) -> K3, V3 Generate the output. K4,V4.

Please note all these steps are logical operation only, not change the original data.

Your question: What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Short answer: To process the data to get desired output. Shuffling is aggregate the data, reduce is get expected output.

How to Delete node_modules - Deep Nested Folder in Windows

Tried everything but didn't work. All the above methods did nothing. At last I was able to delete via VSCode.

  1. Just Open your root folder with VSCode.
  2. Select node_modules folder and delete.
  3. Profit. (It will take few milliseconds to delete.)

VSCode-delete.png

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

HTML5 Audio stop function

The simple way to get around this error is to catch the error.

audioElement.play() returns a promise, so the following code with a .catch() should suffice manage this issue:

_x000D_
_x000D_
function playSound(sound) {_x000D_
  sfx.pause();_x000D_
  sfx.currentTime = 0;_x000D_
  sfx.src = sound;_x000D_
  sfx.play().catch(e => e);_x000D_
}
_x000D_
_x000D_
_x000D_

Note: You may want to replace the arrow function with an anonymous function for backward compatibility.

Locate current file in IntelliJ

You can also click the little cross hairs button in the projects pane:

enter image description here

Note that the symbol won't be shown if Always Select Opened File (previously Autoscroll from Source) option is enabled.

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

Add this rule to your .htaccess

Header add Access-Control-Allow-Origin "*" 

even better, as suggested by @david thomas, you can use a specific domain value, e.g.

Header add Access-Control-Allow-Origin "your-domain.com"

Func vs. Action vs. Predicate

Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

var result = someCollection.Select( x => new { x.Name, x.Address });

Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

button1.Click += (sender, e) => { /* Do Some Work */ }

Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

var filteredResults = 
    someCollection.Where(x => x.someCriteriaHolder == someCriteria);

I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

Partition Function COUNT() OVER possible using DISTINCT

I think the only way of doing this in SQL-Server 2008R2 is to use a correlated subquery, or an outer apply:

SELECT  datekey,
        COALESCE(RunningTotal, 0) AS RunningTotal,
        COALESCE(RunningCount, 0) AS RunningCount,
        COALESCE(RunningDistinctCount, 0) AS RunningDistinctCount
FROM    document
        OUTER APPLY
        (   SELECT  SUM(Amount) AS RunningTotal,
                    COUNT(1) AS RunningCount,
                    COUNT(DISTINCT d2.dateKey) AS RunningDistinctCount
            FROM    Document d2
            WHERE   d2.DateKey <= document.DateKey
        ) rt;

This can be done in SQL-Server 2012 using the syntax you have suggested:

SELECT  datekey,
        SUM(Amount) OVER(ORDER BY DateKey) AS RunningTotal
FROM    document

However, use of DISTINCT is still not allowed, so if DISTINCT is required and/or if upgrading isn't an option then I think OUTER APPLY is your best option

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

missing private key in the distribution certificate on keychain

As long as you still have access to the mac which was used to generate the original distribution certificate it's very simple.

Just use that mac's Keychain Access application to export both the certificate and the private key. Select both using shift or command and right click to export to a .p12 file.

Attached a screenshot to make it very clear.

On your mac, import that .p12 file and you are good to go (just make sure you have a valid provisioning profile).

Just choose export

How to read data from excel file using c#

CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats

Good luck!

Can't load AMD 64-bit .dll on a IA 32-bit platform

Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.

Converting NSString to NSDictionary / JSON

Use this code where str is your JSON string:

NSError *err = nil;
NSArray *arr = 
 [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:NSJSONReadingMutableContainers 
                                   error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
  // do something using dictionary
}

How to display text in pygame?

You can create a surface with text on it. For this take a look at this short example:

pygame.font.init() # you have to call this at the start, 
                   # if you want to use this module.
myfont = pygame.font.SysFont('Comic Sans MS', 30)

This creates a new object on which you can call the render method.

textsurface = myfont.render('Some Text', False, (0, 0, 0))

This creates a new surface with text already drawn onto it. At the end you can just blit the text surface onto your main screen.

screen.blit(textsurface,(0,0))

Bear in mind, that everytime the text changes, you have to recreate the surface again, to see the new text.

How can I do an asc and desc sort using underscore.js?

Similar to Underscore library there is another library called as 'lodash' that has one method "orderBy" which takes in the parameter to determine in which order to sort it. You can use it like

_.orderBy('collection', 'propertyName', 'desc')

For some reason, it's not documented on the website docs.

Pass Model To Controller using Jquery/Ajax

Looks like your IndexPartial action method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPost action method and use jQuery post to post data to that. GET has limitation on the query string value.

[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
   //May be you want to pass the posted model to the parial view?
   return PartialView("_IndexPartial");
}

Your script should be

var url = "@Url.Action("IndexPartial","YourControllerName")";

var model = { Name :"Shyju", Location:"Detroit"};

$.post(url, model, function(res){
   //res contains the markup returned by the partial view
   //You probably want to set that to some Div.
   $("#SomeDivToShowTheResult").html(res);
});

Assuming Name and Location are properties of your DashboardViewModel class and SomeDivToShowTheResult is the id of a div in your page where you want to load the content coming from the partialview.

Sending complex objects?

You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","Stackoverflow"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});

For the above js model to be transformed to your method parameter, Your View Model should be like this.

public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}

And in your action method, specify [FromBody]

[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

Unfortunately, the methods you are using are unsupported in those browsers. To support my answer (this unsupportive behaviour) I have given links below.

onbeforeunload and onunload not working in opera... to support this

onbeforeunload in Opera
http://www.zachleat.com/web/dont-let-the-door-hit-you-onunload-and-onbeforeunload/

Though the onunload event doesn't work completely, you can use onunload to show a warning if a user clicks a link to navigate away from a page with an unsaved form.

onunload not working in safari... to support this

https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/

You could rather try using the pagehide event in the safari browser in lieu of onunload.

onunload not working in firefox... to support this

https://bugzilla.mozilla.org/show_bug.cgi?id=681636

They are yet to come up with a solution in FF too

Wish you good luck cheers.

Background Image for Select (dropdown) does not work in Chrome

select 
{
    -webkit-appearance: none;
}

If you need to you can also add an image that contains the arrow as part of the background.

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Use String.Format:

string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";

string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);

In the format {0,-20} means the first argument has a fixed length 20, and the negative sign guarantees the string is printed from left to right.

Safely remove migration In Laravel

This works for me:

  1. I deleted all tables in my database, mainly the migrations table.
  2. php artisan migrate:refresh

in laravel 5.5.43

Creating all possible k combinations of n items in C++

Here is an algorithm i came up with for solving this problem. You should be able to modify it to work with your code.

void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)
{
    unsigned int n = (startNum - bitVal) << 1;
    n += bitVal ? 1 : 0;

    for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s
        cout << (n >> (i - 1) & 1);
    cout << endl;

    if (!(n & testNum) && n != startNum)
        r_nCr(n, bitVal, testNum);

    if (bitVal && bitVal < testNum)
        r_nCr(startNum, bitVal >> 1, testNum);
}

You can see an explanation of how it works here.

how to kill hadoop jobs

Simply forcefully kill the process ID, the hadoop job will also be killed automatically . Use this command:

kill -9 <process_id> 

eg: process ID no: 4040 namenode

username@hostname:~$ kill -9 4040

MySQL my.ini location

programData is hidden folder so you have to change the option from setting to show hidden folder and then make the change in my.ini file present in that.

Be sure to update the correct my.ini file because it can waste a lot of your time if you keep updating wrong file.

You can look into service to see which my.ini is configured in this service.

Authentication issue when debugging in VS2013 - iis express

VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.

Bash script prints "Command Not Found" on empty lines

Make sure your first line is:

#!/bin/bash

Enter your path to bash if it is not /bin/bash


Try running:

dos2unix script.sh

That wil convert line endings, etc from Windows to unix format. i.e. it strips \r (CR) from line endings to change them from \r\n (CR+LF) to \n (LF).

More details about the dos2unix command (man page)


Another way to tell if your file is in dos/Win format:

cat scriptname.sh | sed 's/\r/<CR>/'

The output will look something like this:

#!/bin/sh<CR>
<CR>
echo Hello World<CR>
<CR>

This will output the entire file text with <CR> displayed for each \r character in the file.

How to stop a vb script running in windows

Create a Name.bat file that has the following line in it.

taskkill /F /IM wscript.exe /T

Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.

Include an SVG (hosted on GitHub) in MarkDown

The purpose of raw.github.com is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.

When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.

Examples

All of the ways stated below will work.

I copied the SVG image from the question to a repo on github in order to create the examples below

Linking to files using relative paths (Works, but obviously only on github.com / github.io)

Code

![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">

Result

See the working example on github.com.

Linking to RAW files

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text

Linking to RAW files using ?sanitize=true

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">

Result

Alt text

Linking to files hosted on github.io

Code

![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text


Some comments regarding changes that happened along the way:

  • Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>) are removed.

    To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true to the SVG's raw URL.

  • As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.

  • The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017

Change the image source on rollover using jQuery

Adapted from Richard Ayotte's code - To target an img in a ul/li list (found via wrapper div class here), something like this:

$('div.navlist li').bind('mouseenter mouseleave', function() {    
    $(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'), 
    'data-alt-src':$(this).find('img').attr('src') }
); 

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

If you don't have permissions to change your default DB you could manually select a different DB at the top of your queries...

USE [SomeOtherDb]
SELECT 'I am now using a different DB'

Will work as long as you have permission to the other DB

Try/catch does not seem to have an effect

This is my solution. When Set-Location fails it throws a non-terminating error which is not seen by the catch block. Adding -ErrorAction Stop is the easiest way around this.

try {
    Set-Location "$YourPath" -ErrorAction Stop;
} catch {
    Write-Host "Exception has been caught";
}

Swift add icon/image in UITextField

Swift 3.1

extension UITextField
{
    enum Direction
    {
        case Left
        case Right
    }

    func AddImage(direction:Direction,imageName:String,Frame:CGRect,backgroundColor:UIColor)
    {
        let View = UIView(frame: Frame)
        View.backgroundColor = backgroundColor

        let imageView = UIImageView(frame: Frame)
        imageView.image = UIImage(named: imageName)

        View.addSubview(imageView)

        if Direction.Left == direction
        {
            self.leftViewMode = .always
            self.leftView = View
        }
        else
        {
            self.rightViewMode = .always
            self.rightView = View
        }
    }

}

Setting unique Constraint with fluent API?

Unfortunately this is not supported in Entity Framework. It was on the roadmap for EF 6, but it got pushed back: Workitem 299: Unique Constraints (Unique Indexes)

Check if a string matches a regex in Bash script

A good way to test if a string is a correct date is to use the command date:

if date -d "${DATE}" >/dev/null 2>&1
then
  # do what you need to do with your date
else
  echo "${DATE} incorrect date" >&2
  exit 1
fi

from comment: one can use formatting

if [ "2017-01-14" == $(date -d "2017-01-14" '+%Y-%m-%d') ] 

Add numpy array as column to Pandas data frame

import numpy as np
import pandas as pd
import scipy.sparse as sparse

df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)

yields

   0  1  2     newcol
0  1  2  3  [0, 1, 0]
1  4  5  6  [0, 0, 1]
2  7  8  9  [1, 0, 0]

Long Press in JavaScript?

You could set the timeout for that element on mouse down and clear it on mouse up:

$("a").mousedown(function() {
    // set timeout for this element
    var timeout = window.setTimeout(function() { /* … */ }, 1234);
    $(this).mouseup(function() {
        // clear timeout for this element
        window.clearTimeout(timeout);
        // reset mouse up event handler
        $(this).unbind("mouseup");
        return false;
    });
    return false;
});

With this each element gets its own timeout.

HTTPS connections over proxy servers

I don't think "have HTTPS connections over proxy servers" means the Man-in-the-Middle attack type of proxy server. I think it's asking whether one can connect to a http proxy server over TLS. And the answer is yes.


Is it possible to have HTTPS connections over proxy servers?

Yes, see my question and answer here. HTTPs proxy server only works in SwitchOmega

If yes, what kind of proxy server allows this?

The kind of proxy server deploys SSL certificates, like how ordinary websites do. But you need a pac file for the brower to configure proxy connection over SSL.

Windows equivalent to UNIX pwd

You can simply put "." the dot sign. I've had a cmd application that was requiring the path and I was already in the needed directory and I used the dot symbol.

Hope it helps.

jQuery: How to get the event object in an event handler function without passing it as an argument?

in IE you can get the event object by window.event in other browsers with no 'use strict' directive, it is possible to get by arguments.callee.caller.arguments[0].

function myFunc(p1, p2, p3) {
    var evt = window.event || arguments.callee.caller.arguments[0];
}

setBackground vs setBackgroundDrawable (Android)

I also had this problem, but I made a workaround using a ImageView.

Try using a RelativeLayout and add a ImageView inside it (width and height: fill_parent, scaleType: center).

Also make sure the imageview is the first element inside the RelativeLayout, so it will act as background.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

I'll leave the discussion of the difference between Build Tools, Platform Tools, and Tools to others. From a practical standpoint, you only need to know the answer to your second question:

Which version should be used?

Answer: Use the most recent version.

For those using Android Studio with Gradle, the buildToolsVersion has to be set in the build.gradle (Module: app) file.

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    ...
}

Where do I get the most recent version number of Build Tools?

Open the Android SDK Manager.

  • In Android Studio go to Tools > Android > SDK Manager > Appearance & Behavior > System Settings > Android SDK
  • Choose the SDK Tools tab.
  • Select Android SDK Build Tools from the list
  • Check Show Package Details.

The last item will show the most recent version.

enter image description here

Make sure it is installed and then write that number as the buildToolsVersion in build.gradle (Module: app).

Is there a good Valgrind substitute for Windows?

There is Pageheap.exe part of the debugging tools for Windows. It's free and is basically a custom memory allocator/deallocator.

See http://support.microsoft.com/kb/286470

How to get the stream key for twitch.tv

This may be an old thread but I came across it and figured that I would give a final answer.

The twitch api is json based and to recieve your stream key you need to authorize your app for use with the api. You do so under the connections tab within your profile on twitch.tv itself.. Down the bottom of said tab there is "register your app" or something similar. Register it and you'll get a client-id header for your get requests.

Now you need to attach your Oauthv2 key to your headers or as a param during the query to the following get request.

curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth ' \ -X GET https://api.twitch.tv/kraken/channel

documentataion here

As you can see in the documentation above, if you've done these two things, your stream key will be made available to you.

As I said - Sorry for the bump but some people do find it hard to read the twitch* api.

Hope that helps somebody in the future.

Angular2 disable button

I think this is the easiest way

<!-- Submit Button-->
<button 
  mat-raised-button       
  color="primary"
  [disabled]="!f.valid"
>
  Submit
</button>

Xcode 6: Keyboard does not show up in simulator

If keyboard do not shown up automatically in simulator, just press [Command+K]

or Hardware -> Keyboard -> Toggle Software Keyboard

Scrollview vertical and horizontal in android

Since this seems to be the first search result in Google for "Android vertical+horizontal ScrollView", I thought I should add this here. Matt Clark has built a custom view based on the Android source, and it seems to work perfectly: Two Dimensional ScrollView

Beware that the class in that page has a bug calculating the view's horizonal width. A fix by Manuel Hilty is in the comments:

Solution: Replace the statement on line 808 by the following:

final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);


Edit: The Link doesn't work anymore but here is a link to an old version of the blogpost.

Using psql how do I list extensions installed in a database?

This SQL query gives output similar to \dx:

SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description" 
FROM pg_catalog.pg_extension e 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace 
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass 
ORDER BY 1;

Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

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

OpenCV self-extractor

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

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

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

enter image description here

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

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

This will completes the OpenCV 2.4.3 installation on your computer.


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

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

New project dialog

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

VC++ empty project

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

Project property dialog

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

Include directories dialog

Click Ok to close the dialog.

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

Library directories dialog

Click Ok to close the dialog.

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

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

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

enter image description here

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

NOTE:

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

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

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

Add new source file

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

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

using namespace cv;
using namespace std;

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

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

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

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

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

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

CSS animation delay in repeating

Heres a little snippet that shows the same thing for 75% of the time, then it slides. This repeat schema emulates delay nicely:

@-webkit-keyframes slide    {
0%   {background-position: 0 0;}
25%  {background-position: 0 0;}
50%  {background-position: 0 0;}
75%  {background-position: 0 0;}
100% {background-position: 13em 0;}
}

@-moz-keyframes slide       {
0%   {background-position: 0 0;}
25%  {background-position: 0 0;}
50%  {background-position: 0 0;}
75%  {background-position: 0 0;}
100% {background-position: 13em 0;}
}

@keyframes slide            {
0%   {background-position: 0 0;}
25%  {background-position: 0 0;}
50%  {background-position: 0 0;}
75%  {background-position: 0 0;}
100% {background-position: 13em 0;}
}

Can constructors be async?

Your problem is comparable to the creation of a file object and opening the file. In fact there are a lot of classes where you have to perform two steps before you can actually use the object: create + Initialize (often called something similar to Open).

The advantage of this is that the constructor can be lightweight. If desired, you can change some properties before actually initializing the object. When all properties are set, the Initialize/Open function is called to prepare the object to be used. This Initialize function can be async.

The disadvantage is that you have to trust the user of your class that he will call Initialize() before he uses any other function of your class. In fact if you want to make your class full proof (fool proof?) you have to check in every function that the Initialize() has been called.

The pattern to make this easier is to declare the constructor private and make a public static function that will construct the object and call Initialize() before returning the constructed object. This way you'll know that everyone who has access to the object has used the Initialize function.

The example shows a class that mimics your desired async constructor

public MyClass
{
    public static async Task<MyClass> CreateAsync(...)
    {
        MyClass x = new MyClass();
        await x.InitializeAsync(...)
        return x;
    }

    // make sure no one but the Create function can call the constructor:
    private MyClass(){}

    private async Task InitializeAsync(...)
    {
        // do the async things you wanted to do in your async constructor
    }

    public async Task<int> OtherFunctionAsync(int a, int b)
    {
        return await ... // return something useful
    }

Usage will be as follows:

public async Task<int> SomethingAsync()
{
    // Create and initialize a MyClass object
    MyClass myObject = await MyClass.CreateAsync(...);

    // use the created object:
    return await myObject.OtherFunctionAsync(4, 7);
}

correct PHP headers for pdf file download

I had the same problem recently and this helped me:

    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename="FILENAME"'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize("PATH/TO/FILE")); 
    ob_clean(); 
    flush(); 
    readfile(PATH/TO/FILE);      
    exit();

I found this answer here

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

Struct memory layout in C

You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.

From the wikipedia article:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

From 6.54.8 Structure-Packing Pragmas of the GCC documentation:

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.

Using Java 8's Optional with Stream::flatMap

I'm adding this second answer based on a proposed edit by user srborlongan to my other answer. I think the technique proposed was interesting, but it wasn't really suitable as an edit to my answer. Others agreed and the proposed edit was voted down. (I wasn't one of the voters.) The technique has merit, though. It would have been best if srborlongan had posted his/her own answer. This hasn't happened yet, and I didn't want the technique to be lost in the mists of the StackOverflow rejected edit history, so I decided to surface it as a separate answer myself.

Basically the technique is to use some of the Optional methods in a clever way to avoid having to use a ternary operator (? :) or an if/else statement.

My inline example would be rewritten this way:

Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
          .findFirst();

An my example that uses a helper method would be rewritten this way:

/**
 * Turns an Optional<T> into a Stream<T> of length zero or one depending upon
 * whether a value is present.
 */
static <T> Stream<T> streamopt(Optional<T> opt) {
    return opt.map(Stream::of)
              .orElseGet(Stream::empty);
}

Optional<Other> result =
    things.stream()
          .flatMap(t -> streamopt(resolve(t)))
          .findFirst();

COMMENTARY

Let's compare the original vs modified versions directly:

// original
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())

// modified
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))

The original is a straightforward if workmanlike approach: we get an Optional<Other>; if it has a value, we return a stream containing that value, and if it has no value, we return an empty stream. Pretty simple and easy to explain.

The modification is clever and has the advantage that it avoids conditionals. (I know that some people dislike the ternary operator. If misused it can indeed make code hard to understand.) However, sometimes things can be too clever. The modified code also starts off with an Optional<Other>. Then it calls Optional.map which is defined as follows:

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

The map(Stream::of) call returns an Optional<Stream<Other>>. If a value was present in the input Optional, the returned Optional contains a Stream that contains the single Other result. But if the value was not present, the result is an empty Optional.

Next, the call to orElseGet(Stream::empty) returns a value of type Stream<Other>. If its input value is present, it gets the value, which is the single-element Stream<Other>. Otherwise (if the input value is absent) it returns an empty Stream<Other>. So the result is correct, the same as the original conditional code.

In the comments discussing on my answer, regarding the rejected edit, I had described this technique as "more concise but also more obscure". I stand by this. It took me a while to figure out what it was doing, and it also took me a while to write up the above description of what it was doing. The key subtlety is the transformation from Optional<Other> to Optional<Stream<Other>>. Once you grok this it makes sense, but it wasn't obvious to me.

I'll acknowledge, though, that things that are initially obscure can become idiomatic over time. It might be that this technique ends up being the best way in practice, at least until Optional.stream gets added (if it ever does).

UPDATE: Optional.stream has been added to JDK 9.