Programs & Examples On #Requesthandler

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Here's a complete solution for Swagger with Spring Security. We probably want to only enable Swagger in our development and QA environment and disable it in the production environment. So, I am using a property (prop.swagger.enabled) as a flag to bypass spring security authentication for swagger-ui only in development/qa environment.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;

@Bean
public Docket SwaggerConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(enableSwagger)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.controller"))
            .paths(PathSelectors.any())
            .build();
}

@Override
public void configure(WebSecurity web) throws Exception {
    if (enableSwagger)  
        web.ignoring().antMatchers("/v2/api-docs",
                               "/configuration/ui",
                               "/swagger-resources/**",
                               "/configuration/security",
                               "/swagger-ui.html",
                               "/webjars/**");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (enableSwagger) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
  }
}

How to use a client certificate to authenticate and authorize in a Web API

Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send

System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:

Here is what the trace log looked like on the machine where the client certificate failed.

System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.

Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL

Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)

After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.

IIS Config Error - This configuration section cannot be used at this path

Click on your project properties, go to the web section, from the Servers section, change from IIS express to Local IIS, it will create a virtual directory for you

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

Just as a follow up for anyone still running into this – I had added the ServicePointManager.SecurityProfile options as noted in the solution:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

And yet I continued to get the same “The request was aborted: Could not create SSL/TLS secure channel” error. I was attempting to connect to some older voice servers with HTTPS SOAP API interfaces (i.e. voice mail, IP phone systems etc… installed years ago). These only support SSL3 connections as they were last updated years ago.

One would think including SSl3 in the list of SecurityProtocols would do the trick here, but it didn’t. The only way I could force the connection was to include ONLY the Ssl3 protocol and no others:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

Then the connection goes through – seems like a bug to me but this didn’t start throwing errors until recently on tools I provide for these servers that have been out there for years – I believe Microsoft has started rolling out system changes that have updated this behavior to force TLS connections unless there is no other alternative.

Anyway – if you’re still running into this against some old sites/servers, it’s worth giving it a try.

Spring Boot: Cannot access REST Controller on localhost (404)

Same 404 response I got after service executed with the below code

@Controller
@RequestMapping("/duecreate/v1.0")
public class DueCreateController {

}

Response:

{
"timestamp": 1529692263422,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/duecreate/v1.0/status"
}

after changing it to below code I received proper response

@RestController
@RequestMapping("/duecreate/v1.0")
public class DueCreateController {

}

Response:

{
"batchId": "DUE1529673844630",
"batchType": null,
"executionDate": null,
"status": "OPEN"
}

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

None of these answers really work. As others noted the Cors package will only use the Access-Control-Allow-Origin header if the request had an Origin header. But you can't generally just add an Origin header to the request because browsers may try to regulate that too.

If you want a quick and dirty way to allow cross site requests to a web api, it's really a lot easier to just write a custom filter attribute:

public class AllowCors : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext == null)
        {
            throw new ArgumentNullException("actionExecutedContext");
        }
        else
        {
            actionExecutedContext.Response.Headers.Remove("Access-Control-Allow-Origin");
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        }
        base.OnActionExecuted(actionExecutedContext);
    }
}

Then just use it on your Controller action:

[AllowCors]
public IHttpActionResult Get()
{
    return Ok("value");
}

I won't vouch for the security of this in general, but it's probably a lot safer than setting the headers in the web.config since this way you can apply them only as specifically as you need them.

And of course it is simple to modify the above to allow only certain origins, methods etc.

Spring Boot application.properties value not populating

The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.

You need to do one of the following:

Better solution

@Component
public class MyBean {

    private final String prop;

    @Autowired
    public MyBean(@Value("${some.prop}") String prop) {
        this.prop = prop;
        System.out.println("================== " + prop + "================== ");
    }
}

Solution that will work but is less testable and slightly less readable

@Component
public class MyBean {

    @Value("${some.prop}")
    private String prop;

    public MyBean() {

    }

    @PostConstruct
    public void init() {
        System.out.println("================== " + prop + "================== ");
    }
}

Also note that is not Spring Boot specific but applies to any Spring application

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

Why is it that "No HTTP resource was found that matches the request URI" here?

Please check the class you inherited. Whether it is simply Controller or APIController.

By mistake we might create a controller from MVC 5 controller. It should be from Web API Controller.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

If nothing happens even if you added all the annotation needed, try to add this dependency to your pom.xml, I just faced the same problem and resolved it by adding this one here:

<dependency>
   <groupId>commons-configuration</groupId>
   <artifactId>commons-configuration</artifactId>
   <version>1.9</version>
</dependency>

Launching Spring application Address already in use

Configure another port number(eg:8181) in /src/main/resources/application.properties

server.port=8181

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

This happened to me on VS2013(Update 5)/ASP.NET 4.5, under project type "Web Application" that includes MVC and Web API 2. Error happened right after creating the project and before adding any code. Adding the following configuration fix it for me. After resolving "System.Web.Helpers" issue two more similar errors surfaced for "System.Web.Mvc" and "System.Web.WebPages".

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

Do the following in the App.config file,

  1. Put the connectionStrings element is after the configSections element.
  2. Put the startup element after the connectionStrings element.
<?xml version="1.0" encoding="utf-8"?>
 <configuration>
   <configSections>
         <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
   </configSections>
   <connectionStrings>
         <add name="SchedulingContext" connectionString="Data Source=XXX\SQL2008R2DEV;Initial Catalog=YYY;Persist Security Info=True;User ID=sa;Password=XXX"   providerName="System.Data.SqlClient"/>
   </connectionStrings>
   <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>       
 </configuration>

java.io.IOException: Broken pipe

You may have not set the output file.

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I know that it's an old question, but you can change the Response using a parameter (P):

public class Response<P> implements Serializable{

private static final long serialVersionUID = 1L;

public enum MessageCode {
    SUCCESS, ERROR, UNKNOWN
}

private MessageCode code;
private String message;
private P payload;

...
public P getPayload() {
    return payload;
}

public void setPayload(P payload) {
    this.payload = payload;
}

}

The method would be

public Response<Departments> getDepartments(){...}

I can't try it now but it should works.

Otherwise it's possible to extends Response

@XmlRootElement    
public class DepResponse extends Response<Department> {<no content>}

How to prevent errno 32 broken pipe?

The broken pipe error usually occurs if your request is blocked or takes too long and after request-side timeout, it'll close the connection and then, when the respond-side (server) tries to write to the socket, it will throw a pipe broken error.

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

Tomcat 7 "SEVERE: A child container failed during start"

I have same problem but in my case By mistake I added a context in server.xml ($Tomcat_Install_Dir/conf/) and doesn't deployed corresponing war in webapps($Tomcat_Install_Dir/webapps). As I removed that context and restarted tomcat it working fine.

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

What could be the possible cause of this exception?

You may not have appropriate Jar in your class path.

How it could be removed?

By putting HTTPClient jar in your class path. If it's a webapp, copy Jar into WEB-INF/lib if it's standalone, make sure you have this jar in class path or explicitly set using -cp option

as the doc says,

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Edit:
If you are using a dependency management like Maven/Gradle (see the answer below) or SBT please use it to bring the httpclient jar for you.

Node JS Error: ENOENT

if your tmp folder is relative to the directory where your code is running remove the / in front of /tmp.

So you just have tmp/test.jpg in your code. This worked for me in a similar situation.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I had a similar problem and after going over a lot on stack overflow and spending time on the jar dependencies, I figured out that in my case, I had two sets of asm.jar. I removed one of them and it worked fine...

Setting Remote Webdriver to run tests in a remote computer using Java

This is how I got rid of the error:

WebDriverException: Error forwarding the new session cannot find : {platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=11}

In your nodeconfig.json, the version must be a String, not an integer.

So instead of using "version": 11 use "version": "11" (note the double quotes).

A full example of a working nodecondig.json file for a RemoteWebDriver:

{
  "capabilities":
  [
    {
      "platform": "WIN8_1",
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver"
      "version": "11"
    }
    ,{
      "platform": "WIN7",
      "browserName": "chrome",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "40"
    }
    ,{
      "platform": "LINUX",
      "browserName": "firefox",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "33"
    }
  ],
  "configuration":
  {
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 3,
    "port": 5555,
    "host": ip,
    "register": true,
    "registerCycle": 5000,
    "hubPort": 4444,
    "hubHost": {your-ip-address}
  }
}

How to get active user's UserDetails

And if you need authorized user in templates (e.g. JSP) use

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>

together with

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring-security.version}</version>
    </dependency>

Problem in running .net framework 4.0 website on iis 7.0

If you look in the ISAPI And CGI Restrictions, and everything is already set to Allowed, then make sure that the ASP.NET v4.0.30319 handlers are even in the list. In my case they were not. This can be easy to overlook.


I added one for 32 %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll and another for 64 bit %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll. You can name them both the same ASP.NET v4.0.30319.

Check Allow extension path to execute.

White spaces are required between publicId and systemId

The error message is actually correct if not obvious. It says that your DOCTYPE must have a SYSTEM identifier. I assume yours only has a public identifier.

You'll get the error with (for instance):

<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

You won't with:

<!DOCTYPE persistence PUBLIC
    "http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" "">

Notice "" at the end in the second one -- that's the system identifier. The error message is confusing: it should say that you need a system identifier, not that you need a space between the publicId and the (non-existent) systemId.

By the way, an empty system identifier might not be ideal, but it might be enough to get you moving.

Routing HTTP Error 404.0 0x80070002

My solution, after trying EVERYTHING:

Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.

My final settings that worked:

  • IIS 7.5, Win2k8r2 x64,
  • Integrated mode application pool
  • Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <authentication mode="None"/>
    
      <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
      <httpRuntime requestPathInvalidCharacters=""/>
    
      <httpModules>
        <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
      </httpModules>
    </system.web>
      <system.webServer>
        <!-- Modules for IIS 7.0 Integrated mode -->
        <modules>
          <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
        </modules>
    
        <!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
        <validation validateIntegratedModeConfiguration="false" />
      </system.webServer>
    
  • Global.ashx: (only method of any note)

    void Application_Start(object sender, EventArgs e) {
        // Register routes...
        System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
              "{*message}",
            //the default value for the message
              new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
            //any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
              new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
              new TestRoute.Handlers.PassthroughRouteHandler()
           );
    
        System.Web.Routing.RouteTable.Routes.Add(echoRoute);
    }
    
  • PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:

    public class PassthroughRouteHandler : IRouteHandler {
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
            requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
            return null;
        }
    }
    

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

The main problem is port number used by another application.So you can change the port number to unused one as shown below.

In windows you can view the used port numbers used by different apps in windows task manager.

python manage.py runserver 127.0.0.1:portnumber
Ex: python manage.py runserver 127.0.0.1:8080

ASP.NET MVC on IIS 7.5

In my case .NET CRL Version in Application pool prppertires was set to No managed code (do not know why). Setting it to .NET CRL Version v4.0.30319 solved the problem.

ASP.NET IIS Web.config [Internal Server Error]

Check this in the web.config and change overrideModeDefault from Deny to Allow.

<configSections>
  <sectionGroup name="system.webServer">
    <section name="handlers" overrideModeDefault="Deny" /> 
    <section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" />

You can also manage sections on web server level in your IIS management console from "Feature Delegation".

Python socket receive - incoming packets always have a different size

That's the nature of TCP: the protocol fills up packets (lower layer being IP packets) and sends them. You can have some degree of control over the MTU (Maximum Transfer Unit).

In other words: you must devise a protocol that rides on top of TCP where your "payload delineation" is defined. By "payload delineation" I mean the way you extract the unit of message your protocol supports. This can be as simple as "every NULL terminated strings".

HttpContext.Current.Session is null when routing requests

Just add attribute runAllManagedModulesForAllRequests="true" to system.webServer\modules in web.config.

This attribute is enabled by default in MVC and Dynamic Data projects.

bootstrap 3 navbar collapse button not working

In <body> you should have two <script> tags:

<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="js/bootstrap.js"></script>

The first one will load jQuery from the CDN, and second one will load Bootstrap's Javascript from a local directory (in this case it's a directory called js).

