Programs & Examples On #Onexception

A failure occurred while executing com.android.build.gradle.internal.tasks

I already had multidex enabled but the version was too old so upgraded and it fixed the issue:

// Old version
implementation 'com.android.support:multidex:1.0.3'
// New version
def multidex_version = "2.0.1"
implementation 'androidx.multidex:multidex:$multidex_version'

Connection Java-MySql : Public Key Retrieval is not allowed

This solution worked for MacOS Sierra, and running MySQL version 8.0.11. Please make sure driver you have added in your build path - "add external jar" should match up with SQL version.

String url = "jdbc:mysql://localhost:3306/syscharacterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";

Unable to compile simple Java 10 / Java 11 project with Maven

As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0 to specify a release of either 9,10,11 without any explicit dependencies.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>11</release>  <!--or <release>10</release>-->
    </configuration>
</plugin>

Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.


Edit [30.12.2018]

In fact, you can make use of the same version of maven-compiler-plugin while compiling the code against JDK/12 as well.

More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.

error: resource android:attr/fontVariationSettings not found

after upgrading to Android 3.4.2 and FTC SDK5.2. I got these errors when building APK:

Android resource linking failed C:\Users\idsid\FTC\SkyStone\TeamCode\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1205: error: resource android:attr/fontVariationSettings not found. C:\Users\idsid\FTC\SkyStone\TeamCode\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1206: error: resource android:attr/ttcIndex not found. error: failed linking references.

What I did is to add following section to project build gradle and problem is fixed.

subprojects {
    afterEvaluate {project ->
        if (project.hasProperty("android")) {
            android {
                compileSdkVersion 28
                buildToolsVersion '29.0.2'
            }
        }
    }
}

Good luck.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Others have answered so I'll add my 2-cents.

You can either use autoconfiguration (i.e. don't use a @Configuration to create a datasource) or java configuration.

Auto-configuration:

define your datasource type then set the type properties. E.g.

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
spring.datasource.hikari.username=sa
spring.datasource.hikari.password=password
spring.datasource.hikari.max-wait=10000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.leak-detection-threshold=600000
spring.datasource.hikari.maximum-pool-size=100
spring.datasource.hikari.pool-name=MyDataSourcePoolName

Java configuration:

Choose a prefix and define your data source

spring.mysystem.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.mysystem.datasource.jdbc- 
url=jdbc:sqlserver://databaseserver.com:18889;Database=MyDatabase;
spring.mysystem.datasource.username=dsUsername
spring.mysystem.datasource.password=dsPassword
spring.mysystem.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.mysystem.datasource.max-wait=10000
spring.mysystem.datasource.connection-timeout=30000
spring.mysystem.datasource.idle-timeout=600000
spring.mysystem.datasource.max-lifetime=1800000
spring.mysystem.datasource.leak-detection-threshold=600000
spring.mysystem.datasource.maximum-pool-size=100
spring.mysystem.datasource.pool-name=MySystemDatasourcePool

Create your datasource bean:

@Bean(name = { "dataSource", "mysystemDataSource" })
@ConfigurationProperties(prefix = "spring.mysystem.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

You can leave the datasource type out, but then you risk spring guessing what datasource type to use.

Entity Framework Core: A second operation started on this context before a previous operation completed

I managed to get that error by passing an IQueryable into a method that then used that IQueryable 'list' as part of a another query to the same context.

public void FirstMethod()
{
    // This is returning an IQueryable
    var stockItems = _dbContext.StockItems
        .Where(st => st.IsSomething);

    SecondMethod(stockItems);
}

public void SecondMethod(IEnumerable<Stock> stockItems)
{
    var grnTrans = _dbContext.InvoiceLines
        .Where(il => stockItems.Contains(il.StockItem))
        .ToList();
}

To stop that happening I used the approach here and materialised that list before passing it the second method, by changing the call to SecondMethod to be SecondMethod(stockItems.ToList()

Failed linking file resources

Run ./gradlew build -stacktrace in Android Studio terminal. It helps you to find a file that causes this error.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Just solve the problem which come from java compiler instead of Build-Run task

Exception : AAPT2 error: check logs for details

AAPT2 Error solution.

If your Android studio has been updated.

Maybe, you would face an error in the studio like "AAPT 2 error: check the log for details"

This error will occur when you have done something wrong in your .xml file such as incorrect value, content not found, etc.

But, At that time you will not have the error specification there. Because the new version of Android Studio does not give you a specific error. It gives like AAPT2 error.

If you want to know where the actual error is then

Follow step.

  1. Look at the panel which is at the right of your Android studio Check out the "Gradle" tab and click on it.
  2. You will see the "app" option. Click on it.
  3. In the app options you will see [Tasks -> build] click on it.
  4. Then you will get options list and see "assembleDebug" double click on it.
  5. Keep the patience and See build tab at the bottom panel of Android studios, you will get an exact error there what you made a mistake in which file and which position.

Click on assembleDebug and see log you can get the actual error is where

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

this worked for me

// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Http;

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options =>
        {
            options.LoginPath = new PathString("/auth/login");
            options.AccessDeniedPath = new PathString("/auth/denied");
        });

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

In my case removing the pre-existing build folder and retrying solved the problem.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..

<dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.11</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.4</version>
    </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.4</version>

        </dependency>

Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I had a same problem. To solve this problem just open your all files(recent working files) in Which you made the changes and check did you forget to delete some which should be deleted.

In my case the problem was with the Unreferenced code which I was using in one of my file and that code is present in that file which should not be present in that file because I was using an interface which I have deleted from my project but I forget to deleted from one of my file).

Error: the entity type requires a primary key

Removed and added back in the table using Scaffold-DbContext and the error went away

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I solved it by myself.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.7.Final</version>
</dependency>

Consider defining a bean of type 'service' in your configuration [Spring boot]

Consider defining a bean of type 'moviecruser.repository.MovieRepository' in your configuration.

This type of issue will generate if you did not add correct dependency. Its the same issue I faced but after I found my JPA dependency is not working correctly, so make sure that first dependency is correct or not.

For example:-

The dependency I used:

    <dependency>
       <groupId>org.springframework.data</groupId>      
       <artifactId>spring-data-jpa</artifactId>
    </dependency>

Description (got this exception):-

Parameter 0 of constructor in moviecruser.serviceImple.MovieServiceImpl required a bean of type 'moviecruser.repository.MovieRepository' that could not be found.

Action:

After change dependency:-

    <!-- 
    <dependency>
       <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

Response:-

2019-09-06 23:08:23.202 INFO 7780 -
[main]moviecruser.MovieCruserApplication]:Started MovieCruserApplication in 10.585 seconds (JVM running for 11.357)

UnsatisfiedDependencyException: Error creating bean with name

Add @Component annotation just above the component definition

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

If you are sure that the modification in the SQL file has no impact on your existing schema, you can also update the checksum of the existing schema.

I did this following a slight change in the sql file.

Here is how I updated the checksum:

update flyway_schema_history set checksum = '-1934991199' where installed_rank = '1';

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

Public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IEventRepository, EventRepository>();           
}

You forgot to add "services.AddScoped" in startup ConfigureServices method.

docker cannot start on windows

For me the error was resolved by stopping a virtual Ubuntu instance that'd been running in Hyper-V:

The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

Once Ubuntu instance had been stopped, and Docker Desktop had been restarted, my usual docker commands ran just fine.

PS: I had the idea to try this because of an Error Log that Docker Desktop had helpfully compiled and offered to send to Docker Hub as user feedback... the log appeared to indicate that my machine was short on RAM, and Docker was failing for this very simple reason. Killing the Ubuntu instance solved that.

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

Whoever still having the same issue. Please add the following line in application.properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database
## I am using Mysql8 so I have declared MySQL8Dialect if you have other versions just add ## that version number
spring.jpa.properties.hibernate.dialect =  org.hibernate.dialect.MySQL8Dialect

ASP.NET Core Web API exception handling

Firstly, thanks to Andrei as I've based my solution on his example.

I'm including mine as it's a more complete sample and might save readers some time.

The limitation of Andrei's approach is that doesn't handle logging, capturing potentially useful request variables and content negotiation (it will always return JSON no matter what the client has requested - XML / plain text etc).

My approach is to use an ObjectResult which allows us to use the functionality baked into MVC.

This code also prevents caching of the response.

The error response has been decorated in such a way that it can be serialized by the XML serializer.

public class ExceptionHandlerMiddleware
{
    private readonly RequestDelegate next;
    private readonly IActionResultExecutor<ObjectResult> executor;
    private readonly ILogger logger;
    private static readonly ActionDescriptor EmptyActionDescriptor = new ActionDescriptor();

    public ExceptionHandlerMiddleware(RequestDelegate next, IActionResultExecutor<ObjectResult> executor, ILoggerFactory loggerFactory)
    {
        this.next = next;
        this.executor = executor;
        logger = loggerFactory.CreateLogger<ExceptionHandlerMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, $"An unhandled exception has occurred while executing the request. Url: {context.Request.GetDisplayUrl()}. Request Data: " + GetRequestData(context));

            if (context.Response.HasStarted)
            {
                throw;
            }

            var routeData = context.GetRouteData() ?? new RouteData();

            ClearCacheHeaders(context.Response);

            var actionContext = new ActionContext(context, routeData, EmptyActionDescriptor);

            var result = new ObjectResult(new ErrorResponse("Error processing request. Server error."))
            {
                StatusCode = (int) HttpStatusCode.InternalServerError,
            };

            await executor.ExecuteAsync(actionContext, result);
        }
    }

    private static string GetRequestData(HttpContext context)
    {
        var sb = new StringBuilder();

        if (context.Request.HasFormContentType && context.Request.Form.Any())
        {
            sb.Append("Form variables:");
            foreach (var x in context.Request.Form)
            {
                sb.AppendFormat("Key={0}, Value={1}<br/>", x.Key, x.Value);
            }
        }

        sb.AppendLine("Method: " + context.Request.Method);

        return sb.ToString();
    }

    private static void ClearCacheHeaders(HttpResponse response)
    {
        response.Headers[HeaderNames.CacheControl] = "no-cache";
        response.Headers[HeaderNames.Pragma] = "no-cache";
        response.Headers[HeaderNames.Expires] = "-1";
        response.Headers.Remove(HeaderNames.ETag);
    }

    [DataContract(Name= "ErrorResponse")]
    public class ErrorResponse
    {
        [DataMember(Name = "Message")]
        public string Message { get; set; }

        public ErrorResponse(string message)
        {
            Message = message;
        }
    }
}

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Override constructor of DbContext Try this :-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

How to unapply a migration in ASP.NET Core with EF Core

You should delete migration '20160703192724_MyFirstMigration' record from '_EFMigrationsHistory' table.

otherwise this command will remove migration and delete migrations folder:

PMC Command:

   > remove-migration -force

CLI Command:

   > dotnet ef migrations remove -f

Link About CLI Commands

Link About PMC Commands

Spring Resttemplate exception handling

I fixed it by overriding the hasError method from DefaultResponseErrorHandler class:

public class BadRequestSafeRestTemplateErrorHandler extends DefaultResponseErrorHandler
{
    @Override
    protected boolean hasError(HttpStatus statusCode)
    {
        if(statusCode == HttpStatus.BAD_REQUEST)
        {
            return false;
        }
        return statusCode.isError();
    }
}

And you need to set this handler for restemplate bean:

@Bean
    protected RestTemplate restTemplate(RestTemplateBuilder builder)
    {
        return builder.errorHandler(new BadRequestSafeRestTemplateErrorHandler()).build();
    }

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

Duplicate name Classes

like

class BackGroundTask extends AsyncTask<String, Void, Void> {

and

class BackgroundTask extends AsyncTask<String, Void, Void> {

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

The number of method references in a .dex file cannot exceed 64k API 17

When your app references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex support library to your project:

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

Multidex support for Android 5.0 and higher

Android 5.0 (API level 21) and higher uses a runtime called ART which natively supports loading multiple DEX files from APK files. Therefore, if your minSdkVersion is 21 or higher, you do not need the multidex support library.

Avoid the 64K limit

  • Remove unused code with ProGuard - Enable code shrinking

Configure multidex in app for

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file

android {
defaultConfig {
    ...
    minSdkVersion 21 
    targetSdkVersion 28
    multiDexEnabled true
  }
 ...
}

if your minSdkVersion is set to 20 or lower, then you must use the multidex support library

android {
defaultConfig {
    ...
    minSdkVersion 15 
    targetSdkVersion 28
    multiDexEnabled true
   }
   ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.3'
}

Override the Application class, change it to extend MultiDexApplication (if possible) as follows:

public class MyApplication extends MultiDexApplication { ... }

add to the manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="MyApplication" >
        ...
    </application>
</manifest>

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

There was conflict in java version. Resolved after using 1.8 for maven.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

Make sure the name of the class created in the package is something like somethingTest.java Maven only picks the java files ending with Test notation.

I was getting the same error and resolving the names of all my classes by adding 'Test' at the end made it work.

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I got the same error and changing the following

SessionFactory sessionFactory =
    new Configuration().configure().buildSessionFactory();

to this

SessionFactory sessionFactory =
    new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

worked for me.

Could not autowire field:RestTemplate in Spring boot application

It's exactly what the error says. You didn't create any RestTemplate bean, so it can't autowire any. If you need a RestTemplate you'll have to provide one. For example, add the following to TestMicroServiceApplication.java:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Note, in earlier versions of the Spring cloud starter for Eureka, a RestTemplate bean was created for you, but this is no longer true.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

So, mine didn't get resolved by adding the multiDexEnabled flag. It actually was there before getting the error message.

What resolved the error for me was making sure I was using the same version of all play-services libraries. In one library I had 11.8.0 but in the app that consumes the library I was using 11.6.0 and that difference was what caused the error message.

So, instead of changing your libraries to a specific version like previous answers, maybe you wanna check you're using the same version all across since mixing versions is explicitly discouraged by Android Studio by warnings.

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

Route::group(['middleware' => 'web'], function () {
Route::auth();

Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);

Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
    Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
    Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});

configuring project ':app' failed to find Build Tools revision

I had c++ codes in my project but i didn't have NDK installed, installing it solved the problem

How to manage exceptions thrown in filters in Spring?

I come across this issue myself and I performed the steps below to reuse my ExceptionController that is annotated with @ControllerAdvise for Exceptions thrown in a registered Filter.

There are obviously many ways to handle exception but, in my case, I wanted the exception to be handled by my ExceptionController because I am stubborn and also because I don't want to copy/paste the same code (i.e. I have some processing/logging code in ExceptionController). I would like to return the beautiful JSON response just like the rest of the exceptions thrown not from a Filter.

{
  "status": 400,
  "message": "some exception thrown when executing the request"
}

Anyway, I managed to make use of my ExceptionHandler and I had to do a little bit of extra as shown below in steps:

Steps


  1. You have a custom filter that may or may not throw an exception
  2. You have a Spring controller that handles exceptions using @ControllerAdvise i.e. MyExceptionController

Sample code

//sample Filter, to be added in web.xml
public MyFilterThatThrowException implements Filter {
   //Spring Controller annotated with @ControllerAdvise which has handlers
   //for exceptions
   private MyExceptionController myExceptionController; 

   @Override
   public void destroy() {
        // TODO Auto-generated method stub
   }

   @Override
   public void init(FilterConfig arg0) throws ServletException {
       //Manually get an instance of MyExceptionController
       ApplicationContext ctx = WebApplicationContextUtils
                  .getRequiredWebApplicationContext(arg0.getServletContext());

       //MyExceptionHanlder is now accessible because I loaded it manually
       this.myExceptionController = ctx.getBean(MyExceptionController.class); 
   }

   @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        try {
           //code that throws exception
        } catch(Exception ex) {
          //MyObject is whatever the output of the below method
          MyObject errorDTO = myExceptionController.handleMyException(req, ex); 

          //set the response object
          res.setStatus(errorDTO .getStatus());
          res.setContentType("application/json");

          //pass down the actual obj that exception handler normally send
          ObjectMapper mapper = new ObjectMapper();
          PrintWriter out = res.getWriter(); 
          out.print(mapper.writeValueAsString(errorDTO ));
          out.flush();

          return; 
        }

        //proceed normally otherwise
        chain.doFilter(request, response); 
     }
}

And now the sample Spring Controller that handles Exception in normal cases (i.e. exceptions that are not usually thrown in Filter level, the one we want to use for exceptions thrown in a Filter)

//sample SpringController 
@ControllerAdvice
public class ExceptionController extends ResponseEntityExceptionHandler {

    //sample handler
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(SQLException.class)
    public @ResponseBody MyObject handleSQLException(HttpServletRequest request,
            Exception ex){
        ErrorDTO response = new ErrorDTO (400, "some exception thrown when "
                + "executing the request."); 
        return response;
    }
    //other handlers
}

Sharing the solution with those who wish to use ExceptionController for Exceptions thrown in a Filter.

Spring Boot @autowired does not work, classes in different package

By default, in Spring boot applications, component scan is done inside the package where your main class resides. any bean which is outside the package will not the created and thus gives the above mentioned exception.

Solution: you could either move the beans to the main spring boot class(which is not a good approach) or create a seperate configutation file and import it:

@Import({CustomConfigutation1.class, CustomConfiguration2.class})
@SpringBootpplication
public class BirthdayApplication {

public static void main(String [] args) {
    springApplication.run(BirthdayApplication.class, args );
}

}

Add beans to these CustomConfiguration files.

Get JSON Data from URL Using Android?

I feel your frustration.

Android is crazy fragmented, and the the sheer amount of different examples on the web when searching is not helping.

That said, I just completed a sample partly based on mustafasevgi sample, partly built from several other stackoverflow answers, I try to achieve this functionality, in the most simplistic way possible, I feel this is close to the goal.

(Mind you, code should be easy to read and tweak, so it does not fit your json object perfectly, but should be super easy to edit, to fit any scenario)

protected class yourDataTask extends AsyncTask<Void, Void, JSONObject>
{
    @Override
    protected JSONObject doInBackground(Void... params)
    {

        String str="http://your.domain.here/yourSubMethod";
        URLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        try
        {
            URL url = new URL(str);
            urlConn = url.openConnection();
            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuffer.append(line);
            }

            return new JSONObject(stringBuffer.toString());
        }
        catch(Exception ex)
        {
            Log.e("App", "yourDataTask", ex);
            return null;
        }
        finally
        {
            if(bufferedReader != null)
            {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(JSONObject response)
    {
        if(response != null)
        {
            try {
                Log.e("App", "Success: " + response.getString("yourJsonElement") );
            } catch (JSONException ex) {
                Log.e("App", "Failure", ex);
            }
        }
    }
}

This would be the json object it is targeted towards.

{
    "yourJsonElement":"Hi, I'm a string",
    "anotherElement":"Ohh, why didn't you pick me"
}

It is working on my end, hope this is helpful to someone else out there.

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

HttpClient was deprecated in API Level 22 and removed in API Level 23. You have to use URLConnection.

ReflectionException: Class ClassName does not exist - Laravel

For some reason I had to run composer dumpautoload -o. Notice flag -o which mean with optimization. I don't have any idea why it works only with it but give it a try. Perhaps it helps someone.

CORS with spring-boot and angularjs not working

If you want to enable CORS without using filters or without config file just add

@CrossOrigin

to the top of your controller and it work.

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

This answer is not for DevOps/ system admin guys, but for them who are using IDE like eclipse and facing invalid LOC header (bad signature) issue.

You can force update the maven dependencies, as follows:

enter image description here

enter image description here

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

Your debug output indicates that Clean is the first thing that it's trying to run, so I'm guessing it's failing to download any plugins from central.

First off, see if you can download the plugin jar directly in a web browser: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5.jar

If that works then your web browser has connectivity to central but maven doesn't. That suggests to me that your web browser is using a proxy that maven isn't configured to use.

Maven proxy settings are described in depth here. To simplify that a little fill this out (replace the protocol/host/port with the values from your internet settings) and put it in the <settings> tag of your maven settings.xml file:

<proxies>
  <proxy>
    <id>proxy</id>
    <active>true</active>
    <protocol>http</protocol>
    <host>proxy.example.com</host>
    <port>8080</port>
  </proxy>
</proxies>

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

To add to already great and easy solution provided by Przemek315, the same config if you use Kotlin DSL:

tasks.test {
    useJUnitPlatform()
}

How to disable spring security for particular url

When using permitAll it means every authenticated user, however you disabled anonymous access so that won't work.

What you want is to ignore certain URLs for this override the configure method that takes WebSecurity object and ignore the pattern.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup");
}

And remove that line from the HttpSecurity part. This will tell Spring Security to ignore this URL and don't apply any filters to them.

How to get local server host and port in Spring Boot?

To get the port number in your code you can use the following:

@Autowired
Environment environment;

@GetMapping("/test")
String testConnection(){
    return "Your server is up and running at port: "+environment.getProperty("local.server.port");      
}

To understand the Environment property you can go through this Spring boot Environment

How to download a file using a Java REST service and a data stream

Refer this:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

Details at: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

The MySQL dependency should be like the following syntax in the pom.xml file.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

Make sure the syntax, groupId, artifactId, Version has included in the dependancy.

Can't Autowire @Repository annotated interface in Spring Boot

To extend onto above answers, You can actually add more than one package in your EnableJPARepositories tag, so that you won't run into "Object not mapped" error after only specifying the repository package.

@SpringBootApplication
@EnableJpaRepositories(basePackages = {"com.test.model", "com.test.repository"})
public class SpringBootApplication{

}

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Additional to all answers, I think it could have similar problems. My Problem was caused by png.9 files. If this files, have a (in my case) too small stretching area with just a few pixels, the building failed with this error also. I have checked all these answers, but nothing helped. Giving a little bit bigger stretching area, solved the problem. I tested it many times, allways when I use small stretching areas it failed. So I am sure, it will help some poeple to make the stretch area a little bit bigger.

The second problem, but this is just an assumption, is the icon name (maybe only for png.9 files too). For examle, I used an image named folder_icon.9.png , with this one, it allways failed. Renaming it to other_folder_icon.9.png, it worked. So I think some names are used by the android system itself, maybe here is a problem too.

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

I had a similar error and fixed it by following steps: 1. Under Servers project (which gets created itself when you add Apache Tomcat Server in Eclipse), open server.xml 2. Comment out the line

<Context docBase=... />

@Autowired - No qualifying bean of type found for dependency at least 1 bean

@Service: It tells that particular class is a Service to the client. Service class contains mainly business Logic. If you have more Service classes in a package than provide @Qualifier otherwise it should not require @Qualifier.

Case 1:

@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
}

