Programs & Examples On #Osmf

Open Source Media Framework (OSMF) is a free, open source, development framework for building video experiences on the web and desktop. OSMF is a pure ActionScript3.0 based framework and is created by Adobe Systems.

Practical uses for the "internal" keyword in C#

Saw an interesting one the other day, maybe week, on a blog that I can't remember. Basically I can't take credit for this but I thought it might have some useful application.

Say you wanted an abstract class to be seen by another assembly but you don't want someone to be able to inherit from it. Sealed won't work because it's abstract for a reason, other classes in that assembly do inherit from it. Private won't work because you might want to declare a Parent class somewhere in the other assembly.

namespace Base.Assembly
{
  public abstract class Parent
  {
    internal abstract void SomeMethod();
  }

  //This works just fine since it's in the same assembly.
  public class ChildWithin : Parent
  {
    internal override void SomeMethod()
    {
    }
  }
}

namespace Another.Assembly
{
  //Kaboom, because you can't override an internal method
  public class ChildOutside : Parent
  {
  }

  public class Test 
  { 

    //Just fine
    private Parent _parent;

    public Test()
    {
      //Still fine
      _parent = new ChildWithin();
    }
  }
}

As you can see, it effectively allows someone to use the Parent class without being able to inherit from.

Using ng-if as a switch inside ng-repeat?

This one is noteworthy as well

<div ng-repeat="post in posts" ng-if="post.type=='article'">
  <h1>{{post.title}}</h1>
</div>

Explicitly calling return in a function or not

I think of return as a trick. As a general rule, the value of the last expression evaluated in a function becomes the function's value -- and this general pattern is found in many places. All of the following evaluate to 3:

local({
1
2
3
})

eval(expression({
1
2
3
}))

(function() {
1
2
3
})()

What return does is not really returning a value (this is done with or without it) but "breaking out" of the function in an irregular way. In that sense, it is the closest equivalent of GOTO statement in R (there are also break and next). I use return very rarely and never at the end of a function.

 if(a) {
   return(a)
 } else {
   return(b)
 }

... this can be rewritten as if(a) a else b which is much better readable and less curly-bracketish. No need for return at all here. My prototypical case of use of "return" would be something like ...

ugly <- function(species, x, y){
   if(length(species)>1) stop("First argument is too long.")
   if(species=="Mickey Mouse") return("You're kidding!")
   ### do some calculations 
   if(grepl("mouse", species)) {
      ## do some more calculations
      if(species=="Dormouse") return(paste0("You're sleeping until", x+y))
      ## do some more calculations
      return(paste0("You're a mouse and will be eating for ", x^y, " more minutes."))
      }
   ## some more ugly conditions
   # ...
   ### finally
   return("The end")
   }

Generally, the need for many return's suggests that the problem is either ugly or badly structured.

[EDIT]

return doesn't really need a function to work: you can use it to break out of a set of expressions to be evaluated.

getout <- TRUE 
# if getout==TRUE then the value of EXP, LOC, and FUN will be "OUTTA HERE"
# .... if getout==FALSE then it will be `3` for all these variables    

EXP <- eval(expression({
   1
   2
   if(getout) return("OUTTA HERE")
   3
   }))

LOC <- local({
   1
   2
   if(getout) return("OUTTA HERE")
   3
   })

FUN <- (function(){
   1
   2
   if(getout) return("OUTTA HERE")
   3
   })()

identical(EXP,LOC)
identical(EXP,FUN)

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

Here is the solution for Ubuntu users

First we have to stop postgresql

sudo /etc/init.d/postgresql stop

Create a new file called /etc/apt/sources.list.d/pgdg.list and add below line

deb http://apt.postgresql.org/pub/repos/apt/ utopic-pgdg main

Follow below commands

wget -q -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get install postgresql-9.4
sudo pg_dropcluster --stop 9.4 main 
sudo /etc/init.d/postgresql start

Now we have everything, just need to upgrade it as below

sudo pg_upgradecluster 9.3 main
sudo pg_dropcluster 9.3 main

That's it. Mostly upgraded cluster will run on port number 5433. Check it with below command

sudo pg_lsclusters

Convert to/from DateTime and Time in Ruby

Unfortunately, the DateTime.to_time, Time.to_datetime and Time.parse functions don't retain the timezone info. Everything is converted to local timezone during conversion. Date arithmetics still work but you won't be able to display the dates with their original timezones. That context information is often important. For example, if I want to see transactions performed during business hours in New York I probably prefer to see them displayed in their original timezones, not my local timezone in Australia (which 12 hrs ahead of New York).

The conversion methods below do keep that tz info.

For Ruby 1.8, look at Gordon Wilson's answer. It's from the good old reliable Ruby Cookbook.

For Ruby 1.9, it's slightly easier.

require 'date'

# Create a date in some foreign time zone (middle of the Atlantic)
d = DateTime.new(2010,01,01, 10,00,00, Rational(-2, 24))
puts d

# Convert DateTime to Time, keeping the original timezone
t = Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec, d.zone)
puts t

# Convert Time to DateTime, keeping the original timezone
d = DateTime.new(t.year, t.month, t.day, t.hour, t.min, t.sec, Rational(t.gmt_offset / 3600, 24))
puts d

This prints the following

2010-01-01T10:00:00-02:00
2010-01-01 10:00:00 -0200
2010-01-01T10:00:00-02:00

The full original DateTime info including timezone is kept.

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

Quoting MSDN:

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing.

In practice this means that some of the statements might fail, leaving the transaction 'partially completed', and there might be no sign of this failure for a caller.

A simple example:

INSERT INTO t1 VALUES (1/0)    
INSERT INTO t2 VALUES (1/1)    
SELECT 'Everything is fine'

This code would execute 'successfully' with XACT_ABORT OFF, and will terminate with an error with XACT_ABORT ON ('INSERT INTO t2' will not be executed, and a client application will raise an exception).

As a more flexible approach, you could check @@ERROR after each statement (old school), or use TRY...CATCH blocks (MSSQL2005+). Personally I prefer to set XACT_ABORT ON whenever there is no reason for some advanced error handling.

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is the default library path which is accessed to check for available dynamic and shared libraries. It is specific to linux distributions.

It is similar to environment variable PATH in windows that linker checks for possible implementations during linking time.

How do I left align these Bootstrap form items?

I was having the exact same problem. I found the issue within bootstrap.min.css. You need to change the label: label {display:inline-block;} to label {display:block;}

connect to host localhost port 22: Connection refused

if you are using centOS or Red Hat, you should first update SElinux. Execute the following statement

ausearch -c 'sshd' --raw | audit2allow -M my-sshd

then you need to execute

semodule -i my-sshd.pp

good luck

Escaping backslash in string - javascript

Add an input id to the element and do something like that:

document.getElementById('inputId').value.split(/[\\$]/).pop()

Datatable to html Table

use this function:

    public static string ConvertDataTableToHTML(DataTable dt)
    {
        string html = "<table>";
        //add header row
        html += "<tr>";
        for(int i=0;i<dt.Columns.Count;i++)
            html+="<td>"+dt.Columns[i].ColumnName+"</td>";
        html += "</tr>";
        //add rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            html += "<tr>";
            for (int j = 0; j< dt.Columns.Count; j++)
                html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
            html += "</tr>";
        }
        html += "</table>";
        return html;
    }

Global variables in Javascript across multiple files

//Javascript file 1

localStorage.setItem('Data',10);

//Javascript file 2

var number=localStorage.getItem('Data');

Don't forget to link your JS files in html :)

Ansible: deploy on multiple hosts in the same time

By default Ansible will attempt to run on all hosts in parallel. See these Ansible docs for details. You can also use the serial parameter to limit the number of parallel hosts you want to be processed at any given time, so if you want to have a playbook run on just one host at a time you can specify serial:1, etc.

Ansible is designed so that each task will be run on all hosts before continuing on to the next task. So if you have 3 tasks it will ensure task 1 runs on all your hosts first, then task 2 is run, then task 3 is run. See this section of the Ansible docs for more details on this.

What's the difference between "2*2" and "2**2" in Python?

To specifically answer your question Why is the code1 used if we can use code2? I might suggest that the programmer was thinking in a mathematically broader sense. Specifically, perhaps the broader equation is a power equation, and the fact that both first numbers are "2" is more coincidence than mathematical reality. I'd want to make sure that the broader context of the code supports it being

var = x * x * y
in all cases, rather than in this specific case alone. This could get you in big trouble if x is anything but 2.

Change name of folder when cloning from GitHub?

In case you want to clone a specific branch only, then,

git clone -b <branch-name> <repo-url> <destination-folder-name>

for example,

git clone -b dev https://github.com/sferik/sign-in-with-twitter.git signin

Rename Oracle Table or View

In order to rename a table in a different schema, try:

ALTER TABLE owner.mytable RENAME TO othertable;

The rename command (as in "rename mytable to othertable") only supports renaming a table in the same schema.

C# DataRow Empty-check

I know this has been answered already and it's an old question, but here's an extension method to do the same:

public static class DataExtensions
{
    public static bool AreAllCellsEmpty(this DataRow row)
    {
        var itemArray = row.ItemArray;
        if(itemArray==null)
            return true;
        return itemArray.All(x => string.IsNullOrWhiteSpace(x.ToString()));            
    }
}

And you use it like so:

if (dr.AreAllCellsEmpty())
// etc

"Cannot instantiate the type..."

I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util instead of implementing my own class.

So if the previous answers did not help you, please check that you import the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.

For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :

import java.util.*; // replace this line
import myCollections.Queue; // by this line

     Queue<Edge> theQueue = new Queue<Edge>();

Insert multiple rows with one query MySQL

While inserting multiple rows with a single INSERT statement is generally faster, it leads to a more complicated and often unsafe code. Below I present the best practices when it comes to inserting multiple records in one go using PHP.

To insert multiple new rows into the database at the same time, one needs to follow the following 3 steps:

  1. Start transaction (disable autocommit mode)
  2. Prepare INSERT statement
  3. Execute it multiple times

Using database transactions ensures that the data is saved in one piece and significantly improves performance.

How to properly insert multiple rows using PDO

PDO is the most common choice of database extension in PHP and inserting multiple records with PDO is quite simple.

$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

// Start transaction
$pdo->beginTransaction();