What is the "-->" operator in C/C++?

Conventional way we define condition in while loop parenthesis"()" and terminating condition inside the braces"{}", but this -- & > is a way one defines all at once. For example:

int abc(){
    int a = 5
    while((a--) > 0){ // Decrement and comparison both at once
        // Code
    }
}

It says, decrement a and run the loop till the time a is greater than 0

Other way it should have been like:

int abc() {
    int a = 5;
    while(a > 0) {
        a = a -1 // Decrement inside loop
        // Code
    }
}

Both ways, we do the same thing and achieve the same goals.

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Just create the database using createdb CLI tool:

PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB

If the database exists, it will return an error:

createdb: database creation failed: ERROR:  database "mydb" already exists

Center the nav in Twitter Bootstrap

You can make the .navbar fixed width, then set it's left and right margin to auto.

Demo

.navbar{
    width: 80%;
    margin: 0 auto;
}?

How to recursively delete an entire directory with PowerShell 2.0?

Remove-Item -Recurse -Force some_dir

does indeed work as advertised here.

rm -r -fo some_dir

are shorthand aliases that work too.

As far as I understood it, the -Recurse parameter just doesn't work correctly when you try deleting a filtered set of files recursively. For killing a single dir and everything below it seems to work fine.

Data binding for TextBox

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text",
                                this.Food,
                                "Name",
                                false,
                                DataSourceUpdateMode.OnPropertyChanged);

That'll fix it.

Note that the default DataSourceUpdateMode is OnValidation, so if you don't specify OnPropertyChanged, the model object won't be updated until after your validations have occurred.

How to use the onClick event for Hyperlink using C# code?

Wow, you have a huge misunderstanding how asp.net works.

This line of code

System.Diagnostics.Process.Start("help/AdminTutorial.html");

Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.

A very easy solution would be to change the href attribute of the link in you page_load method.

Your aspx code:

<a href="#" runat="server" id="myLink">Tutorial</a>

Your codebehind / cs code of page_load:

...
if (userinfo.user == "Admin")
{
  myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else 
{
  myLink.Attributes["href"] = "help/otherSite.html";
}
...

Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.

Java - Best way to print 2D array?

|1 2 3|
|4 5 6| 

Use the code below to print the values.

System.out.println(Arrays.deepToString());

Output will look like this (the whole matrix in one line):

[[1,2,3],[4,5,6]]

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

Just in case anyone has anymore troubles, this is a pretty sure fix.

check your etc/hosts file make sure you have a root user for every host.

i.e.

127.0.0.1   home.dev

localhost   home.dev

Therefore I will have 2 or more users as root for mysql:

root@localhost
[email protected]

this is how I fixed my problem.

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

You do not need any client side code if doing this is ASP.NET. The example below is a boostrap input box with a search button with an fontawesome icon.

You will see that in place of using a regular < div > tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.

In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.

<asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
<asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
<span class="input-group-btn">
    <asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
</span></asp:Panel>

how to change text in Android TextView

I just posted this answer in the android-discuss google group

If you are just trying to add text to the view so that it displays "Step One: blast egg Step Two: fry egg" Then consider using t.appendText("Step Two: fry egg"); instead of t.setText("Step Two: fry egg");

If you want to completely change what is in the TextView so that it says "Step One: blast egg" on startup and then it says "Step Two: fry egg" at a time later you can always use a

Runnable example sadboy gave

Good luck

How do I center an SVG in a div?

Flexbox is another approach: add

_x000D_
_x000D_
.container {
  display: flex;
  justify-content: center;
}
_x000D_
_x000D_
_x000D_

And add the .container class to the div which contains your svg.

How to split a String by space

Use Stringutils.split() to split the string by whites paces. For example StringUtils.split("Hello World") returns "Hello" and "World";

In order to solve the mentioned case we use split method like this

String split[]= StringUtils.split("Hello I'm your String");

when we print the split array the output will be :

Hello

I'm

your

String

For complete example demo check here

CSS3 Continuous Rotate Animation (Just like a loading sundial)

Your code seems correct. I would presume it is something to do with the fact you are using a .png and the way the browser redraws the object upon rotation is inefficient, causing the hang (what browser are you testing under?)

If possible replace the .png with something native.

see; http://kilianvalkhof.com/2010/css-xhtml/css3-loading-spinners-without-images/

Chrome gives me no pauses using this method.

How to check if running as root in a bash script

The $EUID environment variable holds the current user's UID. Root's UID is 0. Use something like this in your script:

if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

Note: If you get 2: [: Illegal number: check if you have #!/bin/sh at the top and change it to #!/bin/bash.

select a value where it doesn't exist in another table

You could use NOT IN:

SELECT A.* FROM A WHERE ID NOT IN(SELECT ID FROM B)

However, meanwhile i prefer NOT EXISTS:

SELECT A.* FROM A WHERE NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID)

There are other options as well, this article explains all advantages and disadvantages very well:

Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?

How do I use Maven through a proxy?

If maven works through proxy but not some of the plugins it is invoking, try setting JAVA_TOOL_OPTIONS as well with -Dhttp*.proxy* settings.

If you have already JAVA_OPTS just do

export JAVA_TOOL_OPTIONS=$JAVA_OPTS

How to generate .json file with PHP?

Insert your fetched values into an array instead of echoing.

Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.

restart mysql server on windows 7

use net stop mysql57 instead, it should be the version that is not specified

Using a batch to copy from network drive to C: or D: drive

You are copying all files to a single file called TEST_BACKUP_FOLDER

try this:

md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER

Command to change the default home directory of a user

From Linux Change Default User Home Directory While Adding A New User:

Simply open this file using a text editor, type:

vi /etc/default/useradd

The default home directory defined by HOME variable, find line that read as follows:

HOME=/home

Replace with:

HOME=/iscsi/user

Save and close the file. Now you can add user using regular useradd command:

# useradd vivek
# passwd vivek

Verify user information:

# finger vivek

Axios having CORS issue

your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms

How to call base.base.method()?

There seems to be a lot of these questions surrounding inheriting a member method from a Grandparent Class, overriding it in a second Class, then calling its method again from a Grandchild Class. Why not just inherit the grandparent's members down to the grandchildren?

class A
{
    private string mystring = "A";    
    public string Method1()
    {
        return mystring;
    }
}

class B : A
{
    // this inherits Method1() naturally
}

class C : B
{
    // this inherits Method1() naturally
}


string newstring = "";
A a = new A();
B b = new B();
C c = new C();
newstring = a.Method1();// returns "A"
newstring = b.Method1();// returns "A"
newstring = c.Method1();// returns "A"

Seems simple....the grandchild inherits the grandparents method here. Think about it.....that's how "Object" and its members like ToString() are inherited down to all classes in C#. I'm thinking Microsoft has not done a good job of explaining basic inheritance. There is too much focus on polymorphism and implementation. When I dig through their documentation there are no examples of this very basic idea. :(

trace a particular IP and port

it can be done by using this command: tcptraceroute -p destination port destination IP. like: tcptraceroute -p 9100 10.0.0.50 but don't forget to install tcptraceroute package on your system. tcpdump and nc by default installed on the system. regards

.NET NewtonSoft JSON deserialize map to a different property name

I am using JsonProperty attributes when serializing but ignoring them when deserializing using this ContractResolver:

public class IgnoreJsonPropertyContractResolver: DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var properties = base.CreateProperties(type, memberSerialization);
            foreach (var p in properties) { p.PropertyName = p.UnderlyingName; }
            return properties;
        }
    }

The ContractResolver just sets every property back to the class property name (simplified from Shimmy's solution). Usage:

var airplane= JsonConvert.DeserializeObject<Airplane>(json, 
    new JsonSerializerSettings { ContractResolver = new IgnoreJsonPropertyContractResolver() });

How is __eq__ handled in Python and in what order?

When Python2.x sees a == b, it tries the following.

  • If type(b) is a new-style class, and type(b) is a subclass of type(a), and type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If type(a) has overridden __eq__ (that is, type(a).__eq__ isn't object.__eq__), then the result is a.__eq__(b).
  • If type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If none of the above are the case, Python repeats the process looking for __cmp__. If it exists, the objects are equal iff it returns zero.
  • As a final fallback, Python calls object.__eq__(a, b), which is True iff a and b are the same object.

If any of the special methods return NotImplemented, Python acts as though the method didn't exist.

Note that last step carefully: if neither a nor b overloads ==, then a == b is the same as a is b.


From https://eev.ee/blog/2012/03/24/python-faq-equality/

gpg: no valid OpenPGP data found

I got this error in an Ubuntu Docker container. I believe the cause was that the container was missing CA certs. To fix it, I had to run:

apt-get update
apt-get install ca-certificates

How to use java.String.format in Scala?

You can use this;

String.format("%1$s %2$s %2$s %3$s", "a", "b", "c");

Output:

a b b c

Read data from a text file using Java

In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:

private List<String> loadFile() {
    URI uri = null;
    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }
    List<String> list = null;
    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}

Adding IN clause List to a JPA Query

public List<DealInfo> getDealInfos(List<String> dealIds) {
        String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
        TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
        query.setParameter("inclList", dealIds);
        return query.getResultList();
    }

Works for me with JPA 2, Jboss 7.0.2

Include another HTML file in a HTML file

Using ES6 backticks ``: template literals!

_x000D_
_x000D_
let nick = "Castor", name = "Moon", nuts = 1_x000D_
_x000D_
more.innerHTML = `_x000D_
_x000D_
<h1>Hello ${nick} ${name}!</h1>_x000D_
_x000D_
You collected ${nuts} nuts so far!_x000D_
_x000D_
<hr>_x000D_
_x000D_
Double it and get ${nuts + nuts} nuts!!_x000D_
_x000D_
` 
_x000D_
<div id="more"></div>
_x000D_
_x000D_
_x000D_

This way we can include html without encoding quotes, include variables from the DOM, and so on.

It is a powerful templating engine, we can use separate js files and use events to load the content in place, or even separate everything in chunks and call on demand:

let inject = document.createElement('script');
inject.src= '//....com/template/panel45.js';
more.appendChild(inject);

https://caniuse.com/#feat=template-literals

ImportError: No module named six

on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve

ImportError: No module named six

when launching Wammu

If it's occurred for python3 program, six come with

pip3 install six

and if you don't have pip3:

apt install python3-pip

with sudo under Ubuntu!

How to downgrade to older version of Gradle

I did following steps to downgrade Gradle back to the original version:

  • I deleted content of '.gradle/caches' folder in user home directory (windows).
  • I deleted content of '.gradle' folder in my project root.
  • I checked that Gradle version is properly set in 'Project' option of 'Project Structure' in Android Studio.
  • I selected 'Use default gradle wrapper' option in 'Settings' in Android Studio, just search for gradle key word to find it.

Probably last step is enough as in my case the path to the new Gradle distribution was hardcoded there under 'Gradle home' option.

Wrapping a react-router Link in an html button

Many of the solutions have focused on complicating things.

Using withRouter is a really long solution for something as simple as a button that links to somewhere else in the App.

If you are going for S.P.A. (single page application), the easiest answer I have found is to use with the button's equivalent className.

This ensures you are maintaining shared state / context without reloading your entire app as is done with

import { NavLink } from 'react-router-dom'; // 14.6K (gzipped: 5.2 K)

// Where link.{something} is the imported data
<NavLink className={`bx--btn bx--btn--primary ${link.className}`} to={link.href} activeClassName={'active'}>
    {link.label}
</NavLink>

// Simplified version:
<NavLink className={'bx--btn bx--btn--primary'} to={'/myLocalPath'}>
    Button without using withRouter
</NavLink>

How to select a drop-down menu value with Selenium using Python?

You can use a css selector combination a well

driver.find_element_by_css_selector("#fruits01 [value='1']").click()

Change the 1 in the attribute = value css selector to the value corresponding with the desired fruit.

How line ending conversions work with git core.autocrlf between different operating systems

Did some tests both on linux and windows. I use a test file containing lines ending in LF and also lines ending in CRLF.
File is committed , removed and then checked out. The value of core.autocrlf is set before commit and also before checkout. The result is below.

commit core.autocrlf false, remove, checkout core.autocrlf false: LF=>LF   CRLF=>CRLF  
commit core.autocrlf false, remove, checkout core.autocrlf input: LF=>LF   CRLF=>CRLF  
commit core.autocrlf false, remove, checkout core.autocrlf true : LF=>LF   CRLF=>CRLF  
commit core.autocrlf input, remove, checkout core.autocrlf false: LF=>LF   CRLF=>LF  
commit core.autocrlf input, remove, checkout core.autocrlf input: LF=>LF   CRLF=>LF  
commit core.autocrlf input, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF  
commit core.autocrlf true, remove, checkout core.autocrlf false: LF=>LF   CRLF=>LF  
commit core.autocrlf true, remove, checkout core.autocrlf input: LF=>LF   CRLF=>LF  
commit core.autocrlf true,  remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF  

Removing elements with Array.map in JavaScript

I just wrote array intersection that correctly handles also duplicates

https://gist.github.com/gkucmierz/8ee04544fa842411f7553ef66ac2fcf0

_x000D_
_x000D_
// array intersection that correctly handles also duplicates_x000D_
_x000D_
const intersection = (a1, a2) => {_x000D_
  const cnt = new Map();_x000D_
  a2.map(el => cnt[el] = el in cnt ? cnt[el] + 1 : 1);_x000D_
  return a1.filter(el => el in cnt && 0 < cnt[el]--);_x000D_
};_x000D_
_x000D_
const l = console.log;_x000D_
l(intersection('1234'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12344'.split``, '3456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('1234'.split``, '33456'.split``)); // [ '3', '4' ]_x000D_
l(intersection('12334'.split``, '33456'.split``)); // [ '3', '3', '4' ]
_x000D_
_x000D_
_x000D_

How do I use dataReceived event of the SerialPort Port Object in C#?

First off I recommend you use the following constructor instead of the one you currently use:

new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);

Next, you really should remove this code:

// Wait 10 Seconds for data...
for (int i = 0; i < 1000; i++)
{
    Thread.Sleep(10);
    Console.WriteLine(sp.Read(buf,0,bufSize)); //prints data directly to the Console
}

And instead just loop until the user presses a key or something, like so:

namespace serialPortCollection
{   class Program
    {
        static void Main(string[] args)
        {
            SerialPort sp = new SerialPort("COM10", 115200);
            sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler

            sp.Open();
            sp.WriteLine("$"); //Command to start Data Stream

            Console.ReadLine();

            sp.WriteLine("!"); //Stop Data Stream Command
            sp.Close();
        }

       // My Event Handler Method
        private static void port_OnReceiveDatazz(object sender, 
                                   SerialDataReceivedEventArgs e)
        {
            SerialPort spL = (SerialPort) sender;
            byte[] buf = new byte[spL.BytesToRead];
            Console.WriteLine("DATA RECEIVED!");
            spL.Read(buf, 0, buf.Length);
            foreach (Byte b in buf)
            {
                Console.Write(b.ToString());
            }
            Console.WriteLine();
        }
    }
}

Also, note the revisions to the data received event handler, it should actually print the buffer now.

UPDATE 1


I just ran the following code successfully on my machine (using a null modem cable between COM33 and COM34)

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread writeThread = new Thread(new ThreadStart(WriteThread));
            SerialPort sp = new SerialPort("COM33", 115200, Parity.None, 8, StopBits.One);
            sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler

            sp.Open();
            sp.WriteLine("$"); //Command to start Data Stream

            writeThread.Start();

            Console.ReadLine();

            sp.WriteLine("!"); //Stop Data Stream Command
            sp.Close();
        }

        private static void port_OnReceiveDatazz(object sender, 
                                   SerialDataReceivedEventArgs e)
        {
            SerialPort spL = (SerialPort) sender;
            byte[] buf = new byte[spL.BytesToRead];
            Console.WriteLine("DATA RECEIVED!");
            spL.Read(buf, 0, buf.Length);
            foreach (Byte b in buf)
            {
                Console.Write(b.ToString() + " ");
            }
            Console.WriteLine();
        }

        private static void WriteThread()
        {
            SerialPort sp2 = new SerialPort("COM34", 115200, Parity.None, 8, StopBits.One);
            sp2.Open();
            byte[] buf = new byte[100];
            for (byte i = 0; i < 100; i++)
            {
                buf[i] = i;
            }
            sp2.Write(buf, 0, buf.Length);
            sp2.Close();
        }
    }
}