Case2:

@Service
public class EmployeeServiceImpl implements EmployeeService{
}

both cases are working...

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

In my case I had inherited from the IdentityDbContext correctly (with my own custom types and key defined) but had inadvertantly removed the call to the base class's OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder); // I had removed this
    /// Rest of on model creating here.
}

Which then fixed up my missing indexes from the identity classes and I could then generate migrations and enable migrations appropriately.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I know the question asking for Spring boot, but I believe lot of people looking for how to do this in non Spring boot, like me searching almost whole day.

Above Spring 4, there is no need to configure MappingJacksonHttpMessageConverter if you only intend to configure ObjectMapper.

You just need to do:

public class MyObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 4219938065516862637L;

    public MyObjectMapper() {
        super();
        enable(SerializationFeature.INDENT_OUTPUT);
    }       
}

And in your Spring configuration, create this bean:

@Bean 
public MyObjectMapper myObjectMapper() {        
    return new MyObjectMapper();
}

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

Yes even I got the same error. So I did the following changes

-> Check the error in the Problems tab located near the Console tab

-> See where the error persists, Its possible that some jar file may be corrupted or is outdated so, pom isn't activated in the Project.

-> I found one of my jar was outdated version so I updated it by getting the dependencies from maven repository from this link https://mvnrepository.com

So to conclude, do check where the error persist and which jar file is outdated and make changes accordingly

A child container failed during start java.util.concurrent.ExecutionException

You must have packaged the servlet-api.jar along with the other libraries in your war file. You can verify this by opening up your war file and navigating to the WEB-INF/lib folder.

Ideally, you should not provide the servlet-api jar. The container, in your case Tomcat, is responsible for providing it at deploy time to your application. If you try to provide it as well, then issues arise due to version mismatch etc. Best practise is to just avoid packaging it. Remove it from the WEB-INF/lib.

Additional Information

If you are using maven for your packaging, then simply add the provided tag with the dependency and maven will make sure not to package it in the final war file. Something like

<dependency>
    <artifact>..
    <group> ...
    <version> ...
    <scope>provided</scope>
</<dependency>

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Looks like the initial problem is with the auto-config.

If you don't need the datasource, simply remove it from the auto-config process:

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

How to autowire RestTemplate using annotations

If you're using Spring Boot 1.4.0 or later as the basis of your annotation-driven, Spring doesn't provides a single auto-configured RestTemplate bean. From their documentation:

https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/html/boot-features-restclient.html

If you need to call remote REST services from your application, you can use Spring Framework’s RestTemplate class. Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder which can be used to create RestTemplate instances when needed. The auto-configured RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied to RestTemplate instances.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

1 Close Android Studio (AS)

2 Delete the folder in C:\Users.gradle\wrapper\dists\gradle-2.1-all

3 Run AS as admin

4 Sync your project files

Android check null or empty string in Android

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

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

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

New solution:

The node module can't handle : in a password properly. Even url encoded, like it would work normally, it does not work.

Don't use typicalspecial characters from an URL in the password!

Like one of the following: : . ? + %


Original, wrong answer:

The error message clearly complains about using PLAIN, it does not mean the crendentials are wrong, it means you must use encrypted data delivery (TLS) instead of plaintext.

Changing amqp:// in the connection string to amqps:// (note the s) solves this.

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

You mean that want to get status codes?

VolleyError has a member variable type of NetworkResponse and it is public.

You can access error.networkResponse.statusCode for http error code.

I hope it is helpful for you.

Spring Boot, Spring Data JPA with multiple DataSources

There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties.

Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file.

Below is my example to setup two dataSources. First dataSource is setup by @EnableAutoConfiguration which can be assigned only for one configuration, not multiple. And that will generate 'transactionManager' by DataSourceTransactionManager, that looks default transactionManager generated by the annotation. However I have seen the transaction not beginning issue on the thread from scheduled thread pool only for the default DataSourceTransactionManager and also when there are multiple transaction managers. So I create transactionManager manually by JpaTransactionManager also for the first dataSource with assigning 'transactionManager' bean name and default entityManagerFactory. That JpaTransactionManager for first dataSource surely resolves the weird transaction issue on the thread from ScheduledThreadPool.

Update for Spring Boot 1.3.0.RELEASE

I found my previous configuration with @EnableAutoConfiguration for default dataSource has issue on finding entityManagerFactory with Spring Boot 1.3 version. Maybe default entityManagerFactory is not generated by @EnableAutoConfiguration, once after I introduce my own transactionManager. So now I create entityManagerFactory by myself. So I don't need to use @EntityScan. So it looks I'm getting more and more out of the setup by @EnableAutoConfiguration.

Second dataSource is setup without @EnableAutoConfiguration and create 'anotherTransactionManager' by manual way.

Since there are multiple transactionManager extends from PlatformTransactionManager, we should specify which transactionManager to use on each @Transactional annotation

Default Repository Config

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        basePackages = {"com.mysource.repository"})
public class RepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Autowired
    DataSource dataSource;

    @Bean(name = "entityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.model");
        emf.setPersistenceUnitName("default");   // <- giving 'default' as name
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManagerFactory());
        return tm;
    }
}

Another Repository Config

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = {"com.mysource.anothersource.repository"})
public class AnotherRepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Value("${another.datasource.url}")
    private String databaseUrl;

    @Value("${another.datasource.username}")
    private String username;

    @Value("${another.datasource.password}")
    private String password;

    @Value("${another.dataource.driverClassName}")
    private String driverClassName;

    @Value("${another.datasource.hibernate.dialect}")
    private String dialect;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "anotherEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", dialect);

        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource());
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.anothersource.model");   // <- package for entities
        emf.setPersistenceUnitName("anotherPersistenceUnit");
        emf.setJpaProperties(properties);
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }
}

application.properties

# database configuration
spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.continueOnError=true
spring.datasource.initialize=false

# another database configuration
another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
another.datasource.username=username
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect 
another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

Choose proper transactionManager for @Transactional annotation

Service for first datasource

@Service("mainService")
@Transactional("transactionManager")
public class DefaultDataSourceServiceImpl implements DefaultDataSourceService       
{

   //

}

Service for another datasource

@Service("anotherService")
@Transactional("anotherTransactionManager")
public class AnotherDataSourceServiceImpl implements AnotherDataSourceService 
{

   //

}

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

I had the same error because of character '@' in my resources/application.properties. All I did was replacing the '@' for its unicode value: eureka.client.serviceUrl.defaultZone=http://discUser:discPassword\u0040localhost:8082/eureka/ and it worked like charm. I know the '@' is a perfectly valid character in .properties files and the file was in UTF-8 encoding and it makes me question my career till today but it's worth a shot if you delete content of your resource files to see if you can get pass this error.

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

You need to put SongsTableSeeder into file SongsTableSeeder.php in the same directory where you have your DatabaseSeeder.php file.

And you need to run in your console:

composer dump-autoload

to generate new class map and then run:

php artisan db:seed

I've just tested it. It is working without a problem in Laravel 5

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

You seems to be missing implementation for interface UserDao. If you look at the exception closely it says

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency:

The way @Autowired works is that it would automatically look for implementation of a dependency you inject via an interface. In this case since there is no valid implementation of interface UserDao you get the error.Ensure you have a valid implementation for this class and your error should go.

Hope that helps.

Problems using Maven and SSL behind proxy

I had the same problem with SSL and maven. My companies IT policy restricts me to make any changes to the computers configuration, so I copied the entire .m2 from my other computer and pasted it .m2 folder and it worked.

.m2 folder is usually found under c\user\admin

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Spring Boot Remove Whitelabel Error Page

I am using Spring Boot version 2.1.2 and the errorAttributes.getErrorAttributes() signature didn't work for me (in acohen's response). I wanted a JSON type response so I did a little digging and found this method did exactly what I needed.

I got most of my information from this thread as well as this blog post.

First, I created a CustomErrorController that Spring will look for to map any errors to.

package com.example.error;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CustomErrorController implements ErrorController {

    private static final String PATH = "error";

    @Value("${debug}")
    private boolean debug;

    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping(PATH)
    @ResponseBody
    public CustomHttpErrorResponse error(WebRequest request, HttpServletResponse response) {
        return new CustomHttpErrorResponse(response.getStatus(), getErrorAttributes(request));
    }

    public void setErrorAttributes(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    private Map<String, Object> getErrorAttributes(WebRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.putAll(this.errorAttributes.getErrorAttributes(request, this.debug));
        return map;
    }
}

Second, I created a CustomHttpErrorResponse class to return the error as JSON.

package com.example.error;

import java.util.Map;

public class CustomHttpErrorResponse {

    private Integer status;
    private String path;
    private String errorMessage;
    private String timeStamp;
    private String trace;

    public CustomHttpErrorResponse(int status, Map<String, Object> errorAttributes) {
        this.setStatus(status);
        this.setPath((String) errorAttributes.get("path"));
        this.setErrorMessage((String) errorAttributes.get("message"));
        this.setTimeStamp(errorAttributes.get("timestamp").toString());
        this.setTrace((String) errorAttributes.get("trace"));
    }

    // getters and setters
}

Finally, I had to turn off the Whitelabel in the application.properties file.

server.error.whitelabel.enabled=false

This should even work for xml requests/responses. But I haven't tested that. It did exactly what I was looking for since I was creating a RESTful API and only wanted to return JSON.

Why am I getting a "401 Unauthorized" error in Maven?

Also, after you've updated your repository ids, make sure you run clean as release:prepare will pick up where it left off. So you can do:

mvn release:prepare -Dresume=false or

mvn release:clean release:prepare

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

In your application context, change the bean with id from emf to entityManagerFactory:

<bean id="emf"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="org.wahid.cse.entity" />
    <property name="dataSource" ref="dataSource" />

    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>

    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
    </property>

</bean>

To

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="org.wahid.cse.entity" />
    <property name="dataSource" ref="dataSource" />

    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>

    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
    </property>

</bean>

When use getOne and findOne methods Spring Data JPA

I had a similar problem understanding why JpaRespository.getOne(id) does not work and throw an error.

I went and change to JpaRespository.findById(id) which requires you to return an Optional.

This is probably my first comment on StackOverflow.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

If you are using tomcat as your server runtime and you get this error in tests (because tomcat runtime is not available during tests) than it makes make sense to include tomcat el runtime instead of the one from glassfish). This would be:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-el-api</artifactId>
        <version>8.5.14</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jasper-el</artifactId>
        <version>8.5.14</version>
        <scope>test</scope>
    </dependency>

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Right-Click on your project -> Properties -> Deployment Assembly.

On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.

'Project and External Dependencies' will have all the spring related jars deployed along with your application

Make sure that the controller has a parameterless public constructor error

If you have an interface in your controller

public myController(IXInterface Xinstance){}

You must register them to Dependency Injection container.