// Prepare statement
$stmt = $pdo->prepare('INSERT 
    INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
    VALUES (?,?,?,?,?,?,?)');

// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
    // All seven parameters are passed into the execute() in a form of an array
    $stmt->execute([$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
}

// Commit the data into the database
$pdo->commit();

How to properly insert multiple rows using mysqli

The mysqli extension is a little bit more cumbersome to use but operates on very similar principles. The function names are different and take slightly different parameters.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'user', 'password', 'database');
$mysqli->set_charset('utf8mb4');

// Start transaction
$mysqli->begin_transaction();

// Prepare statement
$stmt = $mysqli->prepare('INSERT 
    INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
    VALUES (?,?,?,?,?,?,?)');

// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
    // mysqli doesn't accept bind in execute yet, so we have to bind the data first
    // The first argument is a list of letters denoting types of parameters. It's best to use 's' for all unless you need a specific type
    // bind_param doesn't accept an array so we need to unpack it first using '...'
    $stmt->bind_param('sssssss', ...[$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
    $stmt->execute();
}

// Commit the data into the database
$mysqli->commit();

Performance

Both extensions offer the ability to use transactions. Executing prepared statement with transactions greatly improves performance, but it's still not as good as a single SQL query. However, the difference is so negligible that for the sake of conciseness and clean code it is perfectly acceptable to execute prepared statements multiple times. If you need a faster option to insert many records into the database at once, then chances are that PHP is not the right tool.

Non-recursive depth first search algorithm

http://www.youtube.com/watch?v=zLZhSSXAwxI

Just watched this video and came out with implementation. It looks easy for me to understand. Please critique this.

visited_node={root}
stack.push(root)
while(!stack.empty){
  unvisited_node = get_unvisited_adj_nodes(stack.top());
  If (unvisited_node!=null){
     stack.push(unvisited_node);  
     visited_node+=unvisited_node;
  }
  else
     stack.pop()
}

Usage of __slots__?

A very simple example of __slot__ attribute.

Problem: Without __slots__

If I don't have __slot__ attribute in my class, I can add new attributes to my objects.

class Test:
    pass

obj1=Test()
obj2=Test()

print(obj1.__dict__)  #--> {}
obj1.x=12
print(obj1.__dict__)  # --> {'x': 12}
obj1.y=20
print(obj1.__dict__)  # --> {'x': 12, 'y': 20}

obj2.x=99
print(obj2.__dict__)  # --> {'x': 99}

If you look at example above, you can see that obj1 and obj2 have their own x and y attributes and python has also created a dict attribute for each object (obj1 and obj2).

Suppose if my class Test has thousands of such objects? Creating an additional attribute dict for each object will cause lot of overhead (memory, computing power etc.) in my code.

Solution: With __slots__

Now in the following example my class Test contains __slots__ attribute. Now I can't add new attributes to my objects (except attribute x) and python doesn't create a dict attribute anymore. This eliminates overhead for each object, which can become significant if you have many objects.

class Test:
    __slots__=("x")

obj1=Test()
obj2=Test()
obj1.x=12
print(obj1.x)  # --> 12
obj2.x=99
print(obj2.x)  # --> 99

obj1.y=28
print(obj1.y)  # --> AttributeError: 'Test' object has no attribute 'y'

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

Using number as "index" (JSON)

JSON only allows key names to be strings. Those strings can consist of numerical values.

You aren't using JSON though. You have a JavaScript object literal. You can use identifiers for keys, but an identifier can't start with a number. You can still use strings though.

var Game={
    "status": [
        {
            "0": "val",
            "1": "val",
            "2": "val"
        },
        {
            "0": "val",
            "1": "val",
            "2": "val"
        }
    ]
}

If you access the properties with dot-notation, then you have to use identifiers. Use square bracket notation instead: Game.status[0][0].

But given that data, an array would seem to make more sense.

var Game={
    "status": [
        [
            "val",
            "val",
            "val"
        ],
        [
            "val",
            "val",
            "val"
        ]
    ]
}

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

To add to Kevin's answer, I find that in practice nearly all of your non-trivial Spring MVC applications will require an application context (as opposed to only the spring MVC dispatcher servlet context). It is in the application context that you should configure all non-web related concerns such as:

  • Security
  • Persistence
  • Scheduled Tasks
  • Others?

To make this a bit more concrete, here's an example of the Spring configuration I've used when setting up a modern (Spring version 4.1.2) Spring MVC application. Personally, I prefer to still use a WEB-INF/web.xml file but that's really the only xml configuration in sight.

WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  
  <filter>
    <filter-name>openEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
  </filter>
  
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
  </filter>
 
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>openEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
      <param-name>contextClass</param-name>
      <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </init-param>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>com.company.config.WebConfig</param-value>
    </init-param>
  </servlet>
  
  <context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.company.config.AppConfig</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <jsp-config>
    <jsp-property-group>
      <url-pattern>*.jsp</url-pattern>
      <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
  </jsp-config>
  
</web-app>

WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.company.controller")
public class WebConfig {

  @Bean
  public InternalResourceViewResolver getInternalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
  }
}

AppConfig.java

@Configuration
@ComponentScan(basePackages = "com.company")
@Import(value = {SecurityConfig.class, PersistenceConfig.class, ScheduleConfig.class})
public class AppConfig {
  // application domain @Beans here...
}

Security.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private LdapUserDetailsMapper ldapUserDetailsMapper;

  @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/").permitAll()
      .antMatchers("/**/js/**").permitAll()
      .antMatchers("/**/images/**").permitAll()
      .antMatchers("/**").access("hasRole('ROLE_ADMIN')")
      .and().formLogin();

    http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
    }

  @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      auth.ldapAuthentication()
      .userSearchBase("OU=App Users")
      .userSearchFilter("sAMAccountName={0}")
      .groupSearchBase("OU=Development")
      .groupSearchFilter("member={0}")
      .userDetailsContextMapper(ldapUserDetailsMapper)
      .contextSource(getLdapContextSource());
    }

  private LdapContextSource getLdapContextSource() {
    LdapContextSource cs = new LdapContextSource();
    cs.setUrl("ldaps://ldapServer:636");
    cs.setBase("DC=COMPANY,DC=COM");
    cs.setUserDn("CN=administrator,CN=Users,DC=COMPANY,DC=COM");
    cs.setPassword("password");
    cs.afterPropertiesSet();
    return cs;
  }
}

PersistenceConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(transactionManagerRef = "getTransactionManager", entityManagerFactoryRef = "getEntityManagerFactory", basePackages = "com.company")
public class PersistenceConfig {

  @Bean
  public LocalContainerEntityManagerFactoryBean getEntityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
    lef.setDataSource(dataSource);
    lef.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
    lef.setPackagesToScan("com.company");
    return lef;
  }

  private HibernateJpaVendorAdapter getHibernateJpaVendorAdapter() {
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    hibernateJpaVendorAdapter.setDatabase(Database.ORACLE);
    hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect");
    hibernateJpaVendorAdapter.setShowSql(false);
    hibernateJpaVendorAdapter.setGenerateDdl(false);
    return hibernateJpaVendorAdapter;
  }

  @Bean
  public JndiObjectFactoryBean getDataSource() {
    JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
    jndiFactoryBean.setJndiName("java:comp/env/jdbc/AppDS");
    return jndiFactoryBean;
  }

  @Bean
  public JpaTransactionManager getTransactionManager(DataSource dataSource) {
    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
    jpaTransactionManager.setEntityManagerFactory(getEntityManagerFactory(dataSource).getObject());
    jpaTransactionManager.setDataSource(dataSource);
    return jpaTransactionManager;
  }
}

ScheduleConfig.java

@Configuration
@EnableScheduling
public class ScheduleConfig {
  @Autowired
  private EmployeeSynchronizer employeeSynchronizer;

  // cron pattern: sec, min, hr, day-of-month, month, day-of-week, year (optional)
  @Scheduled(cron="0 0 0 * * *")
  public void employeeSync() {
    employeeSynchronizer.syncEmployees();
  }
}

As you can see, the web configuration is only a small part of the overall spring web application configuration. Most web applications I've worked with have many concerns that lie outside of the dispatcher servlet configuration that require a full-blown application context bootstrapped via the org.springframework.web.context.ContextLoaderListener in the web.xml.

base_url() function not working in codeigniter

Load url helper in controller

$this->load->helper('url');

CSS selector for "foo that contains bar"?

No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.

Here are some similar questions with similar results:

How to read integer values from text file

use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.

Trying to SSH into an Amazon Ec2 instance - permission error

I know this question has been answered already but for those that have tried them all and you are still getting the annoying "Permission denied (publickey)". Try running your command with SUDO. Of course this is a temporary solution and you should set permissions correctly but at least that will let you identify that your current user is not running with the privileges you need (as you assumed)

sudo ssh -i amazonec2.pem ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com

Once you do this you'll get a message like this:

Please login as the user "ec2-user" rather than the user "root"

Which is also sparsely documented. In that case just do this:

sudo ssh -i amazonec2.pem ec2-xxx-xxx-xxx-xxx.us-west-2.compute.amazonaws.com -l ec2-user

And you'll get the glorious:

   __|  __|_  )
   _|  (     /   Amazon Linux AMI
  ___|\___|___|

How can I remove an element from a list, with lodash?

As lyyons pointed out in the comments, more idiomatic and lodashy way to do this would be to use _.remove, like this

_.remove(obj.subTopics, {
    subTopicId: stToDelete
});

Apart from that, you can pass a predicate function whose result will be used to determine if the current element has to be removed or not.

_.remove(obj.subTopics, function(currentObject) {
    return currentObject.subTopicId === stToDelete;
});

Alternatively, you can create a new array by filtering the old one with _.filter and assign it to the same object, like this

obj.subTopics = _.filter(obj.subTopics, function(currentObject) {
    return currentObject.subTopicId !== stToDelete;
});

Or

obj.subTopics = _.filter(obj.subTopics, {subTopicId: stToKeep});

jquery UI dialog: how to initialize without a title bar?

This is the easiest way to do it and it will only remove the titlebar in that one specific dialog;

$('.dialog_selector').find('.ui-dialog-titlebar').hide();

HTML5 Video tag not working in Safari , iPhone and iPad

For my use case there were two things:

  1. I wasn't using the new attribute / webkit's policy playsinline;
  2. My video / mime-type or whathathell wasn't properly encoded, so I used this site to convert it to all formats I needed: https://pt.converterpoint.com/

o/

Compare two DataFrames and output their differences side-by-side

The first part is similar to Constantine, you can get the boolean of which rows are empty*:

In [21]: ne = (df1 != df2).any(1)

In [22]: ne
Out[22]:
0    False
1     True
2     True
dtype: bool

Then we can see which entries have changed:

In [23]: ne_stacked = (df1 != df2).stack()

In [24]: changed = ne_stacked[ne_stacked]

In [25]: changed.index.names = ['id', 'col']

In [26]: changed
Out[26]:
id  col
1   score         True
2   isEnrolled    True
    Comment       True
dtype: bool

Here the first entry is the index and the second the columns which has been changed.

In [27]: difference_locations = np.where(df1 != df2)

In [28]: changed_from = df1.values[difference_locations]

In [29]: changed_to = df2.values[difference_locations]

In [30]: pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)
Out[30]:
               from           to
id col
1  score       1.11         1.21
2  isEnrolled  True        False
   Comment     None  On vacation

* Note: it's important that df1 and df2 share the same index here. To overcome this ambiguity, you can ensure you only look at the shared labels using df1.index & df2.index, but I think I'll leave that as an exercise.

Convert month int to month name

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");

How can I pass a Bitmap object from one activity to another

All of the above solutions doesn't work for me, Sending bitmap as parceableByteArray also generates error android.os.TransactionTooLargeException: data parcel size.

Solution

  1. Saved the bitmap in internal storage as:
public String saveBitmap(Bitmap bitmap) {
        String fileName = "ImageName";//no .png or .jpg needed
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
            fo.write(bytes.toByteArray());
            // remember close file output
            fo.close();
        } catch (Exception e) {
            e.printStackTrace();
            fileName = null;
        }
        return fileName;
    }
  1. and send in putExtra(String) as