UPDATE 2


Given all of the traffic on this question recently. I'm beginning to suspect that either your serial port is not configured properly, or that the device is not responding.

I highly recommend you attempt to communicate with the device using some other means (I use hyperterminal frequently). You can then play around with all of these settings (bitrate, parity, data bits, stop bits, flow control) until you find the set that works. The documentation for the device should also specify these settings. Once I figured those out, I would make sure my .NET SerialPort is configured properly to use those settings.

Some tips on configuring the serial port:

Note that when I said you should use the following constructor, I meant that use that function, not necessarily those parameters! You should fill in the parameters for your device, the settings below are common, but may be different for your device.

new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);

It is also important that you setup the .NET SerialPort to use the same flow control as your device (as other people have stated earlier). You can find more info here:

http://www.lammertbies.nl/comm/info/RS-232_flow_control.html

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

submit the form using ajax

Here is a universal solution that iterates through every field in form and creates the request string automatically. It is using new fetch API. Automatically reads form attributes: method and action and grabs all fields inside the form. Support single-dimension array fields, like emails[]. Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.

document.querySelector('.ajax-form').addEventListener('submit', function(e) {
    e.preventDefault();
    let formData = new FormData(this);
    let parsedData = {};
    for(let name of formData) {
      if (typeof(parsedData[name[0]]) == "undefined") {
        let tempdata = formData.getAll(name[0]);
        if (tempdata.length > 1) {
          parsedData[name[0]] = tempdata;
        } else {
          parsedData[name[0]] = tempdata[0];
        }
      }
    }

    let options = {};
    switch (this.method.toLowerCase()) {
      case 'post':
        options.body = JSON.stringify(parsedData);
      case 'get':
        options.method = this.method;
        options.headers = {'Content-Type': 'application/json'};
      break;
    }

    fetch(this.action, options).then(r => r.json()).then(data => {
      console.log(data);
    });
});

<form method="POST" action="some/url">
    <input name="emails[]">
    <input name="emails[]">
    <input name="emails[]">
    <input name="name">
    <input name="phone">
</form>

What do "branch", "tag" and "trunk" mean in Subversion repositories?

Tag = a defined slice in time, usually used for releases

I think this is what one typically means by "tag". But in Subversion:

They don't really have any formal meaning. A folder is a folder to SVN.

which I find rather confusing: a revision control system that knows nothing about branches or tags. From an implementation point of view, I think the Subversion way of creating "copies" is very clever, but me having to know about it is what I'd call a leaky abstraction.

Or perhaps I've just been using CVS far too long.

Onclick CSS button effect

JS provides the tools to do this the right way. Try the demo snippet.

enter image description here

_x000D_
_x000D_
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
  this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
  this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
  this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
  this.classList.remove('mouse-down');_x000D_
  alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling.  It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px'; 
_x000D_
button{_x000D_
  text-transform: uppercase;_x000D_
  background-color:rgba(66, 66, 66,0.3);_x000D_
  border:none;_x000D_
  font-size:4em;_x000D_
  color:white;_x000D_
  -webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  -moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
  outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
  background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
  -webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  -moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);                 _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
  display: flex;_x000D_
  flex-flow: row nowrap ;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
  order:1;_x000D_
  flex: 0 1 auto;_x000D_
  align-self: auto;_x000D_
  min-width: 0;_x000D_
  min-height: auto;_x000D_
}            _x000D_
_x000D_
_x000D_
    
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset=utf-8 />_x000D_
    <meta name="description" content="3d Button Configuration" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <section id="box">_x000D_
      <button>_x000D_
        Submit_x000D_
      </button>_x000D_
    </section>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to read a line from a text file in c/c++?

im not really that good at C , but i believe this code should get you complete single line till the end...

 #include<stdio.h>

 int main()   
{      
  char line[1024];    
  FILE *f=fopen("filename.txt","r");    
  fscanf(*f,"%[^\n]",line);    
  printf("%s",line);    
 }    

Tar error: Unexpected EOF in archive

I had a similar problem with truncated tar files being produced by a cron job and redirecting standard out to a file fixed the issue.

From talking to a colleague, cron creates a pipe and limits the amount of output that can be sent to standard out. I fixed mine by removing -v from my tar command, making it much less verbose and keeping the error output in the same spot as the rest of my cron jobs. If you need the verbose tar output, you'll need to redirect to a file, though.

SQL Server error on update command - "A severe error occurred on the current command"

In my case it was something else, += operator caused this. I had to replace += X with field = field + X to overcome this. I assume this is a bug though I wasn't able to find any related KB on Microsoft sites.

I am using SQL Server 2008 R2(10.50.1600).

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Allow multiple roles to access controller action

If you find yourself applying those 2 roles often you can wrap them in their own Authorize. This is really an extension of the accepted answer.

using System.Web.Mvc;

public class AuthorizeAdminOrMember : AuthorizeAttribute
{
    public AuthorizeAdminOrMember()
    {
        Roles = "members, admin";
    }
}

And then apply your new authorize to the Action. I think this looks cleaner and reads easily.

public class MyController : Controller
{
    [AuthorizeAdminOrMember]
    public ActionResult MyAction()
    {
        return null;
    }
}

How to add a new line of text to an existing file in Java?

Starting from Java 7:

Define a path and the String containing the line separator at the beginning:

Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";

and then you can use one of the following approaches:

  1. Using Files.write (small files):

    try {
        Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.err.println(e);
    }
    
  2. Using Files.newBufferedWriter(text files):

    try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
        writer.write(s);
    } catch (IOException ioe) {
        System.err.format("IOException: %s%n", ioe);
    }
    
  3. Using Files.newOutputStream (interoperable with java.io APIs):

    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
        out.write(s.getBytes());
    } catch (IOException e) {
        System.err.println(e);
    }
    
  4. Using Files.newByteChannel (random access files):

    try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    
  5. Using FileChannel.open (random access files):

    try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    

Details about these methods can be found in the Oracle's tutorial.

What is mod_php?

Just to add on these answers is that, mod_php is the oldest and slowest method available in HTTPD server to use PHP. It is not recommended, unless you are running old versions of Apache HTTPD and PHP. php-fpm and proxy_cgi are the preferred methods.

Copying one structure to another

If the structures are of compatible types, yes, you can, with something like:

memcpy (dest_struct, source_struct, sizeof (*dest_struct));

The only thing you need to be aware of is that this is a shallow copy. In other words, if you have a char * pointing to a specific string, both structures will point to the same string.

And changing the contents of one of those string fields (the data that the char * points to, not the char * itself) will change the other as well.

If you want a easy copy without having to manually do each field but with the added bonus of non-shallow string copies, use strdup:

memcpy (dest_struct, source_struct, sizeof (*dest_struct));
dest_struct->strptr = strdup (source_struct->strptr);

This will copy the entire contents of the structure, then deep-copy the string, effectively giving a separate string to each structure.

And, if your C implementation doesn't have a strdup (it's not part of the ISO standard), get one from here.

Clear text from textarea with selenium

In my experience, this turned out to be the most efficient

driver.find_element_by_css_selector('foo').send_keys(u'\ue009' + u'\ue003')

We are sending Ctrl + Backspace to delete all characters from the input, you can also replace backspace with delete.

EDIT: removed Keys dependency

header location not working in my php code

just use ob_start(); before include function it will help

How do you install GLUT and OpenGL in Visual Studio 2012?

OpenGL should be present already - it will probably be Freeglut / GLUT that is missing.

GLUT is very dated now and not actively supported - so you should certainly be using Freeglut instead. You won't have to change your code at all, and a few additional features become available.