container.Bind<IXInterface>().To<XClass>().InRequestScope();

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
          .ContinueWith((taskwithresponse) =>
          {
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.

EDIT 2:

There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Make Enable32bit Application to TRUE in the IIS App pool which you are consuming

Spring Boot - Cannot determine embedded database driver class for database type NONE

Delete C:\Users\admin\.IntelliJIdea2018.1\system\compile-server

Spring boot Security Disable security

If you need security as a dependency but don't want Spring Boot to configure it for you, you can use this exclusion:

    @EnableAutoConfiguration(exclude = { 
        org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class 
    })

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

Exception clearly indicates the problem.

CompteDAOHib: No default constructor found

For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib.

How to test Spring Data repositories?

With Spring Boot + Spring Data it has become quite easy:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    MyRepository subject;

    @Test
    public void myTest() throws Exception {
        subject.save(new MyEntity());
    }
}

The solution by @heez brings up the full context, this only bring up what is needed for JPA+Transaction to work. Note that the solution above will bring up a in memory test database given that one can be found on the classpath.

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

I had the same issue and solved by using Java 8 from Oracle instead of Java 10 from Openjdk

How to set up datasource with Spring for HikariCP?

I have recently migrated from C3P0 to HikariCP in a Spring and Hibernate based project and it was not as easy as I had imagined and here I am sharing my findings.

For Spring Boot see my answer here

I have the following setup

  • Spring 4.3.8+
  • Hiberante 4.3.8+
  • Gradle 2.x
  • PostgreSQL 9.5

Some of the below configs are similar to some of the answers above but, there are differences.

Gradle stuff

In order to pull in the right jars, I needed to pull in the following jars

//latest driver because *brettw* see https://github.com/pgjdbc/pgjdbc/pull/849
compile 'org.postgresql:postgresql:42.2.0'
compile('com.zaxxer:HikariCP:2.7.6') {
    //they are pulled in separately elsewhere
    exclude group: 'org.hibernate', module: 'hibernate-core'
}

// Recommended to use HikariCPConnectionProvider by Hibernate in 4.3.6+    
compile('org.hibernate:hibernate-hikaricp:4.3.8.Final') {
        //they are pulled in separately elsewhere, to avoid version conflicts
        exclude group: 'org.hibernate', module: 'hibernate-core'
        exclude group: 'com.zaxxer', module: 'HikariCP'
}

// Needed for HikariCP logging if you use log4j
compile('org.slf4j:slf4j-simple:1.7.25')  
compile('org.slf4j:slf4j-log4j12:1.7.25') {
    //log4j pulled in separately, exclude to avoid version conflict
    exclude group: 'log4j', module: 'log4j'
}

Spring/Hibernate based configs

In order to get Spring & Hibernate to make use of Hikari Connection pool, you need to define the HikariDataSource and feed it into sessionFactory bean as shown below.

<!-- HikariCP Database bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfig" />
</bean>

<!-- HikariConfig config that is fed to above dataSource -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="poolName" value="SpringHikariPool" />
        <property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
        <property name="maximumPoolSize" value="20" />
        <property name="idleTimeout" value="30000" />

        <property name="dataSourceProperties">
            <props>
                <prop key="serverName">localhost</prop>
                <prop key="portNumber">5432</prop>
                <prop key="databaseName">dbname</prop>
                <prop key="user">dbuser</prop>
                <prop key="password">dbpassword</prop>
            </props>
        </property>
</bean>

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
        <!-- Your Hikari dataSource below -->
        <property name="dataSource" ref="dataSource"/>
        <!-- your other configs go here -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</prop>
                <!-- Remaining props goes here -->
            </props>
        </property>
 </bean>

Once the above are setup then, you need to add an entry to your log4j or logback and set the level to DEBUG to see Hikari Connection Pool start up.

Log4j1.2

<!-- Keep additivity=false to avoid duplicate lines -->
<logger additivity="false" name="com.zaxxer.hikari">
    <level value="debug"/>
    <!-- Your appenders goes here -->
</logger>

Logback

Via application.properties in Spring Boot

debug=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG 

Using logback.xml

<logger name="com.zaxxer.hikari" level="DEBUG" additivity="false">
    <appender-ref ref="STDOUT" />
</logger>

With the above you should be all good to go! Obviously you need to customize the HikariCP pool configs in order to get the performance that it promises.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

You need to either add fetch=FetchType.EAGER inside your ManyToMany annotations to automatically pull back child entities:

@ManyToMany(fetch = FetchType.EAGER)

A better option would be to implement a spring transactionManager by adding the following to your spring configuration file:

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven />

You can then add an @Transactional annotation to your authenticate method like so:

@Transactional
public Authentication authenticate(Authentication authentication)

This will then start a db transaction for the duration of the authenticate method allowing any lazy collection to be retrieved from the db as and when you try to use them.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

the solution that solved my problem for this is

goto references->right click Newtonsoft.json--goto properties and check the version

this same version should be in

<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-YourDllVersion" newVersion="YourDllVersion" />
</dependentAssembly>

Laravel update model with unique validation rule for attribute

For anyone using a Form request

In my case i tried all of the following none of them worked:

$this->id, $this->user->id, $this->user.

It was because i could not access the model $id nor the $id directly.

So i got the $id from a query using the same unique field i am trying to validate:

    /**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    $id = YourModel::where('unique_field',$this->request->get('unique_field'))->value('id');
    return [
        'unique_field' => ['rule1','rule2',Rule::unique('yourTable')->ignore($id)],
    ];
}

How to write JUnit test with Spring Autowire?

I've done it with two annotations for test class: @RunWith(SpringRunner.class) and @SpringBootTest. Example:

@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {

    @Autowired
    private ProtocolTransactionService protocolTransactionService;
}

@SpringBootTest loads the whole context, which was OK in my case.

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

The solution at my end was to explicitly add a JoinColumn annotation like this:

@JoinColumn(name="mapping_type_id")

The column name is usually the table name + "_id" if there is an id field. Additionally, keep in mind which field it should be based on the relationship, OneToMany or ManyToOne.

Hope this helps.

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Install Entity Framework in each project (Ex: In Web, In Class Libraries) from NuGet Package Manager orelse Open Tools - Nuget Package Manager - Package Manager Console and use Install-Package EntityFramework to install the Entity Framework.

Don't need to add the below code in every config file. By default it will be added in the project where the database is called through Entity Framework.

<entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework>

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

I also got the same issue and not able to create a jar, and I found that in Windows-->Prefernces-->Java-->installed JREs By default JRE was added to the build path of newly created java project so just changed it to your prefered JDK.

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

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

How to Access Hive via Python?

similar to @python-starter solution. But, commands package is not avilable on python3.x. So Alternative solution is to use subprocess in python3.x

import subprocess

cmd = "hive -S -e 'SELECT * FROM db_name.table_name LIMIT 1;' "

status, output = subprocess.getstatusoutput(cmd)

if status == 0:
   print(output)
else:
   print("error")

Spring MVC Multipart Request with JSON

As documentation says:

Raised when the part of a "multipart/form-data" request identified by its name cannot be found.

This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

I fixed this issue by adding following code in my file.

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

XML configuration -

<listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener 
        </listener-class>
</listener>

Above we can do using Java configuration -

@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}

How to add a RequestContextListener with no-xml configuration?

I am using spring version 5.1.4.RELEASE and no need to add below changes in pom.

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.2.10</version>
</dependency>

How to list AD group membership for AD users using input list?

Everything in one line:

get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof  -join ";"  } } | export-csv membership.csv

All shards failed

first thing first, all shards failed exception is not as dramatic as it sounds, it means shards were failed while serving a request(query or index), and there could be multiple reasons for it like

  1. Shards are actually in non-recoverable state, if your cluster and index state are in Yellow and RED, then it is one of the reason.
  2. Due to some shard recovery happening in background, shards didn't respond.
  3. Due to bad syntax of your query, ES responds in all shards failed.

In order to fix the issue, you need to filter it in one of the above category and based on that appropriate fix is required.

The one mentioned in the question, is clearly in the first bucket as cluster health is RED, means one or more primary shards are missing, and my this SO answer will help you fix RED cluster issue, which will fix the all shards exception in this case.

android studio 0.4.2: Gradle project sync failed error

This is what worked for me with Android Studio 1.0.2:

File -> Settings-> Gradle Set 'Use default Gradle wrapper.'

The other methods didn't seem to work for me.

Why is this error, 'Sequence contains no elements', happening?

If this is the offending line:

db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

Then it's because there is no object in Responses for which the ResponseId == item.ResponseId, and you can't get the First() record if there are no matches.

Try this instead:

var response
  = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();

if (response != null)
{
    // take some alternative action
}
else
    temp.Response = response;

The FirstOrDefault() extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null.

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

The entity type <type> is not part of the model for the current context

I get same problem in Entity Framewrok and I solved it by under steps :

1-Open your Model.edmx 2-change a table place (for do change in cs file) 3-save it

I hope help you

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

Delete the java.exe process in Task Manager and re-execute.It worked for me.

@Autowired - No qualifying bean of type found for dependency

If you are testing your controller. Don't forget to use @WebAppConfiguration on your test class.

Could not resolve placeholder in string value

I´m frequently running into this issue on some custom properties that could not be found using IntelliJ IDEA - likely after changing branches.

What helpes in my case is

File -> Invalidate Caches / Restart

I had the assumption that it is more likely a Gradle caching issue than an IDE issue, but ./gradle clean did not help

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.

Try installing the required verison.

If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.

also remove the lines

 <fork>true</fork>
     <executable>${JAVA_1_7_HOME}/bin/javac</executable>

from the pom.xml

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I got this problem because I uninstalled VS 2012, I don't want to reinstall it back, so I downloaded the AspNetMVC4Setup.exe from Microsoft.com and fixed my problem.

https://www.microsoft.com/en-us/download/details.aspx?id=30683

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had the same problem. java.net.UnknownHostException: Unable to resolve host “”...

I'm running Visual Studio 2019 and Xamarin.

I also switched back to my WiFi but was on a hot spot.

I solved this by clean swiping the emulator. Restore to factory settings. Then re-running visual studio xamarin app which wil redeploy your app again to the fresh emulator.

It worked. I thought I was going to battle for days to solve this. Luckily this post pointed me in the right direction.

I could not understand how it worked perfectly before and then stopped with no code change.

This is my code for reference:

using var response = await httpClient.GetAsync(sb.ToString());
string apiResponse = await response.Content.ReadAsStringAsync();

How can I parse a local JSON file from assets folder into a ListView?

Method to read JSON file from Assets folder and return as a string object.

public static String getAssetJsonData(Context context) {
            String json = null;
            try {
                InputStream is = context.getAssets().open("myJson.json");
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                json = new String(buffer, "UTF-8");
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }

            Log.e("data", json);
            return json;

        }

Now for parsing data in your activity:-

String data = getAssetJsonData(getApplicationContext());
        Type type = new TypeToken<Your Data model>() {
        }.getType();
  <Your Data model> modelObject = new Gson().fromJson(data, type);

Handle spring security authentication exceptions with @ExceptionHandler

Ok, I tried as suggested writing the json myself from the AuthenticationEntryPoint and it works.

Just for testing I changed the AutenticationEntryPoint by removing response.sendError

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
    
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");

    }
}

In this way you can send custom json data along with the 401 unauthorized even if you are using Spring Security AuthenticationEntryPoint.

Obviously you would not build the json as I did for testing purposes but you would serialize some class instance.

In Spring Boot, you should add it to http.authenticationEntryPoint() part of SecurityConfiguration file.

Creating Roles in Asp.net Identity MVC 5

In ASP.NET 5 rc1-final, I did following:

Created ApplicationRoleManager (in similar manner as there is ApplicationUser created by template)

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(
        IRoleStore<IdentityRole> store,
        IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
        ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors,
        ILogger<RoleManager<IdentityRole>> logger,
        IHttpContextAccessor contextAccessor)
        : base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
    {
    }
}

To ConfigureServices in Startup.cs, I added it as RoleManager

services.
    .AddIdentity<ApplicationUser, IdentityRole>()
    .AddRoleManager<ApplicationRoleManager>();

For creating new Roles, call from Configure following:

public static class RoleHelper
{
    private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
    {
        if (!await roleManager.RoleExistsAsync(roleName))
        {
            await roleManager.CreateAsync(new IdentityRole(roleName));
        }
    }
    public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
    {
        // add all roles, that should be in database, here
        await EnsureRoleCreated(roleManager, "Developer");
    }
}

public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
{
     ...
     await roleManager.EnsureRolesCreated();
     ...
}

Now, the rules can be assigned to user

await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");

Or used in Authorize attribute

[Authorize(Roles = "Developer")]
public class DeveloperController : Controller
{
}

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

Your problem is that a running process within STS is using files located in your target directory while you execute a mvn clean command. Maven will be unable to delete these files (since other processes are still accessing them) and thus fail with that error.

Try to stop all processes (tests, servers, applications) from within STS before running Maven console commands. Look out: This behaviour might also appear if STS is cleaning up the projects and thus re-compiles the sources, and not running a process.

Entity framework self referencing loop detected

I'm aware that question is quite old, but it's still popular and I can't see any solution for ASP.net Core.

I case of ASP.net Core, you need to add new JsonOutputFormatter in Startup.cs file:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddMvc(options =>
        {
            options.OutputFormatters.Clear();
            options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            }, ArrayPool<char>.Shared));
        });

        //...
    }

After implementing it, JSON serializer will simply ignore loop references. What it means is: it will return null instead of infinitely loading objects referencing each other.

Without above solution using:

var employees = db.Employees.ToList();

Would load Employees and related to them Departments.

After setting ReferenceLoopHandling to Ignore, Departments will be set to null unless you include it in your query:

var employees = db.Employees.Include(e => e.Department);

Also, keep in mind that it will clear all OutputFormatters, if you don't want that you can try removing this line:

options.OutputFormatters.Clear();

But removing it causes again self referencing loop exception in my case for some reason.

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

What is and how to fix System.TypeInitializationException error?

I experienced the System.TypeInitializationException due to a different error in my .NET framework 4 project's app.config. Thank you to pStan for getting me to look at the app.config. My configSections were properly defined. However, an undefined element within one of the sections caused the exception to be thrown.

Bottom line is that problems in the app.config can generated this very misleading TypeInitializationException.

A more meaningful ConfigurationErrorsException can be generated by the same error in the app.config by waiting to access the config values until you are within a method rather than at the class level of the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections.Specialized;

namespace ConfigTest
{
    class Program
    {
        public static string machinename;
        public static string hostname;
        public static NameValueCollection _AppSettings;

        static void Main(string[] args)
        {
            machinename = System.Net.Dns.GetHostName().ToLower();
            hostname = "abc.com";// System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).HostName.ToLower().Replace(machinename + ".", "");
            _AppSettings = ConfigurationManager.GetSection("domain/" + hostname) as System.Collections.Specialized.NameValueCollection;
        }
    }
}

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

Gradle error: could not execute build using gradle distribution

I had the same issue and i solved it by deleteing gradle-wrapper.jar and gradle-wrapper.properties file of Gradle wrapper then clean rebuild work for me.

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

You have to use the iterator's remove() method, which means no enhanced for loop:

for (final Iterator iterator = myArrayList.iterator(); iterator.hasNext(); ) {
    iterator.next();
    if (someCondition) {
        iterator.remove();
    }
}

Why is pydot unable to find GraphViz's executables in Windows 8?

I am running a Windows 10 machine and had some problems, too. I installed graphviz via msi installer. Adding via System settings did not work for me.

I removed the installation with the msi and used chocolatey, a windows package manager. Removing the installed version is necessary, otherwise chocolatey won't install.

Now it runs fine. I would recommend doing it this way.

Exception of type 'System.OutOfMemoryException' was thrown.

This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command

start -> run -> %temp%

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

I had met a similar problem, after i add a scope property of servlet dependency in pom.xml

 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then it was ok . maybe that will help you.

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

It's a very late answer but I resolved the issue turning off the lazy loading:

db.Configuration.LazyLoadingEnabled = false;

conversion from string to json object android

Remove the slashes:

String json = {"phonetype":"N95","cat":"WP"};

try {

    JSONObject obj = new JSONObject(json);

    Log.d("My App", obj.toString());

} catch (Throwable t) {
    Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.

I use this

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2</version>
</plugin>

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

if you are using XDocument.Load(url); to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException

See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."

Android- create JSON Array and JSON Object

public JSONObject makJsonObject(int id[], String name[], String year[],
            String curriculum[], String birthday[], int numberof_students)
            throws JSONException {
        JSONObject obj = null;
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < numberof_students; i++) {
            obj = new JSONObject();
            try {
                obj.put("id", id[i]);
                obj.put("name", name[i]);
                obj.put("year", year[i]);
                obj.put("curriculum", curriculum[i]);
                obj.put("birthday", birthday[i]);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jsonArray.put(obj);
        }

        JSONObject finalobject = new JSONObject();
        finalobject.put("student", jsonArray);
        return finalobject;
    }

Specified argument was out of the range of valid values. Parameter name: site

I had the same issue with VS2017. Following solved the issue.

  1. Run Command prompt as Administrator.
  2. Write following two commands which will update your registry.

reg add HKLM\Software\WOW6432Node\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f

reg add HKLM\Software\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f

This should solve your problem. Refer to this link for more details.

Gradle: Execution failed for task ':processDebugManifest'

This error might be because of an attribute left empty in the manifest file.

An example:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:logo="@drawable/ic_actionbar"
    android:supportsRtl="true"
    android:fullBackupContent="">
...
</application>

The fullBackupContent is empty in the above example.

When it's changed to android:fullBackupContent="true" it will be fixed.

How to check if a json key exists?

Json has a method called containsKey().

You can use it to check if a certain key is contained in the Json set.

File jsonInputFile = new File("jsonFile.json"); 
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();

if frameObj.containsKey("person") {
      //Do stuff
}

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

JDBC API mostly consists of interfaces which work independently of any database. A database specific driver is required for each database which implements the JDBC API.

First download the MySQL connector jar from www.mysql.com, then:

Right Click the project -- > build path -- > configure build path

In the libraries tab press Add External Jar and select your jar.

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.

Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.

How to store JSON object in SQLite database

https://github.com/requery/sqlite-android allows you to query JSON fields (and arrays in them, I've tried it and am using it). Before that I was just storing JSON strings into a TEXT column. It supports FTS3, FTS4, & JSON1

As of July 2019, it still gets version bumps every now and then, so it isn't a dead project.

SQL Error: 0, SQLState: 08S01 Communications link failure

I'm answering on specific to this error code(08s01).

usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".

1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.

2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days

3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.

android.os.NetworkOnMainThreadException with android 4.2

Use StrictMode Something like this:-

   if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 
        }

Junit test case for database insert method with DAO and web service

This is one sample dao test using junit in spring project.

import java.util.List;

import junit.framework.Assert;

import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
    @Autowired
    private MemberDao memberDao;

    @Test
    public void testFindById()
    {
        Member member = memberDao.findById(0l);

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("[email protected]", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testFindByEmail()
    {
        Member member = memberDao.findByEmail("[email protected]");

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("[email protected]", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testRegister()
    {
        Member member = new Member();
        member.setEmail("[email protected]");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");

        memberDao.register(member);
        Long id = member.getId();
        Assert.assertNotNull(id);

        Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
        Member newMember = memberDao.findById(id);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("[email protected]", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }

    @Test
    public void testFindAllOrderedByName()
    {
        Member member = new Member();
        member.setEmail("[email protected]");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");
        memberDao.register(member);

        List<Member> members = memberDao.findAllOrderedByName();
        Assert.assertEquals(2, members.size());
        Member newMember = members.get(0);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("[email protected]", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }
}

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Jackson serialization: ignore empty values (or null)

Or you can use GSON [https://code.google.com/p/google-gson/], where these null fields will be automatically removed.

SampleDTO.java

public class SampleDTO {

    String username;
    String email;
    String password;
    String birthday;
    String coinsPackage;
    String coins;
    String transactionId;
    boolean isLoggedIn;

    // getters/setters
}

Test.java

import com.google.gson.Gson;

public class Test {

    public static void main(String[] args) {
        SampleDTO objSampleDTO = new SampleDTO();
        Gson objGson = new Gson();
        System.out.println(objGson.toJson(objSampleDTO));
    }
}

OUTPUT:

{"isLoggedIn":false}

I used gson-2.2.4

DbEntityValidationException - How can I easily tell what caused the error?

I think "The actual validation errors" may contain sensitive information, and this could be the reason why Microsoft chose to put them in another place (properties). The solution marked here is practical, but it should be taken with caution.

I would prefer to create an extension method. More reasons to this:

  • Keep original stack trace
  • Follow open/closed principle (ie.: I can use different messages for different kind of logs)
  • In production environments there could be other places (ie.: other dbcontext) where a DbEntityValidationException could be thrown.

Getting java.net.SocketTimeoutException: Connection timed out in android

I got this same error as I mistakenly changed the order of the statements

OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .connectTimeout(20, TimeUnit.SECONDS).readTimeout(20,TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS) .build();

After changing the order of writeTimeout and readTimeout, the error resolved. The final code I used is given below:

OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .build();

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Update 3 (11/3/2014)
Google finally released official description.


Update 2 (10/31/2014)
Gradle plugin v0.14.0 for Android adds support for multi-dex. To enable, you just have to declare it in build.gradle:

android {
   defaultConfig {
      ...
      multiDexEnabled  true
   }
}

If your application supports Android prior to 5.0 (that is, if your minSdkVersion is 20 or below) you also have to dynamically patch the application ClassLoader, so it will be able to load classes from secondary dexes. Fortunately, there's a library that does that for you. Add it to your app's dependencies:

dependencies {
  ...
  compile 'com.android.support:multidex:1.0.0'
} 

You need to call the ClassLoader patch code as soon as possible. MultiDexApplication class's documentation suggests three ways to do that (pick one of them, one that's most convenient for you):

1 - Declare MultiDexApplication class as the application in your AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

2 - Have your Application class extend MultiDexApplication class:

public class MyApplication extends MultiDexApplication { .. }

3 - Call MultiDex#install from your Application#attachBaseContext method:

public class MyApplication {
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
        ....
    }
    ....
}

Update 1 (10/17/2014):
As anticipated, multidex support is shipped in revision 21 of Android Support Library. You can find the android-support-multidex.jar in /sdk/extras/android/support/multidex/library/libs folder.


Multi-dex support solves this problem. dx 1.8 already allows generating several dex files.
Android L will support multi-dex natively, and next revision of support library is going to cover older releases back to API 4.

It was stated in this Android Developers Backstage podcast episode by Anwar Ghuloum. I've posted a transcript (and general multi-dex explanation) of the relevant part.

How to access nested elements of json object using getJSONArray method

I would also try it this way

1) Create the Java Beans from the JSON schema

2) Use JSON parser libraries to avoid any sort of exception

3) Cast the parse result to the Java object that was created from the initial JSON schema.

Below is an example JSON Schema"

{
  "USD" : {"15m" : 478.68, "last" : 478.68, "buy" : 478.55, "sell" : 478.68,  "symbol" : "$"},
  "JPY" : {"15m" : 51033.99, "last" : 51033.99, "buy" : 51020.13, "sell" : 51033.99,  "symbol" : "¥"},
}

Code

public class Container { 

    private JPY JPY;

    private USD USD;

    public JPY getJPY ()
    {
        return JPY;
    }

    public void setJPY (JPY JPY)
    {
        this.JPY = JPY;
    }

    public USD getUSD ()
    {
        return USD;
    }

    public void setUSD (USD USD)
    {
        this.USD = USD;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [JPY = "+JPY+", USD = "+USD+"]";
    }
}


public class JPY
{    
    @SerializedName("15m")
    private double  fifitenM;

    private String symbol;

    private double last;

    private double sell;

    private double buy;

    public double getFifitenM ()
    {
        return fifitenM;
    }

    public void setFifitenM (double fifitenM)
    {
        this.fifitenM = fifitenM;
    }

    public String getSymbol ()
    {
        return symbol;
    }

    public void setSymbol (String symbol)
    {
        this.symbol = symbol;
    }

    public double getLast ()
    {
        return last;
    }

    public void setLast (double last)
    {
        this.last = last;
    }

    public double getSell ()
    {
        return sell;
    }

    public void setSell (double sell)
    {
        this.sell = sell;
    }

    public double getBuy ()
    {
        return buy;
    }

    public void setBuy (double buy)
    {
        this.buy = buy;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
    }
}


public class USD
{
    @SerializedName("15m")
    private double fifitenM;

    private String symbol;

    private double last;

    private double sell;

    private double buy;

    public double getFifitenM ()
    {
        return fifitenM;
    }

    public void setFifitenM (double fifitenM)
    {
        this.fifitenM = fifitenM;
    }

    public String getSymbol ()
    {
        return symbol;
    }

    public void setSymbol (String symbol)
    {
        this.symbol = symbol;
    }

    public double getLast ()
    {
        return last;
    }

    public void setLast (double last)
    {
        this.last = last;
    }

    public double getSell ()
    {
        return sell;
    }

    public void setSell (double sell)
    {
        this.sell = sell;
    }

    public double getBuy ()
    {
        return buy;
    }

    public void setBuy (double buy)
    {
        this.buy = buy;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
    }
}


public class MainMethd
{
    public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {
        // TODO Auto-generated method stub
        JsonParser parser = new JsonParser();
        Object obj = parser.parse(new FileReader("C:\\Users\\Documents\\file.json"));
        String res = obj.toString();
        Gson gson = new Gson();
        Container container = new Container();
        container = gson.fromJson(res, Container.class);
        System.out.println(container.getUSD());
        System.out.println("Sell Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getSell());
        System.out.println("Buy Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getBuy());
    }

}

Output from the main method is:

ClassPojo [15m = 478.68, symbol = $, last = 478.68, sell = 478.68, buy = 478.55]

Sell Price : $478.68

Buy Price : $478.55

Hope this helps.

jackson deserialization json to java-objects

You have to change the line

product userFromJSON = mapper.readValue(userDataJSON, product.class);

to

product[] userFromJSON = mapper.readValue(userDataJSON, product[].class);

since you are deserializing an array (btw: you should start your class names with upper case letters as mentioned earlier). Additionally you have to create setter methods for your fields or mark them as public in order to make this work.

Edit: You can also go with Steven Schlansker's suggestion and use

List<product> userFromJSON =
        mapper.readValue(userDataJSON, new TypeReference<List<product>>() {});

instead if you want to avoid arrays.

Post form data using HttpWebRequest

Use this code:

internal void SomeFunction() {
    Dictionary<string, string> formField = new Dictionary<string, string>();
    
    formField.Add("Name", "Henry");
    formField.Add("Age", "21");
    
    string body = GetBodyStringFromDictionary(formField);
    // output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
    string body = string.Empty;
    foreach (var pair in formField)
    {
        body += $"{pair.Key}={pair.Value}&";   
    }

    // delete last "&"
    body = body.Substring(0, body.Length - 1);

    return body;
}

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

In my case, I was getting this error despite registering an existing instance for the interface in question.

Turned out, it was because I was using Unity in WebForms by way of the Unity.WebForms Nuget package, and I had specified a Hierarchical Lifetime manager for the dependency I was providing an instance for, yet a Transient lifetime manager for a subsequent type that depended on the previous type - not usually an issue - but with Unity.WebForms, the lifetime managers work a little differently... your injected types seem to require a Hierarchical lifetime manager, but a new container is still created for every web request (because of the architecture of web forms I guess) as explained excellently in this post.

Anyway, I resolved it by simply not specifying a lifetime manager for the types/instances when registering them.

i.e.

container.RegisterInstance<IMapper>(MappingConfig.GetMapper(), new HierarchicalLifetimeManager());    
container.RegisterType<IUserContext, UserContext>(new TransientLifetimeManager());

becomes

container.RegisterInstance<IMapper>(MappingConfig.GetMapper());
container.RegisterType<IUserContext, UserContext>();

So that IMapper can be resolved successfully here:

public class UserContext : BaseContext, IUserContext
{
    public UserContext(IMapper _mapper) : base(_mapper)
    {

    }
    ...
}

Convert JSON String to Pretty Print JSON output using Jackson

I think, this is the simplest technique to beautify the json data,

String indented = (new JSONObject(Response)).toString(4);

where Response is a String.

Simply pass the 4(indentSpaces) in toString() method.

Note: It works fine in the android without any library. But in java you have to use the org.json library.

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Here is what I did

private void myEvent_Handler(object sender, SomeEvent e)
{
  // I dont know how many times this event will fire
  Task t = new Task(() =>
  {
    if (something == true) 
    {
        DoSomething(e);  
    }
  });
  t.RunSynchronously();
}

working great and not blocking UI thread

Autowiring fails: Not an managed Type

When you extend indirectly JpaRepository ( KassaRepository extends BaseRepository that extends JpaRepository) then you have to annotate BaseRepository with @NoRepositoryBean :

@NoRepositoryBean
public interface BaseRepository<T extends ModelBase> extends JpaRepository<T, Long> {
    T findById(long id);
}

How to change already compiled .class file without decompile?

You can follow these steps to modify your java class:

  1. Decompile the .class file as you have done and save it as .java
  2. Create a project in Eclipse with that java file, the original JAR as library, and all its dependencies
  3. Change the .java and compile
  4. Get the modified .class file and put it again inside the original JAR.

Specify the date format in XMLGregorianCalendar

This is an easy way for any format. Just change it to required format string

XMLGregorianCalendar gregFmt = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
System.out.println(gregFmt);

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>}

Entity Framework Provider type could not be loaded?

I had the same issue with Instantiating DBContext object from a unit test project. I checked my unit test project packages and I figured that EntityFramework package was not installed, I installed that from Nuget and problem solved (I think it's EF bug).

happy coding

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

How to make custom error pages work in ASP.NET MVC 4

You can get errors working correctly without hacking global.cs, messing with HandleErrorAttribute, doing Response.TrySkipIisCustomErrors, hooking up Application_Error, or whatever:

In system.web (just the usual, on/off)

<customErrors mode="On">
  <error redirect="/error/401" statusCode="401" />
  <error redirect="/error/500" statusCode="500" />
</customErrors>

and in system.webServer

<httpErrors existingResponse="PassThrough" />

Now things should behave as expected, and you can use your ErrorController to display whatever you need.

Annotation-specified bean name conflicts with existing, non-compatible bean def

I also had a similar problem. I built the project again and the issue was resolved.

The reason is, there are already defined sequences for the Annotation-specified bean names, in a file. When we do a change on that bean name and try to run the application Spring cannot identify which one to pick. That is why it shows this error.

In my case, I removed the previous bean class from the project and added the same bean name to a new bean class. So Spring has the previous definition for the removed bean class in a file and that conflicts with the newly added class while compiling. So if you do a 'build clean', previous definitions for bean classes will be removed and compilation will success.

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

Just adding this answer to help Google save some punter the hours I have spent to get here. I used ILMerge on my .Net 4.0 project, without the /targetplatform option set, assuming it would be detected correctly from my main assembly. I then had complaints from users only on Windows XP aka WinXP. This now makes sense as XP will never have > .Net 4.0 installed whereas most newer OSes will. So if your XP users are having issues, see the fixes above.

Unable instantiate android.gms.maps.MapFragment

In IntelliJ IDEA (updated for IntelliJ 12):

  1. Create a file ~/android-sdk/extras/google/google_play_services/libproject/google-play-services_lib/src/dummy.java containing class dummy {}.
  2. File->Import Module-> ~/android-sdk/extras/google/google_play_services/libproject/google-play-services_lib
  3. Create Module from Existing Sources
  4. Next->Next->Next->Next->Finish
  5. File->Project Structure->Modules->YourApp
  6. +->Module Dependency->Google-play-services_lib (The + button is in the top right corner of the dialog.)
  7. +->Jars or directories->~/android-sdk/extras/google/google_play_services/libproject/google-play-services_lib/libs/google-play-services.jar
  8. Use the up/down arrows to move <Module source> to the bottom of the list.

You can delete dummy.java if you like.

Edit: After using this for a while I've found that there is a small flaw/bug. IDEA will sometimes complain about not being able to open a .iml project file in the google-play-services_lib directory, despite the fact that you never told it there was a project there. If that happens, rebuilding the project solves the problem, at least until it comes back.

JSON.Net Self referencing loop detected

The JsonSerializer instance can be configured to ignore reference loops. Like in the following, this function allows to save a file with the content of the json serialized object:

    public static void SaveJson<T>(this T obj, string FileName)
    {
   
       JsonSerializer serializer = new JsonSerializer();
        serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        using (StreamWriter sw = new StreamWriter(FileName))
        {
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;
                serializer.Serialize(writer, obj);
            }
        }
    }

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

Update the Maven project:

Steps:

  1. Right-click on "project"
  2. Go to "Maven" >> "Update"
  3. Wait for all the changes to be applied
  4. Commit the changes (if code is on repo)
  5. Run

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Here was my scenario.

I had a multi project solution containing projects A, B, C .. N.

Project B was a code library that contained a factory for selectlist objects.

The project would run as expected in development, but when publishing to our test environment I was getting the error you were encountering:

Could not load file or assembly 'Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

What had happened was through nuget package manager, I had accidentally installed "Microsoft ASP.NET MVC" which installed dependencies for:

  • Microsoft.AspNet.Razor
  • Microsoft.AspNet.WebPages

Low and behold, Microsoft.AspNet.WebPages depends on "Microsoft.Web.Infrastructure".

My solution was uninstalling the three packages mentioned above (MVC, Razor, WebPages) then right click references > add reference > Assemblies > Extensions > System.Web.MVC.

List<String> to ArrayList<String> conversion issue

Tried and tested approach.

public static ArrayList<String> listToArrayList(List<Object> myList) {
        ArrayList<String> arl = new ArrayList<String>();
        for (Object object : myList) {
            arl.add((String) object);
        }
        return arl;

    }

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

I faced the same issue. Setting relative path of the parent in module projects solved the issue.

Use <relativePath>../Parent Project Name/pom.xml</relativePath>

Spring REST Service: how to configure to remove null objects in json response

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
public class Shop {
    //...
}

for jackson 2.0 or later use @JsonInclude(Include.NON_NULL)

This will remove both empty and null Objects.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

I have a files only website. Added MVC 5 to webforms application (targeting net45). I had to modify the packages.config

package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45"

to

package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" developmentDependency="true"

in order for it to startup on local box in debug mode (previously had the top described error). Running VS 2017 on Windows 7...opened through File > Open > Web Site > File (chose root directory outside of IIS).

how to show progress bar(circle) in an activity having a listview before loading the listview with data

I used this one for list view loading may helpful.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp" >

<LinearLayout
    android:id="@+id/progressbar_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <ProgressBar
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:text="Loading data..." />
    </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#C0C0C0" />
</LinearLayout>

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="1dip"
    android:visibility="gone" />

</RelativeLayout>

and my MainActivity class is,

public class MainActivity extends Activity {
ListView listView;
LinearLayout layout;
List<String> stringValues;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listView);
    layout = (LinearLayout) findViewById(R.id.progressbar_view);

    stringValues = new ArrayList<String>();

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, stringValues);

    listView.setAdapter(adapter);
    new Task().execute();
}

class Task extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected void onPreExecute() {
        layout.setVisibility(View.VISIBLE);
        listView.setVisibility(View.GONE);
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        layout.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);
        adapter.notifyDataSetChanged();
        super.onPostExecute(result);
    }

    @Override
    protected Boolean doInBackground(String... params) {
        stringValues.add("String 1");
        stringValues.add("String 2");
        stringValues.add("String 3");
        stringValues.add("String 4");
        stringValues.add("String 5");

        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

this activity display progress for 3sec then it will display listview, instead of adding data statically to stringValues list you can get data from server in doInBackground() and display it.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

I was getting the same issue.

I just installed the m2e (Maven2Eclipse)plugin from below site:

http://www.eclipse.org/m2e/

Eclipse>Help>Install New Software>Available Software Sites>Add

Name: m2e (any name is OK)
Location:m2e - http://download.eclipse.org/technology/m2e/releases/

Under Install Window> Work with:

Select this new location and Add all the plugins that appear. Eclipse restart and it was running properly with no previous errors.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

Windows -> Preferences -> Server -> Runtime Environment -> Delete all Apache servers available. Add the same. Now run your application on server. Its done :)

LDAP Authentication using Java

Following Code authenticates from LDAP using pure Java JNDI. The Principle is:-

  1. First Lookup the user using a admin or DN user.
  2. The user object needs to be passed to LDAP again with the user credential
  3. No Exception means - Authenticated Successfully. Else Authentication Failed.

Code Snippet

public static boolean authenticateJndi(String username, String password) throws Exception{
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
    props.put(Context.SECURITY_PRINCIPAL, "uid=adminuser,ou=special users,o=xx.com");//adminuser - User with special priviledge, dn user
    props.put(Context.SECURITY_CREDENTIALS, "adminpassword");//dn user password


    InitialDirContext context = new InitialDirContext(props);

    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<javax.naming.directory.SearchResult> answers = context.search("o=xx.com", "(uid=" + username + ")", ctrls);
    javax.naming.directory.SearchResult result = answers.nextElement();

    String user = result.getNameInNamespace();

    try {
        props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
        props.put(Context.SECURITY_PRINCIPAL, user);
        props.put(Context.SECURITY_CREDENTIALS, password);

   context = new InitialDirContext(props);
    } catch (Exception e) {
        return false;
    }
    return true;
}

The module was expected to contain an assembly manifest

Check if the manifest is a valid xml file. I had the same problem by doing a DOS copy command at the end of the build, and it turns out that for some reason I can not understand "copy" was adding a strange character (->) at the end of the manifest files. The problem was solved by adding "/b" switch to force binary copy.

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

If the radiobutton-checked event occurs before the content of the window is loaded fully, i.e. the ellipse is loaded fully, such an exception will be thrown. So check if the UI of the window is loaded (probably by Window_ContentRendered event, etc.).

Add JsonArray to JsonObject

I'm starting to learn about this myself, being very new to android development and I found this video very helpful.

https://www.youtube.com/watch?v=qcotbMLjlA4

It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.

Code from the video for JSONArray to JSONObject:

JSONArray queryArray = quoteJSONObject.names();

ArrayList<String> list = new ArrayList<String>();

for(int i = 0; i < queryArray.length(); i++){
    list.add(queryArray.getString(i));
}

for(String item : list){
    Log.v("JSON ARRAY ITEMS ", item);
}

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

First, if you develop an application with Java EE 6 within a server (JBoss), you should better use a DataSource. Then you can obtain the Connection from this DataSource. It's better to use connections pools.

Then, as of JBoss AS 7, the JDBC driver must be declared as a module. This is described here.

With OJDBC 6 (11.x), the name of the driver should be "oracle.jdbc.OracleDriver". This is the name registered in SPI mode (see the content of this file : META-INF/services/java.sql.Driver).
Since Java 6 and JDBC 4.0, the JDBC Drivers are auto-registered.

Finally you will have to declare a DataSource within JBoss : DataSource configuration.

References :

  • Establishing a Connection (link) (JDBC 4.0 <=> Java 6)
  • JDBC 4.0 Enhancements in Java SE 6 > Auto-Loading of JDBC Driver (link)

Could not autowire field in spring. why?

In spring servlet .xml :

<context:component-scan base-package="net.controller" />

(I assumed that the service impl is in the same package as the service interface "net.service")

I think you have to add the package net.service (or all of net) to the component scan. Currently spring only searches in net.controller for components and as your service impl is in net.service, it will not be instantiated by spring.

Credentials for the SQL Server Agent service are invalid

I had a VM that was server 2012 and I had to change the nic to VMXNET 3. It wasn't connecting to the domain fast enough for the services to start I guess.

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

I agree with bizl

[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }

also if you need to apply this included class to an object item you can do like that

[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
    get
    {
        return this.itemsField;
    }
    set
    {
        this.itemsField = value;
    }
}

Parsing JSON string in Java

Here is the example of one Object, For your case you have to use JSONArray.

public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";  
try{  
   JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");  
   String empname=emp.getString("name");  
   int empsalary=emp.getInt("salary");  

   String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;  
   textView1.setText(str);  

}catch (Exception e) {e.printStackTrace();}  
   //Do when JSON has problem.
}

I don't have time but tried to give an idea. If you still can't do it, then I will help.

Handling 'Sequence has no elements' Exception

You are using linq's First() method, which as per the documentation throws an InvalidOperationException if you are calling it on an empty collection.

If you expect the result of your query to be empty sometimes, you likely want to use FirstOrDefault(), which will return null if the collection is empty, instead of throwing an exception.

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

You need to provide a candidate for autowire. That means that an instance of PasswordHint must be known to spring in a way that it can guess that it must reference it.

Please provide the class head of PasswordHint and/or the spring bean definition of that class for further assistance.

Try changing the name of

PasswordHintAction action;

to

PasswordHintAction passwordHintAction;

so that it matches the bean definition.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

I found out that declaring @PersistenceContext as EXTENDED also solves this problem:

@PersistenceContext(type = PersistenceContextType.EXTENDED)

gson throws MalformedJsonException

In the debugger you don't need to add back slashes, the input field understands the special chars.

In java code you need to escape the special chars

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

This exception only happens if you are parsing an empty String/empty byte array.

below is a snippet on how to reproduce it:

String xml = ""; // <-- deliberately an empty string.
ByteArrayInputStream xmlStream = new java.io.ByteArrayInputStream(xml.getBytes());
Unmarshaller u = JAXBContext.newInstance(...)
u.setSchema(...);
u.unmarshal( xmlStream ); // <-- here it will fail

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

how do I find out what is referencing System.Web.WebPages.Razor v2.0.0.0?

Just read your exception stacktrace:

Calling assembly : Microsoft.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

So it seems that you are using the Microsoft.Web.Helpers which in turn depends on System.Web.WebPages.Razor, Version=2.0.0.0.

Hibernate error: ids for this class must be manually assigned before calling save():

Resolved this problem using a Sequence ID defined in Oracle database.

ORACLE_DB_SEQ_ID is defined as a sequence for the table. Also look at the console to see the Hibernate SQL that is used to verify.

@Id
@Column(name = "MY_ID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence")
@SequenceGenerator(name = "id_Sequence", sequenceName = "ORACLE_DB_SEQ_ID")
Long myId;

Multi-Column Join in Hibernate/JPA Annotations

If this doesn't work I'm out of ideas. This way you get the 4 columns in both tables (as Bar owns them and Foo uses them to reference Bar) and the generated IDs in both entities. The set of 4 columns has to be unique in Bar so the many-to-one relation doesn't become a many-to-many.

@Embeddable
public class AnEmbeddedObject
{
    @Column(name = "column_1")
    private Long column1;
    @Column(name = "column_2")
    private Long column2;
    @Column(name = "column_3")
    private Long column3;
    @Column(name = "column_4")
    private Long column4;
}

@Entity
public class Foo
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "FOO_ID_SEQ", allocationSize = 1)
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "column_1", referencedColumnName = "column_1"),
        @JoinColumn(name = "column_2", referencedColumnName = "column_2"),
        @JoinColumn(name = "column_3", referencedColumnName = "column_3"),
        @JoinColumn(name = "column_4", referencedColumnName = "column_4")
    })
    private Bar bar;
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {
    "column_1",
    "column_2",
    "column_3",
    "column_4"
}))
public class Bar
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "BAR_ID_SEQ", allocationSize = 1)
    private Long id;
    @Embedded
    private AnEmbeddedObject anEmbeddedObject;
}

I can't understand why this JAXB IllegalAnnotationException is thrown

In my case, I was able to find the problem by temporarily catching the exception, descending into causes as needed (based on how deep the IllegalAnnotationException was), and calling getErrors() on it.

    try {
        // in my case, this was what gave me an exception
        endpoint.publish("/MyWebServicePort");
    // I got a WebServiceException caused by another exception, which was caused by the IllegalAnnotationsException
    } catch (WebServiceException e) {
        // Incidentally, I need to call getCause().getCause() on it, and cast to IllegalAnnotationsException before calling getErrors()
        System.err.println(((com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException)e.getCause().getCause()).getErrors());
    }

Operation is not valid due to the current state of the object, when I select a dropdown list

I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.

java.lang.ClassNotFoundException: HttpServletRequest

I did not have a servlet-api.jar in the application's WEB-INF/lib directory (or any other jar there). The problem was that in WEB-INF/web.xml I had this...

    ...
    <servlet>
      <servlet-name>MyServlet</servlet-name>
      <servlet-class>com.bizooka.net.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>MyServlet</servlet-name>
      <url-pattern>/MyServlet</url-pattern>
    </servlet-mapping>
    ...

...according to a tutorial. Removing that still allowed the servlet to function, and did not get the error.

Autowiring two beans implementing same interface - how to set default bean to autowire?

What about @Primary?

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.

@Primary
public class HibernateDeviceDao implements DeviceDao

Or if you want your Jdbc version to be used by default:

<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">

@Primary is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.

Do fragments really need an empty constructor?

Here is my simple solution:

1 - Define your fragment

public class MyFragment extends Fragment {

    private String parameter;

    public MyFragment() {
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    } 
}

2 - Create your new fragment and populate the parameter

    myfragment = new MyFragment();
    myfragment.setParameter("here the value of my parameter");

3 - Enjoy it!

Obviously you can change the type and the number of parameters. Quick and easy.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:

Producer:

@Service
public void FooServiceImpl implements FooService{}

Consumer:

@Autowired
private FooService fooService;

or

@Autowired
private void setFooService(FooService fooService) {}

but not ok if you use it by name:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");

It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined In this case, assigning name to @Service("fooService") would make it work.

Update index after sorting data-frame

Since pandas 1.0.0 df.sort_values has a new parameter ignore_index which does exactly what you need:

In [1]: df2 = df.sort_values(by=['x','y'],ignore_index=True)

In [2]: df2
Out[2]:
   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

Ripple effect on Android Lollipop CardView

If the app minSdkVersion which you are working is level 9, you can use:

android:foreground="?selectableItemBackground"
android:clickable="true"

Instead, starting from level 11, you use:

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

From documentation:

clickable - Defines whether this view reacts to click events. Must be a boolean value, either "true" or "false".

foreground - Defines the drawable to draw over the content. This can be used as an overlay. The foreground drawable participates in the padding of the content if the gravity is set to fill.

Can I safely delete contents of Xcode Derived data folder?

I would say it's safe--I often delete the contents of the folder for many kind of iOS projects, this way. And, I haven't had any issues with builds or submitting to the App Store. The procedure deletes derived data and cleans a project's cached assets, for both Xcode 5 and 6.

Sometimes, simply calling rm -rf on the Derived Data directory leaves a lingering file or two, but my script loops until all files are deleted.

Concatenate two slices in Go

I think it's important to point out and to know that if the destination slice (the slice you append to) has sufficient capacity, the append will happen "in-place", by reslicing the destination (reslicing to increase its length in order to be able to accommodate the appendable elements).

This means that if the destination was created by slicing a bigger array or slice which has additional elements beyond the length of the resulting slice, they may get overwritten.

To demonstrate, see this example:

a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)

x, y := a[:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))

x = append(x, y...)
fmt.Printf("x: %v\n", x)

fmt.Printf("a: %v\n", a)

Output (try it on the Go Playground):

a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 10
x: [1 2 3 4]
a: [1 2 3 4 0 0 0 0 0 0]

We created a "backing" array a with length 10. Then we create the x destination slice by slicing this a array, y slice is created using the composite literal []int{3, 4}. Now when we append y to x, the result is the expected [1 2 3 4], but what may be surprising is that the backing array a also changed, because capacity of x is 10 which is sufficient to append y to it, so x is resliced which will also use the same a backing array, and append() will copy elements of y into there.

If you want to avoid this, you may use a full slice expression which has the form

a[low : high : max]

which constructs a slice and also controls the resulting slice's capacity by setting it to max - low.

See the modified example (the only difference is that we create x like this: x = a[:2:2]:

a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)

x, y := a[:2:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))

x = append(x, y...)
fmt.Printf("x: %v\n", x)

fmt.Printf("a: %v\n", a)

Output (try it on the Go Playground)

a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 2
x: [1 2 3 4]
a: [1 2 0 0 0 0 0 0 0 0]

As you can see, we get the same x result but the backing array a did not change, because capacity of x was "only" 2 (thanks to the full slice expression a[:2:2]). So to do the append, a new backing array is allocated that can store the elements of both x and y, which is distinct from a.

What are the differences between a program and an application?

When I studied IT in college my prof. made it simple for me:

"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same. The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."

Got it right on the exam.

So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.

Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :(

Insert using LEFT JOIN and INNER JOIN

you can't use VALUES clause when inserting data using another SELECT query. see INSERT SYNTAX

INSERT INTO user
(
 id, name, username, email, opted_in
)
(
    SELECT id, name, username, email, opted_in
    FROM user
         LEFT JOIN user_permission AS userPerm
            ON user.id = userPerm.user_id
);

How do C++ class members get initialized if I don't do it explicitly?

In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions.

For objects, their default constructor is called. For example, for std::string, the default constructor sets it to an empty string. If the object's class does not have a default constructor, it will be a compile error if you do not explicitly initialize it.

For primitive types (pointers, ints, etc), they are not initialized -- they contain whatever arbitrary junk happened to be at that memory location previously.

For references (e.g. std::string&), it is illegal not to initialize them, and your compiler will complain and refuse to compile such code. References must always be initialized.

So, in your specific case, if they are not explicitly initialized:

    int *ptr;  // Contains junk
    string name;  // Empty string
    string *pname;  // Contains junk
    string &rname;  // Compile error
    const string &crname;  // Compile error
    int age;  // Contains junk

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

Since the Beta, Razor uses a different config section for globally defining namespace imports. In your Views\Web.config file you should add the following:

<configSections>
  <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  </sectionGroup>
</configSections>

<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <!-- Your namespace here -->
    </namespaces>
  </pages>
</system.web.webPages.razor>

Use the MVC 3 upgrade tool to automatically ensure you have the right config values.

Note that you might need to close and reopen the file for the changes to be picked up by the editor.

Regex to validate date format dd/mm/yyyy

Please Following Expression

Regex regex = new Regex(@"(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$");

TypeError: Cannot read property 'then' of undefined

You need to return your promise to the calling function.

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
    });
    return $checkSessionServer; // <-- return your promise to the calling function
}

Android - SMS Broadcast receiver

android.provider.Telephony.SMS_RECEIVED has a capital T, and yours in the manifest does not.

Please bear in mind that this Intent action is not documented.

How do you test a public/private DSA keypair?

Just use puttygen and load your private key into it. It offers different options, e.g. exporting the corresponding public key.

Autocompletion in Vim

Use Ctrl-N to get a list of word suggestions while in insert mode. Type :help i_CTRL-N to see Vim's documentation on this functionality.

Here is an example of importing the Python dictionary into Vim.

Twitter bootstrap hide element on small devices

Bootstrap 4

The display (hidden/visible) classes are changed in Bootstrap 4. To hide on the xs viewport use:

d-none d-sm-block

Also see: Missing visible-** and hidden-** in Bootstrap v4


Bootstrap 3 (original answer)

Use the hidden-xs utility class..

<nav class="col-sm-3 hidden-xs">
        <ul class="list-unstyled">
        <li>Text 10</li>
        <li>Text 11</li>
        <li>Text 12</li>
        </ul>
</nav>

http://bootply.com/90722

How can I shrink the drawable on a button?

Here the function which I created for scaling vector drawables. I used it for setting TextView compound drawable.

/**
 * Used to load vector drawable and set it's size to intrinsic values
 *
 * @param context Reference to {@link Context}
 * @param resId   Vector image resource id
 * @param tint    If not 0 - colour resource to tint the drawable with.
 * @param newWidth If not 0 then set the drawable's width to this value and scale 
 *                 height accordingly.
 * @return On success a reference to a vector drawable
 */
@Nullable
public static Drawable getVectorDrawable(@NonNull Context context,
                                         @DrawableRes int resId,
                                         @ColorRes int tint,
                                         float newWidth)
{
    VectorDrawableCompat drawableCompat =
            VectorDrawableCompat.create(context.getResources(), resId, context.getTheme());
    if (drawableCompat != null)
    {
        if (tint != 0)
        {
            drawableCompat.setTint(ResourcesCompat.getColor(context.getResources(), tint, context.getTheme()));
        }

        drawableCompat.setBounds(0, 0, drawableCompat.getIntrinsicWidth(), drawableCompat.getIntrinsicHeight());

        if (newWidth != 0.0)
        {
            float scale = newWidth / drawableCompat.getIntrinsicWidth();
            float height = scale * drawableCompat.getIntrinsicHeight();
            ScaleDrawable scaledDrawable = new ScaleDrawable(drawableCompat, Gravity.CENTER, 1.0f, 1.0f);
            scaledDrawable.setBounds(0,0, (int) newWidth, (int) height);
            scaledDrawable.setLevel(10000);
            return scaledDrawable;
        }
    }
    return drawableCompat;
}

What's the function like sum() but for multiplication? product()?

Update:

In Python 3.8, the prod function was added to the math module. See: math.prod().

Older info: Python 3.7 and prior

The function you're looking for would be called prod() or product() but Python doesn't have that function. So, you need to write your own (which is easy).

Pronouncement on prod()

Yes, that's right. Guido rejected the idea for a built-in prod() function because he thought it was rarely needed.

Alternative with reduce()

As you suggested, it is not hard to make your own using reduce() and operator.mul():

from functools import reduce  # Required in Python 3
import operator
def prod(iterable):
    return reduce(operator.mul, iterable, 1)

>>> prod(range(1, 5))
24

Note, in Python 3, the reduce() function was moved to the functools module.

Specific case: Factorials

As a side note, the primary motivating use case for prod() is to compute factorials. We already have support for that in the math module:

>>> import math

>>> math.factorial(10)
3628800

Alternative with logarithms

If your data consists of floats, you can compute a product using sum() with exponents and logarithms:

>>> from math import log, exp

>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993

>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998

Note, the use of log() requires that all the inputs are positive.

Html.Textbox VS Html.TextboxFor

IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view.

You can do the same things with both, but you should use typed views and TextboxFor when possible.

How to find good looking font color if background color is known?

This is an interesting question, but I don't think this is actually possible. Whether or not two colors "fit" as background and foreground colors is dependent upon display technology and physiological characteristics of human vision, but most importantly on upon personal tastes shaped by experience. A quick run through MySpace shows pretty clearly that not all human beings perceive colors in the same way. I don't think this is a problem that can be solved algorithmically, although there may be a huge database somewhere of acceptable matching colors.

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

If you really want to insert this record, remove the `abuse_id` field and the corresponding value from the INSERTstatement :

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Same issue here, comparing the htdocs/xampp folder in 5.6.11 with 5.6.8 I saw all the files there are missing in 5.6.11. Copied the entire htdocs/xampp folder from 5.6.8 to 5.6.11 and worked fine.

How to get domain root url in Laravel 4?

My hint:

  1. FIND IF EXISTS in .env:

    APP_URL=http://yourhost.dev

  2. REPLACE TO (OR ADD)

    APP_DOMAIN=yourhost.dev

  3. FIND in config/app.php:

    'url' => env('APP_URL'),

  4. REPLACE TO

    'domain' => env('APP_DOMAIN'),

    'url' => 'http://' . env('APP_DOMAIN'),

  5. USE:

    Config::get('app.domain'); // yourhost.dev

    Config::get('app.url') // http://yourhost.dev

  6. Do your magic!

How to validate an email address in JavaScript

If you are using AngularJS, just add type="email" to the input element:

https://docs.angularjs.org/api/ng/input/input%5Bemail%5D

In case there is no input element, it can be created dynamically:

var isEmail = $compile('<input ng-model="m" type="email">')($rootScope.$new()).
    controller('ngModel').$validators["email"];

if (isEmail('[email protected]')) {
  console.log('valid');
} 

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

Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).