Intent intent = new Intent(ActivitySketcher.this,ActivityEditor.class);
intent.putExtra("KEY", saveBitmap(bmp));
startActivity(intent);
  1. and Receive it in other activity as:
if(getIntent() != null){
  try {
           src = BitmapFactory.decodeStream(openFileInput("myImage"));
       } catch (FileNotFoundException e) {
            e.printStackTrace();
      }

 }


Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

How to convert text column to datetime in SQL

Use convert with style 101.

select convert(datetime, Remarks, 101)

If your column is really text you need to convert to varchar before converting to datetime

select convert(datetime, convert(varchar(30), Remarks), 101)

How to get the current time in milliseconds in C Programming

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

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

I would like to return two values from a function in two separate variables.

What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice() because that would call the function twice.

Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).

When i tried to to use return i, card, it returns a tuple and this is not what i want.

Actually, it's exactly what you want. All you have to do is take the tuple apart again.

And i want to be able to use these values separately.

So just grab the values out of the tuple.

The easiest way to do this is by unpacking:

a, b = select_choice()

anchor jumping by using javascript

Because when you do

window.location.href = "#"+anchor;

You load a new page, you can do:

<a href="#" onclick="jumpTo('one');">One</a>
<a href="#" id="one"></a>

<script>

    function getPosition(element){
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;

        do{
            left += e.offsetLeft;
            top += e.offsetTop;
        }while(e = e.offsetParent);

        return [left, top];
    }

    function jumpTo(id){    
        window.scrollTo(getPosition(id));
    }

</script>

What is the most efficient way to deep clone an object in JavaScript?

Deep copy by performance: Ranked from best to worst

  • Reassignment "=" (string arrays, number arrays - only)
  • Slice (string arrays, number arrays - only)
  • Concatenation (string arrays, number arrays - only)
  • Custom function: for-loop or recursive copy
  • jQuery's $.extend
  • JSON.parse (string arrays, number arrays, object arrays - only)
  • Underscore.js's _.clone (string arrays, number arrays - only)
  • Lo-Dash's _.cloneDeep

Deep copy an array of strings or numbers (one level - no reference pointers):

When an array contains numbers and strings - functions like .slice(), .concat(), .splice(), the assignment operator "=", and Underscore.js's clone function; will make a deep copy of the array's elements.

Where reassignment has the fastest performance:

var arr1 = ['a', 'b', 'c'];
var arr2 = arr1;
arr1 = ['a', 'b', 'c'];

And .slice() has better performance than .concat(), http://jsperf.com/duplicate-array-slice-vs-concat/3

var arr1 = ['a', 'b', 'c'];  // Becomes arr1 = ['a', 'b', 'c']
var arr2a = arr1.slice(0);   // Becomes arr2a = ['a', 'b', 'c'] - deep copy
var arr2b = arr1.concat();   // Becomes arr2b = ['a', 'b', 'c'] - deep copy

Deep copy an array of objects (two or more levels - reference pointers):

var arr1 = [{object:'a'}, {object:'b'}];

Write a custom function (has faster performance than $.extend() or JSON.parse):

function copy(o) {
   var out, v, key;
   out = Array.isArray(o) ? [] : {};
   for (key in o) {
       v = o[key];
       out[key] = (typeof v === "object" && v !== null) ? copy(v) : v;
   }
   return out;
}

copy(arr1);

Use third-party utility functions:

$.extend(true, [], arr1); // Jquery Extend
JSON.parse(arr1);
_.cloneDeep(arr1); // Lo-dash

Where jQuery's $.extend has better performance:

Disable autocomplete via CSS

I tried all suggested ways from this question answers and other articles in the web but not working anyway. I tried autocomplete="new-random-value", autocomplete="off" in form element, using client-side script as below but outside of $(document).ready() as one of the user mentioned:

$(':input').on('focus', function () {
  $(this).attr('autocomplete', 'off')
});

I found maybe another priority in the browser cause this weird behavior! So I searched more and finally, I read again carefully below lines from this good article:

For this reason, many modern browsers do not support autocomplete="off" for login fields:

If a site sets autocomplete="off" for a , and the form includes username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page. If a site sets autocomplete="off" for username and password fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page. This is the behavior in Firefox (since version 38), Google Chrome (since 34), and Internet Explorer (since version 11).

If you are defining a user management page where a user can specify a new password for another person, and therefore you want to prevent auto-filling of password fields, you can use autocomplete="new-password"; however, support for this value has not been implemented on Firefox.

It's just worked. I tried in chrome specially and I hope this continues working and help others.

How to automatically start a service when running a docker container?

Simple! Add at the end of dockerfile:

ENTRYPOINT service mysql start && /bin/bash

gpg: no valid OpenPGP data found

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

apt-get update
apt-get install ca-certificates

How to convert List to Json in Java

For simplicity and well structured sake, use SpringMVC. It's just so simple.

@RequestMapping("/carlist.json")
public @ResponseBody List<String> getCarList() {
    return carService.getAllCars();
}

Reference and credit: https://github.com/xvitcoder/spring-mvc-angularjs

How to upload multiple files using PHP, jQuery and AJAX

Finally I have found the solution by using the following code:

$('body').on('click', '#upload', function(e){
        e.preventDefault();
        var formData = new FormData($(this).parents('form')[0]);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            success: function (data) {
                alert("Data Uploaded: "+data);
            },
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
});

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

           @Html.RadioButton("Insured.GenderType", 1, (Model.Insured.GenderType == 1 ))
           @Web.Mvc.Claims.Resources.PartyResource.MaleLabel
           @Html.RadioButton("Insured.GenderType", 2, Model.Insured.GenderType == 2)
           @Web.Mvc.Claims.Resources.PartyResource.FemaleLabel

What data type to use for money in Java?

You can use Money and Currency API (JSR 354). You can use this API in, provided you add appropriate dependencies to your project.

For Java 8, add the following reference implementation as a dependency to your pom.xml:

<dependency>
    <groupId>org.javamoney</groupId>
    <artifactId>moneta</artifactId>
    <version>1.0</version>
</dependency>

This dependency will transitively add javax.money:money-api as a dependency.

You can then use the API:

package com.example.money;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

import java.util.Locale;

import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.MonetaryRounding;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;

import org.junit.Test;

public class MoneyTest {

    @Test
    public void testMoneyApi() {
        MonetaryAmount eurAmount1 = Monetary.getDefaultAmountFactory().setNumber(1.1111).setCurrency("EUR").create();
        MonetaryAmount eurAmount2 = Monetary.getDefaultAmountFactory().setNumber(1.1141).setCurrency("EUR").create();

        MonetaryAmount eurAmount3 = eurAmount1.add(eurAmount2);
        assertThat(eurAmount3.toString(), is("EUR 2.2252"));

        MonetaryRounding defaultRounding = Monetary.getDefaultRounding();
        MonetaryAmount eurAmount4 = eurAmount3.with(defaultRounding);
        assertThat(eurAmount4.toString(), is("EUR 2.23"));

        MonetaryAmountFormat germanFormat = MonetaryFormats.getAmountFormat(Locale.GERMAN);
        assertThat(germanFormat.format(eurAmount4), is("EUR 2,23") );
    }
}

Open fancybox from function

The answers seems a bit over complicated. I hope I didn't misunderstand the question.

If you simply want to open a fancy box from a click to an "A" tag. Just set your html to

<a id="my_fancybox" href="#contentdiv">click me</a>

The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:

$('#my_fancybox').fancybox({
    'autoScale': true,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 500,
    'speedOut': 300,
    'autoDimensions': true,
    'centerOnScroll': true,
});

This will show a fancybox containing "contentdiv" when your anchor tag is clicked.

How to set a ripple effect on textview or imageview on Android?

In addition to @Bikesh M Annur's answer, be sure to update your support libraries. Previously I was using 23.1.1 and nothing happened. Updating it to 23.3.0 did the trick.

Best practice for partial updates in a RESTful service

I am running into a similar problem. PUT on a sub-resource seems to work when you want to update only a single field. However, sometimes you want to update a bunch of things: Think of a web form representing the resource with option to change some entries. The user's submission of form should not result in a multiple PUTs.

Here are two solution that I can think of:

  1. do a PUT with the entire resource. On the server-side, define the semantics that a PUT with the entire resource ignores all the values that haven't changed.

  2. do a PUT with a partial resource. On the server-side, define the semantics of this to be a merge.

2 is just a bandwidth-optimization of 1. Sometimes 1 is the only option if the resource defines some fields are required fields (think proto buffers).

The problem with both these approaches is how to clear a field. You will have to define a special null value (especially for proto buffers since null values are not defined for proto buffers) that will cause clearing of the field.

Comments?

Keyboard shortcut to comment lines in Sublime Text 3

I might be late to the party but as of my build 3176 it appears the bug is fixed. Just used Ctrl+T and it worked for a CSS file (Kubuntu 18.10)

Use of def, val, and var in scala

Let's take this:

class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
person.age=20
println(person.age)

and rewrite it with equivalent code

class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
(new Person("Kumar", 12)).age_=(20)
println((new Person("Kumar", 12)).age)

See, def is a method. It will execute each time it is called, and each time it will return (a) new Person("Kumar", 12). And these is no error in the "assignment" because it isn't really an assignment, but just a call to the age_= method (provided by var).

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Communicating between a fragment and an activity - best practices

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.

Once it has implemented that interface, you could do anything you want in the method it overrides.

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.

There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.

I hope this was helpful to you!

Does C# support multiple inheritance?

Actually, it depends on your definition of inheritance:

  • you can inherit implementation (members, i.e. data and behavior) from a single class, but
  • you can inherit interfaces from multiple, well, interfaces.

This is not what is usually meant by the term "inheritance", but it is also not entirely unreasonable to define it this way.

How to remove leading and trailing zeros in a string? Python

You can simply do this with a bool:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

How to get first character of a string in SQL?

LEFT(colName, 1) will also do this, also. It's equivalent to SUBSTRING(colName, 1, 1).

I like LEFT, since I find it a bit cleaner, but really, there's no difference either way.

Laravel-5 how to populate select box from database with id value and name value

For Laravel 5 :

$items = Items::lists('name', 'id');

Push an item onto the beginning of the collection.

$items->prepend($value, $key = null);

HTML CSS Button Positioning

as I expected, yeah, it's because the whole DOM element is being pushed down. You have multiple options. You can put the buttons in separate divs, and float them so that they don't affect each other. the simpler solution is to just set the :active button to position:relative; and use top instead of margin or line-height. example fiddle: http://jsfiddle.net/5CZRP/

Changing color of Twitter bootstrap Nav-Pills

This is specific to Bootstrap 4.0.

HTML

<ul class="nav nav-pills">
  <li class="nav-item">
    <a class="nav-link nav-link-color" href="#about">home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link nav-link-color"  href="#contact">contact</a>
  </li>
</ul>

CSS

.nav-pills > li > a.active {
  background-color: #ffffff !important;
  color: #ffffff !important;
}

.nav-pills > li > a:hover {
  color: #ffffff !important;
}

.nav-link-color {
  color: #ffffff;
}

How do I combine 2 javascript variables into a string

