Could not resolve placeholder in string value
This Issue occurs if the application is unable to access the some_file_name.properties file.Make sure that the properties file is placed under resources folder in spring.
Trouble shooting Steps
1: Add the properties file under the resource folder.
2: If you don't have a resource folder. Create one by navigating new by Right click on the project new > Source Folder, name it as resource and place your properties file under it.
For annotation based Implementation
Add @PropertySource(ignoreResourceNotFound = true, value = "classpath:some_file_name.properties")
//Add it before using the place holder
Example:
Assignment1Controller.Java
@PropertySource(ignoreResourceNotFound = true, value = "classpath:assignment1.properties")
@RestController
public class Assignment1Controller {
// @Autowired
// Assignment1Services assignment1Services;
@Value("${app.title}")
private String appTitle;
@RequestMapping(value = "/hello")
public String getValues() {
return appTitle;
}
}
assignment1.properties
app.title=Learning Spring
What is the best algorithm for overriding GetHashCode?
ValueTuple - Update for C# 7
As @cactuaroid mentions in the comments, a value tuple can be used. This saves a few keystrokes and more importantly executes purely on the stack (no Garbage):
(PropA, PropB, PropC, PropD).GetHashCode();
(Note: The original technique using anonymous types seems to create an object on the heap, i.e. garbage, since anonymous types are implemented as classes, though this might be optimized out by the compiler. It would be interesting to benchmark these options, but the tuple option should be superior.)
Anonymous Type (Original Answer)
Microsoft already provides a good generic HashCode generator: Just copy your property/field values to an anonymous type and hash it:
new { PropA, PropB, PropC, PropD }.GetHashCode();
This will work for any number of properties. It does not use boxing. It just uses the algorithm already implemented in the framework for anonymous types.
jQuery Validation plugin: validate check box
You can validate group checkbox and radio button without extra js code, see below example.
Your JS should be look like:
$("#formid").validate();
You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]
<fieldset class="col-md-12">
<legend>Days</legend>
<div class="form-row">
<div class="col-12 col-md-12 form-group">
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="2">Tuesday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="3">Wednesday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="4">Thursday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="5">Friday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="6">Saturday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="7">Sunday
</label>
<label for="daysgroup[]" class="error">Your error message will be display here.</label>
</div>
</div>
</fieldset>
You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.
eg. group radio button:
<fieldset class="col-md-12">
<legend>Gender</legend>
<div class="form-row">
<div class="col-12 col-md-12 form-group">
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
</label>
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="w">woman
</label>
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="o">other
</label>
<label for="gendergroup[]" class="error">Your error message will be display here.</label>
</div>
</div>
</fieldset>
You can check working example here.
- jQuery v3.3.x
- jQuery Validation Plugin - v1.17.0
Run Batch File On Start-up
RunOnce
RunOnce is an option and have a few keys that can be used for pointing a command to start on startup (depending if it concerns a user or the whole system):
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
setting the value:
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v MyBat /D "!C:\mybat.bat"
With setting and exclamation mark at the beginning and if the script exist with a value different than 0 the registry key wont be deleted and the script will be executed every time on startup
SCHTASKS
You can use SCHTASKS and a triggering event:
SCHTASKS /Create /SC ONEVENT /MO ONLOGON /TN ON_LOGON /tr "c:\some.bat"
or
SCHTASKS /Create /SC ONEVENT /MO ONSTART/TN ON_START /tr "c:\some.bat"
Startup Folder
You also have two startup folders - one for the current user and one global.
There you can copy your scripts (or shortcuts) in order to start a file on startup
::the global one
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
::for the current user
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
How to trap on UIViewAlertForUnsatisfiableConstraints?
Followed Stephen's advice and tried to debug the code and whoa! it worked. The answer lies in the debug message itself.
Will attempt to recover by breaking constraint
NSLayoutConstraint:0x191f0920 H:[MPKnockoutButton:0x17a876b0]-(34)-[MPDetailSlider:0x17a8bc50](LTR)>
The line above tells you that the runtime worked by removing this constraint. May be you don't need Horizontal Spacing on your button (MPKnockoutButton). Once you clear this constraint, it won't complain at runtime & you would get the desired behaviour.
Create a list from two object lists with linq
Why you don't just use Concat
?
Concat is a part of linq and more efficient than doing an AddRange()
in your case:
List<Person> list1 = ...
List<Person> list2 = ...
List<Person> total = list1.Concat(list2);
sql how to cast a select query
If you're using SQL (which you didn't say):
select cast(column as varchar(200)) from table
You can use it in any statement, for example:
select value where othervalue in( select cast(column as varchar(200)) from table)
from othertable
If you want to do a join query, the answer is here already in another post :)
Shell script not running, command not found
Unix has a variable called PATH
that is a list of directories where to find commands.
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/david/bin
If I type a command foo
at the command line, my shell will first see if there's an executable command /usr/local/bin/foo
. If there is, it will execute /usr/local/bin/foo
. If not, it will see if there's an executable command /usr/bin/foo
and if not there, it will look to see if /bin/foo
exists, etc. until it gets to /Users/david/bin/foo
.
If it can't find a command foo
in any of those directories, it tell me command not found.
There are several ways I can handle this issue:
- Use the command
bash foo
since foo
is a shell script.
- Include the directory name when you eecute the command like
/Users/david/foo
or $PWD/foo
or just plain ./foo
.
- Change your
$PATH
variable to add the directory that contains your commands to the PATH.
You can modify $HOME/.bash_profile
or $HOME/.profile
if .bash_profile
doesn't exist. I did that to add in /usr/local/bin
which I placed first in my path. This way, I can override the standard commands that are in the OS. For example, I have Ant 1.9.1, but the Mac came with Ant 1.8.4. I put my ant
command in /usr/local/bin
, so my version of ant
will execute first. I also added $HOME/bin
to the end of the PATH for my own commands. If I had a file like the one you want to execute, I'll place it in $HOME/bin to execute it.
Why does using an Underscore character in a LIKE filter give me all the results?
As you want to specifically search for a wildcard character you need to escape that
This is done by adding the ESCAPE
clause to your LIKE
expression. The character that is specified with the ESCAPE
clause will "invalidate" the following wildcard character.
You can use any character you like (just not a wildcard character). Most people use a \
because that is what many programming languages also use
So your query would result in:
select *
from Manager
where managerid LIKE '\_%' escape '\'
and managername like '%\_%' escape '\';
But you can just as well use any other character:
select *
from Manager
where managerid LIKE '#_%' escape '#'
and managername like '%#_%' escape '#';
Here is an SQLFiddle example: http://sqlfiddle.com/#!6/63e88/4
Use URI builder in Android or create URL with variables
Using appendEncodePath()
could save you multiple lines than appendPath()
, the following code snippet builds up this url: http://api.openweathermap.org/data/2.5/forecast/daily?zip=94043
Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.scheme("http");
urlBuilder.authority("api.openweathermap.org");
urlBuilder.appendEncodedPath("data/2.5/forecast/daily");
urlBuilder.appendQueryParameter("zip", "94043,us");
URL url = new URL(urlBuilder.build().toString());
Java: how to use UrlConnection to post request with authorization?
To do oAuth authentication to external app (INSTAGRAM) Step 3 "get the token after receiving the code" Only code below worked for me
Worth to state also that it worked for me using some localhost URL with a callback servlet configured with name "callback in web.xml and callback URL registered: e.g. localhost:8084/MyAPP/docs/insta/callback
BUT after successfully completed authentication steps, using same external site "INSTAGRAM" to do GET of Tags or MEDIA to retrieve JSON data using initial method didn't work.
Inside my servlet to do GET using url like
e.g. api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN only method found HERE worked
Thanks to all contributors
URL url = new URL(httpurl);
HashMap<String, String> params = new HashMap<String, String>();
params.put("client_id", id);
params.put("client_secret", secret);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirect);
params.put("code", code); // your INSTAGRAM code received
Set set = params.entrySet();
Iterator i = set.iterator();
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
conn.disconnect();
System.out.println("INSTAGRAM token returned: "+builder.toString());
HTML5 form validation pattern alphanumeric with spaces?
To avoid an input with only spaces, use: "[a-zA-Z0-9]+[a-zA-Z0-9 ]+"
.
eg: abc | abc aBc | abc 123 AbC 938234
To ensure, for example, that a first AND last name are entered, use a slight variation like
"[a-zA-Z]+[ ][a-zA-Z]+"
eg: abc def
Preloading images with JavaScript
The browser will work best using the link tag in the head.
export function preloadImages (imageSources: string[]): void {
imageSources
.forEach(i => {
const linkEl = document.createElement('link');
linkEl.setAttribute('rel', 'preload');
linkEl.setAttribute('href', i);
linkEl.setAttribute('as', 'image');
document.head.appendChild(linkEl);
});
}
Load properties file in JAR?
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for
your unit tests, you follow the same
pattern as you do for adding resources
to the JAR except the directory you
place resources in is
${basedir}/src/test/resources
. At
this point you would have a project
directory structure that would look
like the following:
my-app
|-- pom.xml
`-- src
|-- main
| |-- java
| | `-- com
| | `-- mycompany
| | `-- app
| | `-- App.java
| `-- resources
| `-- META-INF
| |-- application.properties
`-- test
|-- java
| `-- com
| `-- mycompany
| `-- app
| `-- AppTest.java
`-- resources
`-- test.properties
In a unit test you could use a simple
snippet of code like the following to
access the resource required for
testing:
...
// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );
// Do something with the resource
...
Rubymine: How to make Git ignore .idea files created by Rubymine
using git rm -r --cached .idea
in your terminal worked great for me. It disables the change tracking and unset a number of files under the rubymine folder (idea/) that I could then add and commit to git, thus removing the comparison and allowing the gitignore setting of .idea/
to work.
Linq UNION query to select two elements
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post:
Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
Java creating .jar file
Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.
Converting BitmapImage to Bitmap and vice versa
Here's an extension method for converting a Bitmap to BitmapImage.
public static BitmapImage ToBitmapImage(this Bitmap bitmap)
{
using (var memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
}
Check if option is selected with jQuery, if not select a default
While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
if (!$("#mySelect option:selected").length) {
$("#mySelect option[value='3']").attr('selected', 'selected');
}
});
</script>
How do I get the directory of the PowerShell script I execute?
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
React: "this" is undefined inside a component function
In my case, for a stateless component that received the ref with forwardRef, I had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd
From this (onClick doesn't have access to the equivalent of 'this')
const Com = forwardRef((props, ref) => {
return <input ref={ref} onClick={() => {console.log(ref.current} } />
})
To this (it works)
const useCombinedRefs = (...refs) => {
const targetRef = React.useRef()
useEffect(() => {
refs.forEach(ref => {
if (!ref) return
if (typeof ref === 'function') ref(targetRef.current)
else ref.current = targetRef.current
})
}, [refs])
return targetRef
}
const Com = forwardRef((props, ref) => {
const innerRef = useRef()
const combinedRef = useCombinedRefs(ref, innerRef)
return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})
How to specify Memory & CPU limit in docker compose version 3
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources
In you specific case:
version: "3"
services:
node:
image: USER/Your-Pre-Built-Image
environment:
- VIRTUAL_HOST=localhost
volumes:
- logs:/app/out/
command: ["npm","start"]
cap_drop:
- NET_ADMIN
- SYS_ADMIN
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
volumes:
- logs
networks:
default:
driver: overlay
Note:
- Expose is not necessary, it will be exposed per default on your stack network.
- Images have to be pre-built. Build within v3 is not possible
- "Restart" is also deprecated. You can use restart under deploy with on-failure action
- You can use a standalone one node "swarm", v3 most improvements (if not all) are for swarm
Also Note:
Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable)
Otherwise you have to publish the port like this:
ports:
- 80:80
What is git fast-forwarding?
In Git, to "fast forward" means to update the HEAD
pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...
Fast forwarding is not possible when the new HEAD
is in a diverged state relative to the stream you want to integrate. For instance, you are on master
and have local commits, and git fetch
has brought new upstream commits into origin/master
. The branch now diverges from its upstream and cannot be fast forwarded: your master
HEAD
commit is not an ancestor of origin/master
HEAD
. To simply reset master
to the value of origin/master
would discard your local commits. The situation requires a rebase or merge.
If your local master
has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master
. Usually, no special steps are needed to do fast-forwarding; it is done by merge
or rebase
in the situation when there are no local commits.
Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?
No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)
Switching between GCC and Clang/LLVM using CMake
You can use the toolchain file mechanism of cmake for this purpose, see e.g. here. You write a toolchain file for each compiler containing the corresponding definitions. At config time, you run e.g
cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/clang-toolchain.cmake ..
and all the compiler information will be set during the project() call from the toolchain file. Though in the documentation is mentionend only in the context of cross-compiling, it works as well for different compilers on the same system.
Maximum and minimum values in a textbox
If you are OK with HTML5 it can be accomplished without any JavaScript code at all...
<input type="number" name="textWeight" id="txtWeight" max="5" min="0" />
Otherwise, something like...
var input = document.getElementById('txtWeight');
input.addEventListener('change', function(e) {
var num = parseInt(this.value, 10),
min = 0,
max = 100;
if (isNaN(num)) {
this.value = "";
return;
}
this.value = Math.max(num, min);
this.value = Math.min(num, max);
});
This will only reset the values when the input looses focus, and clears out any input that can't be parsed as an integer...
OBLIGATORY WARNING
You should always perform adequate server-side validation on inputs, regardless of client-side validation.
Spring boot - configure EntityManager
Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample
@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = {
ServiceMarker.class,
RepositoryMarker.class }
)
public class AppConfig {
}
PersistenceConfig
@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
@Autowired
private Environment env;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
private HibernateJpaVendorAdapter vendorAdaptor() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
return entityManagerFactoryBean;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
return properties;
}
}
Main
public static void main(String[] args) {
try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
MyService myService = springContext.getBean(MyServiceImpl.class);
try {
myService.handleProcess(fromDate, toDate);
} catch (Exception e) {
logger.error("Exception occurs", e);
myService.handleException(fromDate, toDate, e);
}
} catch (Exception e) {
logger.error("Exception occurs in loading Spring context: ", e);
}
}
MyService
@Service
public class MyServiceImpl implements MyService {
@Inject
private MyDao myDao;
@Override
public void handleProcess(String fromDate, String toDate) {
List<Student> myList = myDao.select(fromDate, toDate);
}
}
MyDaoImpl
@Repository
@Transactional
public class MyDaoImpl implements MyDao {
@PersistenceContext
private EntityManager entityManager;
public Student select(String fromDate, String toDate){
TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Student> list = query.getResultList();
return CollectionUtils.isEmpty(list) ? null : list;
}
}
Assuming maven project:
Properties file should be in src/main/resources/database
folder
jdbc.properties file
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password
hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true
ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.
Let's say you have package name a.b.c.service.impl
. MyServiceImpl is in this package and so is ServiceMarker.
public interface ServiceMarker {
}
Same for repository marker. Let's say you have a.b.c.repository.impl
or a.b.c.dao.impl
package name. Then MyDaoImpl is in this this package and also Repositorymarker
public interface RepositoryMarker {
}
a.b.c.entities.Student
//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {
private LocalDateTime fromDate;
private LocalDateTime toDate;
//getters setters
}
a.b.c.converters
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Timestamp.valueOf(dateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
}
pom.xml
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.1.RELEASE</org.springframework-version>
<hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<mysql-connector-java.version>5.1.36</mysql-connector-java.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
Hope it helps. Thanks
sorting integers in order lowest to highest java
Well, if you want to do it using an algorithm. There are a plethora of sorting algorithms out there. If you aren't concerned too much about efficiency and more about readability and understandability. I recommend Insertion Sort. Here is the psudo code, it is trivial to translate this into java.
begin
for i := 1 to length(A)-1 do
begin
value := A[i];
j := i - 1;
done := false;
repeat
{ To sort in descending order simply reverse
the operator i.e. A[j] < value }
if A[j] > value then
begin
A[j + 1] := A[j];
j := j - 1;
if j < 0 then
done := true;
end
else
done := true;
until done;
A[j + 1] := value;
end;
end;
How do I use two submit buttons, and differentiate between which one was used to submit the form?
Give name and values to those submit buttons like:
<td>
<input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
</td>
<td>
<input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
</td>
and then in your php script you could check
if($_POST['mybutton'] == 'save')
{
///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
///do publish processing here
}
Setting default value for TypeScript object passed as argument
No, TypeScript doesn't have a natural way of setting defaults for properties of an object defined like that where one has a default and the other does not. You could define a richer structure:
class Name {
constructor(public first : string,
public last: string = "Smith") {
}
}
And use that in place of the inline type definition.
function sayName(name: Name) {
alert(name.first + " " + name.last);
}
You can't do something like this unfortunately:
function sayName(name : { first: string; last?:string }
/* and then assign a default object matching the signature */
= { first: null, last: 'Smith' }) {
}
As it would only set the default if name
was undefined
.
sed edit file in place
Versions of sed
that support the -i
option for editing a file in place write to a temporary file and then rename the file.
Alternatively, you can just use ed
. For example, to change all occurrences of foo
to bar
in the file file.txt
, you can do:
echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt
Syntax is similar to sed
, but certainly not exactly the same.
Even if you don't have a -i
supporting sed
, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file
, you could do inline file sed 's/foo/bar/g'
. Such a script is trivial to write. For example:
#!/bin/sh
IN=$1
shift
trap 'rm -f "$tmp"' 0
tmp=$( mktemp )
<"$IN" "$@" >"$tmp" && cat "$tmp" > "$IN" # preserve hard links
should be adequate for most uses.
Query Mongodb on month, day, year... of a datetime
Dates are stored in their timestamp format. If you want everything that belongs to a specific month, query for the start and the end of the month.
var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);
db.posts.find({created_on: {$gte: start, $lt: end}});
//taken from http://cookbook.mongodb.org/patterns/date_range/
Favicon not showing up in Google Chrome
Cache
Clear your cache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser.
Some where able to get an updated favicon by adding an URL parameter: ?v=1
after the link href which changes the resource link and therefore loads the favicon without cache (thanks @Stanislav).
<link rel="icon" type="image/x-icon" href="favicon.ico?v=2" />
Favicon Usage
How did you import the favicon? How you should add it.
Normal favicon:
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
PNG/GIF favicon:
<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />
in the <head>
Tag.
Chrome local problem
Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver). Only if the file/icon would be in the downloads directory chrome is allowed to load this data - more information about this can be found here: local (file://) website favicon works in Firefox, not in Chrome or Safari- why?
Renaming
Try to rename it from favicon.{whatever}
to {yourfaviconname}.{whatever}
but I would suggest you to still have the normal favicon. This has solved my issue on IE.
Base64 approach
Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:
<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />
Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp
Generate favicons
I can really suggest you this page: http://www.favicon-generator.org/ to create all types of favicons you need.
How to use type: "POST" in jsonp ajax call
Use json
in dataType
and send like this:
$.ajax({
url: "your url which return json",
type: "POST",
crossDomain: true,
data: data,
dataType: "json",
success:function(result){
alert(JSON.stringify(result));
},
error:function(xhr,status,error){
alert(status);
}
});
and put this lines in your server side file:
if PHP:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
if java:
response.addHeader( "Access-Control-Allow-Origin", "*" );
response.addHeader( "Access-Control-Allow-Methods", "POST" );
response.addHeader( "Access-Control-Max-Age", "1000" );
How to horizontally center an unordered list of unknown width?
The answer of philfreo is great, it works perfectly (cross-browser, with IE 7+). Just add my exp for the anchor tag inside li.
#footer ul li { display: inline; }
#footer ul li a { padding: 2px 4px; } /* no display: block here */
#footer ul li { position: relative; float: left; display: block; right: 50%; }
#footer ul li a {display: block; left: 0; }
What is the best Java email address validation method?
Heres my pragmatic approach, where I just want reasonable distinct blah@domain addresses using the allowable characters from the RFC. Addresses must be converted to lowercase beforehand.
public class EmailAddressValidator {
private static final String domainChars = "a-z0-9\\-";
private static final String atomChars = "a-z0-9\\Q!#$%&'*+-/=?^_`{|}~\\E";
private static final String emailRegex = "^" + dot(atomChars) + "@" + dot(domainChars) + "$";
private static final Pattern emailPattern = Pattern.compile(emailRegex);
private static String dot(String chars) {
return "[" + chars + "]+(?:\\.[" + chars + "]+)*";
}
public static boolean isValidEmailAddress(String address) {
return address != null && emailPattern.matcher(address).matches();
}
}
How to use SVG markers in Google Maps API v3
If you need a full svg not only a path and you want it to be modifiable on client side (e.g. change text, hide details, ...) you can use an alternative data 'URL' with included svg:
var svg = '<svg width="400" height="110"><rect width="300" height="100" /></svg>';
icon.url = 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg);
JavaScript (Firefox) btoa() is used to get the base64 encoding from the SVG text. Your may also use http://dopiaza.org/tools/datauri/index.php to generate base data URLs.
Here is a full example jsfiddle:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var template = [
'<?xml version="1.0"?>',
'<svg width="26px" height="26px" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">',
'<circle stroke="#222" fill="{{ color }}" cx="50" cy="50" r="35"/>',
'</svg>'
].join('\n');
var svg = template.replace('{{ color }}', '#800');
var docMarker = new google.maps.Marker({
position: new google.maps.LatLng(-33.92, 151.25),
map: map,
title: 'Dynamic SVG Marker',
icon: { url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg), scaledSize: new google.maps.Size(20, 20) },
optimized: false
});
var docMarker = new google.maps.Marker({
position: new google.maps.LatLng(-33.95, 151.25),
map: map,
title: 'Dynamic SVG Marker',
icon: { url: 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg), scaledSize: new google.maps.Size(20, 20) },
optimized: false
});
</script>
</body>
</html>
Additional Information can be found here.
Avoid base64 encoding:
In order to avoid base64 encoding you can replace 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg)
with 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg)
This should work with modern browsers down to IE9.
The advantage is that encodeURIComponent
is a default js function and available in all modern browsers. You might also get smaller links but you need to test this and consider to use '
instead of "
in your svg.
Also see Optimizing SVGs in data URIs for additional info.
IE support:
In order to support SVG Markers in IE one needs two small adaptions as described here: SVG Markers in IE. I updated the example code to support IE.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Including JavaScript class definition from another file in Node.js
You can simply do this:
user.js
class User {
//...
}
module.exports = User
server.js
const User = require('./user.js')
// Instantiate User:
let user = new User()
This is called CommonJS module.
Export multiple values
Sometimes it could be useful to export more than one value. For example it could be classes, functions or constants. This is an alternative version of the same functionality:
user.js
class User {}
exports.User = User // Spot the difference
server.js
const {User} = require('./user.js') // Destructure on import
// Instantiate User:
let user = new User()
ES Modules
Since Node.js version 14 it's possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.
?? Don't use globals, it creates potential conflicts with the future code.
Freeing up a TCP/IP port?
The "netstat --programs"
command will give you the process information, assuming you're the root
user. Then you will have to kill the "offending" process which may well start up again just to annoy you.
Depending on what you're actually trying to achieve, solutions to that problem will vary based on the processes holding those ports. For example, you may need to disable services (assuming they're unneeded) or configure them to use a different port (if you do need them but you need that port more).
Accessing Object Memory Address
There are a few issues here that aren't covered by any of the other answers.
First, id
only returns:
the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id()
value.
In CPython, this happens to be the pointer to the PyObject
that represents the object in the interpreter, which is the same thing that object.__repr__
displays. But this is just an implementation detail of CPython, not something that's true of Python in general. Jython doesn't deal in pointers, it deals in Java references (which the JVM of course probably represents as pointers, but you can't see those—and wouldn't want to, because the GC is allowed to move them around). PyPy lets different types have different kinds of id
, but the most general is just an index into a table of objects you've called id
on, which is obviously not going to be a pointer. I'm not sure about IronPython, but I'd suspect it's more like Jython than like CPython in this regard. So, in most Python implementations, there's no way to get whatever showed up in that repr
, and no use if you did.
But what if you only care about CPython? That's a pretty common case, after all.
Well, first, you may notice that id
is an integer;* if you want that 0x2aba1c0cf890
string instead of the number 46978822895760
, you're going to have to format it yourself. Under the covers, I believe object.__repr__
is ultimately using printf
's %p
format, which you don't have from Python… but you can always do this:
format(id(spam), '#010x' if sys.maxsize.bit_length() <= 32 else '#18x')
* In 3.x, it's an int
. In 2.x, it's an int
if that's big enough to hold a pointer—which is may not be because of signed number issues on some platforms—and a long
otherwise.
Is there anything you can do with these pointers besides print them out? Sure (again, assuming you only care about CPython).
All of the C API functions take a pointer to a PyObject
or a related type. For those related types, you can just call PyFoo_Check
to make sure it really is a Foo
object, then cast with (PyFoo *)p
. So, if you're writing a C extension, the id
is exactly what you need.
What if you're writing pure Python code? You can call the exact same functions with pythonapi
from ctypes
.
Finally, a few of the other answers have brought up ctypes.addressof
. That isn't relevant here. This only works for ctypes
objects like c_int32
(and maybe a few memory-buffer-like objects, like those provided by numpy
). And, even there, it isn't giving you the address of the c_int32
value, it's giving you the address of the C-level int32
that the c_int32
wraps up.
That being said, more often than not, if you really think you need the address of something, you didn't want a native Python object in the first place, you wanted a ctypes
object.
Updating a JSON object using Javascript
var i = jsonObj.length;
while ( i --> 0 ) {
if ( jsonObj[i].Id === 3 ) {
jsonObj[ i ].Username = 'Thomas';
break;
}
}
Or, if the array is always ordered by the IDs:
jsonObj[ 2 ].Username = 'Thomas';
How do I pass data to Angular routed components?
say you have
- component1.ts
- component1.html
and you want to pass data to component2.ts.
in component1.ts is a variable with data say
//component1.ts
item={name:"Nelson", bankAccount:"1 million dollars"}
//component1.html
//the line routerLink="/meter-readings/{{item.meterReadingId}}" has nothing to
//do with this , replace that with the url you are navigating to
<a
mat-button
[queryParams]="{ params: item | json}"
routerLink="/meter-readings/{{item.meterReadingId}}"
routerLinkActive="router-link-active">
View
</a>
//component2.ts
import { ActivatedRoute} from "@angular/router";
import 'rxjs/add/operator/filter';
/*class name etc and class boiler plate */
data:any //will hold our final object that we passed
constructor(
private route: ActivatedRoute,
) {}
ngOnInit() {
this.route.queryParams
.filter(params => params.reading)
.subscribe(params => {
console.log(params); // DATA WILL BE A JSON STRING- WE PARSE TO GET BACK OUR
//OBJECT
this.data = JSON.parse(params.item) ;
console.log(this.data,'PASSED DATA'); //Gives {name:"Nelson", bankAccount:"1
//million dollars"}
});
}
How to split a string in shell and get the last field
There are many good answers here, but still I want to share this one using basename :
basename $(echo "a:b:c:d:e" | tr ':' '/')
However it will fail if there are already some '/' in your string.
If slash / is your delimiter then you just have to (and should) use basename.
It's not the best answer but it just shows how you can be creative using bash commands.
After installing with pip, "jupyter: command not found"
On Mac OS you need to export ~/.local/bin
inside your $PATH
variable.
# Edit the bash profile:
$ vim ~/.bash_profile
# Add this line inside ~/.bash_profile:
export PATH=$PATH:~/.local/bin
# Update the source:
$ source ~/.bash_profile
# Open Jupyter:
$ jupyter notebook
Get a filtered list of files in a directory
glob.glob()
is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and re.match()
, something like so:
files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]
More flexible, but as you note, less efficient.
Clear text from textarea with selenium
driver.find_element_by_xpath("path").send_keys(Keys.CONTROL + u'\ue003')
worked great with FireFox
- u'\ue003' is a BACK_SPACE for those like me - never remembering it)
Can't start Tomcat as Windows Service
You need to check the ports first. It might be situation that default port(8080) is used by some other application.
Try changing the port from 8080 to some different port in conf/server.xml file.
Also please check that your JRE_HOME variable is set correctly because tomcat needs JRE to run. You can also set your JRE_HOME variable in system. For that go to my computer->right click and select properties->Advanced system settings->Advanced->Environment variable and click on new-> variable name = "JRE_HOME" and variable value = "C:\Program Files\Java\jre7"
Split a python list into other "sublists" i.e smaller lists
I'd say
chunks = [data[x:x+100] for x in range(0, len(data), 100)]
If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange()
, changing the above code to:
chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]
Bootstrap: add margin/padding space between columns
You may use the padding and margin shorthand Bootstrap 4 classes as follows:
For extra small devices i.e. xs
{property}{sides}-{size}
For other devices/viewports (small, medium, large and extra large)
{property}{sides}-{breakpoint}-{size}
Where:
property = m for margin and p for padding
Following are sides shorthand meanings:
l = defines the left-margin or left-padding
r = defines the right-margin or right-padding
t = defines the top-margin or top-padding
b = defines the bottom-margin or right-padding
x = For setting left and right padding and margins by the single call
y = For setting top and bottom margins
blank = margin and padding for all sides
The breakpoint = sm, md, lg, and xl.
Combining all the above, the left padding complete code can be (for example):
For left padding in extra small devices
pl-2
or for medium to extra large
pl-md-2
iPad/iPhone hover problem causes the user to double click a link
To get the links working without breaking touch scrolling, I solved this with jQuery Mobile's "tap" event:
$('a').not('nav.navbar a').on("tap", function () {
var link = $(this).attr('href');
if (typeof link !== 'undefined') {
window.location = link;
}
});
Make copy of an array
If you want to make a copy of:
int[] a = {1,2,3,4,5};
This is the way to go:
int[] b = Arrays.copyOf(a, a.length);
Arrays.copyOf
may be faster than a.clone()
on small arrays. Both copy elements equally fast but clone() returns Object
so the compiler has to insert an implicit cast to int[]
. You can see it in the bytecode, something like this:
ALOAD 1
INVOKEVIRTUAL [I.clone ()Ljava/lang/Object;
CHECKCAST [I
ASTORE 2
MySQL select rows where left join is null
You could use the following query:
SELECT table1.id
FROM table1
LEFT JOIN table2
ON table1.id IN (table2.user_one, table2.user_two)
WHERE table2.user_one IS NULL;
Although, depending on your indexes on table2
you may find that two joins performs better:
SELECT table1.id
FROM table1
LEFT JOIN table2 AS t1
ON table1.id = t1.user_one
LEFT JOIN table2 AS t2
ON table1.id = t2.user_two
WHERE t1.user_one IS NULL
AND t2.user_two IS NULL;
Android Studio - No JVM Installation found
1 .Download 64 bit version of JDK from here
As shown in next picture, go to Control Panel
-> System and Security
-> Advanced system settings
-> Environment Variables
-> New
(System variables)
Then add variable name: JAVA_HOME and variable value: C:\Program Files\Java\jdk1.8.0_25
Please note that jdk1.8.0_25
may be vary depending on JDK version.
- Click OK button on the rest of the windows left.
how to check confirm password field in form without reloading page
We will be looking at two approaches to achieve this. With and without using jQuery.
1. Using jQuery
You need to add a keyup function to both of your password and confirm password fields. The reason being that the text equality should be checked even if the password
field changes. Thanks @kdjernigan for pointing that out
In this way, when you type in the field you will know if the password is same or not:
_x000D_
_x000D_
$('#password, #confirm_password').on('keyup', function () {
if ($('#password').val() == $('#confirm_password').val()) {
$('#message').html('Matching').css('color', 'green');
} else
$('#message').html('Not Matching').css('color', 'red');
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
<input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
<span id='message'></span>
</label>
_x000D_
_x000D_
_x000D_
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/
2. Without using jQuery
We will use the onkeyup event of javascript on both the fields to achieve the same effect.
_x000D_
_x000D_
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'matching';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'not matching';
}
}
_x000D_
<label>password :
<input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onkeyup='check();' />
<span id='message'></span>
</label>
_x000D_
_x000D_
_x000D_
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/
Can I create view with parameter in MySQL?
I previously came up with a different workaround that doesn't use stored procedures, but instead uses a parameter table and some connection_id() magic.
EDIT (Copied up from comments)
create a table that contains a column called connection_id
(make it a bigint). Place columns in that table for parameters for the view. Put a primary key on the connection_id
. replace into the parameter table and use CONNECTION_ID()
to populate the connection_id value. In the view use a cross join to the parameter table and put WHERE param_table.connection_id = CONNECTION_ID()
. This will cross join with only one row from the parameter table which is what you want. You can then use the other columns in the where clause for example where orders.order_id = param_table.order_id
.
Listing all extras of an Intent
Sorry if this is too verbose or too late, but this was the only way I could find to get the job done. The most complicating factor was the fact that java does not have pass by reference functions, so the get---Extra methods need a default to return and cannot modify a boolean value to tell whether or not the default value is being returned by chance, or because the results were not favorable. For this purpose, it would have been nicer to have the method raise an exception than to have it return a default.
I found my information here: Android Intent Documentation.
//substitute your own intent here
Intent intent = new Intent();
intent.putExtra("first", "hello");
intent.putExtra("second", 1);
intent.putExtra("third", true);
intent.putExtra("fourth", 1.01);
// convert the set to a string array
Set Documentation
String[] anArray = {};
Set<String> extras1 = (Set<String>) intent.getExtras().keySet();
String[] extras = (String[]) extras1.toArray(anArray);
// an arraylist to hold all of the strings
// rather than putting strings in here, you could display them
ArrayList<String> endResult = new ArrayList<String>();
for (int i=0; i<extras.length; i++) {
//try using as a String
String aString = intent.getStringExtra(extras[i]);
// is a string, because the default return value for a non-string is null
if (aString != null) {
endResult.add(extras[i] + " : " + aString);
}
// not a string
else {
// try the next data type, int
int anInt = intent.getIntExtra(extras[i], 0);
// is the default value signifying that either it is not an int or that it happens to be 0
if (anInt == 0) {
// is an int value that happens to be 0, the same as the default value
if (intent.getIntExtra(extras[i], 1) != 1) {
endResult.add(extras[i] + " : " + Integer.toString(anInt));
}
// not an int value
// try double (also works for float)
else {
double aDouble = intent.getDoubleExtra(extras[i], 0.0);
// is the same as the default value, but does not necessarily mean that it is not double
if (aDouble == 0.0) {
// just happens that it was 0.0 and is a double
if (intent.getDoubleExtra(extras[i], 1.0) != 1.0) {
endResult.add(extras[i] + " : " + Double.toString(aDouble));
}
// keep looking...
else {
// lastly check for boolean
boolean aBool = intent.getBooleanExtra(extras[i], false);
// same as default, but not necessarily not a bool (still could be a bool)
if (aBool == false) {
// it is a bool!
if (intent.getBooleanExtra(extras[i], true) != true) {
endResult.add(extras[i] + " : " + Boolean.toString(aBool));
}
else {
//well, the road ends here unless you want to add some more data types
}
}
// it is a bool
else {
endResult.add(extras[i] + " : " + Boolean.toString(aBool));
}
}
}
// is a double
else {
endResult.add(extras[i] + " : " + Double.toString(aDouble));
}
}
}
// is an int value
else {
endResult.add(extras[i] + " : " + Integer.toString(anInt));
}
}
}
// to display at the end
for (int i=0; i<endResult.size(); i++) {
Toast.makeText(this, endResult.get(i), Toast.LENGTH_SHORT).show();
}
Preferred Java way to ping an HTTP URL for availability
Is this any good at all (will it do what I want?)
You can do so. Another feasible way is using java.net.Socket
.
public static boolean pingHost(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
} catch (IOException e) {
return false; // Either timeout or unreachable or failed DNS lookup.
}
}
There's also the InetAddress#isReachable()
:
boolean reachable = InetAddress.getByName(hostname).isReachable();
This however doesn't explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.
Do I have to somehow close the connection?
No, you don't explicitly need. It's handled and pooled under the hoods.
I suppose this is a GET request. Is there a way to send HEAD instead?
You can cast the obtained URLConnection
to HttpURLConnection
and then use setRequestMethod()
to set the request method. However, you need to take into account that some poor webapps or homegrown servers may return HTTP 405 error for a HEAD (i.e. not available, not implemented, not allowed) while a GET works perfectly fine. Using GET is more reliable in case you intend to verify links/resources not domains/hosts.
Testing the server for availability is not enough in my case, I need to test the URL (the webapp may not be deployed)
Indeed, connecting a host only informs if the host is available, not if the content is available. It can as good happen that a webserver has started without problems, but the webapp failed to deploy during server's start. This will however usually not cause the entire server to go down. You can determine that by checking if the HTTP response code is 200.
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
// Not OK.
}
// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error
For more detail about response status codes see RFC 2616 section 10. Calling connect()
is by the way not needed if you're determining the response data. It will implicitly connect.
For future reference, here's a complete example in flavor of an utility method, also taking account with timeouts:
/**
* Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in
* the 200-399 range.
* @param url The HTTP URL to be pinged.
* @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
* the total timeout is effectively two times the given timeout.
* @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
* given timeout, otherwise <code>false</code>.
*/
public static boolean pingURL(String url, int timeout) {
url = url.replaceFirst("^https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
return (200 <= responseCode && responseCode <= 399);
} catch (IOException exception) {
return false;
}
}
Invoking JavaScript code in an iframe from the parent page
There are some quirks to be aware of here.
HTMLIFrameElement.contentWindow
is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the window
object.
You can also try HTMLIFrameElement.contentDocument.defaultView
, which a couple of older browsers allow but IE doesn't. Even so, the standard doesn't explicitly say that you get the window
object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care.
window.frames['name']
returning the window is the oldest and hence most reliable interface. But you then have to use a name="..."
attribute to be able to get a frame by name, which is slightly ugly/deprecated/transitional. (id="..."
would be better but IE doesn't like that.)
window.frames[number]
is also very reliable, but knowing the right index is the trick. You can get away with this eg. if you know you only have the one iframe on the page.
It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its window.parent
script when it has finished loaded and is ready to be called back. By passing one of its own objects (eg. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with.
Best way to get value from Collection by index
you definitively want a List:
The List interface provides four methods for positional (indexed) access to list elements.
Lists (like Java arrays) are zero based.
Also
Note that these operations may execute in time proportional to the index value for some
implementations (the LinkedList class, for example). Thus, iterating over the elements in a > list is typically preferable to indexing through it if the caller does not know the
implementation.
If you need the index in order to modify your collection you should note that List provides a special ListIterator that allow you to get the index:
List<String> names = Arrays.asList("Davide", "Francesco", "Angelocola");
ListIterator<String> i = names.listIterator();
while (i.hasNext()) {
System.out.format("[%d] %s\n", i.nextIndex(), i.next());
}
ANTLR: Is there a simple example?
ANTLR mega tutorial by Gabriele Tomassetti is very helpful
It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.
EDIT: other useful articles by Gabriele Tomassetti on ANTLR
How to get last items of a list in Python?
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]
How to send characters in PuTTY serial communication only when pressing enter?
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’
Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
Where to change default pdf page width and font size in jspdf.debug.js?
My case was to print horizontal (landscape) summary section - so:
}).then((canvas) => {
const img = canvas.toDataURL('image/jpg');
new jsPDF({
orientation: 'l', // landscape
unit: 'pt', // points, pixels won't work properly
format: [canvas.width, canvas.height] // set needed dimensions for any element
});
pdf.addImage(img, 'JPEG', 0, 0, canvas.width, canvas.height);
pdf.save('your-filename.pdf');
});
variable or field declared void
It for example happens in this case here:
void initializeJSP(unknownType Experiment);
Try using std::string
instead of just string
(and include the <string>
header). C++ Standard library classes are within the namespace std::
.
What is @RenderSection in asp.net MVC
If you have a _Layout.cshtml view like this
<html>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
then you can have an index.cshtml content view like this
@section scripts {
<script type="text/javascript">alert('hello');</script>
}
the required indicates whether or not the view using the layout page must have a scripts section
Difference between DOMContentLoaded and load events
DOMContentLoaded
==window.onDomReady()
Load
==window.onLoad()
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $(document).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $(window).load(function() { ... })
will run once the entire page (images or iframes), not just the DOM, is ready.
See: Using JQuery Core's document-ready documentation.
In WPF, what are the differences between the x:Name and Name attributes?
The specified x:Name becomes the name of a field that is created in the underlying code when XAML is processed, and that field holds a reference to the object. In Silverlight, using the managed API, the process of creating this field is performed by the MSBuild target steps, which also are responsible for joining the partial classes for a XAML file and its code-behind. This behavior is not necessarily XAML-language specified; it is the particular implementation that Silverlight applies to use x:Name in its programming and application models.
Read More on MSDN...
CSS transition when class removed
In my case i had some problem with opacity transition so this one fix it:
#dropdown {
transition:.6s opacity;
}
#dropdown.ns {
opacity:0;
transition:.6s all;
}
#dropdown.fade {
opacity:1;
}
Mouse Enter
$('#dropdown').removeClass('ns').addClass('fade');
Mouse Leave
$('#dropdown').addClass('ns').removeClass('fade');
Apply CSS styles to an element depending on its child elements
As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.
It'd be wonderful if you could do something like div[div.a]
or div:containing[div.a]
as you said, but this isn't possible.
You may want to consider looking at jQuery. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.
If you use jQuery, something along the lines of this would may work (untested but the theory is there):
$('div:has(div.a)').css('border', '1px solid red');
or
$('div:has(div.a)').addClass('redBorder');
combined with a CSS class:
.redBorder
{
border: 1px solid red;
}
Here's the documentation for the jQuery "has" selector.
Python append() vs. + operator on lists, why do these give different results?
The concatenation operator +
is a binary infix operator which, when applied to lists, returns a new list containing all the elements of each of its two operands. The list.append()
method is a mutator
on list
which appends its single object
argument (in your specific example the list c
) to the subject list
. In your example this results in c
appending a reference to itself (hence the infinite recursion).
An alternative to '+' concatenation
The list.extend()
method is also a mutator method which concatenates its sequence
argument with the subject list
. Specifically, it appends each of the elements of sequence
in iteration order.
An aside
Being an operator, +
returns the result of the expression as a new value. Being a non-chaining mutator
method, list.extend()
modifies the subject list in-place and returns nothing.
Arrays
I've added this due to the potential confusion which the Abel's answer above may cause by mixing the discussion of lists, sequences and arrays.
Arrays
were added to Python after sequences and lists, as a more efficient way of storing arrays of integral data types. Do not confuse arrays
with lists
. They are not the same.
From the array docs:
Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character.
Python error: "IndexError: string index out of range"
There were several problems in your code.
Here you have a functional version you can analyze (Lets set 'hello' as the target word):
word = 'hello'
so_far = "-" * len(word) # Create variable so_far to contain the current guess
while word != so_far: # if still not complete
print(so_far)
guess = input('>> ') # get a char guess
if guess in word:
print("\nYes!", guess, "is in the word!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess # fill the position with new value
else:
new += so_far[i] # same value as before
so_far = new
else:
print("try_again")
print('finish')
I tried to write it for py3k with a py2k ide, be careful with errors.
Upload file to FTP using C#
public static void UploadFileToFtp(string url, string filePath, string username, string password)
{
var fileName = Path.GetFileName(filePath);
var request = (FtpWebRequest)WebRequest.Create(url + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (var fileStream = File.OpenRead(filePath))
{
using (var requestStream = request.GetRequestStream())
{
fileStream.CopyTo(requestStream);
requestStream.Close();
}
}
var response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload done: {0}", response.StatusDescription);
response.Close();
}
jquery input select all on focus
There are some decent answers here and @user2072367 's is my favorite, but it has an unexpected result when you focus via tab rather than via click. ( unexpected result: to select text normally after focus via tab, you must click one additional time )
This fiddle fixes that small bug and additionally stores $(this) in a variable to avoid redundant DOM selection. Check it out! (:
Tested in IE > 8
$('input').on('focus', function() {
var $this = $(this)
.one('mouseup.mouseupSelect', function() {
$this.select();
return false;
})
.one('mousedown', function() {
// compensate for untriggered 'mouseup' caused by focus via tab
$this.off('mouseup.mouseupSelect');
})
.select();
});
Cursor adapter and sqlite example
Really simple example.
Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.
There are two main parts to using a Cursor Adapter with SQLite:
Create a proper Cursor from the Database.
Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.
1. Create a proper Cursor from the Database.
In your Activity:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper(
context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();
String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';'
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
ClientCursorAdapter adapter = new ClientCursorAdapter(
this, R.layout.clients_listview_row, cursor, 0 );
this.setListAdapter(adapter);
2. Create a Custom Cursor Adapter.
Note: Extending from ResourceCursorAdapter
assumes you use XML to create your views.
public class ClientCursorAdapter extends ResourceCursorAdapter {
public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
super(context, layout, cursor, flags);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(cursor.getString(cursor.getColumnIndex("name")));
TextView phone = (TextView) view.findViewById(R.id.phone);
phone.setText(cursor.getString(cursor.getColumnIndex("phone")));
}
}
What is the difference between a string and a byte string?
Note: I will elaborate more my answer for Python 3 since the end of life of Python 2 is very close.
In Python 3
bytes
consists of sequences of 8-bit unsigned values, while str
consists of sequences of Unicode code points that represent textual characters from human languages.
>>> # bytes
>>> b = b'h\x65llo'
>>> type(b)
<class 'bytes'>
>>> list(b)
[104, 101, 108, 108, 111]
>>> print(b)
b'hello'
>>>
>>> # str
>>> s = 'nai\u0308ve'
>>> type(s)
<class 'str'>
>>> list(s)
['n', 'a', 'i', '¨', 'v', 'e']
>>> print(s)
nai¨ve
Even though bytes
and str
seem to work the same way, their instances are not compatible with each other, i.e, bytes
and str
instances can't be used together with operators like >
and +
. In addition, keep in mind that comparing bytes
and str
instances for equality, i.e. using ==
, will always evaluate to False
even when they contain exactly the same characters.
>>> # concatenation
>>> b'hi' + b'bye' # this is possible
b'hibye'
>>> 'hi' + 'bye' # this is also possible
'hibye'
>>> b'hi' + 'bye' # this will fail
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat str to bytes
>>> 'hi' + b'bye' # this will also fail
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "bytes") to str
>>>
>>> # comparison
>>> b'red' > b'blue' # this is possible
True
>>> 'red'> 'blue' # this is also possible
True
>>> b'red' > 'blue' # you can't compare bytes with str
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'bytes' and 'str'
>>> 'red' > b'blue' # you can't compare str with bytes
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'bytes'
>>> b'blue' == 'red' # equality between str and bytes always evaluates to False
False
>>> b'blue' == 'blue' # equality between str and bytes always evaluates to False
False
Another issue when dealing with bytes
and str
is present when working with files that are returned using the open
built-in function. On one hand, if you want ot read or write binary data to/from a file, always open the file using a binary mode like 'rb' or 'wb'. On the other hand, if you want to read or write Unicode data to/from a file, be aware of the default encoding of your computer, so if necessary pass the encoding
parameter to avoid surprises.
In Python 2
str
consists of sequences of 8-bit values, while unicode
consists of sequences of Unicode characters. One thing to keep in mind is that str
and unicode
can be used together with operators if str
only consists of 7-bit ASCI characters.
It might be useful to use helper functions to convert between str
and unicode
in Python 2, and between bytes
and str
in Python 3.
How do I stop/start a scheduled task on a remote computer programmatically?
Here's what I found.
stop:
schtasks /end /s <machine name> /tn <task name>
start:
schtasks /run /s <machine name> /tn <task name>
C:\>schtasks /?
SCHTASKS /parameter [arguments]
Description:
Enables an administrator to create, delete, query, change, run and
end scheduled tasks on a local or remote system. Replaces AT.exe.
Parameter List:
/Create Creates a new scheduled task.
/Delete Deletes the scheduled task(s).
/Query Displays all scheduled tasks.
/Change Changes the properties of scheduled task.
/Run Runs the scheduled task immediately.
/End Stops the currently running scheduled task.
/? Displays this help message.
Examples:
SCHTASKS
SCHTASKS /?
SCHTASKS /Run /?
SCHTASKS /End /?
SCHTASKS /Create /?
SCHTASKS /Delete /?
SCHTASKS /Query /?
SCHTASKS /Change /?
What is the difference between `throw new Error` and `throw someObject`?
you can throw
as object
throw ({message: 'This Failed'})
then for example in your try/catch
try {
//
} catch(e) {
console.log(e); //{message: 'This Failed'}
console.log(e.message); //This Failed
}
or just throw a string error
throw ('Your error')
try {
//
} catch(e) {
console.log(e); //Your error
}
throw new Error //only accept a string
How to do a join in linq to sql with method syntax?
To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:
public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
{
var result = entityFrameworkObjectContext.SomeClass
.Join(entityFrameworkObjectContext.SomeOtherClass,
sc => sc.property1,
soc => soc.property2,
(sc, soc) => new {sc, soc})
.Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
.Select(s => new ThirdNonEntityClass
{
dataValue1 = s.sc.dataValueA,
dataValue2 = s.soc.dataValueB
})
.ToList();
}
return result;
}
Pay special attention to the intermediate object that is created in the Where and Select clauses.
Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.
I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.
How to get twitter bootstrap modal to close (after initial launch)
.modal('hide') manually hides a modal. Use following code to close your bootstrap model
$('#myModal').modal('hide');
Take a look at working codepen here
Or
Try here
_x000D_
_x000D_
$(function () {_x000D_
$(".custom-close").on('click', function() {_x000D_
$('#myModal').modal('hide');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- Button trigger modal -->_x000D_
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
Launch demo modal_x000D_
</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
_x000D_
_x000D_
<a class="custom-close"> My Custom Close Link </a>_x000D_
_x000D_
_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
<button type="button" class="btn btn-primary">Save changes</button>_x000D_
</div>_x000D_
</div><!-- /.modal-content -->_x000D_
</div><!-- /.modal-dialog -->_x000D_
</div><!-- /.modal -->
_x000D_
_x000D_
_x000D_
Propagation Delay vs Transmission delay
Transmission Delay : Amount of time required to pump all bits/packets into the electric wire/optic fibre.
Propagation delay : It's the amount of time needed for a packet to reach the destination.
If propagation delay is very high than transmission delay the chance of losing the packet is high.
Difference between wait and sleep
A wait
can be "woken up" by another thread calling notify
on the monitor which is being waited on whereas a sleep
cannot. Also a wait
(and notify
) must happen in a block synchronized
on the monitor object whereas sleep
does not:
Object mon = ...;
synchronized (mon) {
mon.wait();
}
At this point the currently executing thread waits and releases the monitor. Another thread may do
synchronized (mon) { mon.notify(); }
(on the same mon
object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
You can also call notifyAll
if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait
is in a synchronized
block) and carry on – the others will then be blocked until they can acquire the monitor's lock.
Another point is that you call wait
on Object
itself (i.e. you wait on an object's monitor) whereas you call sleep
on Thread
.
Yet another point is that you can get spurious wakeups from wait
(i.e. the thread which is waiting resumes for no apparent reason). You should always wait
whilst spinning on some condition as follows:
synchronized {
while (!condition) { mon.wait(); }
}
How to open a workbook specifying its path
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
How to right-align and justify-align in Markdown?
Specific to your usage of a Jupyter Notebook: the ability to specify table column alignment should return in a future release. (Current releases default to right-aligned everywhere.)
From PR #4130:
Allow markdown tables to specify their alignment with the :--, :--:, --: syntax while still allowing --- to default to right alignment.
This reverts a previous change (part of #2534) that stripped the alignment information from the rendered HTML coming out of the marked renderer. To be clear this does not change the right alignment default but does bring back support for overriding this alignment per column by using the gfm table alignment syntax.
...
How to remove all elements in String array in java?
Usually someone uses collections if something frequently changes.
E.g.
List<String> someList = new ArrayList<String>();
// initialize list
someList.add("Mango");
someList.add("....");
// remove all elements
someList.clear();
// empty list
An ArrayList
for example uses a backing Array
. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.
How to detect the device orientation using CSS media queries?
I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good.
Ex:
For Mobile
@media screen and (max-width:767px) {
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {
..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.
}
For Tablet
@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){
..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.
}
Desktop
make as per your design requirement enjoy...(:
Thanks,
Jitu
Importing class from another file
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
Prevent screen rotation on Android
Activity.java
@Override
public void onConfigurationChanged(Configuration newConfig) {
try {
super.onConfigurationChanged(newConfig);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// land
} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
// port
}
} catch (Exception ex) {
}
AndroidManifest.xml
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name="QRCodeActivity" android:label="@string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Generate SQL Create Scripts for existing tables with Query
do you mean you wish to create a TSQL script which generates a CREATE script, or use the Management tools in SQL SERVER Management Studio to generate a Create script?
If it's the latter, it's a simply matter of right-clicking a table, and selecting Script Table As -> Create To -> New Query Window.
If you want the whole database scripted, then right click the database and select Tasks--> Generate Scripts... and then follow the wizard
otherwise it's a matter of selecting all sorts of fun things out of the various system tables.
Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1
This problem usually occurs when there are more than two versions of XCode are installed in which different Swift versions incorporated for Ex. XCode 6.4 and XCode 7.3 are installed which are running Swift 1.2 and Swift 2.0. By mistake you tries to compile code with icorrect version for Ex. your project in in Swift 1.2 and you tries to compile it with xcode 7.3. In this case drive data stores information for swift version but when you tries to compile code with correct XCode it gives error.
To resolve this
- Delete drive Data
a. In Xcode select preferences
- Once preferences are open click on Location tab and click on the arrow in front of the 'Drived data' path. It will open drived data folder
- Quit Xcode
- Delete all drive data.
- reopen the project in correct XCode error is fixed !!!!!!
How do I get the base URL with PHP?
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";
$dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '',$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']);
echo $url = $http . $dir;
// echo $url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];
How to find the port for MS SQL Server 2008?
In the ERROLOG log for a line like below. If you don't see it the SQL Server isn't enabled for remote access, or it is just not via TCP. You can change this via the SQL Server Configuration Manager.
Server is listening on [ 192.128.3.2 <ipv4> 1433].
How do I access named capturing groups in a .NET Regex?
You specify the named capture group string by passing it to the indexer of the Groups
property of a resulting Match
object.
Here is a small example:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
String sample = "hello-world-";
Regex regex = new Regex("-(?<test>[^-]*)-");
Match match = regex.Match(sample);
if (match.Success)
{
Console.WriteLine(match.Groups["test"].Value);
}
}
}
Java optional parameters
If you are planning to use an interface with multiple parameters,
one can use the following structural pattern and implement or override apply - a method based on your requirement.
public abstract class Invoker<T> {
public T apply() {
return apply(null);
}
public abstract T apply(Object... params);
}
How to read value of a registry key c#
You need to first add using Microsoft.Win32;
to your code page.
Then you can begin to use the Registry
classes:
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
{
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String); //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
//do what you like with version
}
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE
. Sometimes even reading values can be a suspect operation without admin rights.
Rebuild all indexes in a Database
DECLARE @String NVARCHAR(MAX);
USE Databse Name;
SELECT @String
=
(
SELECT 'ALTER INDEX [' + dbindexes.[name] + '] ON [' + db.name + '].[' + dbschemas.[name] + '].[' + dbtables.[name]
+ '] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);' + CHAR(10) AS [text()]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables
ON dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas
ON dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes
ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
INNER JOIN sys.databases AS db
ON db.database_id = indexstats.database_id
WHERE dbindexes.name IS NOT NULL
AND indexstats.database_id = DB_ID()
AND indexstats.avg_fragmentation_in_percent >= 10
ORDER BY indexstats.page_count DESC
FOR XML PATH('')
);
EXEC (@String);
iOS 6 apps - how to deal with iPhone 5 screen size?
@Pascal's comment on the OP's question is right. By simply adding the image, it removes the black borders and the app will use the full height.
You will need to make adjustments to any CGRects by determining that the device is using the bigger display. I.e. If you need something aligned to the bottom of the screen.
I am sure there is a built in method, but I haven't seen anything and a lot is still under NDA so the method we use in our apps is quite simply a global function. Add the following to your .pch file and then its a simple if( is4InchRetina() ) { ... }
call to make adjustments to your CGRects etc.
static BOOL is4InchRetina()
{
if (![UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 548 || [UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 568)
return YES;
return NO;
}
How to close Browser Tab After Submitting a Form?
This worked brilliantly for me, :
$query = "INSERT INTO `table` (...or put your preferred sql stuff)"
$result = mysqli_query($connect, $query);
if($result){
// If everything runs fine with your sql query you will see a message and then the window
//closes
echo '<script language="javascript">';
echo 'alert("Successful!")';
echo '</script>';
echo "<script>window.close();</script>";
}
else {
echo '<script language="javascript">';
echo 'alert("Problem with database or something!")';
echo '</script>';
}
Reverse HashMap keys and values in Java
Iterate through the list of keys and values, then add them.
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (String key : myHashMap.keySet()){
reversedHashMap.put(myHashMap.get(key), key);
}
Oracle: not a valid month
1.
To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE
is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...
SQL> select sysdate from dual;
SYSDATE
---------
26-SEP-12
Which means my session's setting is DD-Mon-YY
SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;
TO_CHAR(SY
----------
09/26/2012
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
*
ERROR at line 1:
ORA-01843: not a valid month
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;
TO_DATE(T
---------
26-SEP-12
2.
More importantly, Why are you converting to char and then to date, instead of directly comparing
MaxDate = REP_DATE
If you want to ignore the time component in MaxDate before comparision, you should use..
trunc(MaxDate ) = rep_date
instead.
==Update : based on updated question.
Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00
I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.
If it is a running system and you have no control over repdate, you could try this.
trunc(rep_date) = trunc(maxdate) and
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')
Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.
Floating Point Exception C++ Why and what is it?
Problem is in the for loop in the code snippet:
for (i > 0; i--;)
Here, your intention seems to be entering the loop if (i > 0) and
decrement the value of i by one after the completion of for loop.
Does it work like that? lets see.
Look at the for() loop syntax:
**for ( initialization; condition check; increment/decrement ) {
statements;
}**
Initialization gets executed only once in the beginning of the loop.
Pay close attention to ";" in your code snippet and map it with for loop syntax.
Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.
Condition check : i -- : post decrement.
Here, i is used for condition check and then it is decremented.
Decremented value will be used in statements within for loop.
This condition check is working as increment/decrement too in your code.
Lets stop here and see floating point exception.
what is it? One easy example is Divide by 0. Same is happening with your code.
When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.
Modulo operation at line #9 results in divide by zero operation.
With this background you should be able to fix the problem in for loop.
Oracle date to string conversion
Try this. Oracle has this feature to distinguish the millennium years..
As you mentioned, if your column is a varchar, then the below query will yield you 1989..
select to_date(column_name,'dd/mm/rr') from table1;
When the format rr is used in year, the following would be done by oracle.
if rr->00 to 49 ---> result will be 2000 - 2049,
if rr->50 to 99 ---> result will be 1950 - 1999
How to append a date in batch files
This is all awkward and not local settings independent. Do it like this:
%CYGWIN_DIR%\bin\date +%%Y%%m%%d_%%H%%M% > date.txt
for /f "delims=" %%a in ('type "date.txt" 2^>NUL') do set datetime=%%a
echo %datetime%
del date.txt
Yes, use Cygwin date and all your problems are gone!
What's the difference between MyISAM and InnoDB?
The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".
If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.
Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.
Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.
So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.
A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.
The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.
Error: «Could not load type MvcApplication»
Ahh this was annoying.
Got this error after a power cut and i returned to my project.
I tried restarted VS.
I tried setting the output path to \bin.
I checked my name spaces.
But what worked for me was rebuilding the solution.
Rebuild Solution!!!
Remove blank attributes from an Object in Javascript
You can do a recursive removal in one line using json.stringify's replacer argument
const removeEmptyValues = obj => (
JSON.parse(JSON.stringify(obj, (k,v) => v ?? undefined))
)
Usage:
removeEmptyValues({a:{x:1,y:null,z:undefined}}) // Returns {a:{x:1}}
As mentioned in Emmanuel's comment, this technique only worked if your data structure contains only data types that can be put into JSON format (strings, numbers, lists, etc).
(This answer has been updated to use the new Nullish Coalescing operator. depending on browser support needs you may want to use this function instead: (k,v) => v!=null ? v : undefined
)
Asyncio.gather vs asyncio.wait
asyncio.wait
is more low level than asyncio.gather
.
As the name suggests, asyncio.gather
mainly focuses on gathering the results. It waits on a bunch of futures and returns their results in a given order.
asyncio.wait
just waits on the futures. And instead of giving you the results directly, it gives done and pending tasks. You have to manually collect the values.
Moreover, you could specify to wait for all futures to finish or just the first one with wait
.
missing FROM-clause entry for table
SELECT
AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit,
BillLimit, Mode, PNotes, gtab82.memno
FROM
VCustomer AS v1
INNER JOIN
gtab82 ON gtab82.memacid = v1.AcId
WHERE (AcGrCode = '204' OR CreDebt = 'True')
AND Masked = 'false'
ORDER BY AcName
You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer
but only use it in the ON
clause for uncertain reasons. You may want to review that aspect of your code.
ITextSharp insert text to an existing pdf
I found a way to do it (dont know if it is the best but it works)
string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
I hope this can be usefull for someone =) (and post here any errors)
Remove HTML Tags from an NSString on the iPhone
UITextView *textview= [[UITextView alloc]initWithFrame:CGRectMake(10, 130, 250, 170)];
NSString *str = @"This is <font color='red'>simple</font>";
[textview setValue:str forKey:@"contentToHTMLString"];
textview.textAlignment = NSTextAlignmentLeft;
textview.editable = NO;
textview.font = [UIFont fontWithName:@"vardana" size:20.0];
[UIView addSubview:textview];
work fine for me
How to send only one UDP packet with netcat?
I did not find the -q1
option on my netcat. Instead I used the -w1
option. Below is the bash script I did to send an udp packet to any host and port:
#!/bin/bash
def_host=localhost
def_port=43211
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "$1" | nc -4u -w1 $HOST $PORT
jQuery .get error response function?
You can get detail error by using responseText property.
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error + "\nError detail: " + xhr.responseText);
}
});
Convert array of strings to List<string>
From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.
Usage looks like this:
using System.Linq;
// ...
public void My()
{
var myArray = new[] { "abc", "123", "zyx" };
List<string> myList = myArray.ToList();
}
PS. There's also ToArray()
method that works in other way.
How to make a phone call programmatically?
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+198+","+1+","+1));
startActivity(callIntent);
for multiple ordered call
This is used to DTMF calling systems.
If call is drop then, you should pass more " , " between numbers.
Removing a list of characters in string
I am thinking about a solution for this. First I would make the string input as a list. Then I would replace the items of list. Then through using join command, I will return list as a string. The code can be like this:
def the_replacer(text):
test = []
for m in range(len(text)):
test.append(text[m])
if test[m]==','\
or test[m]=='!'\
or test[m]=='.'\
or test[m]=='\''\
or test[m]==';':
#....
test[n]=''
return ''.join(test)
This would remove anything from the string. What do you think about that?
pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/
I found the solutions from Daniel F and mattdedek very helpful: use an https URL, and upgrade pip in order to make that the default. But that still didn't fix the problem for me. I had this error, under Mac OS X / Python 3.4:
$ pip3 install Flask
Downloading/unpacking Flask
Cannot fetch index base URL https://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement Flask
Cleaning up...
No distributions at all found for Flask
Storing debug log for failure in /Users/huttarl/.pip/pip.log
and pip.log basically showed the same thing:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip/index.py", line 277, in find_requirement
raise DistributionNotFound('No distributions at all found for %s' % req)
pip.exceptions.DistributionNotFound: No distributions at all found for Flask
With help from a friend, I learned that upgrading from Python 3.4 to 3.8 fixed the problem. Apparently this is because one of the newer versions of Python 3 included updated certificates:
Certificate verification and OpenSSL
This package includes its own private copy of OpenSSL 1.1.1. The
trust certificates in system and user keychains managed by the
Keychain Access application and the security command line utility are
not used as defaults by the Python ssl module. A sample command
script is included in /Applications/Python 3.8 to install a curated
bundle of default root certificates from the third-party certifi
package (https://pypi.org/project/certifi/). Double-click on Install
Certificates to run it.
The bundled pip has its own default certificate store for verifying
download connections.
After this upgrade, and running Install Certificates.command
, the pip3 install Flask
runs successfully.
You may have already upgraded to Python 3.6+ in Mac OS, and just overlooked this certificate installation command. In that case, browse to Applications/Python 3.x and double-click Install Certificates.command
. (See Mac OSX python ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749))
Parsing a YAML file in Python, and accessing the data?
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
How to add default signature in Outlook
I have made this a Community Wiki answer because I could not have created it without PowerUser's research and the help in earlier comments.
I took PowerUser's Sub X
and added
Debug.Print "n------" 'with different values for n
Debug.Print ObjMail.HTMLBody
after every statement. From this I discovered the signature is not within .HTMLBody
until after ObjMail.Display
and then only if I haven't added anything to the body.
I went back to PowerUser's earlier solution that used C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures\Mysig.txt")
. PowerUser was unhappy with this because he wanted his solution to work for others who would have different signatures.
My signature is in the same folder and I cannot find any option to change this folder. I have only one signature so by reading the only HTM file in this folder, I obtained my only/default signature.
I created an HTML table and inserted it into the signature immediately following the <body> element and set the html body to the result. I sent the email to myself and the result was perfectly acceptable providing you like my formatting which I included to check that I could.
My modified subroutine is:
Sub X()
Dim OlApp As Outlook.Application
Dim ObjMail As Outlook.MailItem
Dim BodyHtml As String
Dim DirSig As String
Dim FileNameHTMSig As String
Dim Pos1 As Long
Dim Pos2 As Long
Dim SigHtm As String
DirSig = "C:\Users\" & Environ("username") & _
"\AppData\Roaming\Microsoft\Signatures"
FileNameHTMSig = Dir$(DirSig & "\*.htm")
' Code to handle there being no htm signature or there being more than one
SigHtm = GetBoiler(DirSig & "\" & FileNameHTMSig)
Pos1 = InStr(1, LCase(SigHtm), "<body")
' Code to handle there being no body
Pos2 = InStr(Pos1, LCase(SigHtm), ">")
' Code to handle there being no closing > for the body element
BodyHtml = "<table border=0 width=""100%"" style=""Color: #0000FF""" & _
" bgColor=#F0F0F0><tr><td align= ""center"">HTML table</td>" & _
"</tr></table><br>"
BodyHtml = Mid(SigHtm, 1, Pos2 + 1) & BodyHtml & Mid(SigHtm, Pos2 + 2)
Set OlApp = Outlook.Application
Set ObjMail = OlApp.CreateItem(olMailItem)
ObjMail.BodyFormat = olFormatHTML
ObjMail.Subject = "Subject goes here"
ObjMail.Recipients.Add "my email address"
ObjMail.Display
End Sub
Since both PowerUser and I have found our signatures in C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures
I suggest this is the standard location for any Outlook installation. Can this default be changed? I cannot find anything to suggest it can. The above code clearly needs some development but it does achieve PowerUser's objective of creating an email body containing an HTML table above a signature.
label or @html.Label ASP.net MVC 4
Depends on what your are doing.
If you have SPA (Single-Page Application) the you can use:
<input id="txtName" type="text" />
Otherwise using Html helpers is recommended, to get your controls bound with your model.
Removing a non empty directory programmatically in C or C++
The easiest way to do this is with remove_all function of the Boost.Filesystem library. Besides, the resulting code will be portable.
If you want to write something specific for Unix (rmdir) or for Windows (RemoveDirectory) then you'll have to write a function that deletes are subfiles and subfolders recursively.
EDIT
Looks like this question was already asked, in fact someone already recommended Boost's remove_all. So please don't upvote my answer.
Check if a div does NOT exist with javascript
There's an even better solution. You don't even need to check if the element returns null
. You can simply do this:
if (document.getElementById('elementId')) {
console.log('exists')
}
That code will only log exists
to console if the element actually exists in the DOM.
How to unzip a file in Powershell?
function unzip {
param (
[string]$archiveFilePath,
[string]$destinationPath
)
if ($archiveFilePath -notlike '?:\*') {
$archiveFilePath = [System.IO.Path]::Combine($PWD, $archiveFilePath)
}
if ($destinationPath -notlike '?:\*') {
$destinationPath = [System.IO.Path]::Combine($PWD, $destinationPath)
}
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archiveFile = [System.IO.File]::Open($archiveFilePath, [System.IO.FileMode]::Open)
$archive = [System.IO.Compression.ZipArchive]::new($archiveFile)
if (Test-Path $destinationPath) {
foreach ($item in $archive.Entries) {
$destinationItemPath = [System.IO.Path]::Combine($destinationPath, $item.FullName)
if ($destinationItemPath -like '*/') {
New-Item $destinationItemPath -Force -ItemType Directory > $null
} else {
New-Item $destinationItemPath -Force -ItemType File > $null
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($item, $destinationItemPath, $true)
}
}
} else {
[System.IO.Compression.ZipFileExtensions]::ExtractToDirectory($archive, $destinationPath)
}
}
Using:
unzip 'Applications\Site.zip' 'C:\inetpub\wwwroot\Site'
Return value in a Bash function
The problem with other answers is they either use a global, which can be overwritten when several functions are in a call chain, or echo
which means your function cannot output diagnostic info (you will forget your function does this and the "result", i.e. return value, will contain more info than your caller expects, leading to weird bug), or eval
which is way too heavy and hacky.
The proper way to do this is to put the top level stuff in a function and use a local
with bash's dynamic scoping rule. Example:
func1()
{
ret_val=hi
}
func2()
{
ret_val=bye
}
func3()
{
local ret_val=nothing
echo $ret_val
func1
echo $ret_val
func2
echo $ret_val
}
func3
This outputs
nothing
hi
bye
Dynamic scoping means that ret_val
points to a different object depending on the caller! This is different from lexical scoping, which is what most programming languages use. This is actually a documented feature, just easy to miss, and not very well explained, here is the documentation for it (emphasis is mine):
Variables local to the function may be declared with the local
builtin. These variables are visible only to the function and the
commands it invokes.
For someone with a C/C++/Python/Java/C#/javascript background, this is probably the biggest hurdle: functions in bash are not functions, they are commands, and behave as such: they can output to stdout
/stderr
, they can pipe in/out, they can return an exit code. Basically there is no difference between defining a command in a script and creating an executable that can be called from the command line.
So instead of writing your script like this:
top-level code
bunch of functions
more top-level code
write it like this:
# define your main, containing all top-level code
main()
bunch of functions
# call main
main
where main()
declares ret_val
as local
and all other functions return values via ret_val
.
See also the following Unix & Linux question: Scope of Local Variables in Shell Functions.
Another, perhaps even better solution depending on situation, is the one posted by ya.teck which uses local -n
.
How to get datetime in JavaScript?
@Shadow Wizard's code should return 02:45 PM instead of 14:45 PM. So I modified his code a bit:
function getNowDateTimeStr(){
var now = new Date();
var hour = now.getHours() - (now.getHours() >= 12 ? 12 : 0);
return [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(hour), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
}
//Pad given value to the left with "0"
function AddZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
How can I run a PHP script in the background after a form is submitted?
Use Amphp to execute jobs in parallel & asynchronously.
Install the library
composer require amphp/parallel-functions
Code sample
<?php
require "vendor/autoload.php";
use Amp\Promise;
use Amp\ParallelFunctions;
echo 'started</br>';
$promises[1] = ParallelFunctions\parallel(function (){
// Send Email
})();
$promises[2] = ParallelFunctions\parallel(function (){
// Send SMS
})();
Promise\wait(Promise\all($promises));
echo 'finished';
Fo your use case, You can do something like below
<?php
use function Amp\ParallelFunctions\parallelMap;
use function Amp\Promise\wait;
$responses = wait(parallelMap([
'[email protected]',
'[email protected]',
'[email protected]',
], function ($to) {
return send_mail($to);
}));
How to pass datetime from c# to sql correctly?
You've already done it correctly by using a DateTime
parameter with the value from the DateTime
, so it should already work. Forget about ToString()
- since that isn't used here.
If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).
I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357
Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281
. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.
How can I get the console logs from the iOS Simulator?
If you are using Swift, remember that println
will only print to the debug log (which appears in xCode's debug area). If you want to print to system.log, you have to use NSLog
as in the old days.
Then you can view the simulator log via its menu, Debug > Open System Log... (cmd + /)
Comparing floating point number to zero
No.
Equality is equality.
The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.
If you really want to test two doubles for equality, use this one:
inline bool isEqual(double x, double y)
{
return x == y;
}
Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y
is the code you want.
10.000000000000001 is not equal to 10.0, no matter what they tell you.
An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:
const double NO_DATA = -1.0;
double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);
if (myData != NO_DATA)
{
...
}
How do I copy to the clipboard in JavaScript?
Reading and modifying the clipboard from a webpage raises security and privacy concerns. However, in Internet Explorer, it is possible to do it. I found this example snippet:
_x000D_
_x000D_
<script type="text/javascript">_x000D_
function select_all(obj) {_x000D_
var text_val=eval(obj);_x000D_
text_val.focus();_x000D_
text_val.select();_x000D_
r = text_val.createTextRange();_x000D_
if (!r.execCommand) return; // feature detection_x000D_
r.execCommand('copy');_x000D_
}_x000D_
</script>_x000D_
<input value="http://www.sajithmr.com"_x000D_
onclick="select_all(this)" name="url" type="text" />
_x000D_
_x000D_
_x000D_
Read Content from Files which are inside Zip file
If you're wondering how to get the file content from each ZipEntry
it's actually quite simple. Here's a sample code:
public static void main(String[] args) throws IOException {
ZipFile zipFile = new ZipFile("C:/test.zip");
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
InputStream stream = zipFile.getInputStream(entry);
}
}
Once you have the InputStream you can read it however you want.
Generating a drop down list of timezones with PHP
This PHP function do the Job for you an give back an array:
function time_zonelist(){
$return = array();
$timezone_identifiers_list = timezone_identifiers_list();
foreach($timezone_identifiers_list as $timezone_identifier){
$date_time_zone = new DateTimeZone($timezone_identifier);
$date_time = new DateTime('now', $date_time_zone);
$hours = floor($date_time_zone->getOffset($date_time) / 3600);
$mins = floor(($date_time_zone->getOffset($date_time) - ($hours*3600)) / 60);
$hours = 'GMT' . ($hours < 0 ? $hours : '+'.$hours);
$mins = ($mins > 0 ? $mins : '0'.$mins);
$text = str_replace("_"," ",$timezone_identifier);
$return[$timezone_identifier] = $text.' ('.$hours.':'.$mins.')';
}
return $return;
}
This PHP function give back an array of all existing Timezones including Offset:
Use it e.g. like this:
print_r(time_zonelist());
How to get page content using cURL?
For a realistic approach that emulates the most human behavior, you may want to add a referer in your curl options. You may also want to add a follow_location to your curl options. Trust me, whoever said that cURLING Google results is impossible, is a complete dolt and should throw his/her computer against the wall in hopes of never returning to the internetz again.
Everything that you can do "IRL" with your own browser can all be emulated using PHP cURL or libCURL in Python. You just need to do more cURLS to get buff. Then you will see what I mean. :)
$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
$ch = curl_init();
curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, urlencode($url));
$response = curl_exec($ch);
curl_close($ch);
How to get a resource id with a known resource name?
• Kotlin Version
via Extension Function
To find a resource id by its name In Kotlin, add below snippet in a kotlin file:
ExtensionFunctions.kt
import android.content.Context
import android.content.res.Resources
fun Context.resIdByName(resIdName: String?, resType: String): Int {
resIdName?.let {
return resources.getIdentifier(it, resType, packageName)
}
throw Resources.NotFoundException()
}
• Usage
Now all resource ids are accessible wherever you have a context reference using resIdByName
method:
val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.
How do I copy the contents of one stream to another?
From .NET 4.5 on, there is the Stream.CopyToAsync
method
input.CopyToAsync(output);
This will return a Task
that can be continued on when completed, like so:
await input.CopyToAsync(output)
// Code from here on will be run in a continuation.
Note that depending on where the call to CopyToAsync
is made, the code that follows may or may not continue on the same thread that called it.
The SynchronizationContext
that was captured when calling await
will determine what thread the continuation will be executed on.
Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).
From .NET 4.0 on, there's is the Stream.CopyTo
method
input.CopyTo(output);
For .NET 3.5 and before
There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length
? Because that Length may not be available! From the docs:
If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.
Escaping special characters in Java Regular Expressions
Use this Utility function escapeQuotes()
in order to escape strings in between Groups and Sets of a RegualrExpression
.
List of Regex Literals to escape <([{\^-=$!|]})?*+.>
public class RegexUtils {
static String escapeChars = "\\.?![]{}()<>*+-=^$|";
public static String escapeQuotes(String str) {
if(str != null && str.length() > 0) {
return str.replaceAll("[\\W]", "\\\\$0"); // \W designates non-word characters
}
return "";
}
}
From the Pattern class the backslash character ('\')
serves to introduce escaped constructs. The string literal "\(hello\)"
is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)"
must be used.
Example: String to be matched (hello)
and the regex with a group is (\(hello\))
. Form here you only need to escape matched string as shown below. Test Regex online
public static void main(String[] args) {
String matched = "(hello)", regexExpGrup = "(" + escapeQuotes(matched) + ")";
System.out.println("Regex : "+ regexExpGrup); // (\(hello\))
}
How to determine device screen size category (small, normal, large, xlarge) using code?
Here is a Xamarin.Android version of Tom McFarlin's answer
//Determine screen size
if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) {
Toast.MakeText (this, "Large screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) {
Toast.MakeText (this, "Normal screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) {
Toast.MakeText (this, "Small screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeXlarge) {
Toast.MakeText (this, "XLarge screen", ToastLength.Short).Show ();
} else {
Toast.MakeText (this, "Screen size is neither large, normal or small", ToastLength.Short).Show ();
}
//Determine density
DisplayMetrics metrics = new DisplayMetrics();
WindowManager.DefaultDisplay.GetMetrics (metrics);
var density = metrics.DensityDpi;
if (density == DisplayMetricsDensity.High) {
Toast.MakeText (this, "DENSITY_HIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Medium) {
Toast.MakeText (this, "DENSITY_MEDIUM... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Low) {
Toast.MakeText (this, "DENSITY_LOW... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xhigh) {
Toast.MakeText (this, "DENSITY_XHIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xxhigh) {
Toast.MakeText (this, "DENSITY_XXHIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xxxhigh) {
Toast.MakeText (this, "DENSITY_XXXHIGH... Density is " + density, ToastLength.Long).Show ();
} else {
Toast.MakeText (this, "Density is neither HIGH, MEDIUM OR LOW. Density is " + density, ToastLength.Long).Show ();
}
How to specify a multi-line shell variable?
read
does not export the variable (which is a good thing most of the time). Here's an alternative which can be exported in one command, can preserve or discard linefeeds, and allows mixing of quoting-styles as needed. Works for bash and zsh.
oneLine=$(printf %s \
a \
" b " \
$'\tc\t' \
'd ' \
)
multiLine=$(printf '%s\n' \
a \
" b " \
$'\tc\t' \
'd ' \
)
I admit the need for quoting makes this ugly for SQL, but it answers the (more generally expressed) question in the title.
I use it like this
export LS_COLORS=$(printf %s \
':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33' \
...
':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')
in a file sourced from both my .bashrc
and .zshrc
.