Steps for open SDF Files:

  1. Click Add Connection

  2. Select Build data context automatically and Default (LINQ to SQL), then Next.

  3. Under Provider choose SQL CE 4.0.

  4. Under Database with Attach database file selected, choose Browse to select your .sdf file.

  5. Click OK.

Can you explain the HttpURLConnection connection process?

On which point does HTTPURLConnection try to establish a connection to the given URL?

On the port named in the URL if any, otherwise 80 for HTTP and 443 for HTTPS. I believe this is documented.

On which point can I know that I was able to successfully establish a connection?

When you call getInputStream() or getOutputStream() or getResponseCode() without getting an exception.

Are establishing a connection and sending the actual request done in one step/method call? What method is it?

No and none.

Can you explain the function of getOutputStream() and getInputStream() in layman's term?

Either of them first connects if necessary, then returns the required stream.

I notice that when the server I'm trying to connect to is down, I get an Exception at getOutputStream(). Does it mean that HTTPURLConnection will only start to establish a connection when I invoke getOutputStream()? How about the getInputStream()? Since I'm only able to get the response at getInputStream(), then does it mean that I didn't send any request at getOutputStream() yet but simply establishes a connection? Do HttpURLConnection go back to the server to request for response when I invoke getInputStream()?

See above.

Am I correct to say that openConnection() simply creates a new connection object but does not establish any connection yet?