Use the concatenation operator +, and the fact that numeric types will convert automatically into strings:

var a = 1;
var b = "bob";
var c = b + a;

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

implementing merge sort in C++

I have completed @DietmarKühl s way of merge sort. Hope it helps all.

template <typename T>
void merge(vector<T>& array, vector<T>& array1, vector<T>& array2) {
    array.clear();

    int i, j, k;
    for( i = 0, j = 0, k = 0; i < array1.size() && j < array2.size(); k++){
        if(array1.at(i) <= array2.at(j)){
            array.push_back(array1.at(i));
            i++;
        }else if(array1.at(i) > array2.at(j)){
            array.push_back(array2.at(j));
            j++;
        }
        k++;
    }

    while(i < array1.size()){
        array.push_back(array1.at(i));
        i++;
    }

    while(j < array2.size()){
        array.push_back(array2.at(j));
        j++;
    }
}

template <typename T>
void merge_sort(std::vector<T>& array) {
    if (1 < array.size()) {
        std::vector<T> array1(array.begin(), array.begin() + array.size() / 2);
        merge_sort(array1);
        std::vector<T> array2(array.begin() + array.size() / 2, array.end());
        merge_sort(array2);
        merge(array, array1, array2);
    }
}

Pass a datetime from javascript to c# (Controller)

Try to use toISOString(). It returns string in ISO8601 format.

GET method

javascript

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});

c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}

POST method

javascript

$.post('/example/do', { date: date.toISOString() }, function (result) {
    console.log(result);
});

c#

[HttpPost]
public JsonResult Do(DateTime date)
{
     return Json(date.ToString());
}

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

Java: set timeout on a certain block of code?

If you want a CompletableFuture way you could have a method like

public MyResponseObject retrieveDataFromEndpoint() {

   CompletableFuture<MyResponseObject> endpointCall 
       = CompletableFuture.supplyAsync(() ->
             yourRestService.callEnpoint(withArg1, withArg2));

   try {
       return endpointCall.get(10, TimeUnit.MINUTES);
   } catch (TimeoutException 
               | InterruptedException 
               | ExecutionException e) {
       throw new RuntimeException("Unable to fetch data", e);
   }
}

If you're using spring, you could annotate the method with a @Retryable so that it retries the method three times if an exception is thrown.

CSS set li indent

I found that doing it in two relatively simple steps seemed to work quite well. The first css definition for ul sets the base indent that you want for the list as a whole. The second definition sets the indent value for each nested list item within it. In my case they are the same, but you can obviously pick whatever you want.

ul {
    margin-left: 1.5em;
}

ul > ul {
    margin-left: 1.5em;
}

Get source JARs from Maven repository

For debugging you can also use a "Java Decompiler" such as: JAD and decompile source on the fly (although the generated source is never the same as the original). Then install JAD as a plugin in Eclipse or your favorite IDE.

In excel how do I reference the current row but a specific column?

To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1) and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row

If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)

Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.

Html helper for <input type="file" />

Improved version of Paulius Zaliaduonis' answer:

In order to make the validation work properly I had to change the Model to:

public class ViewModel
{
      public HttpPostedFileBase File { get; set; }

        [Required(ErrorMessage="A header image is required"), FileExtensions(ErrorMessage = "Please upload an image file.")]
        public string FileName
        {
            get
            {
                if (File != null)
                    return File.FileName;
                else
                    return String.Empty;
            }
        }
}

and the view to:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m => m.File, new { type = "file" })
    @Html.ValidationMessageFor(m => m.FileName)
}

This is required because what @Serj Sagan wrote about FileExtension attribute working only with strings.

How to print a float with 2 decimal places in Java?

Try this:-

private static String getDecimalFormat(double value) {

    String getValue = String.valueOf(value).split("[.]")[1];

      if (getValue.length() == 1) {
          return String.valueOf(value).split("[.]")[0] +
                "."+ getValue.substring(0, 1) + 
                String.format("%0"+1+"d", 0);
       } else {
          return String.valueOf(value).split("[.]")[0]
            +"." + getValue.substring(0, 2);
      }


 }

how do you view macro code in access?

In Access 2010, go to the Create tab on the ribbon. Click Macro. An "Action Catalog" panel should appear on the right side of the screen. Underneath, there's a section titled "In This Database." Clicking on one of the macro names should display its code.

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

I also have the same error. I have updated the jackson library version and error has gone.

<!-- Jackson to convert Java object to Json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

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

and also check your data classes that have you created getters and setters for all the properties.

How do I crop an image in Java?

This is a method which will work:

import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Graphics;

public BufferedImage crop(BufferedImage src, Rectangle rect)
{
    BufferedImage dest = new BufferedImage(rect.getWidth(), rect.getHeight(), BufferedImage.TYPE_ARGB_PRE);
    Graphics g = dest.getGraphics();
    g.drawImage(src, 0, 0, rect.getWidth(), rect.getHeight(), rect.getX(), rect.getY(), rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(), null);
    g.dispose();
    return dest;
}

Of course you have to make your own JComponent:

import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Graphics;
import javax.swing.JComponent;

public class JImageCropComponent extends JComponent implements MouseListener, MouseMotionListener
{
   private BufferedImage img;
   private int x1, y1, x2, y2;

   public JImageCropComponent(BufferedImage img)
   {
       this.img = img;
       this.addMouseListener(this);
       this.addMouseMotionListener(this);
   }

   public void setImage(BufferedImage img)
   {
       this.img = img;
   }

   public BufferedImage getImage()
   {
       return this;
   }

   @Override
   public void paintComponent(Graphics g)
   {
      g.drawImage(img, 0, 0, this);
      if (cropping)
      {
          // Paint the area we are going to crop.
          g.setColor(Color.RED);
          g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2));
      }
   }

   @Override
   public void mousePressed(MouseEvent evt)
   {
       this.x1 = evt.getX();
       this.y1 = evt.getY();
   }

   @Override
   public void mouseReleased(MouseEvent evt)
   {
       this.cropping = false;
       // Now we crop the image;
       // This is the method a wrote in the other snipped
       BufferedImage cropped = crop(new Rectangle(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2));
       // Now you have the cropped image;
       // You have to choose what you want to do with it
       this.img = cropped;
   }

   @Override
   public void mouseDragged(MouseEvent evt)
   {
       cropping = true;
       this.x2 = evt.getX();
       this.y2 = evt.getY();
   }

   //TODO: Implement the other unused methods from Mouse(Motion)Listener

}

I didn't test it. Maybe there are some mistakes (I'm not sure about all the imports).

You can put the crop(img, rect) method in this class. Hope this helps.

Validate phone number with JavaScript

If you are looking for 10 and only 10 digits, ignore everything but the digits-

   return value.match(/\d/g).length===10;

HTML: how to make 2 tables with different CSS

<table id="table1"></table>
<table id="table2"></table>

or

<table class="table1"></table>
<table class="table2"></table>

Undefined reference to pthread_create in Linux

For Linux the correct command is:

gcc -o term term.c -lpthread
  1. you have to put -lpthread just after the compile command,this command will tell to the compiler to execute program with pthread.h library.
  2. gcc -l links with a library file.Link -l with library name without the lib prefix.

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

Java Wait and Notify: IllegalMonitorStateException

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

class Runner implements Runnable
{
  public void run()
  {
    try
    {
      synchronized(Main.main) {
        Main.main.wait();
      }
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

The same rule applies to notify()/notifyAll() as well.

The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Docker remove <none> TAG images

To remove all images with none we have to be sure that we removed all stopped containers which they can use run:

docker rm $(docker ps -a -q)

then we can remove all images:

docker image prune

Python argparse command line flags without arguments

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag

Set QLineEdit to accept only numbers

If you're using QT Creator 5.6 you can do that like this:

#include <QIntValidator>

ui->myLineEditName->setValidator( new QIntValidator);

I recomend you put that line after ui->setupUi(this);

I hope this helps.

Android Studio: Add jar as library?

I have read all the answers here and they all seem to cover old versions of Android Studio!

With a project created with Android Studio 2.2.3 I just needed to create a libs directory under app and place my jar there. I did that with my file manager, no need to click or edit anything in Android Studio.

Why it works? Open Build / Edit Libraries and Dependencies and you will see:

{include=[*.jar], dir=libs}

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

Console output in a Qt GUI app?

It may have been an oversight of other answers, or perhaps it is a requirement of the user to indeed need console output, but the obvious answer to me is to create a secondary window that can be shown or hidden (with a checkbox or button) that shows all messages by appending lines of text to a text box widget and use that as a console?

The benefits of such a solution are:

  • A simple solution (providing all it displays is a simple log).
  • The ability to dock the 'console' widget onto the main application window. (In Qt, anyhow).
  • The ability to create many consoles (if more than 1 thread, etc).
  • A pretty easy change from local console output to sending log over network to a client.

Hope this gives you food for thought, although I am not in any way yet qualified to postulate on how you should do this, I can imagine it is something very achievable by any one of us with a little searching / reading!

What does FETCH_HEAD in Git mean?

git pull is combination of a fetch followed by a merge. When git fetch happens it notes the head commit of what it fetched in FETCH_HEAD (just a file by that name in .git) And these commits are then merged into your working directory.

How to get host name with port from a http or https request

Seems like you need to strip the URL from the URL, so you can do it in a following way:

request.getRequestURL().toString().replace(request.getRequestURI(), "")

How can I open an Excel file in Python?

You can use xlpython package that requires xlrd only. Find it here https://pypi.python.org/pypi/xlpython and its documentation here https://github.com/morfat/xlpython

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

Search a whole table in mySQL for a string

for specific requirement the following will work for search:

select * from table_name where (column_name1='%var1%' or column_name2='var2' or column_name='%var3%') and column_name='var';

if you want to query for searching data from the database this will work perfectly.

HTML Drag And Drop On Mobile Devices

There is a new polyfill for translating touch events to drag-and-drop, such that HTML5 Drag And Drop is utilizable on mobile.

The polyfill was introduced by Bernardo Castilho on this post.

Here's a demo from that post.

The post also presents several considerations of the folyfill design.

How do I inject a controller into another controller in AngularJS

<div ng-controller="TestCtrl1">
    <div ng-controller="TestCtrl2">
      <!-- your code--> 
    </div> 
</div>

This works best in my case, where TestCtrl2 has it's own directives.

var testCtrl2 = $controller('TestCtrl2')

This gives me an error saying scopeProvider injection error.

   var testCtrl1ViewModel = $scope.$new();
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); 

This doesn't really work if you have directives in 'TestCtrl1', that directive actually have a different scope from this one created here. You end up with two instances of 'TestCtrl1'.

Download and install an ipa from self hosted url on iOS

There are online tools that simplify this process of sharing, for example https://abbashare.com or https://diawi.com Create an ipa file from xcode with adhoc or inhouse profile, and upload this file on these site. I prefer abbashare because save file on your dropbox and you can delete it whenever you want

100% width in React Native Flexbox

width: '100%' and alignSelf: 'stretch' didn't work for me. Dimensions didn't suite my task cause I needed to operate on a deeply nested view. Here's what worked for me, if I rewrite your code. I just added some more Views and used flex properties to achieve the needed layout:

  {/* a column */}
  <View style={styles.container}>
    {/* some rows here */}
    <Text style={styles.welcome}>
      Welcome to React Natives
    </Text>
    {/* this row should take all available width */}
    <View style={{ flexDirection: 'row' }}>
      {/* flex 1 makes the view take all available width */}
      <View style={{ flex: 1 }}>
        <Text style={styles.line1}>
          line1
        </Text>
      </View>
      {/* I also had a button here, to the right of the text */}
    </View>
    {/* the rest of the rows */}
    <Text style={styles.instructions}>
      Press Cmd+R to reload,{'\n'}
      Cmd+D or shake for dev menu
    </Text>
  </View>

How to center horizontally div inside parent div

You can use the "auto" value for the left and right margins to let the browser distribute the available space equally at both sides of the inner div:

<div id='parent' style='width: 100%;'>
   <div id='child' style='width: 50px; height: 100px; margin-left: auto; margin-right: auto'>Text</div>
</div>

EC2 Instance Cloning

There is no explicit Clone button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.

First create an image from an existing EC2 instance.

enter image description here


Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.

enter image description here


Then, you need to create a new instance and use that image as the AMI.

enter image description here

enter image description here

How to open standard Google Map application from my application?

This is written in Kotlin, it will open the maps app if it's found and place the point and let you start the trip:

  val gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=" + adapter.getItemAt(position).latitud + "," + adapter.getItemAt(position).longitud)
        val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
        mapIntent.setPackage("com.google.android.apps.maps")
        if (mapIntent.resolveActivity(requireActivity().packageManager) != null) {
            startActivity(mapIntent)
        }

Replace requireActivity() with your Context.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

It would be more helpful if you posed a more complete working (or in this case non-working) example.

I tried the following:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()

This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1].

Further, as per the hist documentation (i.e. ax.hist? from ipython), I think the sum is fine too:

*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``.  In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::