You'll find pre-packaged sets of files from here: http://freeglut.sourceforge.net/index.php#download If you don't see the "lib" folder, it's because you didn't download the pre-packaged set. "Martin Payne's Windows binaries" is posted at above link and works on Windows 8.1 with Visual Studio 2013 at the time of this writing.

When you download these you'll find that the Freeglut folder has three subfolders: - bin folder: this contains the dll files for runtime - include: the header files for compilation - lib: contains library files for compilation/linking

Installation instructions usually suggest moving these files into the visual studio folder and the Windows system folder: It is best to avoid doing this as it makes your project less portable, and makes it much more difficult if you ever need to change which version of the library you are using (old projects might suddenly stop working, etc.)

Instead (apologies for any inconsistencies, I'm basing these instructions on VS2010)... - put the freeglut folder somewhere else, e.g. C:\dev - Open your project in Visual Studio - Open project properties - There should be a tab for VC++ Directories, here you should add the appropriate include and lib folders, e.g.: C:\dev\freeglut\include and C:\dev\freeglut\lib - (Almost) Final step is to ensure that the opengl lib file is actually linked during compilation. Still in project properties, expand the linker menu, and open the input tab. For Additional Dependencies add opengl32.lib (you would assume that this would be linked automatically just by adding the include GL/gl.h to your project, but for some reason this doesn't seem to be the case)

At this stage your project should compile OK. To actually run it, you also need to copy the freeglut.dll files into your project folder

VBA - Select columns using numbers?

In this way, you can start to select data even behind column "Z" and select a lot of columns.

Sub SelectColumNums()
    Dim xCol1 As Integer, xNumOfCols as integer
    xCol1 = 26
    xNumOfCols = 17
    Range(Columns(xCol1), Columns(xCol1 + xNumOfCols)).Select
End Sub

How to change sa password in SQL Server 2008 express?

If you want to change your 'sa' password with SQL Server Management Studio, here are the steps:

  1. Login using Windows Authentication and ".\SQLExpress" as Server Name
  2. Change server authentication mode - Right click on root, choose Properties, from Security tab select "SQL Server and Windows Authentication mode", click OK Change server authentication mode

  3. Set sa password - Navigate to Security > Logins > sa, right click on it, choose Properties, from General tab set the Password (don't close the window) Set sa password

  4. Grant permission - Go to Status tab, make sure the Grant and Enabled radiobuttons are chosen, click OK Grant permission

  5. Restart SQLEXPRESS service from your local services (Window+R > services.msc)

How to insert array of data into mysql using php

I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation

DB::create($db, 'YOUR_TABLE_NAME', $dataArray);

where $db is your Database connection.

Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download : https://github.com/pairavanvvl/crud

How to get primary key of table?

I've got it, finally!

<?php

function mysql_get_prim_key($table){
$sql = "SHOW INDEX FROM $table WHERE Key_name = 'PRIMARY'";
$gp = mysql_query($sql);
$cgp = mysql_num_rows($gp);
if($cgp > 0){
// Note I'm not using a while loop because I never use more than one prim key column
$agp = mysql_fetch_array($gp);
extract($agp);
return($Column_name);
}else{
return(false);
}
}

?>

How to detect control+click in Javascript from an onclick div attribute?

When there is a mouse click ctrlKey is event attribute which can be accessed as e.ctrlKey. Look down for example

$("xyz").click(function(e)){
  if(e.ctrlKey){
    //if ctrl key is pressed
  }
  else{
    // if ctrl key is not pressed
  }
}

note: https://www.w3schools.com/jsref/event_key_keycode.asp

Google API authentication: Not valid origin for the client

Clear your browser cache. Started getting this error in Chrome and then I created a new client id and was still getting the issue. Opened firefox and it worked, so I cleared the cache on Chrome and it started working.

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

You have Numpy Data Type, Just change to normal int() or float() data type. it will work fine.

TensorFlow, "'module' object has no attribute 'placeholder'"

I also got the same error. May be because of the version of tensorflow. After installing tensorflow 1.4.0, I got relief from the error.

pip install tensorflow==1.4.0

WCF - How to Increase Message Size Quota

For me, all I had to do is add maxReceivedMessageSize="2147483647" to the client app.config. The server left untouched.

What does %~dp0 mean, and how does it work?

Calling

for /?

in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found).

In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
               environment variable for %I and expands to the
               drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.

There are different letters you can use like f for "full path name", d for drive letter, p for path, and they can be combined. %~ is the beginning for each of those sequences and a number I denotes it works on the parameter %I (where %0 is the complete name of the batch file, just like you assumed).

How to change font size in a textbox in html

To actually do it in HTML with inline CSS (not with an external CSS style sheet)

<input type="text" style="font-size: 44pt">

A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html> or <body> tag, and such is appropriate there.

How to convert PDF files to images

(Disclaimer I worked on this component at Software Siglo XXI)

You could use Super Pdf2Image Converter to generate a TIFF multi-page file with all the rendered pages from the PDF in high resolution. It's available for both 32 and 64 bit and is very cheap and effective. I'd recommend you to try it.

Just one line of code...

GetImage(outputFileName, firstPage, lastPage, resolution, imageFormat)

Converts specifies pages to image and save them to outputFileName (tiff allows multi-page or creates several files)

You can take a look here: http://softwaresigloxxi.com/SuperPdf2ImageConverter.html

ERROR! MySQL manager or server PID file could not be found! QNAP

I was able to solve this on OS X by shutting down the existing mysql.server that was running:

mysql.server stop

The starting:

mysql.server start

From there I could run mysql.server restart without throwing the ERROR.

Delete all rows in table

As other have said, TRUNCATE TABLE is far quicker, but it does have some restrictions (taken from here):

You cannot use TRUNCATE TABLE on tables that:

- Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.)
- Participate in an indexed view.
- Are published by using transactional replication or merge replication.

For tables with one or more of these characteristics, use the DELETE statement instead.

The biggest drawback is that if the table you are trying to empty has foreign keys pointing to it, then the truncate call will fail.

Regular Expression for password validation

Update to Justin answer above. if you want to use it using Data Annotation in MVC you can do as follow

[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$", ErrorMessage = "Password must be between 6 and 20 characters and contain one uppercase letter, one lowercase letter, one digit and one special character.")]

OR, AND Operator

if(A == "haha" && B == "hihi") {
//hahahihi?
}

if(A == "haha" || B != "hihi") {
//hahahihi!?
}

How to import local packages in go?

Local package is a annoying problem in go.

For some projects in our company we decide not use sub packages at all.

  • $ glide install
  • $ go get
  • $ go install

All work.

For some projects we use sub packages, and import local packages with full path:

import "xxxx.gitlab.xx/xxgroup/xxproject/xxsubpackage

But if we fork this project, then the subpackages still refer the original one.

jQuery append() - return appended elements

A little reminder, when elements are added dynamically, functions like append(), appendTo(), prepend() or prependTo() return a jQuery object, not the HTML DOM element.

DEMO

var container=$("div.container").get(0),
    htmlA="<div class=children>A</div>",
    htmlB="<div class=children>B</div>";

// jQuery object
alert( $(container).append(htmlA) ); // outputs "[object Object]"

// HTML DOM element
alert( $(container).append(htmlB).get(0) ); // outputs "[object HTMLDivElement]"

Add params to given URL in Python

You can also use the furl module https://github.com/gruns/furl

>>> from furl import furl
>>> print furl('http://example.com/search?q=question').add({'lang':'en','tag':'python'}).url
http://example.com/search?q=question&lang=en&tag=python

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

There's also another way to do this-

select TO_CHAR(SA.[RequestStartDate] , 'DD/MM/YYYY') as RequestStartDate from ... ;

How to visualize an XML schema?

You can use XMLGrid's Online viewer which provides a great XSD support and many other features:

  • Display XML data in an XML data grid.
  • Supports XML, XSL, XSLT, XSD, HTML file types.
  • Easy to modify or delete existing nodes, attributes, comments.
  • Easy to add new nodes, attributes or comments.
  • Easy to expand or collapse XML node tree.
  • View XML source code.

Screenshot:

Screenshot

Can inner classes access private variables?

An inner class has access to all members of the outer class, but it does not have an implicit reference to a parent class instance (unlike some weirdness with Java). So if you pass a reference to the outer class to the inner class, it can reference anything in the outer class instance.

Seeding the random number generator in Javascript

In PHP, there is function srand(seed) which generate fixed random value for particular seed. But, in JS, there is no such inbuilt function.

However, we can write simple and short function.

Step 1: Choose some Seed (Fix Number).
var seed = 100;
Number should be Positive Integer and greater than 1, further explanation in Step 2.

Step 2: Perform Math.sin() function on Seed, it will give sin value of that number. Store this value in variable x.

var x; 
x = Math.sin(seed); // Will Return Fractional Value between -1 & 1 (ex. 0.4059..)

sin() method returns a Fractional value between -1 and 1.
And we don't need Negative value, therefore, in first step choose number greater than 1.

Step 3: Returned Value is a Fractional value between -1 and 1.
So mulitply this value with 10 for making it more than 1.

x = x * 10; // 10 for Single Digit Number

Step 4: Multiply the value with 10 for additional digits

x = x * 10; // Will Give value between 10 and 99 OR
x = x * 100; // Will Give value between 100 and 999

Multiply as per requirement of digits.

The result will be in decimal.

Step 5: Remove value after Decimal Point by Math's Round (Math.round()) Method.

x = Math.round(x); // This will give Integer Value.

Step 6: Turn Negative Values into Positive (if any) by Math.abs method

x = Math.abs(x); // Convert Negative Values into Positive(if any)

Explanation End.

Final Code

var seed = 111; // Any Number greater than 1
var digit = 10 // 1 => single digit, 10 => 2 Digits, 100 => 3 Digits and so. (Multiple of 10) 

var x; // Initialize the Value to store the result
x = Math.sin(seed); // Perform Mathematical Sin Method on Seed.
x = x * 10; // Convert that number into integer
x = x * digit; // Number of Digits to be included
x = Math.round(x); // Remove Decimals
x = Math.abs(x); // Convert Negative Number into Positive

Clean and Optimized Functional Code

function random_seed(seed, digit = 1) {
    var x = Math.abs(Math.round(Math.sin(seed++) * 10 * digit));
    return x;
}

Then Call this function using
random_seed(any_number, number_of_digits)
any_number is must and should be greater than 1.
number_of_digits is optional parameter and if nothing passed, 1 Digit will return.

random_seed(555); // 1 Digit
random_seed(234, 1); // 1 Digit
random_seed(7895656, 1000); // 4 Digit

Collection was modified; enumeration operation may not execute

So a different way to solve this problem would be instead of removing the elements create a new dictionary and only add the elements you didnt want to remove then replace the original dictionary with the new one. I don't think this is too much of an efficiency problem because it does not increase the number of times you iterate over the structure.

Angular 2: How to call a function after get a response from subscribe http.post

get_categories(number){
 return this.http.post( url, body, {headers: headers, withCredentials:true})
      .map(t=>  {
          this.total = t.json();
          return total;
      }).share();
  );     
}

then

this.get_category(1).subscribe(t=> {
      this.callfunc();
});

Back button and refreshing previous activity

I think onRestart() works better for this.

@Override
public void onRestart() { 
    super.onRestart();
    //When BACK BUTTON is pressed, the activity on the stack is restarted
    //Do what you want on the refresh procedure here
}

You could code what you want to do when the Activity is restarted (called again from the event 'back button pressed') inside onRestart().

For example, if you want to do the same thing you do in onCreate(), paste the code in onRestart() (eg. reconstructing the UI with the updated values).

Best implementation for Key Value Pair Data Structure?

There is an actual Data Type called KeyValuePair, use like this

KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue");

No resource found - Theme.AppCompat.Light.DarkActionBar

A simple solution - replace contents this file (/res/values/styles.xml) to this is text:

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

regex to remove all text before a character

The regular expression:

^[^_]*_(.*)$

Then get the part between parenthesis. In perl:

my var = "3.04_somename.jpg";
$var =~ m/^[^_]*_(.*)$/;
my fileName = $1;

In Java:

String var = "3.04_somename.jpg";
String fileName = "";
Pattern pattern = Pattern.compile("^[^_]*_(.*)$");
Matcher matcher = pattern.matcher(var);
if (matcher.matches()) {
    fileName = matcher.group(1);
}

...

Javascript to set hidden form value on drop down change

I'd fought with this a long time $('#myelement').val(x) just wasn't working ... until I realized the # construction requires an ID, not a NAME. So if ".val(x) doesn't work!" is your problem, check your element and be sure it has an ID!

It's an embarrassing gotcha, but I felt I had to share to save others much hair-tearing.

On Duplicate Key Update same as insert

There is no other way, I have to specify everything twice. First for the insert, second in the update case.

How to pass extra variables in URL with WordPress

One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.

See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.

What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.

add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );

function add_custom_setcookie_rewrite_endpoints() {
    //add ?c=123 endpoint with
    //EP_ALL so endpoint is present across all places
    //no effect on the query vars
    add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}

This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.

Remember to flush your rewrite rules after adding/modifying this.

How do I enumerate the properties of a JavaScript object?

I think an example of the case that has caught me by surprise is relevant:

var myObject = { name: "Cody", status: "Surprised" };
for (var propertyName in myObject) {
  document.writeln( propertyName + " : " + myObject[propertyName] );
}

But to my surprise, the output is

name : Cody
status : Surprised
forEach : function (obj, callback) {
    for (prop in obj) {
        if (obj.hasOwnProperty(prop) && typeof obj[prop] !== "function") {
            callback(prop);
        }
    }
}

Why? Another script on the page has extended the Object prototype:

Object.prototype.forEach = function (obj, callback) {
  for ( prop in obj ) {
    if ( obj.hasOwnProperty( prop ) && typeof obj[prop] !== "function" ) {
      callback( prop );
    }
  }
};

How to compare data between two table in different databases using Sql Server 2008?

If both database on same server. You can check similar tables by using following query :

select 
      fdb.name, sdb.name 
from 
      FIRSTDBNAME.sys.tables fdb 
      join SECONDDBNAME.sys.tables sdb
      on fdb.name = sdb.name -- compare same name tables
order by 
      1     

By listing out similar table you can compare columns schema using sys.columns view.

Hope this helps you.

Passing parameters in Javascript onClick event

This will work from JS without coupling to HTML:

document.getElementById("click-button").onclick = onClickFunction;

function onClickFunction()
{
    return functionWithArguments('You clicked the button!');
}

function functionWithArguments(text) {
    document.getElementById("some-div").innerText = text;
}

Assigning a variable NaN in python without numpy

Yes -- use math.nan.

>>> from math import nan
>>> print(nan)
nan
>>> print(nan + 2)
nan
>>> nan == nan
False
>>> import math
>>> math.isnan(nan)
True

Before Python 3.5, one could use float("nan") (case insensitive).

Note that checking to see if two things that are NaN are equal to one another will always return false. This is in part because two things that are "not a number" cannot (strictly speaking) be said to be equal to one another -- see What is the rationale for all comparisons returning false for IEEE754 NaN values? for more details and information.

Instead, use math.isnan(...) if you need to determine if a value is NaN or not.

Furthermore, the exact semantics of the == operation on NaN value may cause subtle issues when trying to store NaN inside container types such as list or dict (or when using custom container types). See Checking for NaN presence in a container for more details.


You can also construct NaN numbers using Python's decimal module:

>>> from decimal import Decimal
>>> b = Decimal('nan')
>>> print(b)
NaN
>>> print(repr(b))
Decimal('NaN')
>>>
>>> Decimal(float('nan'))
Decimal('NaN')
>>> 
>>> import math
>>> math.isnan(b)
True

math.isnan(...) will also work with Decimal objects.


However, you cannot construct NaN numbers in Python's fractions module:

>>> from fractions import Fraction
>>> Fraction('nan')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\fractions.py", line 146, in __new__
    numerator)
ValueError: Invalid literal for Fraction: 'nan'
>>>
>>> Fraction(float('nan'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\fractions.py", line 130, in __new__
    value = Fraction.from_float(numerator)
  File "C:\Python35\lib\fractions.py", line 214, in from_float
    raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
ValueError: Cannot convert nan to Fraction.

Incidentally, you can also do float('Inf'), Decimal('Inf'), or math.inf (3.5+) to assign infinite numbers. (And also see math.isinf(...))

However doing Fraction('Inf') or Fraction(float('inf')) isn't permitted and will throw an exception, just like NaN.

If you want a quick and easy way to check if a number is neither NaN nor infinite, you can use math.isfinite(...) as of Python 3.2+.


If you want to do similar checks with complex numbers, the cmath module contains a similar set of functions and constants as the math module:

How to Compare a long value is equal to Long value

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b.longValue())
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

or:

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b)
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

Mongoose: findOneAndUpdate doesn't return updated document

Why this happens?

The default is to return the original, unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: an object with the new property set to true.

From the mongoose docs:

Query#findOneAndUpdate

Model.findOneAndUpdate(conditions, update, options, (error, doc) => {
  // error: any errors that occurred
  // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
});

Available options

  • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)

Solution

Pass {new: true} if you want the updated result in the doc variable:

//                                                         V--- THIS WAS ADDED
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});

Making button go full-width?

Why not use the Bootstrap predefined class input-block-level that does the job?

<a href="#" class="btn input-block-level">Full-Width Button</a> <!-- BS2 -->
<a href="#" class="btn form-control">Full-Width Button</a> <!-- BS3 -->

<!-- And let's join both for BS# :) -->
<a href="#" class="btn input-block-level form-control">Full-Width Button</a>

Learn more here in the Control Sizing^ section.

`export const` vs. `export default` in ES6

export default affects the syntax when importing the exported "thing", when allowing to import, whatever has been exported, by choosing the name in the import itself, no matter what was the name when it was exported, simply because it's marked as the "default".

A useful use case, which I like (and use), is allowing to export an anonymous function without explicitly having to name it, and only when that function is imported, it must be given a name:


Example:

Export 2 functions, one is default:

export function divide( x ){
    return x / 2;
}

// only one 'default' function may be exported and the rest (above) must be named
export default function( x ){  // <---- declared as a default function
    return x * x;
}

Import the above functions. Making up a name for the default one:

// The default function should be the first to import (and named whatever)
import square, {divide} from './module_1.js'; // I named the default "square" 

console.log( square(2), divide(2) ); // 4, 1

When the {} syntax is used to import a function (or variable) it means that whatever is imported was already named when exported, so one must import it by the exact same name, or else the import wouldn't work.


Erroneous Examples:

  1. The default function must be first to import

    import {divide}, square from './module_1.js
    
  2. divide_1 was not exported in module_1.js, thus nothing will be imported

    import {divide_1} from './module_1.js
    
  3. square was not exported in module_1.js, because {} tells the engine to explicitly search for named exports only.

    import {square} from './module_1.js
    

How to normalize a 2-dimensional numpy array in python less verbose?

You could use built-in numpy function: np.linalg.norm(a, axis = 1, keepdims = True)

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

Set NOW() as Default Value for datetime datatype?

mysql 5.6 docs say that CURRENT_TIMESTAMP can be used as default for both TIMESTAMP and DATETIME data types:

http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html

Rounding a double value to x number of decimal places in swift

The code for specific digits after decimals is:

var a = 1.543240952039
var roundedString = String(format: "%.3f", a)

Here the %.3f tells the swift to make this number rounded to 3 decimal places.and if you want double number, you may use this code:

// String to Double

var roundedString = Double(String(format: "%.3f", b))

How to get the selected item from ListView?

You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.

What you should change, in your above example, is to

public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    MyClass item = (MyClass) adapter.getItem(position);
}

How do I speed up the gwt compiler?

Let's start with the uncomfortable truth: GWT compiler performance is really lousy. You can use some hacks here and there, but you're not going to get significantly better performance.

A nice performance hack you can do is to compile for only specific browsers, by inserting the following line in your gwt.xml:

<define-property name="user.agent" values="ie6,gecko,gecko1_8"></define-property>

or in gwt 2.x syntax, and for one browser only:

<set-property name="user.agent" value="gecko1_8"/>

This, for example, will compile your application for IE and FF only. If you know you are using only a specific browser for testing, you can use this little hack.

Another option: if you are using several locales, and again using only one for testing, you can comment them all out so that GWT will use the default locale, this shaves off some additional overhead from compile time.

Bottom line: you're not going to get order-of-magnitude increase in compiler performance, but taking several relaxations, you can shave off a few minutes here and there.

How can I check whether an array is null / empty?

There's a key difference between a null array and an empty array. This is a test for null.

int arr[] = null;
if (arr == null) {
  System.out.println("array is null");
}

"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:

arr = new int[0];
if (arr.length == 0) {
  System.out.println("array is empty");
}

An alternative definition of "empty" is if all the elements are null:

Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
  if (arr[i] != null) {
    empty = false;
    break;
  }
}

or

Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
  if (ob != null) {
    empty = false;
    break;
  }
}

Adding elements to object

If anyone comes looking to create a similar JSON, just without using cart as an array, here goes:

I have an array of objects myArr as:

var myArr = [{resourceType:"myRT",
            id: 1,
            value:"ha"},
            {resourceType:"myRT",
            id: 2,
            value:"he"},
            {resourceType:"myRT",
            id: 3,
            value:"Li"}];

and I will attempt to create a JSON with the following structure:

{
 "1":{"resourceType":"myRT","id":"1","value":"ha"},
 "2":{"resourceType":"myRT","id":"2","value":"he"},
 "3":{"resourceType":"myRT","id":"3","value":"Li"}
}

you can simply do-

var cart = {};
myArr.map(function(myObj){
                    cart[myObj.id]= myObj;
                    });

Refreshing Web Page By WebDriver When Waiting For Specific Condition

Another way to refresh the current page using selenium in Java.

//first: get the current URL in a String variable
String currentURL = driver.getCurrentUrl(); 
//second: call the current URL
driver.get(currentURL); 

Using this will refresh the current page like clicking the address bar of the browser and pressing enter.

How to write to error log file in PHP

you can simply use :

error_log("your message");

By default, the message will be send to the php system logger.

Excel: last character/string match in a string

Considering a part of a Comment made by @SSilk my end goal has really been to get everything to the right of that last occurence an alternative approach with a very simple formula is to copy a column (say A) of strings and on the copy (say ColumnB) apply Find and Replace. For instance taking the example: Drive:\Folder\SubFolder\Filename.ext

Find what

This returns what remains (here Filename.ext) after the last instance of whatever character is chosen (here \) which is sometimes the objective anyway and facilitates finding the position of the last such character with a short formula such as:

=FIND(B1,A1)-1

Comparing arrays for equality in C++

When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 ) actually compares two addresses. Those pointers do not address the same object.

Close all infowindows in Google Maps API v3

I have something like the following