Yes.

How can I measure the read overhead and connect overhead?

Connect: take the time getInputStream() or getOutputStream() takes to return, whichever you call first. Read: time from starting first read to getting the EOS.

How to pass prepareForSegue: an object

My solution is similar.

// In destination class: 
var AddressString:String = String()

// In segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if (segue.identifier == "seguetobiddetailpagefromleadbidder")
    {
        let secondViewController = segue.destinationViewController as! BidDetailPage
        secondViewController.AddressString = pr.address as String
    }
}

Find the number of columns in a table

Well I tried Nathan Koop's answer and it didn't work for me. I changed it to the following and it did work:

SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_name'

It also didn't work if I put USE 'database_name' nor WHERE table_catalog = 'database_name' AND table_name' = 'table_name'. I actually will be happy to know why.

Format JavaScript date as yyyy-mm-dd

Yet another combination of the answers. Nicely readable, but a little lengthy.

function getCurrentDayTimestamp() {
  const d = new Date();

  return new Date(
    Date.UTC(
      d.getFullYear(),
      d.getMonth(),
      d.getDate(),
      d.getHours(),
      d.getMinutes(),
      d.getSeconds()
    )
  // `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
  // and we want the first part ("2017-08-22")
  ).toISOString().slice(0, 10);
}

Comparing strings in C# with OR in an if statement

try

if (testString.Equals(testString2)){
}

How do I pass variables and data from PHP to JavaScript?

Use:

<?php
    $your_php_variable= 22;
    echo "<script type='text/javascript'>var your_javascript_variable = $your_php_variable;</script>";
?>

and that will work. It's just assigning a JavaScript variable and then passing the value of an existing PHP variable. Since PHP writes the JavaScript lines here, it has the value of of the PHP variable and can pass it directly.

Button inside of anchor link works in Firefox but not in Internet Explorer?

If you're using a framework like Twitter bootstrap you could simply add class "btn" to an a tag -- I just had a user call in about this problem apparently my checkout button wasn't working because I had a button inside an a tag... instead I just added the btn class to it and it works perfectly now.. Big mistake, one that probably cost customers -- and I sometimes forget to code check everything works in IE..

E.g. <a href="link.com" class="btn" >Checkout</a>

How can I make a menubar fixed on the top while scrolling

This should get you started

 <div class="menuBar">
        <img class="logo" src="logo.jpg"/>
        <div class="nav"> 
            <ul>
                <li>Menu1</li>
                <li>Menu 2</li>
                <li>Menu 3</li>
            </ul> 
        </div>
    </div>



body{
    margin-top:50px;}
.menuBar{
    width:100%;
    height:50px;
    display:block;
    position:absolute;
    top:0;
    left:0;
    }
.logo{
    float:left;
    }
.nav{
    float:right;
    margin-right:10px;}
.nav ul li{
    list-style:none;
    float:left;
    }

How to do a LIKE query with linq?

String [] obj = (from c in db.Contacts
                           where c.FirstName.StartsWith(prefixText)
                           select c.FirstName).ToArray();
            return obj;

StartsWith() and EndsWith() can help you a lot here. If you want to find data in between the field, then Contains() can be used.

XAMPP - MySQL shutdown unexpectedly

Step 1 : Close Xampp controller completely
Step 2 : Open C:\xampp\mysql\backup
Step 3 : Copy all the files from backup folder
Step 4 : Open C:\xampp\mysql\data
Step 5 : Paste the all the files in data folder
Step 6 : Re-start the Xampp controller

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

what happens when you type in a URL in browser

Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Calculate median in c#

Is there a function in the .net Math library?

No.

It's not hard to write your own though. The naive algorithm sorts the array and picks the middle (or the average of the two middle) elements. However, this algorithm is O(n log n) while its possible to solve this problem in O(n) time. You want to look at selection algorithms to get such an algorithm.

Mysql service is missing

I have done it by the following way

  1. Start cmd
  2. Go to the "C:\Program Files\MySQL\MySQL Server 5.6\bin"
  3. type mysqld --install

Like the following image. See for more information.

enter image description here

Xcode "Device Locked" When iPhone is unlocked

I had to re-add device to xcode.

In XCode open Devices and Simulators (CMD+Shift+2), in left list press + button and re-add the same device.

YouTube: How to present embed video with sound muted

Updated

Add &mute=1 to the end of your url.

Your new code would be:

_x000D_
_x000D_
<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?rel=0&amp;autoplay=1&mute=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
_x000D_
_x000D_
_x000D_

How to find the serial port number on Mac OS X?

While entering the serial port name into the code in arduino IDE, enter the whole port address i.e:

/dev/cu.usbmodem*

or

/dev/cu.UG-*

where the * is the port number.

And for the port number in case of mac just open terminal and type