    pdf, bins, patches = ax.hist(...)
    print np.sum(pdf * np.diff(bins))

Giving this a try after the commands above:

np.sum(n * np.diff(bins))

I get a return value of 1.0 as expected. Remember that normed=True doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n) returned approx 7.2767.

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

PHP - cannot use a scalar as an array warning

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

What is the difference between UTF-8 and Unicode?

UTF-8 is one possible encoding scheme for Unicode text.

Unicode is a broad-scoped standard which defines over 140,000 characters and allocates each a numerical code (a code point). It also defines rules for how to sort this text, normalise it, change its case, and more. A character in Unicode is represented by a code point from zero up to 0x10FFFF inclusive, though some code points are reserved and cannot be used for characters.

There is more than one way that a string of Unicode code points can be encoded into a binary stream. These are called "encodings". The most straightforward encoding is UTF-32, which simply stores each code point as a 32-bit integer, with each being 4 bytes wide.

UTF-8 is another encoding, and is becoming the de-facto standard, due to a number of advantages over UTF-32 and others. UTF-8 encodes each code point as a sequence of either 1, 2, 3 or 4 byte values. Code points in the ASCII range are encoded as a single byte value, to be compatible with ASCII. Code points outside this range use either 2, 3, or 4 bytes each, depending on what range they are in.

UTF-8 has been designed with these properties in mind:

  • ASCII characters are encoded exactly as they are in ASCII, such that an ASCII string is also a valid UTF-8 string representing the same characters.

  • Binary sorting: Sorting UTF-8 strings using a binary sort will still result in all code points being sorted in numerical order.

  • When a code point uses multiple bytes, none of those bytes contain values in the ASCII range, ensuring that no part of them could be mistaken for an ASCII character. This is also a security feature.

  • UTF-8 can be easily validated, and distinguished from other character encodings by a validator. Text in other 8-bit or multi-byte encodings will very rarely also validate as UTF-8 due to the very specific structure of UTF-8.

  • Random access: At any point in a UTF-8 string it is possible to tell if the byte at that position is the first byte of a character or not, and to find the start of the next or current character, without needing to scan forwards or backwards more than 3 bytes or to know how far into the string we started reading from.

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

The identity used to sign the executable is no longer valid

you debug it on simulator only if you don't have iPhone Developer certificate. check on left corner in xcode you select simulator not device.

How to click an element in Selenium WebDriver using JavaScript

Cross browser testing java scripts

public class MultipleBrowser {

    public WebDriver driver= null;
    String browser="mozilla";
    String url="https://www.omnicard.com";

    @BeforeMethod
    public void LaunchBrowser() {

        if(browser.equalsIgnoreCase("mozilla"))
            driver= new FirefoxDriver();
        else if(browser.equalsIgnoreCase("safari"))
            driver= new SafariDriver();
        else if(browser.equalsIgnoreCase("chrome"))
            //System.setProperty("webdriver.chrome.driver","/Users/mhossain/Desktop/chromedriver");
            driver= new ChromeDriver(); 
        driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
        driver.navigate().to(url);
    }

}

but when you want to run firefox you need to chrome path disable, otherwise browser will launch but application may not.(try both way) .

How to make Python speak

Please note that this only work with python 2.x

You should try using the PyTTSx package since PyTTS is outdated. PyTTSx works with the lastest python version.

http://pypi.python.org/pypi/pyttsx/1.0 -> The package

Hope it helps

react-native: command not found

If for some strange reasons, the path to react-native is not in the PATH, you should take note where the react-native executable is installed. Generally, the issue with command not found is because they are not in PATH.

For example, I use nodenv and run npm install -g react-native

/Users/khoa/.nodenv/versions/10.10.0/bin/react-native -> /Users/khoa/.nodenv/versions/10.10.0/lib/node_modules/react-native/local-cli/wrong-react-native.js

So I need to add that to my PATH

export PATH=$HOME/.nodenv/versions/10.10.0/bin:$PATH

You can verify with echo $PATH

Or you can use npx to execute local npm modules, for example

npx react-native run-ios --simulator='iPhone X'

How to convert string to boolean php

filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

$string = 1; // true
$string ='1'; // true
$string = 'true'; // true
$string = 'trUe'; // true
$string = 'TRUE'; // true
$string = 0; // false
$string = '0'; // false
$string = 'false'; // false
$string = 'False'; // false
$string = 'FALSE'; // false
$string = 'sgffgfdg'; // null

You must specify

FILTER_NULL_ON_FAILURE
otherwise you'll get always false even if $string contains something else.

Why is Thread.Sleep so harmful

Sleep is used in cases where independent program(s) that you have no control over may sometimes use a commonly used resource (say, a file), that your program needs to access when it runs, and when the resource is in use by these other programs your program is blocked from using it. In this case, where you access the resource in your code, you put your access of the resource in a try-catch (to catch the exception when you can't access the resource), and you put this in a while loop. If the resource is free, the sleep never gets called. But if the resource is blocked, then you sleep for an appropriate amount of time, and attempt to access the resource again (this why you're looping). However, bear in mind that you must put some kind of limiter on the loop, so it's not a potentially infinite loop. You can set your limiting condition to be N number of attempts (this is what I usually use), or check the system clock, add a fixed amount of time to get a time limit, and quit attempting access if you hit the time limit.

Android - Dynamically Add Views into View

// Parent layout
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.layout);

// Layout inflater
LayoutInflater layoutInflater = getLayoutInflater();
View view;

for (int i = 1; i < 101; i++){
    // Add the text layout to the parent layout
    view = layoutInflater.inflate(R.layout.text_layout, parentLayout, false);

    // In order to get the view we have to use the new view with text_layout in it
    TextView textView = (TextView)view.findViewById(R.id.text);
    textView.setText("Row " + i);

    // Add the text view to the parent layout
    parentLayout.addView(textView);
}

What is the best way to add a value to an array in state

Another simple way using concat:

this.setState({
  arr: this.state.arr.concat('new value')
})

SQL Server: combining multiple rows into one row

There are several methods.

If you want just the consolidated string value returned, this is a good quick and easy approach

DECLARE @combinedString VARCHAR(MAX)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + stringvalue
FROM jira.customfieldValue
WHERE customfield = 12534
    AND ISSUE = 19602

SELECT @combinedString as StringValue 

Which will return your combined string.

You can also try one of the XML methods e.g.

SELECT DISTINCT Issue, Customfield, StringValues
FROM Jira.customfieldvalue v1
CROSS APPLY ( SELECT StringValues + ',' 
              FROM jira.customfieldvalue v2
              WHERE v2.Customfield = v1.Customfield 
                  AND v2.Issue = v1.issue 
              ORDER BY ID 
                  FOR XML PATH('') )  D ( StringValues )
WHERE customfield = 12534
    AND ISSUE = 19602

How to select id with max date group by category in PostgreSQL?

Try this one:

SELECT t1.* FROM Table1 t1
JOIN 
(
   SELECT category, MAX(date) AS MAXDATE
   FROM Table1
   GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE

See this SQLFiddle

Sql Query to list all views in an SQL Server 2005 database

Necromancing.

Since you said ALL views, technically, all answers to date are WRONG.
Here is how to get ALL views:

SELECT 
     sch.name AS view_schema 
    ,sysv.name AS view_name 
    ,ISNULL(sysm.definition, syssm.definition) AS view_definition 
    ,create_date 
    ,modify_date 
FROM sys.all_views AS sysv 

INNER JOIN sys.schemas AS sch 
    ON sch.schema_id = sysv.schema_id 

LEFT JOIN sys.sql_modules AS sysm 
    ON sysm.object_id = sysv.object_id 

LEFT JOIN sys.system_sql_modules AS syssm 
    ON syssm.object_id = sysv.object_id 

-- INNER JOIN sys.objects AS syso ON syso.object_id = sysv.object_id 

WHERE (1=1) 
AND (sysv.type = 'V') -- seems unnecessary, but who knows
-- AND sch.name = 'INFORMATION_SCHEMA' 
/*
AND sysv.is_ms_shipped = 0  
AND NOT EXISTS 
(
    SELECT * FROM sys.extended_properties AS syscrap
    WHERE syscrap.major_id = sysv.object_id
    AND syscrap.minor_id = 0 
    AND syscrap.class = 1 
    AND syscrap.name = N'microsoft_database_tools_support' 
)  
*/

ORDER BY 
     view_schema 
    ,view_name 

Add inline style using Javascript

Use cssText

nFilter.style.cssText +=';width:330px;float:left;';

Display array values in PHP

use implode(',', $array); for output as apple,banana,orange

Or

foreach($array as $key => $value)
{
   echo $key." is ". $value;
}

How can I prevent the backspace key from navigating back?

For anyone who is interested, I've put together a jQuery plugin that incorporates thetoolman's (plus @MaffooClock/@cdmckay's comments) and @Vladimir Kornea's ideas above.

Usage:

//# Disable backspace on .disabled/.readOnly fields for the whole document
$(document).disableBackspaceNavigation();

//# Disable backspace on .disabled/.readOnly fields under FORMs
$('FORM').disableBackspaceNavigation();

//# Disable backspace on .disabled/.readOnly fields under #myForm
$('#myForm').disableBackspaceNavigation();

//# Disable backspace on .disabled/.readOnly fields for the whole document with confirmation
$(document).disableBackspaceNavigation(true);

//# Disable backspace on .disabled/.readOnly fields for the whole document with all options
$(document).disableBackspaceNavigation({
    confirm: true,
    confirmString: "Are you sure you want to navigate away from this page?",
    excludeSelector: "input, select, textarea, [contenteditable='true']",
    includeSelector: ":checkbox, :radio, :submit"
});

Plugin:

//# Disables backspace initiated navigation, optionally with a confirm dialog
//#     From: https://stackoverflow.com/questions/1495219/how-can-i-prevent-the-backspace-key-from-navigating-back
$.fn.disableBackspaceNavigation = function (vOptions) {
    var bBackspaceWasPressed = false,
        o = $.extend({
            confirm: (vOptions === true),   //# If the caller passed in `true` rather than an Object, default .confirm accordingly,
            confirmString: "Are you sure you want to leave this page?",
            excludeSelector: "input, select, textarea, [contenteditable='true']",
            includeSelector: ":checkbox, :radio, :submit"
        }, vOptions)
    ;

    //# If we are supposed to use the bConfirmDialog, hook the beforeunload event
    if (o.confirm) {
        $(window).on('beforeunload', function () {
            if (bBackspaceWasPressed) {
                bBackspaceWasPressed = false;
                return o.confirmString;
            }
        });
    }

    //# Traverse the passed elements, then return them to the caller (enables chainability)
    return this.each(function () {
        //# Disable backspace on disabled/readonly fields
        $(this).bind("keydown keypress", function (e) {
            var $target = $(e.target /*|| e.srcElement*/);

            //# If the backspace was pressed
            if (e.which === 8 /*|| e.keyCode === 8*/) {
                bBackspaceWasPressed = true;

                //# If we are not using the bConfirmDialog and this is not a typeable input (or a non-typeable input, or is .disabled or is .readOnly), .preventDefault
                if (!o.confirm && (
                    !$target.is(o.excludeSelector) ||
                    $target.is(o.includeSelector) ||
                    e.target.disabled ||
                    e.target.readOnly
                )) {
                    e.preventDefault();
                }
            }
        });
    });
}; //# $.fn.disableBackspaceNavigation

Store query result in a variable using in PL/pgSQL

The usual pattern is EXISTS(subselect):

BEGIN
  IF EXISTS(SELECT name
              FROM test_table t
             WHERE t.id = x
               AND t.name = 'test')
  THEN
     ---
  ELSE
     ---
  END IF;

This pattern is used in PL/SQL, PL/pgSQL, SQL/PSM, ...

Why does an SSH remote command get fewer environment variables then when run manually?

I had similar issue, but in the end I found out that ~/.bashrc was all I needed.

However, in Ubuntu, I had to comment the line that stops processing ~/.bashrc :

#If not running interactively, don't do anything
[ -z "$PS1" ] && return

How to read all rows from huge table?

Use a CURSOR in PostgreSQL or let the JDBC-driver handle this for you.

LIMIT and OFFSET will get slow when handling large datasets.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

Pandas: sum DataFrame rows for given columns

Following syntax helped me when I have columns in sequence

awards_frame.values[:,1:4].sum(axis =1)

Pip Install not installing into correct directory?

I totally agree with the guys, it's better to use virtualenv so you can set a custom environment for every project. It ideal for maintenance because it's like a different world for every project and every update of an application you make won't interfere with other projects.

Here you can find a nutshell of virtualenv related to installation and first steps.

Why does foo = filter(...) return a <filter object>, not a list?

Please see this sample implementation of filter to understand how it works in Python 3:

def my_filter(function, iterable):
    """my_filter(function or None, iterable) --> filter object

    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true."""
    if function is None:
        return (item for item in iterable if item)
    return (item for item in iterable if function(item))

The following is an example of how you might use filter or my_filter generators:

>>> greetings = {'hello'}
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye'))
>>> print('\n'.join(spoken))
hello

Entity Framework and Connection Pooling

Accoriding to EF6 (4,5 also) documentation: https://msdn.microsoft.com/en-us/data/hh949853#9

9.3 Context per request

Entity Framework’s contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience. Contexts are expected to be short lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible. In web scenarios it’s important to keep this in mind and not have a context for more than the duration of a single request. Similarly, in non-web scenarios, context should be discarded based on your understanding of the different levels of caching in the Entity Framework. Generally speaking, one should avoid having a context instance throughout the life of the application, as well as contexts per thread and static contexts.

What is the command for cut copy paste a file from one directory to other directory

E:>move "blogger code.txt" d:/"blogger code.txt"

    1 file(s) moved.

"blogger code.txt" is a file name

The file move from E: drive to D: drive

How would I run an async Task<T> method synchronously?

use below code snip

Task.WaitAll(Task.Run(async () => await service.myAsyncMethod()));

Static method in a generic class?

Since static variables are shared by all instances of the class. For example if you are having following code

class Class<T> {
  static void doIt(T object) {
    // using T here 
  }
}

T is available only after an instance is created. But static methods can be used even before instances are available. So, Generic type parameters cannot be referenced inside static methods and variables

Show which git tag you are on?

When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.

It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:

$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

mysql update multiple columns with same now()

There are 2 ways to this;

First, I would advice you declare now() as a variable before injecting it into the sql statement. Lets say;

var x = now();
mysql> UPDATE table SET last_update=$x, last_monitor=$x WHERE id=1;

Logically if you want a different input for last_monitor then you will add another variable like;

var y = time();
mysql> UPDATE table SET last_update=$x, last_monitor=$y WHERE id=1;

This way you can use the variables as many times as you can, not only in mysql statements but also in the server-side scripting-language(like PHP) you are using in your project. Remember these same variables can be inserted as inputs in a form on the front-end of the application. That makes the project dynamic and not static.

Secondly if now() indicates time of update then using mysql you can decalre the property of the row as a timestamp. Every time a row is inserted or updated time is updated too.

How to urlencode a querystring in Python?

In Python 3, this worked with me

import urllib

urllib.parse.quote(query)

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

How do I import the javax.servlet API in my Eclipse project?

Many of us develop in Eclipse via a Maven project. If so, you can include Tomcat dependencies in Maven via the tomcat-servlet-api and tomcat-jsp-api jars. One exists for each version of Tomcat. Usually adding these with scope provided to your POM is sufficient. This will keep your build more portable.

If you upgrade Tomcat in the future, you simply update the version of these jars as well.

Android Studio Gradle Already disposed Module

For me this happened when I removed a module and tried to build the project:

Simple solution was to Invalidate the cache & Restart.

Android Studio>File>Invalidate Caches>Invalidate & Restart

What does this GCC error "... relocation truncated to fit..." mean?

On Cygwin -mcmodel=medium is already default and doesn't help. To me adding -Wl,--image-base -Wl,0x10000000 to GCC linker did fixed the error.

How do I plot only a table in Matplotlib?

This is another option to write a pandas dataframe directly into a matplotlib table:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

ax.table(cellText=df.values, colLabels=df.columns, loc='center')

fig.tight_layout()

plt.show()

enter image description here

What are the ways to make an html link open a folder

Do you want to open a shared folder in Windows Explorer? You need to use a file: link, but there are caveats:

  • Internet Explorer will work if the link is a converted UNC path (file://server/share/folder/).
  • Firefox will work if the link is in its own mangled form using five slashes (file://///server/share/folder) and the user has disabled the security restriction on file: links in a page served over HTTP. Thankfully IE also accepts the mangled link form.
  • Opera, Safari and Chrome can not be convinced to open a file: link in a page served over HTTP.

Font Awesome not working, icons showing as squares

The /css/all.css file contains the core styling plus all of the icon styles that you’ll need when using Font Awesome. The /webfonts folder contains all of the typeface files that the above CSS references and depends on.

Copy the entire /webfonts folder and the /css/all.css into your project’s static assets directory (or where ever you prefer to keep front end assets or vendor stuff).

Add a reference to the copied /css/all.css file into the of each template or page that you want to use Font Awesome on.

Just Visit - https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself You will get the answer.

Load HTML page dynamically into div with jQuery

You can use jQuery's getJSON() or Load(); with the latter, you can reference an existing html file. For more details, see http://www.codeproject.com/Articles/661782/Three-Ways-to-Dynamically-Load-HTML-Content-into-a

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

PHP - Get array value with a numeric index

Yes, for scalar values, a combination of implode and array_slice will do:

$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));

Or mix it up with array_values and list (thanks @nikic) so that it works with all types of values:

list($bar) = array_values(array_slice($array, 0, 1));

MongoDB running but can't connect using shell

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

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

How to save an image locally using Python whose URL address I already know?

A solution which works with Python 2 and Python 3:

try:
    from urllib.request import urlretrieve  # Python 3
except ImportError:
    from urllib import urlretrieve  # Python 2

url = "http://www.digimouth.com/news/media/2011/09/google-logo.jpg"
urlretrieve(url, "local-filename.jpg")

or, if the additional requirement of requests is acceptable and if it is a http(s) URL:

def load_requests(source_url, sink_path):
    """
    Load a file from an URL (e.g. http).

    Parameters
    ----------
    source_url : str
        Where to load the file from.
    sink_path : str
        Where the loaded file is stored.
    """
    import requests
    r = requests.get(source_url, stream=True)
    if r.status_code == 200:
        with open(sink_path, 'wb') as f:
            for chunk in r:
                f.write(chunk)

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

public class RemoveExtraSpacesEfficient {

    public static void main(String[] args) {

        String s = "my    name is    mr    space ";

        char[] charArray = s.toCharArray();

        char prev = s.charAt(0);

        for (int i = 0; i < charArray.length; i++) {
            char cur = charArray[i];
            if (cur == ' ' && prev == ' ') {

            } else {
                System.out.print(cur);
            }
            prev = cur;
        }
    }
}

The above solution is the algorithm with the complexity of O(n) without using any java function.

How to provide animation when calling another activity in Android?

Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

On Windows 10,

I just solved this issue by doing the following.

  1. Goto my.ini and add these 2 lines under [mysqld]

    skip-log-bin
    log_bin_trust_function_creators = 1
    
  2. restart MySQL service

CSS How to set div height 100% minus nPx

If you don't want to use absolute positioning and all that jazz, here's a fix I like to use:

your html:

<body>    
   <div id="header"></div>
   <div id="wrapper"></div>
</body>

your css:

body {
     height:100%;
     padding-top:60px;
}
#header {
     margin-top:60px;
     height:60px;
}
#wrapper {
     height:100%;
}

How to get the list of properties of a class?

That's my solution

public class MyObject
{
    public string value1 { get; set; }
    public string value2 { get; set; }