function initMap()
{
    //...create new map here
    var infowindow;
    $('.business').each(function(el){
        //...get lat/lng
        var position = new google.maps.LatLng(lat, lng);
        var content = "contents go here";
        var title = "titleText";
        var openWindowFn;
        var closure = function(content, position){.
            openWindowFn = function()
            {
                if (infowindow)
                {
                    infowindow.close();
                }
                infowindow = new google.maps.InfoWindow({
                    position:position,
                    content:content
                });
                infowindow.open(map, marker);
            }
        }(content, position);
        var marker = new google.maps.Marker({
            position:position,
            map:map,
            title:title.
        });
        google.maps.event.addListener(marker, 'click', openWindowFn);
    }
}

In my understanding, using a closure like that allows the capturing of variables and their values at the time of function declaration, rather than relying on global variables. So when openWindowFn is called later, on the first marker for example, the content and position variable have the values they did during the first iteration in the each() function.

I'm not really sure how openWindowFn has infowindow in its scope. I'm also not sure I'm doing things right, but it works, even with multiple maps on one page (each map gets one open infowindow).

If anyone has any insights, please comment.

Plain Old CLR Object vs Data Transfer Object

Don't even call them DTOs. They're called Models....Period. Models never have behavior. I don't know who came up with this dumb term DTO but it must be a .NET thing is all I can figure. Think of view models in MVC, same dam** thing, models are used to transfer state between layers server side or over the wire period, they are all models. Properties with data. These are models you pass ove the wire. Models, Models Models. That's it.

I wish the stupid term DTO would go away from our vocabulary.

How to make an element in XML schema optional?

Set the minOccurs attribute to 0 in the schema like so:

<?xml version="1.0"?>
  <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="request">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="amenity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="description" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element> </xs:schema>

Set value for particular cell in pandas DataFrame with iloc

One thing I would add here is that the at function on a dataframe is much faster particularly if you are doing a lot of assignments of individual (not slice) values.

df.at[index, 'col_name'] = x

In my experience I have gotten a 20x speedup. Here is a write up that is Spanish but still gives an impression of what's going on.

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

T-SQL query to show table definition?

There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.

SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
       , IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'

SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')

How does data binding work in AngularJS?

This is my basic understanding. It may well be wrong!

  1. Items are watched by passing a function (returning the thing to be watched) to the $watch method.
  2. Changes to watched items must be made within a block of code wrapped by the $apply method.
  3. At the end of the $apply the $digest method is invoked which goes through each of the watches and checks to see if they changed since last time the $digest ran.
  4. If any changes are found then the digest is invoked again until all changes stabilize.

In normal development, data-binding syntax in the HTML tells the AngularJS compiler to create the watches for you and controller methods are run inside $apply already. So to the application developer it is all transparent.

How to split a comma-separated value to columns

I encountered a similar problem but a complex one and since this is the first thread i found regarding that issue i decided to post my finding. i know it is complex solution to a simple problem but i hope that i could help other people who go to this thread looking for a more complex solution. i had to split a string containing 5 numbers (column name: levelsFeed) and to show each number in a separate column. for example: 8,1,2,2,2 should be shown as :

1  2  3  4  5
-------------
8  1  2  2  2

Solution 1: using XML functions: this solution for the slowest solution by far

SELECT Distinct FeedbackID, 
, S.a.value('(/H/r)[1]', 'INT') AS level1
, S.a.value('(/H/r)[2]', 'INT') AS level2
, S.a.value('(/H/r)[3]', 'INT') AS level3
, S.a.value('(/H/r)[4]', 'INT') AS level4
, S.a.value('(/H/r)[5]', 'INT') AS level5
FROM (            
    SELECT *,CAST (N'<H><r>' + REPLACE(levelsFeed, ',', '</r><r>')  + '</r> </H>' AS XML) AS [vals]
    FROM Feedbacks 
)  as d
CROSS APPLY d.[vals].nodes('/H/r') S(a)

Solution 2: using Split function and pivot. (the split function split a string to rows with the column name Data)

SELECT FeedbackID, [1],[2],[3],[4],[5]
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY feedbackID ORDER BY (SELECT  null)) as rn 
FROM (
    SELECT FeedbackID, levelsFeed
    FROM Feedbacks 
) as a
CROSS APPLY dbo.Split(levelsFeed, ',')
) as SourceTable
PIVOT
(
    MAX(data)
    FOR rn IN ([1],[2],[3],[4],[5])
)as pivotTable

Solution 3: using string manipulations functions - fastest by small margin over solution 2

SELECT FeedbackID,
SUBSTRING(levelsFeed,0,CHARINDEX(',',levelsFeed)) AS level1,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),4) AS level2,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),3) AS level3,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),2) AS level4,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),1) AS level5
FROM Feedbacks

since the levelsFeed contains 5 string values i needed to use the substring function for the first string.

i hope that my solution will help other that got to this thread looking for a more complex split to columns methods

What is java pojo class, java bean, normal class?

POJO stands for Plain Old Java Object, and would be used to describe the same things as a "Normal Class" whereas a JavaBean follows a set of rules. Most commonly Beans use getters and setters to protect their member variables, which are typically set to private and have a no-argument public constructor. Wikipedia has a pretty good rundown of JavaBeans: http://en.wikipedia.org/wiki/JavaBeans

POJO is usually used to describe a class that doesn't need to be a subclass of anything, or implement specific interfaces, or follow a specific pattern.

How to select records from last 24 hours using SQL?

In MySQL:

SELECT  *
FROM    mytable
WHERE   record_date >= NOW() - INTERVAL 1 DAY

In SQL Server:

SELECT  *
FROM    mytable
WHERE   record_date >= DATEADD(day, -1, GETDATE())

In Oracle:

SELECT  *
FROM    mytable
WHERE   record_date >= SYSDATE - 1

In PostgreSQL:

SELECT  *
FROM    mytable
WHERE   record_date >= NOW() - '1 day'::INTERVAL

In Redshift:

SELECT  *
FROM    mytable
WHERE   record_date >= GETDATE() - '1 day'::INTERVAL

In SQLite:

SELECT  *
FROM    mytable
WHERE   record_date >= datetime('now','-1 day')

In MS Access:

SELECT  *
FROM    mytable
WHERE   record_date >= (Now - 1)

Lost connection to MySQL server during query?

You might like to read this - http://dev.mysql.com/doc/refman/5.0/en/gone-away.html - that very well explains the reasons and fixes for "lost connection during query" scenarios.

In your case, it might be because of the max allowed packet size as pointed by Augusto. Or if you've verified it isn't the case, then it might be the connection wait timeout setting due to which the client is losing connection. However, I do not think latter is true here because it's a CSV file and not containing queries.

How to stop and restart memcached server?

if linux

if install by apt-get

service memcached stop
service memcached restart

if install by source code

Usage: /etc/init.d/memcached {start|stop|restart|force-reload|status}

can also simply kill $pid to stop

"Sources directory is already netbeans project" error when opening a project from existing sources

This means the project folder is already a netbeans project. So instead of adding it as a new project open it asenter image description here

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

Works for any number from 0 to 999999999.

This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.

#include <iostream>
using namespace std;
int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
long input, nFake = 0;
const char ones[][20] = {"",       "one",       "two",      "three",
                         "four",    "five",      "six",      "seven",
                         "eight",   "nine",      "ten",      "eleven",
                         "twelve",  "thirteen",  "fourteen", "fifteen",
                         "sixteen", "seventeen", "eighteen", "nineteen"};
const char tens[][20] = {"",     "ten",   "twenty",  "thirty", "forty",
                         "fifty", "sixty", "seventy", "eighty", "ninety"};
void convert(int funcVar);
int main() {
  cout << "Enter the number:";
  cin >> input;
  nFake = input;
  buffer = 0;
  while (nFake) {
    part[buffer] = nFake % 1000;
    nFake /= 1000;
    buffer++;
  }
  if (buffer == 0) {
    cout << "Zero.";
  } else if (buffer == 1) {
    convert(part[0]);
  } else if (buffer == 2) {
    convert(part[1]);
    cout << " thousand,";
    convert(part[0]);
  } else {
    convert(part[2]);
    cout << " million,";

    if (part[1]) {
      convert(part[1]);
      cout << " thousand,";
    } else {
      cout << "";
    }
    convert(part[0]);
  }
  system("pause");
  return (0);
}

void convert(int funcVar) {
  buffer = 0;
  if (funcVar >= 100) {
    a = funcVar / 100;
    b = funcVar % 100;
    if (b)
      cout << " " << ones[a] << " hundred and";
    else
      cout << " " << ones[a] << " hundred ";
    if (b < 20)
      cout << " " << ones[b];
    else {
      c = b / 10;
      cout << " " << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  } else {
    b = funcVar;
    if (b < 20)
      cout << ones[b];
    else {
      c = b / 10;
      cout << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  }
}

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

Body set to overflow-y:hidden but page is still scrollable in Chrome

Setting a height on your body and html of 100% should fix you up. Without a defined height your content is not overflowing, so you will not get the desired behavior.

html, body {
  overflow-y:hidden;
  height:100%;
}

How to detect if user select cancel InputBox VBA Excel

Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.

Sub unhidesheet()

Dim ws As Worksheet
Dim pw As String

pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then

   Exit Sub
ElseIf pw = NullString Then
   Exit Sub
ElseIf pw = 123456 Then
    For Each ws In ThisWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next
End If
End Sub

What is the difference between Numpy's array() and asarray() functions?

The definition of asarray is:

def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)

So it is like array, except it has fewer options, and copy=False. array has copy=True by default.

The main difference is that array (by default) will make a copy of the object, while asarray will not unless necessary.

How to access the value of a promise?

In the Node REPL, to get a DB connection that was the value of a promise, I took the following approach:

let connection
try {
  (async () => {
    connection = await returnsAPromiseResolvingToConnection()
  })()
} catch(err) {
  console.log(err)
}

The line with await would normally return a promise. This code can be pasted into the Node REPL or if saved in index.js it can be run in Bash with

node -i -e "$(< index.js)"

which leaves you in the Node REPL after running the script with access to the set variable. To confirm that the asynchronous function has returned, you can log connection for example, and then you're ready to use the variable. One of course wouldn't want to count on the asynchronous function being resolved yet for any code in the script outside the asynchronous function.

How to create an Array, ArrayList, Stack and Queue in Java?

Without more details as to what the question is exactly asking, I am going to answer the title of the question,

Create an Array:

String[] myArray = new String[2];
int[] intArray = new int[2];

// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};

Create an ArrayList:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");

ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);

This means, create an ArrayList of String and Integer objects. You cannot use int because thats a primitive data types, see the link for a list of primitive data types.

Create a Stack:

Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);

Create an Queue: (using LinkedList)

Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);

Same thing as an ArrayList, this declaration means create an Queue of String and Integer objects.


Update:

In response to your comment from the other given answer,

i am pretty confused now, why are using string. and what does <String> means

We are using String only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.

I have posted some links to explain the difference between the two, but here are a list of primitive types

  • byte
  • short
  • char
  • int
  • long
  • boolean
  • double
  • float

Which means, you are not allowed to make an ArrayList of integer's like so:

ArrayList<int> numbers = new ArrayList<int>(); 
           ^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
            ^ perfectly valid

Also, you can use your own objects, here is my Monster object I created,

public class Monster {
   String name = null;
   String location = null;
   int age = 0;

public Monster(String name, String loc, int age) { 
   this.name = name;
   this.loc = location;
   this.age = age;
 }

public void printDetails() {
   System.out.println(name + " is from " + location +
                                     " and is " + age + " old.");
 }
} 

Here we have a Monster object, but now in our Main.java class we want to keep a record of all our Monster's that we create, so let's add them to an ArrayList

public class Main {
    ArrayList<Monster> myMonsters = new ArrayList<Monster>();

public Main() {
    Monster yetti = new Monster("Yetti", "The Mountains", 77);
    Monster lochness = new Monster("Lochness Monster", "Scotland", 20);

    myMonsters.add(yetti); // <-- added Yetti to our list
    myMonsters.add(lochness); // <--added Lochness to our list
  
    for (Monster m : myMonsters) {
        m.printDetails();
     }
   }

public static void main(String[] args) {
    new Main();
 }
}

(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)

Read from file in eclipse

you just need to get the absolute-path of the file, since the file you are looking for doesnt exist in the eclipse's runtime workspace you can use - getProperty() or getLocationURI() methods to get the absolute-path of the file

How can I run multiple curl requests processed sequentially?

You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.

What is Model in ModelAndView from Spring MVC?

It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.

So ...

   new ModelAndView(view, name, value);

is equivalent to:

   Map model = ...
   model.put(name, value);
   new ModelAndView(view, model);

Finding square root without using sqrt function?

There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:

#include <math.h>

double sqrt(double x) {
    if (x <= 0)
        return 0;       // if negative number throw an exception?
    int exp = 0;
    x = frexp(x, &exp); // extract binary exponent from x
    if (exp & 1) {      // we want exponent to be even
        exp--;
        x *= 2;
    }
    double y = (1+x)/2; // first approximation
    double z = 0;
    while (y != z) {    // yes, we CAN compare doubles here!
        z = y;
        y = (y + x/y) / 2;
    }
    return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}

Algorithm starts with 1 as first approximation for square root value. Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt(x), it will be the same. If y > sqrt(x), then x/y < sqrt(x) by about the same amount. In other words, it will converge very fast.