ls /dev/*

and then search for the port that u have set in arduino IDE.

Half circle with CSS (border, outline only)

Below is a minimal code to achieve the effect.

This also works responsively since the border-radius is in percentage.

_x000D_
_x000D_
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
_x000D_
_x000D_

How can I disable an <option> in a <select> based on its value in JavaScript?

You can also use this function,

function optionDisable(selectId, optionIndices)
{
    for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
    {
        document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
        document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
        document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
    }
}

`IF` statement with 3 possible answers each based on 3 different ranges

This is what I did:

Very simply put:

=IF(C7>100,"Profit",IF(C7=100,"Quota Met","Loss"))

The first IF Statement, if true will input Profit, and if false will lead on to the next IF statement and so forth :)

I only have basic formula knowledge but it's working so I will accept I am right!

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

Escaping a forward slash in a regular expression

What context/language? Some languages use / as the pattern delimiter, so yes, you need to escape it, depending on which language/context. You escape it by putting a backward slash in front of it: \/ For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the / has is it may be the designated pattern delimiter.

Call javascript from MVC controller action

Yes, it is definitely possible using Javascript Result:

return JavaScript("Callback()");

Javascript should be referenced by your view:

function Callback(){
    // do something where you can call an action method in controller to pass some data via AJAX() request
}

How to remove unused imports from Eclipse

Use ALT + CTRL + O. It will organize all the imports. You can find various other options in the "Code" Menu.

EDIT: Sorry it is CTRL + SHIFT + O

Shell script variable not empty (-z option)

Why would you use -z? To test if a string is non-empty, you typically use -n:

if test -n "$errorstatus"; then
  echo errorstatus is not empty
fi

How do I compare version numbers in Python?

The way that setuptools does it, it uses the pkg_resources.parse_version function. It should be PEP440 compliant.

Example:

#! /usr/bin/python
# -*- coding: utf-8 -*-
"""Example comparing two PEP440 formatted versions
"""
import pkg_resources

VERSION_A = pkg_resources.parse_version("1.0.1-beta.1")
VERSION_B = pkg_resources.parse_version("v2.67-rc")
VERSION_C = pkg_resources.parse_version("2.67rc")
VERSION_D = pkg_resources.parse_version("2.67rc1")
VERSION_E = pkg_resources.parse_version("1.0.0")

print(VERSION_A)
print(VERSION_B)
print(VERSION_C)
print(VERSION_D)

print(VERSION_A==VERSION_B) #FALSE
print(VERSION_B==VERSION_C) #TRUE
print(VERSION_C==VERSION_D) #FALSE
print(VERSION_A==VERSION_E) #FALSE

How to change bower's default components folder?

Something worth mentioning...

As noted above by other contributors, using a .bowerrc file with the JSON

{ "directory": "some/path" }

is necessary -- HOWEVER, you may run into an issue on Windows while creating that file. If Windows gives you a message imploring you to add a "file name", simply use a text editor / IDE such as Notepad++.

Add the JSON to an unnamed file, save it as .bowerrc -- you're good to go!

Probably an easy assumption, but I hope this save others the unnecessary headache :)

How can I format date by locale in Java?

SimpleDateFormat has a constructor which takes the locale, have you tried that?

http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Something like new SimpleDateFormat("your-pattern-here", Locale.getDefault());

Working with dictionaries/lists in R

I'll just comment you can get a lot of mileage out of table when trying to "fake" a dictionary also, e.g.

> x <- c("a","a","b","b","b","c")
> (t <- table(x))
x
a b c 
2 3 1 
> names(t)
[1] "a" "b" "c"
> o <- order(as.numeric(t))
> names(t[o])
[1] "c" "a" "b"

etc.

How to do a newline in output

Actually you don't even need the block:

  Dir.chdir 'C:/Users/name/Music'
  music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
  puts 'what would you like to call the playlist?'
  playlist_name = gets.chomp + '.m3u'

  File.open(playlist_name, 'w').puts(music)

Git branching: master vs. origin/master vs. remotes/origin/master

Technically there aren't actually any "remote" things at all1 in your Git repo, there are just local names that should correspond to the names on another, different repo. The ones named origin/whatever will initially match up with those on the repo you cloned-from:

git clone ssh://some.where.out.there/some/path/to/repo # or git://some.where...

makes a local copy of the other repo. Along the way it notes all the branches that were there, and the commits those refer-to, and sticks those into your local repo under the names refs/remotes/origin/.

Depending on how long you go before you git fetch or equivalent to update "my copy of what's some.where.out.there", they may change their branches around, create new ones, and delete some. When you do your git fetch (or git pull which is really fetch plus merge), your repo will make copies of their new work and change all the refs/remotes/origin/<name> entries as needed. It's that moment of fetching that makes everything match up (well, that, and the initial clone, and some cases of pushing too—basically whenever Git gets a chance to check—but see caveat below).

Git normally has you refer to your own refs/heads/<name> as just <name>, and the remote ones as origin/<name>, and it all just works because it's obvious which one is which. It's sometimes possible to create your own branch names that make it not obvious, but don't worry about that until it happens. :-) Just give Git the shortest name that makes it obvious, and it will go from there: origin/master is "where master was over there last time I checked", and master is "where master is over here based on what I have been doing". Run git fetch to update Git on "where master is over there" as needed.


Caveat: in versions of Git older than 1.8.4, git fetch has some modes that don't update "where master is over there" (more precisely, modes that don't update any remote-tracking branches). Running git fetch origin, or git fetch --all, or even just git fetch, does update. Running git fetch origin master doesn't. Unfortunately, this "doesn't update" mode is triggered by ordinary git pull. (This is mainly just a minor annoyance and is fixed in Git 1.8.4 and later.)


1Well, there is one thing that is called a "remote". But that's also local! The name origin is the thing Git calls "a remote". It's basically just a short name for the URL you used when you did the clone. It's also where the origin in origin/master comes from. The name origin/master is called a remote-tracking branch, which sometimes gets shortened to "remote branch", especially in older or more informal documentation.

Allow user to select camera or gallery for image

As per David Manpearl answer
https://stackoverflow.com/a/12347567/7226732

we just need to modify onActivityResult() like

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == YOUR_SELECT_PICTURE_REQUEST_CODE) {
            final boolean isCamera;
            if (data.getExtras() == null) {
                isCamera = true;
            } else {
                final String action = data.getAction();
                if (action == null) {
                    isCamera = false;
                } else {
                    isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                }
            }
            Uri selectedImageUri;
            if (isCamera) {
                selectedImageUri = fileUri;
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
                    Toast.makeText(CreateWaterType.this, "Image Saved!", Toast.LENGTH_SHORT).show();
                    image_view.setImageBitmap(bitmap);

                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(CreateWaterType.this, "Failed!", Toast.LENGTH_SHORT).show();
                }

            } else {
                selectedImageUri = data == null ? null : data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);

                    Toast.makeText(CreateWaterType.this, "Image Saved!", Toast.LENGTH_SHORT).show();
                    image_view.setImageBitmap(bitmap);

                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(CreateWaterType.this, "Failed!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}

and set the capture or pick images in image view.

How to change row color in datagridview?

Works on Visual Studio 2010. (I tried it and it works!) It will paint your entire row.

  1. Create a button for the datagridview.
  2. Create a CellClick event and put the next line of code inside of it.

if (dataGridView3.Columns[e.ColumnIndex].Index.Equals(0)    
{
    dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Beige;
}

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

Paused in debugger in chrome?

At the right upper corner second last icon (encircled red in attached image) is for activate/deactivate debugging. Click it to toggle debugging anytime.

Chrome Debug console

Detect when an HTML5 video finishes

Here is a full example, I hope it helps =).

<!DOCTYPE html> 
<html> 
<body> 

<video id="myVideo" controls="controls">
  <source src="your_video_file.mp4" type="video/mp4">
  <source src="your_video_file.mp4" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script type='text/javascript'>
    document.getElementById('myVideo').addEventListener('ended',myHandler,false);
    function myHandler(e) {
        if(!e) { e = window.event; }
        alert("Video Finished");
    }
</script>
</body> 
</html>

limit text length in php and provide 'Read more' link

This is what I use:

// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {

    // truncate string
    $stringCut = substr($string, 0, 500);
    $endPoint = strrpos($stringCut, ' ');

    //if the string doesn't contain any space then it will cut without word basis.
    $string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
    $string .= '... <a href="/this/story">Read More</a>';
}
echo $string;

You can tweak it further but it gets the job done in production.

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse

var  jsonArrayString = @"
[
  {
    ""country"": ""India"",
    ""city"": ""Mall Road, Gurgaon"",
  },
  {
    ""country"": ""India"",
    ""city"": ""Mall Road, Kanpur"",
  }
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

Get key from a HashMap using the value

The put method in HashMap is defined like this:

Object  put(Object key, Object value) 

key is the first parameter, so in your put, "one" is the key. You can't easily look up by value in a HashMap, if you really want to do that, it would be a linear search done by calling entrySet(), like this:

for (Map.Entry<Object, Object> e : hashmap.entrySet()) {
    Object key = e.getKey();
    Object value = e.getValue();
}

However, that's O(n) and kind of defeats the purpose of using a HashMap unless you only need to do it rarely. If you really want to be able to look up by key or value frequently, core Java doesn't have anything for you, but something like BiMap from the Google Collections is what you want.

If else on WHERE clause

Here is a sample query for a table having a foreign key relationship to the same table with a query parameter.

enter image description here

SET @x = -1;
SELECT id, categoryName 
FROM Catergory WHERE IF(@x > 0,category_ParentId = @x,category_ParentId IS NOT NULL);

@x can be changed.

How to push local changes to a remote git repository on bitbucket

Meaning the 2nd parameter('master') of the "git push" command -

$ git push origin master

can be made clear by initiating "push" command from 'news-item' branch. It caused local "master" branch to be pushed to the remote 'master' branch. For more information refer

https://git-scm.com/docs/git-push

where <refspec> in

[<repository> [<refspec>…?]

is written to mean "specify what destination ref to update with what source object."

For your reference, here is a screen capture how I verified this statement.

<code>enter image description here</code>

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

How to create a string with format?

Simple functionality is not included in Swift, expected because it's included in other languages, can often be quickly coded for reuse. Pro tip for programmers to create a bag of tricks file that contains all this reuse code.

So from my bag of tricks we first need string multiplication for use in indentation.

@inlinable func * (string: String, scalar: Int) -> String {
    let array = [String](repeating: string, count: scalar)
    return array.joined(separator: "")
}

and then the code to add commas.

extension Int {
    @inlinable var withCommas:String {
        var i = self
        var retValue:[String] = []
        while i >= 1000 {
            retValue.append(String(format:"%03d",i%1000))
            i /= 1000
        }
        retValue.append("\(i)")
        return retValue.reversed().joined(separator: ",")
    }

    @inlinable func withCommas(_ count:Int = 0) -> String {
        let retValue = self.withCommas
        let indentation = count - retValue.count
        let indent:String = indentation >= 0 ? " " * indentation : ""

        return indent + retValue
    }
}

I just wrote this last function so I could get the columns to line up.

The @inlinable is great because it takes small functions and reduces their functionality so they run faster.

You can use either the variable version or, to get a fixed column, use the function version. Lengths set less than the needed columns will just expand the field.

Now you have something that is pure Swift and does not rely on some old objective C routine for NSString.

Eclipse: Set maximum line length for auto formatting?

For XHTML files: Web -> HTML Files -> Editor -> Line width

How to store and retrieve a dictionary with redis

If you don't know exactly how to organize data in Redis, I did some performance tests, including the results parsing. The dictonary I used (d) had 437.084 keys (md5 format), and the values of this form:

{"path": "G:\tests\2687.3575.json",
 "info": {"f": "foo", "b": "bar"},
 "score": 2.5}

First Test (inserting data into a redis key-value mapping):

conn.hmset('my_dict', d)  # 437.084 keys added in 8.98s

conn.info()['used_memory_human']  # 166.94 Mb

for key in d:
    json.loads(conn.hget('my_dict', key).decode('utf-8').replace("'", '"'))
    #  41.1 s

import ast
for key in d:
    ast.literal_eval(conn.hget('my_dict', key).decode('utf-8'))
    #  1min 3s

conn.delete('my_dict')  # 526 ms

Second Test (inserting data directly into Redis keys):

for key in d:
    conn.hmset(key, d[key])  # 437.084 keys added in 1min 20s

conn.info()['used_memory_human']  # 326.22 Mb

for key in d:
    json.loads(conn.hgetall(key)[b'info'].decode('utf-8').replace("'", '"'))
    #  1min 11s

for key in d:
    conn.delete(key)
    #  37.3s

As you can see, in the second test, only 'info' values have to be parsed, because the hgetall(key) already returns a dict, but not a nested one.

And of course, the best example of using Redis as python's dicts, is the First Test

CXF: No message body writer found for class - automatically mapping non-simple resources

I encountered this problem while upgrading from CXF 2.7.0 to 3.0.2. Here is what I did to resolve it:

Included the following in my pom.xml

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-providers</artifactId>
        <version>3.0.2</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.0</version>
    </dependency>

and added the following provider

    <jaxrs:providers>
        <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
    </jaxrs:providers>

Custom header to HttpClient request

There is a Headers property in the HttpRequestMessage class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders in the HttpClient class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.

Hope this makes things more clear, at least for someone seeing this answer in future.

How to avoid Sql Query Timeout

My team were experiencing these issues intermittently with long running SSIS packages. This has been happening since Windows server patching.

Our SSIS and SQL servers are on separate VM servers.

Working with our Wintel Servers team we rebooted both servers and for the moment, the problem appears to have gone away.

The engineer has said that they're unsure if the issue is the patches or new VMTools that they updated at the same time. We'll monitor for now and if the timeout problems recur, they'll try rolling back the VMXNET3 driver, first, then if that doesn't work, take off the June Rollup patches.

So for us the issue is nothing to do with our SQL Queries (we're loading billions of new rows so it has to be long running).

How do I supply an initial value to a text field?

This can be achieved using TextEditingController.

To have an initial value you can add

TextEditingController _controller = TextEditingController(text: 'initial value');

or

If you are using TextFormField you have a initialValue property there. Which basically provides this initialValue to the controller automatically.

TextEditingController _controller = TextEditingController();
TextFormField(
  controller: _controller,
  initialValue: 'initial value'
)

To clear the text you can use _controller.clear() method.

Change "on" color of a Switch

make drawable "newthumb.xml"

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/Green" android:state_checked="true"/>
    <item android:color="@color/Red" android:state_checked="false"/>
</selector>

and make drawable "newtrack.xml"

<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="@color/black" android:state_checked="true"/>
        <item android:color="@color/white" android:state_checked="false"/>
    </selector>

and add it in Switch :

<Switch
        android:trackTint="@drawable/newtrack"
        android:thumbTint="@drawable/newthumb"
         />

How can I list all tags for a Docker image on a remote registry?

See CLI utility: https://www.npmjs.com/package/docker-browse

Allows enumeration of tags and images.

docker-browse tags <image> will list all tags for the image. e.g. docker-browse tags library/alpine

docker-browse images will list all images in the registry. Not currently available for index.docker.io.

You may connect it to any registry, including your private one, so long as it supports Docker Registry HTTP API V2

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

Try this:

$Wsdl = 'http://xxxx.xxx.xx/webservice3.asmx?WSDL';
libxml_disable_entity_loader(false); //adding this worked for me
$Client = new SoapClient($Wsdl);
//Code...

How to make an android app to always run in background?

In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.

Merge 2 arrays of objects

merge(a, b, key) {
    let merged = [];
    a.forEach(aitem => {
        let found = b.find( bitem => aitem[key] === bitem[key]);
        merged.push(found? found: aitem);
    });
    return merged;
}

Label word wrapping

If you want some dynamic sizing in conjunction with a word-wrapping label you can do the following:

  1. Put the label inside a panel
  2. Handle the ClientSizeChanged event for the panel, making the label fill the space:

    private void Panel2_ClientSizeChanged(object sender, EventArgs e)
    {
        label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
    }
    
  3. Set Auto-Size for the label to true

  4. Set Dock for the label to Fill

Php header location redirect not working

Pekka answered my question in the comments. He didn't post an answer, so I am now. Use the exit() method after the header redirect. For some reason the rest of the code of the page continues to execute after the header() method redirect. When the rest of the code executes, the echo statement is outputted to the page. And you can't redirect using the header function after you output to the page. To avoid rest of the code from executing, use exit(). Thanks Pekka.

UPDATE: When using the web browser Internet Explorer, I have noticed that $_POST['cancel'] is not reliable. I am not exactly sure why this is, but I suspect IE posts additional variables on a form submit, specifically the variable 'cancel' is posted. I solved this by using a variable name other than 'cancel'. The combination of using exit() and a unique variable name is working for me.

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

AJAX Mailchimp signup form integration

You should use the server-side code in order to secure your MailChimp account.

The following is an updated version of this answer which uses PHP:

The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.

1) Download the PHP 5 jQuery example here...

http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip

If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.

http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip

2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.

3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php file using the corresponding Merge Variables.

Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:

<?php

function storeAddress(){

    require_once('MCAPI.class.php');  // same directory as store-address.php

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI('123456789-us2');

    $merge_vars = Array( 
        'EMAIL' => $_GET['email'],
        'FNAME' => $_GET['fname'], 
        'LNAME' => $_GET['lname']
    );

    // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
    $list_id = "123456a";

    if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
        // It worked!   
        return 'Success!&nbsp; Check your inbox or spam folder for a message containing a confirmation link.';
    }else{
        // An error ocurred, return error message   
        return '<b>Error:</b>&nbsp; ' . $api->errorMessage;
    }

}

// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>

4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.

Here is something like what my index.html file looks like:

<form id="signup" action="index.html" method="get">
    <input type="hidden" name="ajax" value="true" />
    First Name: <input type="text" name="fname" id="fname" />
    Last Name: <input type="text" name="lname" id="lname" />
    email Address (required): <input type="email" name="email" id="email" />
    HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
    Text: <input type="radio" name="emailtype" value="text" />
    <input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>

<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript"> 
$(document).ready(function() {
    $('#signup').submit(function() {
        $("#message").html("<span class='error'>Adding your email address...</span>");
        $.ajax({
            url: 'inc/store-address.php', // proper url to your "store-address.php" file
            data: $('#signup').serialize(),
            success: function(msg) {
                $('#message').html(msg);
            }
        });
        return false;
    });
});
</script>

Required pieces...

  • index.html constructed as above or similar. With jQuery, the appearance and options are endless.

  • store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.

  • MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.

How do I get a value of datetime.today() in Python that is "timezone aware"?

Here's a stdlib solution that works on both Python 2 and 3:

from datetime import datetime

now = datetime.now(utc) # Timezone-aware datetime.utcnow()
today = datetime(now.year, now.month, now.day, tzinfo=utc) # Midnight

where today is an aware datetime instance representing the beginning of the day (midnight) in UTC and utc is a tzinfo object (example from the documentation):

from datetime import tzinfo, timedelta

ZERO = timedelta(0)

class UTC(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTC()

Related: performance comparison of several ways to get midnight (start of a day) for a given UTC time. Note: it is more complex, to get midnight for a time zone with a non-fixed UTC offset.

error: package com.android.annotations does not exist

Open gradle.properties and use following code:

android.useAndroidX=false
android.enableJetifier=false

or U can use these dependencies too:

implementation 'androidx.appcompat:appcompat:1.0.2'
 implementation 'androidx.annotation:annotation:1.0.2'

How do you set a JavaScript onclick event to a class with css

You can do this by thinking of it a little bit differently. Detect when the body is clicked (document.body.onclick - i.e. anything on the page) and then check if the element clicked (event.srcElement / e.target) has a class and that that class name is the one you want:

document.body.onclick = function(e) {   //when the document body is clicked
    if (window.event) {
        e = event.srcElement;           //assign the element clicked to e (IE 6-8)
    }
    else {
        e = e.target;                   //assign the element clicked to e
    }

    if (e.className && e.className.indexOf('someclass') != -1) {
        //if the element has a class name, and that is 'someclass' then...
        alert('hohoho');
    }
}

Or a more concise version of the above:

document.body.onclick= function(e){
   e=window.event? event.srcElement: e.target;
   if(e.className && e.className.indexOf('someclass')!=-1)alert('hohoho');
}

Your project path contains non-ASCII characters android studio

I solved this issue by adding this line

android.overridePathCheck=true

to

gradle.properties

As this message said

This warning can be disabled by using 
the command line flag -Dcom.android.build.gradle.overridePathCheck=true,
 or adding the line 
'com.android.build.gradle.overridePathCheck=true'
 to gradle.properties file in the project directory.

How to scroll UITableView to specific position

Swift 4.2 version:

let indexPath:IndexPath = IndexPath(row: 0, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .none, animated: true)

Enum: These are the available tableView scroll positions - here for reference. You don't need to include this section in your code.

public enum UITableViewScrollPosition : Int {

case None
case Top
case Middle
case Bottom
}

DidSelectRow:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let theCell:UITableViewCell? = tableView.cellForRowAtIndexPath(indexPath)

    if let theCell = theCell {
        var tableViewCenter:CGPoint = tableView.contentOffset
        tableViewCenter.y += tableView.frame.size.height/2

        tableView.contentOffset = CGPointMake(0, theCell.center.y-65)
        tableView.reloadData()
    }

}

Find provisioning profile in Xcode 5

The following works for me at a command prompt

cd ~/Library/MobileDevice/Provisioning\ Profiles/
for f in *.mobileprovision; do echo $f; openssl asn1parse -inform DER -in $f | grep -A1 application-identifier; done

Finding out which signing keys are used by a particular profile is harder to do with a shell one-liner. Basically you need to do:

openssl asn1parse -inform DER -in your-mobileprovision-filename

then cut-and-paste each block of base64 data after the DeveloperCertificates entry into its own file. You can then use:

openssl asn1parse -inform PEM -in file-with-base64

to dump each certificate. The line after the second commonName in the output will be the key name e.g. "iPhone Developer: Joe Bloggs (ABCD1234X)".

What is float in Java?

The thing is that decimal numbers defaults to double. And since double doesn't fit into float you have to tell explicitely you intentionally define a float. So go with:

float b = 3.6f;

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

 <uses-permission android:name="android.permission.INTERNET" />

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

How to change btn color in Bootstrap

2019 Update for Bootstrap 4

Now that Bootstrap 4 uses SASS, you can easily change the primary button color using the button-variant mixins:

$mynewcolor:#77cccc;

.btn-primary {
    @include button-variant($mynewcolor, darken($mynewcolor, 7.5%), darken($mynewcolor, 10%), lighten($mynewcolor,5%), lighten($mynewcolor, 10%), darken($mynewcolor,30%));
}
    
.btn-outline-primary {
    @include button-outline-variant($mynewcolor, #222222, lighten($mynewcolor,5%), $mynewcolor);
}

https://codeply.com/go/2bHYxYSC0n (SASS demo)

This SASS compiles into the following CSS...

.btn-primary {
    color: #212529;
    background-color: #7cc;
    border-color: #5bc2c2
}

.btn-primary:hover {
    color: #212529;
    background-color: #52bebe;
    border-color: #8ad3d3
}

.btn-primary:focus,
.btn-primary.focus {
    box-shadow: 0 0 0 .2rem rgba(91, 194, 194, 0.5)
}

.btn-primary.disabled,
.btn-primary:disabled {
    color: #212529;
    background-color: #7cc;
    border-color: #5bc2c2
}

.btn-primary:not(:disabled):not(.disabled):active,
.btn-primary:not(:disabled):not(.disabled).active,
.show>.btn-primary.dropdown-toggle {
    color: #212529;
    background-color: #9cdada;
    border-color: #2e7c7c
}

.btn-primary:not(:disabled):not(.disabled):active:focus,
.btn-primary:not(:disabled):not(.disabled).active:focus,
.show>.btn-primary.dropdown-toggle:focus {
    box-shadow: 0 0 0 .2rem rgba(91, 194, 194, 0.5)
}

.btn-outline-primary {
    color: #7cc;
    background-color: transparent;
    background-image: none;
    border-color: #7cc
}

.btn-outline-primary:hover {
    color: #222;
    background-color: #8ad3d3;
    border-color: #7cc
}

.btn-outline-primary:focus,
.btn-outline-primary.focus {
    box-shadow: 0 0 0 .2rem rgba(119, 204, 204, 0.5)
}

.btn-outline-primary.disabled,
.btn-outline-primary:disabled {
    color: #7cc;
    background-color: transparent
}

.btn-outline-primary:not(:disabled):not(.disabled):active,
.btn-outline-primary:not(:disabled):not(.disabled).active,
.show>.btn-outline-primary.dropdown-toggle {
    color: #212529;
    background-color: #8ad3d3;
    border-color: #7cc
}

.btn-outline-primary:not(:disabled):not(.disabled):active:focus,
.btn-outline-primary:not(:disabled):not(.disabled).active:focus,
.show>.btn-outline-primary.dropdown-toggle:focus {
    box-shadow: 0 0 0 .2rem rgba(119, 204, 204, 0.5)
}

https://codeply.com/go/lD3tUE01lo (CSS demo)


To change the primary color for all classes see: Customizing Bootstrap CSS template and How to change the bootstrap primary color?

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


Is there a way to check if a file is in use?

Here is some code that as far as I can best tell does the same thing as the accepted answer but with less code:

    public static bool IsFileLocked(string file)
    {
        try
        {
            using (var stream = File.OpenRead(file))
                return false;
        }
        catch (IOException)
        {
            return true;
        }        
    }

However I think it is more robust to do it in the following manner:

    public static void TryToDoWithFileStream(string file, Action<FileStream> action, 
        int count, int msecTimeOut)
    {
        FileStream stream = null;
        for (var i = 0; i < count; ++i)
        {
            try
            {
                stream = File.OpenRead(file);
                break;
            }
            catch (IOException)
            {
                Thread.Sleep(msecTimeOut);
            }
        }
        action(stream);
    }

How to POST request using RestSharp

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

Only using @JsonIgnore during serialization, but not deserialization

Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore to the getter.

Which you've tried:

Add @JsonIgnore on the getter method only

Do this, and also add a specific @JsonProperty annotation for your JSON "password" field name to the setter method for the password on your object.

More recent versions of Jackson have added READ_ONLY and WRITE_ONLY annotation arguments for JsonProperty. So you could also do something like:

@JsonProperty(access = Access.WRITE_ONLY)
private String password;

Docs can be found here.

Get a resource using getResource()

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

How can you profile a Python script?

The python wiki is a great page for profiling resources: http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code

as is the python docs: http://docs.python.org/library/profile.html

as shown by Chris Lawlor cProfile is a great tool and can easily be used to print to the screen:

python -m cProfile -s time mine.py <args>

or to file:

python -m cProfile -o output.file mine.py <args>

PS> If you are using Ubuntu, make sure to install python-profile

apt-get install python-profiler 

If you output to file you can get nice visualizations using the following tools

PyCallGraph : a tool to create call graph images
install:

 pip install pycallgraph

run:

 pycallgraph mine.py args

view:

 gimp pycallgraph.png

You can use whatever you like to view the png file, I used gimp
Unfortunately I often get

dot: graph is too large for cairo-renderer bitmaps. Scaling by 0.257079 to fit

which makes my images unusably small. So I generally create svg files:

pycallgraph -f svg -o pycallgraph.svg mine.py <args>

PS> make sure to install graphviz (which provides the dot program):

pip install graphviz

Alternative Graphing using gprof2dot via @maxy / @quodlibetor :

pip install gprof2dot
python -m cProfile -o profile.pstats mine.py
gprof2dot -f pstats profile.pstats | dot -Tsvg -o mine.svg

What is the purpose of backbone.js?

I have to admit that all the "advantages" of MVC have never made my work easier, faster, or better. It just makes the whole codeing experience more abstract and time consuming. Maintenance is a nightmare when trying to debug someone elses conception of what separation means. Don't know how many of you people have ever tried to update a FLEX site that used Cairngorm as the MVC model but what should take 30 seconds to update can often take over 2 hours (hunting/tracing/debugging just to find a single event). MVC was and still is, for me, an "advantage" that you can stuff.

How/When does Execute Shell mark a build as failure in Jenkins?

So by adding the #!/bin/sh will allow you to execute with no option.

It also helped me in fixing an issue where I was executing bash script from Jenkins master on my Linux slave. By just adding #!/bin/bash above my actual script in "Execute Shell" block it fixed my issue as otherwise it was executing windows git provided version of bash shell that was giving an error.

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Git removing upstream from local repository

Using git version 1.7.9.5 there is no "remove" command for remote. Use "rm" instead.

$ git remote rm upstream
$ git remote add upstream https://github.com/Foo/repos.git

or, as noted in the previous answer, set-url works.

I don't know when the command changed, but Ubuntu 12.04 shipped with 1.7.9.5.

How to access a value defined in the application.properties file in Spring Boot

Best ways to get property values are using.

1. Using Value annotation

@Value("${property.key}")
private String propertyKeyVariable;

2. Using Enviornment bean

@Autowired
private Environment env;

public String getValue() {
    return env.getProperty("property.key");
}

public void display(){
  System.out.println("# Value : "+getValue);
}

Remove warning messages in PHP

You could suppress the warning using error_reporting but the much better way is to fix your script in the first place.

If you don't know how, edit your question and show us the line in question and the warning that is displayed.

How to force composer to reinstall a library?

First execute composer clearcache

Then clear your vendors folder

rm -rf vendor/*

or better yet just remove the specific module which makes problems to avoid having to download all over again.

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

I also got the same error. Reason for that I was compiling the project using Maven. I had JAVA_HOME pointing to JDK7 and hence java 1.7 was being used for compilation and when running the project I was using JDK1.5. Changing the below entry in .classpath file or change in the eclipse as in the screenshot resolved the issue.

classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5

or change in the run configuarions of eclipse as enter image description here

Which one is the best PDF-API for PHP?

I personally generate XSL:FO from PHP and use Apache FOP to convert it to PDF. Not a PHP-native solution, not very efficient either, but it works well even if you need to generate PDF with very complex layouts.

RSA: Get exponent and modulus given a public key

If you need to parse ASN.1 objects in script, there's a library for that: https://github.com/lapo-luchini/asn1js

For doing the math, I found jsbn convenient: http://www-cs-students.stanford.edu/~tjw/jsbn/

Walking the ASN.1 structure and extracting the exp/mod/subject/etc. is up to you -- I never got that far!

Android studio Gradle build speed up

  1. Enable Offline Work

  2. Improve Gradle Performance by adding following code in gradle.properties

org.gradle.daemon=true
org.gradle.parallel=true

Step by step guide:http://www.viralandroid.com/2015/08/how-to-make-android-studio-fast.html

jquery append external html file into my page

Use selectors like CSS3

$("banner.html>div:first-child").append(data);

Ruby array to string conversion

array.inspect.inspect.gsub(/\[|\]/, "") could do the trick

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

After trying all the mentioned solutions I found the PlatformTarget somehow added to AnyCPU configuration in my project .csproj.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

Removing the line worked for me.

Get last 30 day records from today date in SQL Server

This Should Work Fine

SELECT * FROM product 
WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime')

How do you set the Content-Type header for an HttpClient request?

You need to do it like this:

    HttpContent httpContent = new StringContent(@"{ the json string }");
    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                
    HttpResponseMessage message = client.PostAsync(@"{url}", httpContent).Result;

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

Restarting MySQL works fine for me.

Insert picture into Excel cell

You can add the image into a comment.

Right-click cell > Insert Comment > right-click on shaded (grey area) on outside of comment box > Format Comment > Colors and Lines > Fill > Color > Fill Effects > Picture > (Browse to picture) > Click OK

Image will appear on hover over.

Microsoft Office 365 (2019) introduced new things called comments and renamed the old comments as "notes". Therefore in the steps above do New Note instead of Insert Comment. All other steps remain the same and the functionality still exists.


There is also a $20 product for Windows - Excel Image Assistant...

XDocument or XmlDocument

Also, note that XDocument is supported in Xbox 360 and Windows Phone OS 7.0. If you target them, develop for XDocument or migrate from XmlDocument.

Java - Check Not Null/Empty else assign default value

Use org.apache.commons.lang3.StringUtils

String emptyString = new String();    
result = StringUtils.defaultIfEmpty(emptyString, "default");
System.out.println(result);

String nullString = null;
result = StringUtils.defaultIfEmpty(nullString, "default");
System.out.println(result);

Both of the above options will print:

default

default

How to hide TabPage from TabControl

private System.Windows.Forms.TabControl _tabControl;
private System.Windows.Forms.TabPage _tabPage1;
private System.Windows.Forms.TabPage _tabPage2;

...
// Initialise the controls
...

// "hides" tab page 2
_tabControl.TabPages.Remove(_tabPage2);

// "shows" tab page 2
// if the tab control does not contain tabpage2
if (! _tabControl.TabPages.Contains(_tabPage2))
{
    _tabControl.TabPages.Add(_tabPage2);
}

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

In June 2018, in an effort to raise security and comply with modern standards, the insecure TLS 1.0 & 1.1 protocols will no longer be supported for SSL connections to Central. This should only affect users of Java 6 (and Java 7) that are also using https to access central, which by our metrics is less than .2% of users.

For more details and workarounds, see the blog and faq here: https://blog.sonatype.com/enhancing-ssl-security-and-http/2-support-for-central

How to find where gem files are installed

You can check it from your command prompt by running gem help commands and then selecting the proper command:

kirti@kirti-Aspire-5733Z:~$  gem help commands
GEM commands are:

    build                  Build a gem from a gemspec
    cert                   Manage RubyGems certificates and signing settings
    check                  Check a gem repository for added or missing files
    cleanup                Clean up old versions of installed gems in the local
                           repository
    contents               Display the contents of the installed gems
    dependency             Show the dependencies of an installed gem
    environment            Display information about the RubyGems environment
    fetch                  Download a gem and place it in the current directory
    generate_index         Generates the index files for a gem server directory
    help                   Provide help on the 'gem' command
    install                Install a gem into the local repository
    list                   Display gems whose name starts with STRING
    lock                   Generate a lockdown list of gems
    mirror                 Mirror all gem files (requires rubygems-mirror)
    outdated               Display all gems that need updates
    owner                  Manage gem owners on RubyGems.org.
    pristine               Restores installed gems to pristine condition from
                           files located in the gem cache
    push                   Push a gem up to RubyGems.org
    query                  Query gem information in local or remote repositories
    rdoc                   Generates RDoc for pre-installed gems
    regenerate_binstubs    Re run generation of executable wrappers for gems.
    search                 Display all gems whose name contains STRING
    server                 Documentation and gem repository HTTP server
    sources                Manage the sources and cache file RubyGems uses to
                           search for gems
    specification          Display gem specification (in yaml)
    stale                  List gems along with access times
    uninstall              Uninstall gems from the local repository
    unpack                 Unpack an installed gem to the current directory
    update                 Update installed gems to the latest version
    which                  Find the location of a library file you can require
    yank                   Remove a specific gem version release from
                           RubyGems.org

For help on a particular command, use 'gem help COMMAND'.

Commands may be abbreviated, so long as they are unambiguous.
e.g. 'gem i rake' is short for 'gem install rake'.
kirti@kirti-Aspire-5733Z:~$ 

Now from the above I can see the command environment is helpful. So I would do:

kirti@kirti-Aspire-5733Z:~$ gem help environment
Usage: gem environment [arg] [options]


  Common Options:
    -h, --help                       Get help on this command
    -V, --[no-]verbose               Set the verbose level of output
    -q, --quiet                      Silence commands
        --config-file FILE           Use this config file instead of default
        --backtrace                  Show stack backtrace on errors
        --debug                      Turn on Ruby debugging


  Arguments:
    packageversion  display the package version
    gemdir          display the path where gems are installed
    gempath         display path used to search for gems
    version         display the gem format version
    remotesources   display the remote gem servers
    platform        display the supported gem platforms
    <omitted>       display everything

  Summary:
    Display information about the RubyGems environment

  Description:
    The RubyGems environment can be controlled through command line arguments,
    gemrc files, environment variables and built-in defaults.

    Command line argument defaults and some RubyGems defaults can be set in a
    ~/.gemrc file for individual users and a /etc/gemrc for all users. These
    files are YAML files with the following YAML keys:

      :sources: A YAML array of remote gem repositories to install gems from
      :verbose: Verbosity of the gem command. false, true, and :really are the
                levels
      :update_sources: Enable/disable automatic updating of repository metadata
      :backtrace: Print backtrace when RubyGems encounters an error
      :gempath: The paths in which to look for gems
      :disable_default_gem_server: Force specification of gem server host on
    push
      <gem_command>: A string containing arguments for the specified gem command

    Example:

      :verbose: false
      install: --no-wrappers
      update: --no-wrappers
      :disable_default_gem_server: true

    RubyGems' default local repository can be overridden with the GEM_PATH and
    GEM_HOME environment variables. GEM_HOME sets the default repository to
    install into. GEM_PATH allows multiple local repositories to be searched for
    gems.

    If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
    HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
    proxy server.

    If you would like to push gems to a private gem server the RUBYGEMS_HOST
    environment variable can be set to the URI for that server.

    If you are packaging RubyGems all of RubyGems' defaults are in
    lib/rubygems/defaults.rb.  You may override these in
    lib/rubygems/defaults/operating_system.rb
kirti@kirti-Aspire-5733Z:~$ 

Finally to show you what you asked, I would do:

kirti@kirti-Aspire-5733Z:~$ gem environment gemdir
/home/kirti/.rvm/gems/ruby-2.0.0-p0
kirti@kirti-Aspire-5733Z:~$ gem environment gempath
/home/kirti/.rvm/gems/ruby-2.0.0-p0:/home/kirti/.rvm/gems/ruby-2.0.0-p0@global
kirti@kirti-Aspire-5733Z:~$ 

window.onload vs document.onload

Window.onload is the standard, however - the web browser in the PS3 (based on Netfront) doesn't support the window object, so you can't use it there.

How to make IPython notebook matplotlib plot inline

You can simulate this problem with a syntax mistake, however, %matplotlib inline won't resolve the issue.

First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.

df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))

df_randNumbers1.ix[:,["A","B"]].plot.kde()

However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.

Erronious code:

df_randNumbers1.ix[:,["A","B"]].plot.kde

Example error:

<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>

Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.

Get visible items in RecyclerView

Following Linear / Grid LayoutManager methods can be used to check which items are visible

int findFirstVisibleItemPosition();
int findLastVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();

and if you want to track is item visible on screen for some threshold then you can refer to the following blog.

https://proandroiddev.com/detecting-list-items-perceived-by-user-8f164dfb1d05

How to apply bold text style for an entire row using Apache POI?

This worked for me

    Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
            { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };

    String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };

    int noOfColumns = headers.length;
    int rowCount = 0;

    Row rowZero = sheet.createRow(rowCount++);
    CellStyle style = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style.setFont(font);
    for (int col = 1; col <= noOfColumns; col++) {
        Cell cell = rowZero.createCell(col);
        cell.setCellValue(headers[col - 1]);
        cell.setCellStyle(style);
    }

jQuery UI Dialog - missing close icon

I was facing same issue , In my case JQuery-ui.js version was 1.10.3, After referring jquery-ui-1.12.1.min.js close button started to visible.

How to echo out table rows from the db (php)

$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
    echo "<tr>";
    foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
        echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function. 
    }
    echo "</tr>";
}
echo "</table>";

PHP convert XML to JSON

Try to use this

$xml = ... // Xml file data

// first approach
$Json = json_encode(simplexml_load_string($xml));

---------------- OR -----------------------

// second approach
$Json = json_encode(simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA));

echo $Json;

Or

You can use this library : https://github.com/rentpost/xml2array

Creating the checkbox dynamically using JavaScript?

   /* worked for me  */
     <div id="divid"> </div>
     <script type="text/javascript">
         var hold = document.getElementById("divid");
         var checkbox = document.createElement('input');
         checkbox.type = "checkbox";
         checkbox.name = "chkbox1";
         checkbox.id = "cbid";
         var label = document.createElement('label');
         var tn = document.createTextNode("Not A RoBot");
         label.htmlFor="cbid";
         label.appendChild(tn); 
         hold.appendChild(label);
         hold.appendChild(checkbox);
      </script>  