    public PropertyInfo[] GetProperties()
    {
        try
        {
            return this.GetType().GetProperties();
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    public PropertyInfo GetByParameterName(string ParameterName)
    {
        try
        {
            return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
    {
        try
        {
            obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
            return obj;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

add item to dropdown list in html using javascript

Since your script is in <head>, you need to wrap it in window.onload:

window.onload = function () {
    var select = document.getElementById("year");
    for(var i = 2011; i >= 1900; --i) {
        var option = document.createElement('option');
        option.text = option.value = i;
        select.add(option, 0);
    }
};

You can also do it in this way

<body onload="addList()">

How do I execute a bash script in Terminal?

$prompt: /path/to/script and hit enter. Note you need to make sure the script has execute permissions.

PostgreSQL: how to convert from Unix epoch to date?

The solution above not working for the latest version on PostgreSQL. I found this way to convert epoch time being stored in number and int column type is on PostgreSQL 13:

SELECT TIMESTAMP 'epoch' + (<table>.field::int) * INTERVAL '1 second' as started_on from <table>;

For more detail explanation, you can see here https://www.yodiw.com/convert-epoch-time-to-timestamp-in-postgresql/#more-214

java: use StringBuilder to insert at the beginning

You can use the insert method with the offset. as offset set to '0' means you are appending to the front of your StringBuilder.

StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
    sb.insert(0,i);
}

NOTE: as the insert method accept all types of primitives, you can use for int, long, char[] etc.

Creating the Singleton design pattern in PHP5

I have written long back thought to share here

class SingletonDesignPattern {

    //just for demo there will be only one instance
    private static $instanceCount =0;

    //create the private instance variable
    private static $myInstance=null;

    //make constructor private so no one create object using new Keyword
    private function  __construct(){}

    //no one clone the object
    private function  __clone(){}

    //avoid serialazation
    public function __wakeup(){}

    //ony one way to create  object
    public static  function  getInstance(){

        if(self::$myInstance==null){
            self::$myInstance=new SingletonDesignPattern();
            self::$instanceCount++;
        }
        return self::$myInstance;
    }

    public static function getInstanceCount(){
        return self::$instanceCount;
    }

}

//now lets play with singleton design pattern

$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();

echo "number of instances: ".SingletonDesignPattern::getInstanceCount();

'POCO' definition

POCO stands for "Plain Old CLR Object".

Get list of databases from SQL Server

Since you are using .NET you can use the SQL Server Management Objects

Dim server As New Microsoft.SqlServer.Management.Smo.Server("localhost")
For Each db As Database In server.Databases
    Console.WriteLine(db.Name)
Next

Vue.js data-bind style backgroundImage not working

Binding background image style using a dynamic value from v-for loop could be done like this.

<div v-for="i in items" :key="n" 
  :style="{backgroundImage: 'url('+require('./assets/cars/'+i.src+'.jpg')+')'}">
</div>

pip install failing with: OSError: [Errno 13] Permission denied on directory

Option a) Create a virtualenv, activate it and install:

virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt

Option b) Install in your homedir:

pip install --user -r requirements.txt

My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.

How to add a line break in an Android TextView?

As Html.fromHtml deprecated I simply I used this code to get String2 in next line.

textView.setText(fromHtml("String1 <br/> String2"));

.

@SuppressWarnings("deprecation")
    public static Spanned fromHtml(String html){
        Spanned result;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
        } else {
            result = Html.fromHtml(html);
        }
        return result;
    }

How to convert String to Date value in SAS?

You don't need substr or strip.

input(monyy,date9.);

What are invalid characters in XML

The only illegal characters are &, < and > (as well as " or ' in attributes, depending on which character is used to delimit the attribute value: attr="must use &quot; here, ' is allowed" and attr='must use &apos; here, " is allowed').

They're escaped using XML entities, in this case you want &amp; for &.

Really, though, you should use a tool or library that writes XML for you and abstracts this kind of thing away for you so you don't have to worry about it.

How to Delete Session Cookie?

Deleting a jQuery cookie:

$(function() {
    var COOKIE_NAME = 'test_cookie';
    var options = { path: '/', expires: 10 };
    $.cookie(COOKIE_NAME, 'test', options); // sets the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns test
    $.cookie(COOKIE_NAME, null, options);   // deletes the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns null
});

How can I use a local image as the base image with a dockerfile?

You can have - characters in your images. Assume you have a local image (not a local registry) named centos-base-image with tag 7.3.1611.

docker version 
      Client:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

      Server:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

docker images
 REPOSITORY            TAG
 centos-base-image     7.3.1611

Dockerfile

FROM centos-base-image:7.3.1611
RUN yum -y install epel-release libaio bc flex

Result

Sending build context to Docker daemon 315.9 MB
Step 1 : FROM centos-base-image:7.3.1611
  ---> c4d84e86782e
Step 2 : RUN yum -y install epel-release libaio bc flex
  ---> Running in 36d8abd0dad9
...

In the example above FROM is fetching your local image, you can provide additional instructions to fetch an image from your custom registry (e.g. FROM localhost:5000/my-image:with.tag). See https://docs.docker.com/engine/reference/commandline/pull/#pull-from-a-different-registry and https://docs.docker.com/registry/#tldr

Finally, if your image is not being resolved when providing a name, try adding a tag to the image when you create it

This GitHub thread describes a similar issue of not finding local images by name.

By omitting a specific tag, docker will look for an image tagged "latest", so either create an image with the :latest tag, or change your FROM

How to get a subset of a javascript object's properties

If you are using ES6 there is a very concise way to do this using destructuring. Destructuring allows you to easily add on to objects using a spread, but it also allows you to make subset objects in the same way.

const object = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
}

// Remove "c" and "d" fields from original object:
const {c, d, ...partialObject} = object;
const subset = {c, d};

console.log(partialObject) // => { a: 'a', b: 'b'}
console.log(subset) // => { c: 'c', d: 'd'};

How to use UTF-8 in resource properties with ResourceBundle

look at this : http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)

the properties accept an Reader object as arguments, which you can create from an InputStream.

at the create time, you can specify the encoding of the Reader:

InputStreamReader isr = new InputStreamReader(stream, "UTF-8");

then apply this Reader to the load method :

prop.load(isr);

BTW: get the stream from .properties file :

 InputStream stream = this.class.getClassLoader().getResourceAsStream("a.properties");

BTW: get resource bundle from InputStreamReader:

ResourceBundle rb = new PropertyResourceBundle(isr);

hope this can help you !

How to set gradle home while importing existing project in Android studio

If you are on a Windows machine, go to the directory:

C:\Program Files\Android\Android Studio\gradle\

Click the gradle-4.4 folder from Android Studio\File\Settings, and then click the Apply button.

enter image description here

How to convert a single char into an int

Or you could use the "correct" method, similar to your original atoi approach, but with std::stringstream instead. That should work with chars as input as well as strings. (boost::lexical_cast is another option for a more convenient syntax)

(atoi is an old C function, and it's generally recommended to use the more flexible and typesafe C++ equivalents where possible. std::stringstream covers conversion to and from strings)

Deck of cards JAVA

There are many errors in your code, for example you are not really calling your deck by just typing deck in your Shuffle method. You can only call it by typing theCard.deck

I have changed your shuffle method:

public void Shuffle(){
    for (int i = 0; i < theCard.deck.length; i++) {
        int index = (int)(Math.random()*theCard.deck.length );
        int temp = theCard.deck[i];
        theCard.deck[i] = theCard.deck[index];
        theCard.deck[index] = temp;
        remainingCards--;
    }
}

Also, as it is said you have structural problem. You should name classes as you understand in real life, for example, when you say card, it is only one card, when you say deck it is supposed to be 52+2 cards. In this way your code would be more understandable.

Git ignore local file changes

If you dont want your local changes, then do below command to ignore(delete permanently) the local changes.

  • If its unstaged changes, then do checkout (git checkout <filename> or git checkout -- .)
  • If its staged changes, then first do reset (git reset <filename> or git reset) and then do checkout (git checkout <filename> or git checkout -- .)
  • If it is untracted files/folders (newly created), then do clean (git clean -fd)

If you dont want to loose your local changes, then stash it and do pull or rebase. Later merge your changes from stash.

  • Do git stash, and then get latest changes from repo git pull orign master or git rebase origin/master, and then merge your changes from stash git stash pop stash@{0}

Volley JsonObjectRequest Post request not working

It worked for can try this for calling with Volley Json Request and Response ith Java Code .

public void callLogin(String sMethodToCall, String sUserId, String sPass) {
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST, ConstantValues.ROOT_URL_LOCAL + sMethodToCall.toString().trim(), addJsonParams(sUserId, sPass),
//                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("onResponse", response.toString());
                        Toast.makeText(VolleyMethods.this, response.toString(), Toast.LENGTH_LONG).show(); // Test

                        parseResponse(response);
//                        msgResponse.setText(response.toString());
//                        hideProgressDialog();
                    }
                },
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("onErrorResponse", "Error: " + error.getMessage());
                        Toast.makeText(VolleyMethods.this, error.toString(), Toast.LENGTH_LONG).show();
//                hideProgressDialog();
                    }
                }) {

            /**
             * Passing some request headers
             */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }


        };

        requestQueue.add(jsonObjectRequest);
    }

    public JSONObject addJsonParams(String sUserId, String sPass) {
        JSONObject jsonobject = new JSONObject();
        try {
//            {"id":,"login":"secretary","password":"password"}

            ///***//
            Log.d("addJsonParams", "addJsonParams");

//            JSONObject jsonobject = new JSONObject();

//            JSONObject jsonobject_one = new JSONObject();
//
//            jsonobject_one.put("type", "event_and_offer");
//            jsonobject_one.put("devicetype", "I");
//
//            JSONObject jsonobject_TWO = new JSONObject();
//            jsonobject_TWO.put("value", "event");
//            JSONObject jsonobject = new JSONObject();
//
//            jsonobject.put("requestinfo", jsonobject_TWO);
//            jsonobject.put("request", jsonobject_one);

            jsonobject.put("id", "");
            jsonobject.put("login", sUserId); // sUserId
            jsonobject.put("password", sPass); // sPass


//            js.put("data", jsonobject.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonobject;
    }

    public void parseResponse(JSONObject response) {

        Boolean bIsSuccess = false; // Write according to your logic this is demo.
        try {
            JSONObject jObject = new JSONObject(String.valueOf(response));
            bIsSuccess = jObject.getBoolean("success");


        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(VolleyMethods.this, "" + e.toString(), Toast.LENGTH_LONG).show(); // Test
        }

    }

Using Razor within JavaScript

One thing to add - I found that Razor syntax hilighter (and probably the compiler) interpret the position of the opening bracket differently:

<script type="text/javascript">
    var somevar = new Array();

    @foreach (var item in items)
    {  // <----  placed on a separate line, NOT WORKING, HILIGHTS SYNTAX ERRORS
        <text>
        </text>
    }

    @foreach (var item in items) {  // <----  placed on the same line, WORKING !!!
        <text>
        </text>
    }
</script>

How to `wget` a list of URLs in a text file?

If you also want to preserve the original file name, try with:

wget --content-disposition --trust-server-names -i list_of_urls.txt

How to retrieve all keys (or values) from a std::map and put them into a vector?

The following functor retrieves the key set of a map:

#include <vector>
#include <iterator>
#include <algorithm>

template <class _Map>
std::vector<typename _Map::key_type> keyset(const _Map& map)
{
    std::vector<typename _Map::key_type> result;
    result.reserve(map.size());
    std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {
        return kvpair.first;
    });
    return result;
}

Bonus: The following functors retrieve the value set of a map:

#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>

template <class _Map>
std::vector<typename _Map::mapped_type> valueset(const _Map& map)
{
    std::vector<typename _Map::mapped_type> result;
    result.reserve(map.size());
    std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {
        return kvpair.second;
    });
    return result;
}