UPDATE: To speed up convergence on very large or very small numbers, changed sqrt() function to extract binary exponent and compute square root from number in [1, 4) range. It now needs frexp() from <math.h> to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp().

Getting the current Fragment instance in the viewpager

After reading all comments and answers I am going to explain an optimal solution for this problem. The best option is @rik's solution, so my improvement is base on his.

Instead of having to ask each FragmentClass like

if(FragmentClass1){
   ...
if(FragmentClass2){
   ...
}

Create your own interface, and maker your child fragments implement it, something like

public interface MyChildFragment {
    void updateView(int position);
}

Then, you can do something like this to initiate and update your inner fragments.

Fragment childFragment = (Fragment) mViewPagerDetailsAdapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());

if (childFragment != null) {
   ((MyChildFragment) childFragment).updateView();
}

P.S. Be careful where you put that code, if you call insatiateItem before the system actually create it the savedInstanceState of your child fragment will be null therefor

public void onCreate(@Nullable Bundle savedInstanceState){
      super(savedInstanceState)
}

Will crash your app.

Good luck

Resize jqGrid when browser is resized?

I'm using 960.gs for layout so my solution is as follows:

    $(window).bind(
        'resize',
        function() {
                    //  Grid ids we are using
            $("#demogr, #allergygr, #problemsgr, #diagnosesgr, #medicalhisgr").setGridWidth(
                    $(".grid_5").width());
            $("#clinteamgr, #procedgr").setGridWidth(
                    $(".grid_10").width());
        }).trigger('resize');
// Here we set a global options

jQuery.extend(jQuery.jgrid.defaults, {
    // altRows:true,
    autowidth : true,
    beforeSelectRow : function(rowid, e) { // disable row highlighting onclick
        return false;
    },
    datatype : "jsonstring",
    datastr : grdata,  //  JSON object generated by another function
    gridview : false,
    height : '100%',
    hoverrows : false,
    loadonce : true,
    sortable : false,
    jsonReader : {
        repeatitems : false
    }
});

// Demographics Grid

$("#demogr").jqGrid( {
    caption : "Demographics",
    colNames : [ 'Info', 'Data' ],
    colModel : [ {
        name : 'Info',
        width : "30%",
        sortable : false,
        jsonmap : 'ITEM'
    }, {
        name : 'Description',
        width : "70%",
        sortable : false,
        jsonmap : 'DESCRIPTION'
    } ],
    jsonReader : {
        root : "DEMOGRAPHICS",
        id : "DEMOID"
    }
});

// Other grids defined below...

How to animate RecyclerView items when they appear

Made Simple with XML only

Visit Gist Link

res/anim/layout_animation.xml

<?xml version="1.0" encoding="utf-8"?>
    <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:animation="@anim/item_animation_fall_down"
        android:animationOrder="normal"
        android:delay="15%" />

res/anim/item_animation_fall_down.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500">

    <translate
        android:fromYDelta="-20%"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <scale
        android:fromXScale="105%"
        android:fromYScale="105%"
        android:toXScale="100%"
        android:toYScale="100%"
        android:pivotX="50%"
        android:pivotY="50%"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

</set>

Use in layouts and recylcerview like:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutAnimation="@anim/layout_animation"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

Using ng-click vs bind within link function of Angular Directive

myApp.directive("clickme",function(){
    return function(scope,element,attrs){
        element.bind("mousedown",function(){
             <<call the Controller function>>
              scope.loadEditfrm(attrs.edtbtn); 
        });
    };
});

this will act as onclick events on the attribute clickme

List<Map<String, String>> vs List<? extends Map<String, String>>

You cannot assign expressions with types such as List<NavigableMap<String,String>> to the first.

(If you want to know why you can't assign List<String> to List<Object> see a zillion other questions on SO.)

What does "async: false" do in jQuery.ajax()?

Setting async to false means the instructions following the ajax request will have to wait for the request to complete. Below is one case where one have to set async to false, for the code to work properly.

var phpData = (function get_php_data() {
  var php_data;
  $.ajax({
    url: "http://somesite/v1/api/get_php_data",
    async: false, 
    //very important: else php_data will be returned even before we get Json from the url
    dataType: 'json',
    success: function (json) {
      php_data = json;
    }
  });
  return php_data;
})();

Above example clearly explains the usage of async:false

By setting it to false, we have made sure that once the data is retreived from the url ,only after that return php_data; is called

Python pip install module is not found. How to link python to pip location?

Below steps helped me fix this.

  • upgrade pip version
  • remove the created environment by using command rm -rf env-name
  • create environment using command python3 -m venv env-aide
  • now install the package and check

Elastic Search: how to see the indexed data

A tool that helps me a lot to debug ElasticSearch is ElasticHQ. Basically, it is an HTML file with some JavaScript. No need to install anywhere, let alone in ES itself: just download it, unzip int and open the HTML file with a browser.

Not sure it is the best tool for ES heavy users. Yet, it is really practical to whoever is in a hurry to see the entries.

Executing a batch script on Windows shutdown

You can create a local computer policy on Windows. See the TechNet at http://technet.microsoft.com/en-us/magazine/dd630947

  1. Run gpedit.msc to open the Group Policy Editor,
  2. Navigate to Computer Configuration | Windows Settings | Scripts (Startup/Shutdown).

enter image description here

How to get the excel file name / path in VBA

this is a simple alternative that gives all responses, Fullname, Path, filename.

Dim FilePath, FileOnly, PathOnly As String

FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))

How to deny access to a file in .htaccess

Strong pattern matching — This is the method that I use here at Perishable Press. Using strong pattern matching, this technique prevents external access to any file containing “.hta”, “.HTA”, or any case-insensitive combination thereof. To illustrate, this code will prevent access through any of the following requests:

  • .htaccess
  • .HTACCESS
  • .hTaCcEsS
  • testFILE.htaccess
  • filename.HTACCESS
  • FILEROOT.hTaCcEsS

..etc., etc. Clearly, this method is highly effective at securing your site’s HTAccess files. Further, this technique also includes the fortifying “Satisfy All” directive. Note that this code should be placed in your domain’s root HTAccess file:

# STRONG HTACCESS PROTECTION
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

What is the difference between Left, Right, Outer and Inner Joins?

There are only 4 kinds:

  1. Inner join: The most common type. An output row is produced for every pair of input rows that match on the join conditions.
  2. Left outer join: The same as an inner join, except that if there is any row for which no matching row in the table on the right can be found, a row is output containing the values from the table on the left, with NULL for each value in the table on the right. This means that every row from the table on the left will appear at least once in the output.
  3. Right outer join: The same as a left outer join, except with the roles of the tables reversed.
  4. Full outer join: A combination of left and right outer joins. Every row from both tables will appear in the output at least once.

A "cross join" or "cartesian join" is simply an inner join for which no join conditions have been specified, resulting in all pairs of rows being output.

Thanks to RusselH for pointing out FULL joins, which I'd omitted.

Vim clear last search highlighting

To turn off highlighting until the next search:

:noh

Or turn off highlighting completely:

set nohlsearch

Or, to toggle it:

set hlsearch!

nnoremap <F3> :set hlsearch!<CR>

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

This worked for me. Might want to try editing virtual machine settings:

Click on Edit virtual machine settings

Switch to Always Enabled in Options, Shared Folders

How to remove leading and trailing white spaces from a given html string?

See the String method trim() - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim

var myString = '  bunch    of <br> string data with<p>trailing</p> and leading space   ';
myString = myString.trim();
// or myString = String.trim(myString);

Edit

As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex:

if(!String.prototype.trim) {  
  String.prototype.trim = function () {  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
} 

... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.

How to format string to money

try

amtf =  amtf.Insert(amtf.Length - 2, ".");

php.ini & SMTP= - how do you pass username & password

After working all day on this, I finally found a solution. Here's how I send from Windows XP with WAMP.

  1. Use Google's SMTP server. You probably need an account.
  2. Download and install Fake Sendmail. I just downloaded it, unzipped it and put it in the WAMP folder.
  3. Create a test PHP file. See below.
<?php
    $message = "test message body";
    $result = mail('[email protected]', 'message subject', $message);
    echo "result: $result";
?>
  1. Update your php.ini file and your sendmail.ini file (sendmail.ini is in the sendmail folder).
  2. Check the error.log file in the sendmail folder that you just created if it doesn't work.

Reference:

Create a temporary table in MySQL with an index from a select

Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...

CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;

CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid), 
INDEX(tmpid))  
SELECT * FROM tmpLivecheck;

... solved my problem.

Greetings...

How do I work with a git repository within another repository?

If I understand your problem well you want the following things:

  1. Have your media files stored in one single git repository, which is used by many projects
  2. If you modify a media file in any of the projects in your local machine, it should immediately appear in every other project (so you don't want to commit+push+pull all the time)

Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.

First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?

If you don't need to know that, the solution is easy:

  1. create a repository for the media files and one for each project
  2. create a symbolic link in your projects which point to the locally cloned media repository. You can either create a relative symbolic link (e.g. ../media) and assume that everybody will checkout the project so that the media directory is in the same place, or write the name of the symbolic link into .gitignore, and everybody can decide where he/she puts the media files.

In most of the cases, however, you want to know this versioning information. In this case you have two choices:

  1. Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)

  2. Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.

If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:

  1. Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.

  2. You can add one of your copy of the media repository as a remote repository to all of your projects.

You can add local directories as a remote this way:

cd /my/project2/media
git remote add project1 /my/project1/media

If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:

cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master

You are free to remove these commits later (with git reset) because you haven't shared them with other users.

How do I print the full value of a long string in gdb?

The printf command will print the complete strings:

(gdb) printf "%s\n", string

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.

//on ubuntu server
sudo /etc/init.d/mysql start

To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.

$ sudo initctl stop mysql
$ sudo initctl start mysql

To verify the working, you can check the status of the service and get the process id (pid), simulate a failure by killing the "mysql" process and verify its status as running with new process id after sometime (typically within 1 minute) using the following commands.

$ sudo initctl status mysql         # get pid
$ sudo kill -9 <pid>                # kill mysql process
$ sudo initctl status mysql         # verify status as running after sometime

Note : In latest Ubuntu version now initctl is replaced by systemctl

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

Open IIS Setting in your plesk panel and enter default document name first page of website (deafault values are

 Index.html
Index.htm
Index.cfm
Index.shtml
Index.shtm
Index.stm
Index.php
Index.php3
Index.asp
Index.aspx
Default.htm
Default.asp
Default.aspx) 

This will work properly

Android Min SDK Version vs. Target SDK Version

For those who want a summary,

android:minSdkVersion

is minimum version till your application supports. If your device has lower version of android , app will not install.

while,

android:targetSdkVersion

is the API level till which your app is designed to run. Means, your phone's system don't need to use any compatibility behaviours to maintain forward compatibility because you have tested against till this API.

Your app will still run on Android versions higher than given targetSdkVersion but android compatibility behaviour will kick in.

Freebie -

android:maxSdkVersion

if your device's API version is higher, app will not install. Ie. this is the max API till which you allow your app to install.

ie. for MinSDK -4, maxSDK - 8, targetSDK - 8 My app will work on minimum 1.6 but I also have used features that are supported only in 2.2 which will be visible if it is installed on a 2.2 device. Also, for maxSDK - 8, this app will not install on phones using API > 8.

At the time of writing this answer, Android documentation was not doing a great job at explaining it. Now it is very well explained. Check it here

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

I'm not sure why you're avoiding the AND clause. It is the simplest solution.

Otherwise, you would need to do an INTERSECT of multiple queries:

SELECT word FROM table WHERE word NOT LIKE '%a%'
INTERSECT
SELECT word FROM table WHERE word NOT LIKE '%b%'
INTERSECT
SELECT word FROM table WHERE word NOT LIKE '%c%';

Alternatively, you can use a regular expression if your version of SQL supports it.

Failed to resolve: com.android.support:appcompat-v7:28.0

Run

gradlew -q app:dependencies

It will remove what is wrong.

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Running ASP.Net on a Linux based server