Can a variable number of arguments be passed to a function?

Adding to the other excellent posts.

Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).

def manyArgs1(args):
  print args.a, args.b #note args.c is not used here

def manyArgs2(args):
  print args.c #note args.b and .c are not used here

class Args: pass

args = Args()
args.a = 1
args.b = 2
args.c = 3

manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3

Then you can do things like

myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
  fun(args)

Fastest way to check if a file exist using standard C++/C++11/C?

It depends on where the files reside. For instance, if they are all supposed to be in the same directory, you can read all the directory entries into a hash table and then check all the names against the hash table. This might be faster on some systems than checking each file individually. The fastest way to check each file individually depends on your system ... if you're writing ANSI C, the fastest way is fopen because it's the only way (a file might exist but not be openable, but you probably really want openable if you need to "do something on it"). C++, POSIX, Windows all offer additional options.

While I'm at it, let me point out some problems with your question. You say that you want the fastest way, and that you have thousands of files, but then you ask for the code for a function to test a single file (and that function is only valid in C++, not C). This contradicts your requirements by making an assumption about the solution ... a case of the XY problem. You also say "in standard c++11(or)c++(or)c" ... which are all different, and this also is inconsistent with your requirement for speed ... the fastest solution would involve tailoring the code to the target system. The inconsistency in the question is highlighted by the fact that you accepted an answer that gives solutions that are system-dependent and are not standard C or C++.

How to extract closed caption transcript from YouTube video?

(Obligatory 'this is probably an internal youtube.com interface and might break at any time')

Instead of linking to another tool that does this, here's an answer to the question of "how to do this"

Use fiddler or your browser devtools (e.g. Chrome) to inspect the youtube.com HTTP traffic, and there's a response from /api/timedtext that contains the closed caption info as XML.

It seems that a response like this:

    <p t="0" d="5430" w="1">
        <s p="2" ac="136">we&#39;ve</s>
        <s t="780" ac="252"> got</s>
    </p>
    <p t="2280" d="7170" w="1">
        <s ac="243">we&#39;re</s>
        <s t="810" ac="233"> going</s>
    </p>

means at time 0 is the word we've and at time 0+780 is the word got and at time 2280+810 is the word going, etc. This time is in milliseconds so for time 3090 you'd want to append &t=3 to the URL.

You can use any tool to stitch together the XML into something readable, but here's my Power BI Desktop script to find words like "privilege":

let
    Source = Xml.Tables(File.Contents("C:\Download\body.xml")),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Attribute:format", Int64.Type}}),
    body = #"Changed Type"{0}[body],
    p = body{0}[p],
    #"Changed Type1" = Table.TransformColumnTypes(p,{{"Attribute:t", Int64.Type}, {"Attribute:d", Int64.Type}, {"Attribute:w", Int64.Type}, {"Attribute:a", Int64.Type}, {"Attribute:p", Int64.Type}}),
    #"Expanded s" = Table.ExpandTableColumn(#"Changed Type1", "s", {"Attribute:ac", "Attribute:p", "Attribute:t", "Element:Text"}, {"s.Attribute:ac", "s.Attribute:p", "s.Attribute:t", "s.Element:Text"}),
    #"Changed Type2" = Table.TransformColumnTypes(#"Expanded s",{{"s.Attribute:t", Int64.Type}}),
    #"Removed Other Columns" = Table.SelectColumns(#"Changed Type2",{"s.Attribute:t", "s.Element:Text", "Attribute:t"}),
    #"Replaced Value" = Table.ReplaceValue(#"Removed Other Columns",null,0,Replacer.ReplaceValue,{"s.Attribute:t"}),
    #"Filtered Rows" = Table.SelectRows(#"Replaced Value", each [#"s.Element:Text"] <> null),
    #"Added Custom" = Table.AddColumn(#"Filtered Rows", "Time", each [#"Attribute:t"] + [#"s.Attribute:t"]),
    #"Filtered Rows1" = Table.SelectRows(#"Added Custom", each ([#"s.Element:Text"] = " privilege" or [#"s.Element:Text"] = " privileged" or [#"s.Element:Text"] = " privileges" or [#"s.Element:Text"] = "privilege" or [#"s.Element:Text"] = "privileges"))
in
    #"Filtered Rows1"

How do I rename both a Git local and remote branch name?

I use these git alias and it pretty much does the job automatic:

git config --global alias.move '!git checkout master; git branch -m $1 $2; git status; git push --delete origin $1; git status; git push -u origin $2; git branch -a; exit;'

Usage: git move FROM_BRANCH TO_BRANCH

It works if you have the default names like master, origin etc. You can modify as you wish but it gives you the idea.

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

The ENABLEDELAYEDEXPANSION part is REQUIRED in certain programs that use delayed expansion, that is, that takes the value of variables that were modified inside IF or FOR commands by enclosing their names in exclamation-marks.

If you enable this expansion in a script that does not require it, the script behaves different only if it contains names enclosed in exclamation-marks !LIKE! !THESE!. Usually the name is just erased, but if a variable with the same name exist by chance, then the result is unpredictable and depends on the value of such variable and the place where it appears.

The SETLOCAL part is REQUIRED in just a few specialized (recursive) programs, but is commonly used when you want to be sure to not modify any existent variable with the same name by chance or if you want to automatically delete all the variables used in your program. However, because there is not a separate command to enable the delayed expansion, programs that require this must also include the SETLOCAL part.

Can't find android device using "adb devices" command

Just because your Android device is in Developer Mode, doesn't mean it has USB debugging enabled!! Go into Settings > Developer options then enable "USB debugging" and then you should see your device. It's a common mistake that's easily overlooked.

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Effective swapping of elements of an array in Java

public class SwapElements {

public static void main(String[] args) {

    int[] arr1 = new int[5];
    int[] arr2 = {10,20,30,40};

    System.out.println("arr1 Before Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 Before Swapping " + Arrays.toString(arr2));

    int temp[];
    arr1[3] = 5;
    arr1[0] = 2;
    arr1[1] = 3;
    arr1[2] = 6;
    arr1[4] = 10;

    temp = arr1;
    arr1 = arr2;
    arr2 = temp;
    System.out.println("arr1 after Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 after Swapping " + Arrays.toString(arr2));
}

}

How to install php-curl in Ubuntu 16.04

Do:

apt-get update

And then:

apt-get install php5-curl

Mac install and open mysql using terminal

In the terminal, I typed:

/usr/local/mysql/bin/mysql -u root -p

I was then prompted to enter the temporary password that was given to me upon completion of the installation.

Regex for quoted string with escaping quotes

If it is searched from the beginning, maybe this can work?

\"((\\\")|[^\\])*\"

How to find a min/max with Ruby

In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:

def max(*values)
 values.max
end

Output:

max(7, 1234, 9, -78, 156)
=> 1234

This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil, since calling Enumerable#max on an empty array object returns nil.

If you want to define this method on the Math module, this should do the trick:

module Math
 def self.max(*values)
  values.max
 end
end

Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:). See Dave Morse's answer for a simpler and faster method.

Error in contrasts when defining a linear model in R

If the error happens to be because your data has NAs, then you need to set the glm() function options of how you would like to treat the NA cases. More information on this is found in a relevant post here: https://stats.stackexchange.com/questions/46692/how-the-na-values-are-treated-in-glm-in-r

How to set up tmux so that it starts up with specified windows opened?

I just tried using all the ideas on this page and I didn't like any of them. I just wanted a solution that started tmux with a specific set of windows when my terminal opened. I also wanted it to be idempotent, i.e. opening a new terminal window takes over the tmux session from the previous one.

The above solutions often tend to open multiple tmux sessions and I want just one. First, I added this to my ~/.bash_profile:

tmux start-server
if [[ -z "$TMUX" ]]
then
  exec tmux attach -d -t default
fi

then I added the following to my ~/.tmux.conf:

new -s default -n emacs /usr/local/bin/emacs
neww -n shell /usr/local/bin/bash
neww -n shell /usr/local/bin/bash
selectw -t 1

now every time I start a terminal or start tmux or whatever, I either reattach to my existing desired setup (the session named default), or create a new session with that setup.

What is the difference between '@' and '=' in directive scope in AngularJS?

I implemented all the possible options in a fiddle.

It deals with all the options:

scope:{
    name:'&'
},

scope:{
    name:'='
},

scope:{
    name:'@'
},

scope:{

},

scope:true,

https://jsfiddle.net/rishulmatta/v7xf2ujm

In Django, how do I check if a user is in a certain group?

Your User object is linked to the Group object through a ManyToMany relationship.

You can thereby apply the filter method to user.groups.

So, to check if a given User is in a certain group ("Member" for the example), just do this :

def is_member(user):
    return user.groups.filter(name='Member').exists()

If you want to check if a given user belongs to more than one given groups, use the __in operator like so :

def is_in_multiple_groups(user):
    return user.groups.filter(name__in=['group1', 'group2']).exists()

Note that those functions can be used with the @user_passes_test decorator to manage access to your views :

from django.contrib.auth.decorators import login_required, user_passes_test
@login_required
@user_passes_test(is_member) # or @user_passes_test(is_in_multiple_groups)
def myview(request):
    # Do your processing

Hope this help

How do I cancel form submission in submit button onclick event?

You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:

<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>

function btnClick() {
    if (!validData()) return false;
}

Edit onSubmit belongs in the form tag.

How to update std::map after using the find method?

I would use the operator[].

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

So using this technique it becomes really easy to read all the character from a stream and count them:

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

Arithmetic overflow error converting numeric to data type numeric

check your value which you want to store in integer column. I think this is greater then range of integer. if you want to store value greater then integer range. you should use bigint datatype

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I had the exact same problem when working with several developers. If I RUN the project from my ADT it works well, but from theirs it isn't..

The answer was to put their SHA-1 key with the package name in Google API console as well as mine. We are three developers, so we needed to put in three SHA-1 keys..

I hope it gives you some inspiration...

ASP.NET MVC controller actions that return JSON or partial html

I think you should consider the AcceptTypes of the request. I am using it in my current project to return the correct content type as follows.

Your action on the controller can test it as on the request object

if (Request.AcceptTypes.Contains("text/html")) {
   return View();
}
else if (Request.AcceptTypes.Contains("application/json"))
{
   return Json( new { id=1, value="new" } );
}
else if (Request.AcceptTypes.Contains("application/xml") || 
         Request.AcceptTypes.Contains("text/xml"))
{
   //
}

You can then implement the aspx of the view to cater for the partial xhtml response case.

Then in jQuery you can fetch it passing the type parameter as json:

$.get(url, null, function(data, textStatus) {
        console.log('got %o with status %s', data, textStatus);
        }, "json"); // or xml, html, script, json, jsonp or text

Hope this helps James

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values.

Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.

I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution: @Enumerated(EnumType.STRING)

How can I define an array of objects?

You can also try

    interface IData{
        id: number;
        name:string;
    }

    let userTestStatus:Record<string,IData> = {
        "0": { "id": 0, "name": "Available" },
        "1": { "id": 1, "name": "Ready" },
        "2": { "id": 2, "name": "Started" }
    };

To check how record works: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

Here in our case Record is used to declare an object whose key will be a string and whose value will be of type IData so now it will provide us intellisense when we will try to access its property and will throw type error in case we will try something like userTestStatus[0].nameee

Found conflicts between different versions of the same dependent assembly that could not be resolved

As stated in dotnet CLI issue 6583 the issue should be solved with dotnet nuget locals --clear all command.

Cannot find mysql.sock

(Q1) How can I find the socket file?

The default location for the socket file is /tmp/mysql.sock, to find the socket file for your system use this.

mysqladmin variables | grep socket

If you have just installed MySql the mysql.sock file will not be created until the server is started. Use this command to start it.

sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

If prompted for a password you can pass the username root or other username like this. Terminal will prompt you for the password.

mysqladmin --user root --password variables | grep socket

(Q2) How can I refresh locate index

Refresh the locate db with this command.

sudo /usr/libexec/locate.updatedb

Can't import Numpy in Python

Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.

Try find / -iname '*numpy*'

How do you comment an MS-access Query?

I decided to add a condition to the Where Clause that always evaluates true but allows the coder to find your comment.

Select
   ...
From
   ...
Where
   ....
   And "Comment: FYI, Access doesn't support normal comments!"<>""

The last line always evaluates to true so it doesn't affect the data returned but allows you to leave a comment for the next guy.

How can I find and run the keytool

Robby Pond's answer can be generalized to use JAVA_HOME environment variable and to also compensate for any blanks that might occur in the path (like Program Files):

"%JAVA_HOME%\bin\keytool" -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

What is the parameter "next" used for in Express?

It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an id was given, and assign it to req.user.

Below, you could have a route like:

app.get('/users', function(req, res) {
  // check for and maybe do something with req.user
});

Since /users/123 will match the route in your example first, that will first check and find user 123; then /users can do something with the result of that.

Route middleware is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Users model with an async findOne():

function loadUser(req, res, next) {
  if (req.params.userId) {
    Users.findOne({ id: req.params.userId }, function(err, user) {
      if (err) {
        next(new Error("Couldn't find user: " + err));
        return;
      }

      req.user = user;
      next();
    });
  } else {
    next();
  }
}

// ...

app.get('/user/:userId', loadUser, function(req, res) {
  // do something with req.user
});

app.get('/users/:userId?', loadUser, function(req, res) {
  // if req.user was set, it's because userId was specified (and we found the user).
});

// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {
  req.user.items.append(req.item.name);
});

Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:

/**
 * Only allows the page to be accessed if the user is an admin.
 * Requires use of `loadUser` middleware.
 */
function requireAdmin(req, res, next) {
  if (!req.user || !req.user.admin) {
    next(new Error("Permission denied."));
    return;
  }

  next();
}

app.get('/top/secret', loadUser, requireAdmin, function(req, res) {
  res.send('blahblahblah');
});

Hope this gave you some inspiration!

How to run Visual Studio post-build events for debug build only

Add your post build event like normal. Then save your project, open it in Notepad (or your favorite editor), and add condition to the PostBuildEvent property group. Here's an example:

<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
    <PostBuildEvent>start gpedit</PostBuildEvent>
</PropertyGroup>

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

Force unmount of NFS-mounted directory

Couldn't find a working answer here; but on linux you can run "umount.nfs4 /volume -f" and it definitely unmounts it.

SVN: Is there a way to mark a file as "do not commit"?

I got tired of waiting for this to get built into SVN. I was using tortoiseSVN with ignore-on-commit, but that pops up a user dialog box that you can't suppress from the command line, and when I run my build script and go and make a cup of tea, I hate it when I come back to discover it's waiting for user input 10% of the way through.

So here's a windows powershell script that commits only files that aren't in a changelist:

# get list of changed files into targets
[XML]$svnStatus = svn st -q --xml C:\SourceCode\Monad
# select the nodes that aren't in a changelist
$fileList = $svnStatus.SelectNodes('/status/target/entry[wc-status/@item != "unversioned"]') | Foreach-Object {$_.path};
# create a temp file of targets
$fileListPath =  [IO.Path]::GetTempFileName();
$fileList | out-file $fileListPath -Encoding ASCII
# do the commit
svn commit --targets $fileListPath -m "Publish $version" --keep-changelists 
# remove the temp file
Remove-Item $filelistPath

How to sort in mongoose?

As of October 2020, to fix your issue you should add .exec() to the call. don't forget that if you want to use this data outside of the call you should run something like this inside of an async function.

let post = await callQuery();

async function callQuery() {
      return Post.find().sort(['updatedAt', 1].exec();
}

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

How to disable 'X-Frame-Options' response header in Spring Security?

If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .headers().disable()
      ...;
  }
}

Get JSF managed bean by name in any Servlet related class

I use this:

public static <T> T getBean(Class<T> clazz) {
    try {
        String beanName = getBeanName(clazz);
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return facesContext.getApplication().evaluateExpressionGet(facesContext, "#{" + beanName + "}", clazz);
    //return facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, nomeBean);
    } catch (Exception ex) {
        return null;
    }
}

public static <T> String getBeanName(Class<T> clazz) {
    ManagedBean managedBean = clazz.getAnnotation(ManagedBean.class);
    String beanName = managedBean.name();

    if (StringHelper.isNullOrEmpty(beanName)) {
        beanName = clazz.getSimpleName();
        beanName = Character.toLowerCase(beanName.charAt(0)) + beanName.substring(1);
    }

    return beanName;
}

And then call:

MyManageBean bean = getBean(MyManageBean.class);

This way you can refactor your code and track usages without problems.

What is the difference between char array and char pointer in C?

Let's see:

#include <stdio.h>
#include <string.h>

int main()
{
    char *p = "hello";
    char q[] = "hello"; // no need to count this

    printf("%zu\n", sizeof(p)); // => size of pointer to char -- 4 on x86, 8 on x86-64
    printf("%zu\n", sizeof(q)); // => size of char array in memory -- 6 on both

    // size_t strlen(const char *s) and we don't get any warnings here:
    printf("%zu\n", strlen(p)); // => 5
    printf("%zu\n", strlen(q)); // => 5

    return 0;
}

foo* and foo[] are different types and they are handled differently by the compiler (pointer = address + representation of the pointer's type, array = pointer + optional length of the array, if known, for example, if the array is statically allocated), the details can be found in the standard. And at the level of runtime no difference between them (in assembler, well, almost, see below).

Also, there is a related question in the C FAQ:

Q: What is the difference between these initializations?

char a[] = "string literal";   
char *p  = "string literal";   

My program crashes if I try to assign a new value to p[i].

A: A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways:

  1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size).
  2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element.

Some compilers have a switch controlling whether string literals are writable or not (for compiling old code), and some may have options to cause string literals to be formally treated as arrays of const char (for better error catching).

See also questions 1.31, 6.1, 6.2, 6.8, and 11.8b.

References: K&R2 Sec. 5.5 p. 104

ISO Sec. 6.1.4, Sec. 6.5.7

Rationale Sec. 3.1.4

H&S Sec. 2.7.4 pp. 31-2

Getting the name of the currently executing method

An alternative method is to create, but not throw, an Exception, and use that object from which to get the stack trace data, since the enclosing method will typically be at index 0 - as long as the JVM stores that information, as others have mentioned above. This not the cheapest method, however.

From Throwable.getStackTrace() (this has been the same since Java 5 at least):

The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown.

The snippet below assumes the class is non-static (because of getClass()), but that's an aside.

System.out.printf("Class %s.%s\n", getClass().getName(), new Exception("is not thrown").getStackTrace()[0].getMethodName());

How can I count the occurrences of a string within a file?

None of the existing answers worked for me with a single-line 10GB file. Grep runs out of memory even on a machine with 768 GB of RAM!

$ cat /proc/meminfo | grep MemTotal
MemTotal:       791236260 kB
$ ls -lh test.json
-rw-r--r-- 1 me all 9.2G Nov 18 15:54 test.json
$ grep -o '0,0,0,0,0,0,0,0,' test.json  | wc -l
grep: memory exhausted
0

So I wrote a very simple Rust program to do it.

  1. Install Rust.
  2. cargo install count_occurences
$ count_occurences '0,0,0,0,0,0,0,0,' test.json
99094198

It's a little slow (1 minute for 10GB), but at least it doesn't run out of memory!

Javac is not found

You don't have jdk1.7.0_17 in your PATH - check again. There is only JRE which may not contain 'javac' compiler.

Besides it is best to set JAVA_HOME variable, and then include it in PATH.

How to store an array into mysql?

You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html

Show percent % instead of counts in charts of categorical variables

Since this was answered there have been some meaningful changes to the ggplot syntax. Summing up the discussion in the comments above:

 require(ggplot2)
 require(scales)

 p <- ggplot(mydataf, aes(x = foo)) +  
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        ## version 3.0.0
        scale_y_continuous(labels=percent)

Here's a reproducible example using mtcars:

 ggplot(mtcars, aes(x = factor(hp))) +  
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        scale_y_continuous(labels = percent) ## version 3.0.0

enter image description here

This question is currently the #1 hit on google for 'ggplot count vs percentage histogram' so hopefully this helps distill all the information currently housed in comments on the accepted answer.

Remark: If hp is not set as a factor, ggplot returns:

enter image description here

How to permanently add a private key with ssh-add on Ubuntu?

A solution would be to force the key files to be kept permanently, by adding them in your ~/.ssh/config file:

IdentityFile ~/.ssh/gitHubKey
IdentityFile ~/.ssh/id_rsa_buhlServer

If you do not have a 'config' file in the ~/.ssh directory, then you should create one. It does not need root rights, so simply:

nano ~/.ssh/config

...and enter the lines above as per your requirements.

For this to work the file needs to have chmod 600. You can use the command chmod 600 ~/.ssh/config.

If you want all users on the computer to use the key put these lines into /etc/ssh/ssh_config and the key in a folder accessible to all.

Additionally if you want to set the key specific to one host, you can do the following in your ~/.ssh/config :

Host github.com
    User git
    IdentityFile ~/.ssh/githubKey

This has the advantage when you have many identities that a server doesn't reject you because you tried the wrong identities first. Only the specific identity will be tried.

Case-Insensitive List Search

I realise this is an old post, but just in case anyone else is looking, you can use Contains by providing the case insensitive string equality comparer like so:

using System.Linq;

// ...

if (testList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Keyword Exists");
}

This has been available since .net 2.0 according to msdn.

Find and replace entire mysql database

BE CAREFUL, when replacing with REPLACE command!

why?

because there is a great chance that your database contains serialized data (especially wp_options table), so using just "replace" might break data.

Use recommended serialization: https://puvox.software/tools/wordpress-migrator

Which is better, return value or out parameter?

I would prefer the following instead of either of those in this simple example.

public int Value
{
    get;
    private set;
}

But, they are all very much the same. Usually, one would only use 'out' if they need to pass multiple values back from the method. If you want to send a value in and out of the method, one would choose 'ref'. My method is best, if you are only returning a value, but if you want to pass a parameter and get a value back one would likely choose your first choice.

nginx - client_max_body_size has no effect

You need to apply following changes:

  1. Update php.ini (Find right ini file from phpinfo();) and increase post_max_size and upload_max_filesize to size you want:

    sed -i "s/post_max_size =.*/post_max_size = 200M/g" /etc/php5/fpm/php.ini
    sed -i "s/upload_max_filesize =.*/upload_max_filesize = 200M/g" /etc/php5/fpm/php.ini```
    
  2. Update NginX settings for your website and add client_max_body_size value in your location, http, or server context.

    location / {
        client_max_body_size 200m;
        ...
    }
    
  3. Restart NginX and PHP-FPM:

    service nginx restart
    service php5-fpm restart
    

NOTE: Sometime (In my case almost every time) you need to kill php-fpm process if it didn't refresh by service command properly. To do that you can get list of processes (ps -elf | grep php-fpm) and kill one by one (kill -9 12345) or use following command to do it for you:

ps -elf | grep php-fpm | grep -v grep | awk '{ print $4 }' | xargs kill -9

How to ping ubuntu guest on VirtualBox

If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces still configured for eth0.

Diagnose:

ethtool -i eth0
Cannot get driver information: no such device

Find your interfaces:

ls /sys/class/net
eth1 eth2 lo

Fix it:

Edit /etc/networking/interfaces and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)

:%s/eth0/eth2/g

How do you specify a byte literal in Java?

You have to cast, I'm afraid:

f((byte)0);

I believe that will perform the appropriate conversion at compile-time instead of execution time, so it's not actually going to cause performance penalties. It's just inconvenient :(

Excel - Sum column if condition is met by checking other column in same table

Actually a more refined solution is use the build-in function sumif, this function does exactly what you need, will only sum those expenses of a specified month.

example

=SUMIF(A2:A100,"=January",B2:B100)

What is the main difference between Inheritance and Polymorphism?

In Java, the two are closely related. This is because Java uses a technique for method invocation called "dynamic dispatch". If I have

public class A {
  public void draw() { ... }
  public void spin() { ... }
}

public class B extends A {
  public void draw() { ... }
  public void bad() { ... }
}

...

A testObject = new B();

testObject.draw(); // calls B's draw, polymorphic
testObject.spin(); // calls A's spin, inherited by B
testObject.bad(); // compiler error, you are manipulating this as an A

Then we see that B inherits spin from A. However, when we try to manipulate the object as if it were a type A, we still get B's behavior for draw. The draw behavior is polymorphic.

In some languages, polymorphism and inheritance aren't quite as closely related. In C++, for example, functions not declared virtual are inherited, but won't be dispatched dynamically, so you won't get that polymorphic behavior even when you use inheritance.

In javascript, every function call is dynamically dispatched and you have weak typing. This means you could have a bunch of unrelated objects, each with their own draw, have a function iterate over them and call the function, and each would behave just fine. You'd have your own polymorphic draw without needing inheritance.

How to generate a Makefile with source in sub-directories using just one makefile

This is another trick.

In main 'Makefile' define SRCDIR for each source dir and include 'makef.mk' for each value of SRCDIR. In each source dir put file 'files.mk' with list of source files and compile options for some of them. In main 'Makefile' one can define compile options and exclude files for each value of SRCDIR.

Makefile:

PRG             := prog-name

OPTIMIZE        := -O2 -fomit-frame-pointer

CFLAGS += -finline-functions-called-once
LDFLAGS += -Wl,--gc-section,--reduce-memory-overheads,--relax


.DEFAULT_GOAL   := hex

OBJDIR          := obj

MK_DIRS         := $(OBJDIR)


SRCDIR          := .
include         makef.mk

SRCDIR := crc
CFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE
ASFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE
include makef.mk

################################################################

CC              := avr-gcc -mmcu=$(MCU_TARGET) -I.
OBJCOPY         := avr-objcopy
OBJDUMP         := avr-objdump

C_FLAGS         := $(CFLAGS) $(REGS) $(OPTIMIZE)
CPP_FLAGS       := $(CPPFLAGS) $(REGS) $(OPTIMIZE)
AS_FLAGS        := $(ASFLAGS)
LD_FLAGS        := $(LDFLAGS) -Wl,-Map,$(OBJDIR)/$(PRG).map


C_OBJS          := $(C_SRC:%.c=$(OBJDIR)/%.o)
CPP_OBJS        := $(CPP_SRC:%.cpp=$(OBJDIR)/%.o)
AS_OBJS         := $(AS_SRC:%.S=$(OBJDIR)/%.o)

C_DEPS          := $(C_OBJS:%=%.d)
CPP_DEPS        := $(CPP_OBJS:%=%.d)
AS_DEPS         := $(AS_OBJS:%=%.d)

OBJS            := $(C_OBJS) $(CPP_OBJS) $(AS_OBJS)
DEPS            := $(C_DEPS) $(CPP_DEPS) $(AS_DEPS)


hex:  $(PRG).hex
lst:  $(PRG).lst


$(OBJDIR)/$(PRG).elf : $(OBJS)
    $(CC) $(C_FLAGS) $(LD_FLAGS) $^ -o $@

%.lst: $(OBJDIR)/%.elf
    -@rm $@ 2> /dev/nul
    $(OBJDUMP) -h -s -S $< > $@

%.hex: $(OBJDIR)/%.elf
    -@rm $@ 2> /dev/nul
    $(OBJCOPY) -j .text -j .data -O ihex $< $@


$(C_OBJS) : $(OBJDIR)/%.o : %.c Makefile
    $(CC) -MMD -MF [email protected] -c $(C_FLAGS) $(C_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]

$(CPP_OBJS) : $(OBJDIR)/%.o : %.cpp Makefile
    $(CC) -MMD -MF [email protected] -c $(CPP_FLAGS) $(CPP_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]

$(AS_OBJS) : $(OBJDIR)/%.o : %.S Makefile
    $(CC) -MMD -MF [email protected] -c $(AS_FLAGS) $(AS_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]


clean:
    -@rm -rf $(OBJDIR)/$(PRG).elf
    -@rm -rf $(PRG).lst $(OBJDIR)/$(PRG).map
    -@rm -rf $(PRG).hex $(PRG).bin $(PRG).srec
    -@rm -rf $(PRG)_eeprom.hex $(PRG)_eeprom.bin $(PRG)_eeprom.srec
    -@rm -rf $(MK_DIRS:%=%/*.o) $(MK_DIRS:%=%/*.o.d)
    -@rm -f tags cscope.out

#   -rm -rf $(OBJDIR)/*
#   -rm -rf $(OBJDIR)
#   -rm $(PRG)


tag: tags
tags: $(SRC_FILES)
    if [ -e tags ] ; then ctags -u $? ; else ctags $^ ; fi
    cscope -U -b $^


# include dep. files
ifneq "$(MAKECMDGOALS)" "clean"
-include $(DEPS)
endif


# Create directory
$(shell mkdir $(MK_DIRS) 2>/dev/null)

makef.mk

SAVE_C_SRC := $(C_SRC)
SAVE_CPP_SRC := $(CPP_SRC)
SAVE_AS_SRC := $(AS_SRC)

C_SRC :=
CPP_SRC :=
AS_SRC :=


include $(SRCDIR)/files.mk
MK_DIRS += $(OBJDIR)/$(SRCDIR)


clear_name = $(subst /,_,$(1))


define rename_var
$(2)_$(call clear_name,$(SRCDIR))_$(call clear_name,$(1)) := \
    $($(subst _,,$(2))_$(call clear_name,$(SRCDIR))) $($(call clear_name,$(1)))
$(call clear_name,$(1)) :=
endef


define proc_lang

ORIGIN_SRC_FILES := $($(1)_SRC)

ifneq ($(strip $($(1)_ONLY_FILES)),)
$(1)_SRC := $(filter $($(1)_ONLY_FILES),$($(1)_SRC))
else

ifneq ($(strip $(ONLY_FILES)),)
$(1)_SRC := $(filter $(ONLY_FILES),$($(1)_SRC))
else
$(1)_SRC := $(filter-out $(EXCLUDE_FILES),$($(1)_SRC))
endif

endif

$(1)_ONLY_FILES :=
$(foreach name,$($(1)_SRC),$(eval $(call rename_var,$(name),$(1)_FLAGS)))
$(foreach name,$(ORIGIN_SRC_FILES),$(eval $(call clear_name,$(name)) :=))

endef


$(foreach lang,C CPP AS, $(eval $(call proc_lang,$(lang))))


EXCLUDE_FILES :=
ONLY_FILES :=


SAVE_C_SRC += $(C_SRC:%=$(SRCDIR)/%)
SAVE_CPP_SRC += $(CPP_SRC:%=$(SRCDIR)/%)
SAVE_AS_SRC += $(AS_SRC:%=$(SRCDIR)/%)

C_SRC := $(SAVE_C_SRC)
CPP_SRC := $(SAVE_CPP_SRC)
AS_SRC := $(SAVE_AS_SRC)

./files.mk

C_SRC   := main.c
CPP_SRC :=
AS_SRC  := timer.S

main.c += -DDEBUG

./crc/files.mk

C_SRC    := byte-modbus-crc.c byte-crc8.c
AS_SRC   := modbus-crc.S crc8.S modbus-crc-table.S crc8-table.S

byte-modbus-crc.c += --std=gnu99
byte-crc8.c       += --std=gnu99

How to convert milliseconds into human readable form?

Here's my solution using TimeUnit.

UPDATE: I should point out that this is written in groovy, but Java is almost identical.

def remainingStr = ""

/* Days */
int days = MILLISECONDS.toDays(remainingTime) as int
remainingStr += (days == 1) ? '1 Day : ' : "${days} Days : "
remainingTime -= DAYS.toMillis(days)

/* Hours */
int hours = MILLISECONDS.toHours(remainingTime) as int
remainingStr += (hours == 1) ? '1 Hour : ' : "${hours} Hours : "
remainingTime -= HOURS.toMillis(hours)

/* Minutes */
int minutes = MILLISECONDS.toMinutes(remainingTime) as int
remainingStr += (minutes == 1) ? '1 Minute : ' : "${minutes} Minutes : "
remainingTime -= MINUTES.toMillis(minutes)

/* Seconds */
int seconds = MILLISECONDS.toSeconds(remainingTime) as int
remainingStr += (seconds == 1) ? '1 Second' : "${seconds} Seconds"

OperationalError, no such column. Django

You did every thing correct, I have been gone through same problem. First delete you db and migrations I solved my adding name of my app in makemigrations:

python manage.py makemigrations appname
python manage.py migrate

This will definitely work.

Prevent BODY from scrolling when a modal is opened

The accepted answer doesn't work on mobile (iOS 7 w/ Safari 7, at least) and I don't want MOAR JavaScript running on my site when CSS will do.

This CSS will prevent the background page from scrolling under the modal:

body.modal-open {
    overflow: hidden;
    position: fixed;
}

However, it also has a slight side-affect of essentially scrolling to the top. position:absolute resolves this but, re-introduces the ability to scroll on mobile.

If you know your viewport (my plugin for adding viewport to the <body>) you can just add a css toggle for the position.

body.modal-open {
    // block scroll for mobile;
    // causes underlying page to jump to top;
    // prevents scrolling on all screens
    overflow: hidden;
    position: fixed;
}
body.viewport-lg {
    // block scroll for desktop;
    // will not jump to top;
    // will not prevent scroll on mobile
    position: absolute; 
}

I also add this to prevent the underlying page from jumping left/right when showing/hiding modals.

body {
    // STOP MOVING AROUND!
    overflow-x: hidden;
    overflow-y: scroll !important;
}

this answer is a x-post.

Best way to check for null values in Java?

If at all you going to check with double equal "==" then check null with object ref like

if(null == obj) 

instead of

if(obj == null)

because if you mistype single equal if(obj = null) it will return true (assigning object returns success (which is 'true' in value).

updating Google play services in Emulator

Based from Google documentation,

If you want to test your app on the emulator, expand the directory for Android 4.2.2 (API 17) or a higher version, select Google APIs, and install it. Then create a new AVD with Google APIs as the platform target.

Try to navigate to settings--> apps in your emulator and then find Google Play Services. Check the version number and use it in you build.gradle. To update it with the latest version, you can see it in these documentation and SO question.

cmake - find_library - custom library location

I've encountered a similar scenario. I solved it by adding in this following code just before find_library():

set(CMAKE_PREFIX_PATH /the/custom/path/to/your/lib/)

then it can find the library location.

How do I compare two strings in Perl?

print "Matched!\n" if ($str1 eq $str2)

Perl has seperate string comparison and numeric comparison operators to help with the loose typing in the language. You should read perlop for all the different operators.

Couldn't connect to server 127.0.0.1:27017

Although the answers are received, I would wish to discuss about network errors in MongoDB.

Network errors MongoDB

Setting the safe write concerns is not the full proof method to make sure that we're safe. Let's assume that w=1 & j=true are set, what if the write acknowledgement didn't received from the server? Well, the likelyhood is it didn't happened, but it might have happened. The reason why this might have happened is that there are network errors - there are reasons that we may not receive an affirmative response. So, we can send the request from the application through a driver of language of choice. mongod can complete it successfully and then there could be a TCP reset, and the network actually can get reset in a way that we never receive response. So, we could get an error and on the error, we might assume that we got an error. It didn't happened, but it may happen.

For an insert, it's possible to guard against it. It's possible because if we let the driver create the _id and we do an insert - then we could do that insert multiple times and it would be any harm. Because, if we do this 1st time and we get an error and we're not sure whether or not that insert completed because it's a network error, then we could just do it again. And provided we perform it again, tyr to perform it with the exact _id. The worst case scenario is we'll get a duplicate key error when we try to insert it.

However, an update is where the problem occurs. Especially, the update which is not item potent, that for instance included a $ink command. So, we're telling the database to increment a certain field. Well in that case, if we get a network error and we don't know whether or not the update occurred. Now, maybe we know enough about the values that we can check with them that the update occurred, which is fine. But if we don't know the starting value in the database for that field, then it's not possible for us to know whether or not it occurred or not in case of network error. This kind of issues are extremely rare with a fine network.

And if we really need to avoid it at all costs, what we need to do is turn on all our updates into inserts, by reading the full value of the document out of the database and then potentially deleting it and inserting it again or just inserting a new one.

The reasons why an application may receive an error back even if the write was successful:

  • The network TCP connection between the application and the server was reset after the server received a write but before a response could be sent.
  • The MongoDB server terminates between receiving the write and responding to it.
  • The network fails between the time of the write and the time the client receives a response to the write.

gradlew command not found?

the same problem occurs to me... I check the file wrx permissions with:
$ls -l ./gradlew -> -rw-rw-r-- (no execute permission)

so I use command $chmod +x ./gradlew and this problem solved.

Call PHP function from Twig template

I am surprised the code answer is not posted already, it's a one liner.

You could just {{ categeory_id | getVariations }}

It's a one-liner:

$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));

Manifest Merger failed with multiple errors in Android Studio

Put this at the end of your app module build.gradle:

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '25.3.0'
        }
    }
}}

from this

Show div #id on click with jQuery

The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready() then it should work perfectly well:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").show("slow");
        });

    });

An alternative is to place the <script></script> at the foot of the page, so it's encountered after the DOM has been loaded and ready.

To make the div hide again, once the #music element is clicked, simply use toggle():

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").toggle();
        });
    });

JS Fiddle demo.

And for fading:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").fadeToggle();
        });
    });

JS Fiddle demo.