template <class _Map>
std::vector<std::reference_wrapper<typename _Map::mapped_type>> valueset(_Map& map)
{
    std::vector<std::reference_wrapper<typename _Map::mapped_type>> result;
    result.reserve(map.size());
    std::transform(map.begin(), map.end(), std::back_inserter(result), [](typename _Map::reference kvpair) {
        return std::ref(kvpair.second);
    });
    return result;
}

Usage:

int main()
{
    std::map<int, double> map{
        {1, 9.0},
        {2, 9.9},
        {3, 9.99},
        {4, 9.999},
    };
    auto ks = keyset(map);
    auto vs = valueset(map);
    for (auto& k : ks) std::cout << k << '\n';
    std::cout << "------------------\n";
    for (auto& v : vs) std::cout << v << '\n';
    for (auto& v : vs) v += 100.0;
    std::cout << "------------------\n";
    for (auto& v : vs) std::cout << v << '\n';
    std::cout << "------------------\n";
    for (auto& [k, v] : map) std::cout << v << '\n';

    return 0;
}

Expected output:

1
2
3
4
------------------
9
9.9
9.99
9.999
------------------
109
109.9
109.99
109.999
------------------
109
109.9
109.99
109.999

npm can't find package.json

My issue was I didn't have a package.json file for some reason. After I wget this file into my directory, I was able to run npm install

https://raw.githubusercontent.com/twbs/bootstrap/master/package.json

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

I get get the same minicom error, "cannot open /dev/ttyUSB0: No such file or directory"

Three notes:

  1. I get the error when the device attached to the serial port end of my Prolific Technology PL2303 USB/Serial adapter is turned off. After turning on the device (an embedded controller running Linux) minicom connected fine.

  2. I have to run as super user (i.e. sudo minicom)

  3. Sometimes I have to unplug and plug back in the USB-to-serial adapter to get minicom to connect to it.

I am running Ubuntu 10.04 LTS (Lucid Lynx) under VMware (running on Windows 7). In this situation, make sure the device is attached to VM operating system by right clicking on the USB/Serial USB icon in the lower right of the VMware window and select Connect (Disconnect from Host).

Remember to press Ctrl + A to get minicom's prompt, and type X to exit the program. Just exiting the terminal session running minicom will leave the process running.

SASS - use variables across multiple files

You can do it like this:

I have a folder named utilities and inside that I have a file named _variables.scss

in that file i declare variables like so:

$black: #000;
$white: #fff;

then I have the style.scss file in which i import all of my other scss files like this:

// Utilities
@import "utilities/variables";

// Base Rules
@import "base/normalize";
@import "base/global";

then, within any of the files I have imported, I should be able to access the variables I have declared.

Just make sure you import the variable file before any of the others you would like to use it in.

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

You can first read the whole content of file into a String.

FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
    fileInputStream=new FileInputStream(filename);
    int i;
    while((i=fileInputStream.read())!=-1)
    {
        stringBuffer.append((char)i);
    }
    data = stringBuffer.toString();
}
catch(Exception e){
        LoggerUtil.printStackTrace(e);
}
finally{
    if(fileInputStream!=null){  
        fileInputStream.close();
    }
}

Now You will have the whole content into String ( data variable ).

JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);

After that you can use jsonArray as you want.

Select default option value from typescript angular 6

In case you use Angular's FormBuilder this is the way to go (at least for Angular 9):

HTML view: yourelement.component.html

Use [formGroup] to reference form variable, and use formControlName to reference form's inner variable (both defined in TypeScrit file). Preferably, use [value] to reference some type of option ID.

<form [formGroup] = "uploadForm" (ngSubmit)="onSubmit()">
   . . .html
   <select class="form-control" formControlName="form_variable" required>
       <option *ngFor="let elem of list" [value]="elem.id">{{elem.nanme}}</option>
   </select>
   . . .
</form>

Logic file: yourelement.component.ts

In the initialization of FormBuilderobject, in ngOnInit() function, set the default value you desire to be as default selected.

. . .
// Remember to add imports of "FormsModule" and "ReactiveFormsModule" to app.module.ts
import { FormBuilder, FormGroup } from '@angular/forms';
. . .

export class YourElementComponent implements OnInit {
  // <form> variable
  uploadForm: FormGroup;

  constructor( private formBuilder: FormBuilder ){}

  ngOnInit() {
     this.uploadForm = this.formBuilder.group({
          . . .
          form_variable: ['0'], // <--- Here is the "value" ID of default selected
          . . .
     });
  }
}

SVN checkout the contents of a folder, not the folder itself

svn co svn://path destination

To specify current directory, use a "." for your destination directory:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

How to Determine the Screen Height and Width in Flutter

Just declare a function

Size screenSize() {
return MediaQuery.of(context).size;
}

Use like below

return Container(
      width: screenSize().width,
      height: screenSize().height,
      child: ...
 )

How to auto import the necessary classes in Android Studio with shortcut?

To import classes on the fly :

On OSX press Alt(Option) + Enter.

How do I write dispatch_after GCD in Swift 3, 4, and 5?

try this

let when = DispatchTime.now() + 1.5
    DispatchQueue.main.asyncAfter(deadline: when) {
        //some code
    }

dyld: Library not loaded ... Reason: Image not found

If you use cmake, add DYLIB_INSTALL_NAME_BASE "@rpath" to target properties:

set_target_properties(target_dyLib PROPERTIES
        # # for FRAMEWORK begin
        # FRAMEWORK TRUE
        # FRAMEWORK_VERSION C
        # MACOSX_FRAMEWORK_IDENTIFIER com.cmake.targetname
        # MACOSX_FRAMEWORK_INFO_PLIST ./Info.plist
        # PUBLIC_HEADER targetname.h
        # # for FRAMEWORK end
        IPHONEOS_DEPLOYMENT_TARGET "8.0"
        DYLIB_INSTALL_NAME_BASE "@rpath" # this is the key point
        XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer"
        DEVELOPMENT_TEAM "${DEVELOPMENT_TEAM}"
    )

or in Xcode dynamic library project Target -> Build Setting set Dynamic Library Install Name Base to @rpath

Best way to clear a PHP array's values

I'd say the first, if the array is associative. If not, use a for loop:

for ($i = 0; $i < count($array); $i++) { unset($array[$i]); }

Although if possible, using

$array = array();

To reset the array to an empty array is preferable.

Disable scrolling when touch moving certain element

Set the touch-action CSS property to none, which works even with passive event listeners:

touch-action: none;

Applying this property to an element will not trigger the default (scroll) behavior when the event is originating from that element.

Assigning a function to a variable

when you perform y=x() you are actually assigning y to the result of calling the function object x and the function has a return value of None. Function calls in python are performed using (). To assign x to y so you can call y just like you would x you assign the function object x to y like y=x and call the function using y()

Selecting multiple columns with linq query and lambda expression

Not sure what you table structure is like but see below.

public NamePriceModel[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts
                .Where(x => x.Status == 1)
                .Select(x => new NamePriceModel { 
                    Name = x.Name, 
                    Id = x.Id, 
                    Price = x.Price
                })
                .OrderBy(x => x.Id)
                .ToArray();
         }
     }
     catch
     {
         return null;
     }
 }

This would return an array of type anonymous with the members you require.

Update:

Create a new class.

public class NamePriceModel 
{
    public string Name {get; set;}
    public decimal? Price {get; set;}
    public int Id {get; set;}
}

I've modified the query above to return this as well and you should change your method from returning string[] to returning NamePriceModel[].

FTP/SFTP access to an Amazon S3 Bucket

WinSCp now supports S3 protocol

First, make sure your AWS user with S3 access permissions has an “Access key ID” created. You also have to know the “Secret access key”. Access keys are created and managed on Users page of IAM Management Console.

Make sure New site node is selected.

On the New site node, select Amazon S3 protocol.

Enter your AWS user Access key ID and Secret access key

Save your site settings using the Save button.

Login using the Login button.

How to run Spyder in virtual environment?

I follow one of the advice above and indeed it works. In summary while you download Anaconda on Ubuntu using the advice given above can help you to 'create' environments. The default when you download Spyder in my case is: (base) smith@ubuntu ~$. After you create the environment, i.e. fenics and activate it with $ conda activate fenics the prompt change to (fenics) smith@ubuntu ~$. Then you launch Spyder from this prompt, i.e $ spyder and your system open the Spyder IDE, and you can write fenics code on it. Remember every time you open a terminal your system open the default prompt. You have to activate your environment where your package is and the prompt change to it i.e. (fenics).

How to add a new schema to sql server 2008?

I use something like this:

if schema_id('newSchema') is null
    exec('create schema newSchema');

The advantage is if you have this code in a long sql-script you can always execute it with the other code, and its short.

Ternary operation in CoffeeScript

In almost any language this should work instead:

a = true  && 5 || 10
a = false && 5 || 10

How can I read a large text file line by line using Java?

Look at this blog:

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;

//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
}

//Close the input stream
fstream.close();

React Native absolute positioning horizontal centre

If you want to center one element itself you could use alignSelf:

logoImg: {
    position: 'absolute',
    alignSelf: 'center',
    bottom: '-5%'
}

This is an example (Note the logo parent is a view with position: relative)

enter image description here

Which port we can use to run IIS other than 80?

I'm going to make a few assumptions and come at the problem from a different angle... in that because you have skype installed and running on the same machine, that it is not a production machine and instead used for testing / development?

If so, you may wish to look at alternatives to IIS completely to alleviate your issue. If you use IISExpress or the web server built into recent versions of Visual Studio, they will automatically pick a port for you.

Of course this does mean that it's not particularly useful for giving other people access, but is fine for local development for personal use.

I think the other answers probably offer a better alternative in most situations, but this may offer a different insight.

Here is an intro to IIS Express: http://learn.iis.net/page.aspx/860/iis-express/

how to change attribute "hidden" in jquery

Use prop() for updating the hidden property, and change() for handling the change event.

_x000D_
_x000D_
$('#check').change(function() {_x000D_
  $("#delete").prop("hidden", !this.checked);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <input id="check" type="checkbox" name="del_attachment_id[]" value="<?php echo $attachment['link'];?>">_x000D_
    </td>_x000D_
_x000D_
    <td id="delete" hidden="true">_x000D_
      the file will be deleted from the newsletter_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Difference between \w and \b regular expression meta characters

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".

In all flavors, the characters [a-zA-Z0-9_] are word characters. These are also matched by the short-hand character class \w. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.

\w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

\W is short for [^\w], the negated version of \w.

What's the difference between commit() and apply() in SharedPreferences

The difference between commit() and apply()

We might be confused by those two terms, when we are using SharedPreference. Basically they are probably the same, so let’s clarify the differences of commit() and apply().

1.Return value:

apply() commits without returning a boolean indicating success or failure. commit() returns true if the save works, false otherwise.

  1. Speed:

apply() is faster. commit() is slower.

  1. Asynchronous v.s. Synchronous:

apply(): Asynchronous commit(): Synchronous

  1. Atomic:

apply(): atomic commit(): atomic

  1. Error notification:

apply(): No commit(): Yes