The Mono project is your best option. However, it has a lot of pitfalls (like incomplete API support in some areas), and it's legally gray (people like Richard Stallman have derided the use of Mono because of the possibility of Microsoft coming down on Mono by using its patent rights, but that's another story).

Anyway, Apache supports .NET/Mono through a module, but the last time I checked the version supplied with Debian, it gave Perl language support only; I can't say if it's changed since, perhaps someone else can correct me there.

Create folder with batch but only if it doesn't already exist

if exist C:\VTS\NUL echo "Folder already exists"

if not exist C:\VTS\NUL echo "Folder does not exist"

See also https://support.microsoft.com/en-us/kb/65994

(Update March 7, 2018; Microsoft article is down, archive on https://web.archive.org/web/20150609092521/https://support.microsoft.com/en-us/kb/65994 )

failed to push some refs to [email protected]

Another issue could come from the use of backticks, those are not supported by the compiler (uglifier).

To fix it, replace config.assets.js_compressor = :uglifier with config.assets.js_compressor = Uglifier.new(harmony: true).

credits: https://medium.com/@leog7one/how-to-fix-execjs-runtimeerror-syntaxerror-unexpected-character-on-heroku-push-deployment-c0b105a64655

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

My problem were that we were using spring securyty, and the previous page doesn't call the page using faces-redirect=true, then the page show a java warning, and the control doesn't fire the change event.

Solution: The previous page must call the page using, faces-redirect=true

Create table variable in MySQL

If you don't want to store table in database then @Evan Todd already has been provided temporary table solution.

But if you need that table for other users and want to store in db then you can use below procedure.

Create below ‘stored procedure’:

————————————

DELIMITER $$

USE `test`$$

DROP PROCEDURE IF EXISTS `sp_variable_table`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_variable_table`()
BEGIN

SELECT CONCAT(‘zafar_’,REPLACE(TIME(NOW()),’:',’_')) INTO @tbl;

SET @str=CONCAT(“create table “,@tbl,” (pbirfnum BIGINT(20) NOT NULL DEFAULT ’0', paymentModes TEXT ,paymentmodeDetails TEXT ,shippingCharges TEXT ,shippingDetails TEXT ,hypenedSkuCodes TEXT ,skuCodes TEXT ,itemDetails TEXT ,colorDesc TEXT ,size TEXT ,atmDesc TEXT ,promotional TEXT ,productSeqNumber VARCHAR(16) DEFAULT NULL,entity TEXT ,entityDetails TEXT ,kmtnmt TEXT ,rating BIGINT(1) DEFAULT NULL,discount DECIMAL(15,0) DEFAULT NULL,itemStockDetails VARCHAR(38) NOT NULL DEFAULT ”) ENGINE=INNODB DEFAULT CHARSET=utf8");
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT ‘Table has been created’;
END$$

DELIMITER ;

———————————————–

Now you can execute this procedure to create a variable name table as per below-

call sp_variable_table();

You can check new table after executing below command-

use test;show tables like ‘%zafar%’; — test is here ‘database’ name.

You can also check more details at below path-

http://mydbsolutions.in/how-can-create-a-table-with-variable-name/

Remove characters from C# string

A string is just a character array so use Linq to do the replace (similar to Albin above except uses a linq contains statement to do the replace):

var resultString = new string(
        (from ch in "My name @is ,Wan.;'; Wan"
         where ! @"@,.;\'".Contains(ch)
         select ch).ToArray());

The first string is the string to replace chars in and the second is a simple string containing the chars

Converting from signed char to unsigned char and back again?

Do you realize, that CLAMP255 returns 0 for v < 0 and 255 for v >= 0?
IMHO, CLAMP255 should be defined as:

#define CLAMP255(v) (v > 255 ? 255 : (v < 0 ? 0 : v))

Difference: If v is not greater than 255 and not less than 0: return v instead of 255

How can I return two values from a function in Python?

I think you what you want is a tuple. If you use return (i, card), you can get these two results by:

i, card = select_choice()

How to use mongoimport to import csv

Your example worked for me with MongoDB 1.6.3 and 1.7.3. Example below was for 1.7.3. Are you using an older version of MongoDB?

$ cat > locations.csv
Name,Address,City,State,ZIP
Jane Doe,123 Main St,Whereverville,CA,90210
John Doe,555 Broadway Ave,New York,NY,10010
 ctrl-d
$ mongoimport -d mydb -c things --type csv --file locations.csv --headerline
connected to: 127.0.0.1
imported 3 objects
$ mongo
MongoDB shell version: 1.7.3
connecting to: test
> use mydb
switched to db mydb
> db.things.find()
{ "_id" : ObjectId("4d32a36ed63d057130c08fca"), "Name" : "Jane Doe", "Address" : "123 Main St", "City" : "Whereverville", "State" : "CA", "ZIP" : 90210 }
{ "_id" : ObjectId("4d32a36ed63d057130c08fcb"), "Name" : "John Doe", "Address" : "555 Broadway Ave", "City" : "New York", "State" : "NY", "ZIP" : 10010 }

Function for Factorial in Python

Another way to do it is to use np.prod shown below:

def factorial(n):
    if n == 0:
        return 1
    else:
         return np.prod(np.arange(1,n+1))

Is there a decent wait function in C++?

What you have can be written easier. Instead of:

#include<iostream>
int main()
{
    std::cout<<"Hello, World!\n";
    return 0;
}

write

#include<iostream>
int main()
{
    std::cout<<"Hello, World!\n";
    system("PAUSE");
    return 0;
}

The system function executes anything you give it as if it was written in the command prompt. It suspends execution of your program while the command is executing so you can do anything with it, you can even compile programs from your cpp program.

Where's my invalid character (ORA-00911)

One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .

"Too many values to unpack" Exception

try unpacking in one variable,

python will handle it as a list,

then unpack from the list

def returnATupleWithThreeValues():
    return (1,2,3)
a = returnATupleWithThreeValues() # a is a list (1,2,3)
print a[0] # list[0] = 1
print a[1] # list[1] = 2
print a[2] # list[2] = 3

Nullable DateTime conversion

You can try this

var lastPostDate = reader[3] == DBNull.Value ?
                                default(DateTime?): 
                                Convert.ToDateTime(reader[3]);

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

How do I get the resource id of an image if I know its name?

With something like this:

String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

Tool to generate JSON schema from JSON data

For node.js > 6.0.0 there is also the json-schema-by-example module.

Add border-bottom to table row <tr>

Display the row as a block.

tr {
    display: block;
    border-bottom: 1px solid #000;
}

and to display alternate colors simply:

tr.oddrow {
    display: block;
    border-bottom: 1px solid #F00;
}

How do I copy folder with files to another folder in Unix/Linux?

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder:

cp -r dir1/ ~/Pictures/

Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd.

When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:

man [insert command here]

at a terminal prompt.

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

If anyone is getting this error using Nginx, try adding the following to your server config:

server {
    listen 443 ssl;
    ...
}

The issue stems from Nginx serving an HTTP server to a client expecting HTTPS on whatever port you're listening on. When you specify ssl in the listen directive, you clear this up on the server side.

String comparison in Objective-C

You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:

if ([category isEqualToString:@"Some String"])
{
   // Both strings are equal without respect to their case.
}

Case-insensitive is like this:

if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
   // Both strings are equal with respect to their case.
}

Save modifications in place with awk

Using tee

 awk '{awk code}' file | tee file

the tee command take place and executed after the awk command is finished due to the |.

How to create composite primary key in SQL Server 2008

First create the database and table, manually adding the columns. In which column to be primary key. You should right click this column and set primary key and set the seed value of the primary key.

How do I add comments to package.json for npm install?

I have a funny hack idea.

Create an npm package name suitably as a comment divider for dependencies and devDependencies block in file package.json, for example x----x----x

{
    "name": "app-name",
    "dependencies": {
        "x----x----x": "this is the first line of a comment",
        "babel-cli": "6.x.x",
        "babel-core": "6.x.x",
        "x----x----x": "this is the second line of a comment",
        "knex": "^0.11.1",
        "mocha": "1.20.1",
        "x----x----x": "*"
    }
}

NOTE: You must add the last comment divider line with a valid version, like * in the block.

phpinfo() - is there an easy way for seeing it?

From the CLI the best way is to use grep like:

php -i | grep libxml

Reading/writing an INI file

There is an Ini Parser available in CommonLibrary.NET

This has various very convenient overloads for getting sections/values and is very light weight.

Convert InputStream to JSONObject

Simple Solution:

JsonElement element = new JsonParser().parse(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(element.getAsJsonObject().toString());

How to create a hex dump of file containing only the hex characters without spaces in bash?

It seems to depend on the details of the version of od. On OSX, use this:

od -t x1 -An file |tr -d '\n '

(That's print as type hex bytes, with no address. And whitespace deleted afterwards, of course.)

How to detect when facebook's FB.init is complete

Another way to check if FB has initialized is by using the following code:

ns.FBInitialized = function () {
    return typeof (FB) != 'undefined' && window.fbAsyncInit.hasRun;
};

Thus in your page ready event you could check ns.FBInitialized and defer the event to later phase by using setTimeOut.

Is there a naming convention for MySQL?

Consistency is the key to any naming standard. As long as it's logical and consistent, you're 99% there.

The standard itself is very much personal preference - so if you like your standard, then run with it.

To answer your question outright - no, MySQL doesn't have a preferred naming convention/standard, so rolling your own is fine (and yours seems logical).

socket connect() vs bind()

Too Long; Don't Read: The difference is whether the source (local) or the destination address/port is being set. In short, bind() set the source and connect() set the destination. Regardless of TCP or UDP.

bind()

bind() set the socket's local (source) address. This is the address where packets are received. Packets sent by the socket carry this as the source address, so the other host will know where to send back its packets.

If receive is not needed the socket source address is useless. Protocols like TCP require receiving enabled in order to send properly, as the destination host send back a confirmation when one or more packets have arrived (i.e. acknowledgement).

connect()

  • TCP has a "connected" state. connect() triggers the TCP code to try to establish a connection to the other side.
  • UDP has no "connected" state. connect() only set a default address to where packets are sent when no address is specified. When connect() is not used, sendto() or sendmsg() must be used containing the destination address.

When connect() or a send function is called, and no address is bound, Linux automatically bind the socket to a random port. For technical details, take a look at inet_autobind() in Linux kernel source code.

Side notes

  • listen() is TCP only.
  • In AF_INET family, the socket's source or destination address (struct sockaddr_in) is composed by an IP address (see IP header), and TCP or UDP port (see TCP and UDP header).

Make scrollbars only visible when a Div is hovered over?

This will work:

#div{
     max-height:300px;
     overflow:hidden;
}
#div:hover{
     overflow-y:scroll;
}

PHP Try and Catch for SQL Insert

Checking the documentation shows that its returns false on an error. So use the return status rather than or die(). It will return false if it fails, which you can log (or whatever you want to do) and then continue.

$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
     //handle the error here
}
//page continues loading

How to decrypt hash stored by bcrypt

To answer the original posters question.... to 'decrypt' the password, you have to do what a password cracker would do.

In other words, you'd run a program to read from a large list of potential passwords (a password dictionary) and you'd hash each one using bcrypt and the salt and complexity from the password you're trying to decipher. If you're lucky you'll find a match, but if the password is a strong one then you likely won't find a match.

Bcrypt has the added security characteristic of being a slow hash. If your password had been hashed with md5 (terrible choice) then you'd be able to check billions of passwords per second, but since it's hashed using bcrypt you will be able to check far fewer per second.

The fact that bcrypt is slow to hash and salted is what makes it a good choice for password storage even today. That being said I believe NIST recommends the PBKDF2 for password hashing.

CSS: How can I set image size relative to parent height?

Use max-width property of CSS, like this :

img{
  max-width:100%;
}

Is there a Visual Basic 6 decompiler?

For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.

Removing pip's cache?

If you like to set the --no-cache-dir option by default, you can put this into pip.conf:

[global]
no-cache-dir = false

Note 1: It's confusing, but to enable the no-cache-dir option you actually have to set it to false. Pretty silly if you ask me... but that's how it is. There is a github issue to fix this.

Note 2: The location of pip.conf depends on your OS. See the documentation for more info.