How to set up datasource with Spring for HikariCP?
You can create a datasource bean in servlet context as:
<beans:bean id="dataSource"
class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<beans:property name="dataSourceClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
<beans:property name="maximumPoolSize" value="5" />
<beans:property name="maxLifetime" value="30000" />
<beans:property name="idleTimeout" value="30000" />
<beans:property name="dataSourceProperties">
<beans:props>
<beans:prop key="url">jdbc:mysql://localhost:3306/exampledb</beans:prop>
<beans:prop key="user">root</beans:prop>
<beans:prop key="password"></beans:prop>
<beans:prop key="prepStmtCacheSize">250</beans:prop>
<beans:prop key="prepStmtCacheSqlLimit">2048</beans:prop>
<beans:prop key="cachePrepStmts">true</beans:prop>
<beans:prop key="useServerPrepStmts">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
Seeing the underlying SQL in the Spring JdbcTemplate?
This works for me with org.springframework.jdbc-3.0.6.RELEASE.jar.
I could not find this anywhere in the Spring docs (maybe I'm just lazy) but I found (trial and error) that the TRACE level did the magic.
I'm using log4j-1.2.15 along with slf4j (1.6.4) and properties file to configure the log4j:
log4j.logger.org.springframework.jdbc.core = TRACE
This displays both the SQL statement and bound parameters like this:
Executing prepared SQL statement [select HEADLINE_TEXT, NEWS_DATE_TIME from MY_TABLE where PRODUCT_KEY = ? and NEWS_DATE_TIME between ? and ? order by NEWS_DATE_TIME]
Setting SQL statement parameter value: column index 1, parameter value [aaa], value class [java.lang.String], SQL type unknown
Setting SQL statement parameter value: column index 2, parameter value [Thu Oct 11 08:00:00 CEST 2012], value class [java.util.Date], SQL type unknown
Setting SQL statement parameter value: column index 3, parameter value [Thu Oct 11 08:00:10 CEST 2012], value class [java.util.Date], SQL type unknown
Not sure about the SQL type unknown but I guess we can ignore it here
For just an SQL (i.e. if you're not interested in bound parameter values) DEBUG
should be enough.
Spring Boot default H2 jdbc connection (and H2 console)
In order to get the tables all you need to do is create 2 sql files schema.sql(for table creation) and data.sql(data for the created tables). These files to be put in src/main/resources folder. Spring boot auto detects them and takes care of the rest during runtime.
If your using more than 2 DB in your project ensure to use specific files like (schema-h2.sql -- for h2 DB , schema-oracle.sql -- for oracle DB). The same to be followed for data.sql too.
Also ensure that you drop tables by adding drop table statement in your schema.sql as first statement. To avoid appending of duplicate records.
The link for spring boot is here.
My application.properties is as follows.
spring.datasource.url=jdbc:h2:~/file/Shiva;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.platform=h2
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.datasource.initialize=true
spring.error.whitelabel.enabled=true
spring.h2.console.path=/console
spring.datasource.continue-on-error=true
spring.jpa.hibernate.ddl-auto=create
spring.hibernate.hbm2ddl.auto=update
spring.hibernate.show_sql=true
You can follow the steps in the below link.
https://springframework.guru/using-the-h2-database-console-in-spring-boot-with-spring-security/
Spring - @Transactional - What happens in background?
This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on Aspect-Oriented Programming and Transactions, as Spring's declarative transaction support uses AOP at its foundation.
But at a very high level, Spring creates proxies for classes that declare @Transactional on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with @Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.
Transactions in EJB work similarly, by the way.
As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the "this" reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in this forum post in which I use a BeanFactoryPostProcessor to inject an instance of the proxy into "self-referencing" classes at runtime. I save this reference to a member variable called "me". Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. "me.someMethod()".) The forum post explains in more detail. Note that the BeanFactoryPostProcessor code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Pointer-to-pointer dynamic two-dimensional array
What you describe for the second method only gives you a 1D array:
int *board = new int[10];
This just allocates an array with 10 elements. Perhaps you meant something like this:
int **board = new int*[4];
for (int i = 0; i < 4; i++) {
board[i] = new int[10];
}
In this case, we allocate 4 int*
s and then make each of those point to a dynamically allocated array of 10 int
s.
So now we're comparing that with int* board[4];
. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*
s, as the array will be destroyed at the end of its scope.
The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:
for (int i = 0; i < 4; i++) {
delete[] board[i];
}
delete[] board;
I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4>
or perhaps a std::vector<std::vector<int>>
which you initialise to the appropriate size.
Renaming branches remotely in Git
Sure. Just rename the branch locally, push the new branch, and push a deletion of the old.
The only real issue is that other users of the repository won't have local tracking branches renamed.
jQuery Ajax calls and the Html.AntiForgeryToken()
function DeletePersonel(id) {
var data = new FormData();
data.append("__RequestVerificationToken", "@HtmlHelper.GetAntiForgeryToken()");
$.ajax({
type: 'POST',
url: '/Personel/Delete/' + id,
data: data,
cache: false,
processData: false,
contentType: false,
success: function (result) {
}
});
}
public static class HtmlHelper {
public static string GetAntiForgeryToken() {
System.Text.RegularExpressions.Match value =
System.Text.RegularExpressions.Regex.Match(System.Web.Helpers.AntiForgery.GetHtml().ToString(),
"(?:value=\")(.*)(?:\")");
if (value.Success) {
return value.Groups[1].Value;
}
return "";
}
}
Tablix: Repeat header rows on each page not working - Report Builder 3.0
I have 2.0 and found the above to help; however, the selecting of a static did not highlight the cell for some reason.
I followed these steps:
- Under column groups select the advanced and the statics will show up
- Click on the static which shows up in the row groups
- Set KeepWithGroup to After and RepeatOnNewPage to true
Now your column headers should repeat on each page.
Setting up and using Meld as your git difftool and mergetool
It can be complicated to compute a diff in your head from the different sections in $MERGED and apply that. In my setup, meld helps by showing you these diffs visually, using:
[merge]
tool = mymeld
conflictstyle = diff3
[mergetool "mymeld"]
cmd = meld --diff $BASE $REMOTE --diff $REMOTE $LOCAL --diff $LOCAL $MERGED
It looks strange but offers a very convenient work-flow, using three tabs:
in tab 1 you see (from left to right) the change that you should make in tab 2 to solve the merge conflict.
in the right side of tab 2 you apply the "change that you should make" and copy the entire file contents to the clipboard (using ctrl-a and ctrl-c).
in tab 3 replace the right side with the clipboard contents. If everything is correct, you will now see - from left to right - the same change as shown in tab 1 (but with different contexts). Save the changes made in this tab.
Notes:
- don't edit anything in tab 1
- don't save anything in tab 2 because that will produce annoying popups in tab 3
The OutputPath property is not set for this project
If you are using WiX look at this (there is a bug)
http://www.cnblogs.com/xixifusigao/archive/2012/03/20/2407651.html
Sometimes new build configurations get added to the .wixproj
file further down the file, that is, separated from their sibling config definitions by other unrelated XML elements.
Simply edit the .wixproj
file so that all the <PropertyGroup>
sections that define your build configs are adjacent to one another. (To edit the .wixproj
in VS2013 right click on project in Solution Explorer, Unload project, right-click again->Edit YourProject.wixproj. Reload after editing the file.)
How to use the "required" attribute with a "radio" input field
I had to use required="required"
along with the same name and type, and then validation worked fine.
<input type="radio" name="user-radio" id="" value="User" required="required" />
<input type="radio" name="user-radio" id="" value="Admin" />
<input type="radio" name="user-radio" id="" value="Guest" />
Find IP address of directly connected device
To use DHCP, you'd have to run a DHCP server on the primary and a client on the secondary; the primary could then query the server to find out what address it handed out. Probably overkill.
I can't help you with Windows directly. On Unix, the "arp" command will tell you what IP addresses are known to be attached to the local ethernet segment. Windows will have this same information (since it's a core part of the IP/Ethernet interface) but I don't know how you get at it.
Of course, the networking stack will only know about the other host if it has previously seen traffic from it. You may have to first send a broadcast packet on the interface to elicit some sort of response and thus populate the local ARP table.
How do you import a large MS SQL .sql file?
I have encountered the same problem and invested a whole day to find the way out but this is resolved by making the copy of .sql file and change the extension to .txt file and open the .txt file into chrome browser. I have seen the magic and file is opened in a browser.
Thanks and Best Regards,
Why are my PHP files showing as plain text?
Yet another reason (not for this case, but maybe it'll save some nerves for someone) is that in PHP 5.5 short open tags <? phpinfo(); ?>
are disabled by default.
So the PHP interpreter would process code within short tags as plain text. In previous versions PHP this feature was enable by default. So the new behaviour can be a little bit mysterious.
HTML.ActionLink vs Url.Action in ASP.NET Razor
Html.ActionLink
generates an <a href=".."></a>
tag automatically.
Url.Action
generates only an url.
For example:
@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)
generates:
<a href="/controllerName/actionName/<id>">link text</a>
and
@Url.Action("actionName", "controllerName", new { id = "<id>" })
generates:
/controllerName/actionName/<id>
Best plus point which I like is using Url.Action(...)
You are creating anchor tag by your own where you can set your own linked text easily even with some other html tag.
<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">
<img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />
@Html.DisplayFor(model => model.<SomeModelField>)
</a>
jQuery click not working for dynamically created items
You have to add click event to an exist element.
You can not add event to dom elements dynamic created.
I you want to add event to them, you should bind event to an existed element using ".on".
$('p').on('click','selector_you_dynamic_created',function(){...});
.delegate should work,too.
how to check redis instance version?
Run the command INFO
. The version will be the first item displayed.
The advantage of this over redis-server --version is that sometimes you don't have access to the server (e.g. when it's provided to you on the cloud), in which case INFO
is your only option.
Case insensitive std::string.find()
why not use Boost.StringAlgo:
#include <boost/algorithm/string/find.hpp>
bool Foo()
{
//case insensitive find
std::string str("Hello");
boost::iterator_range<std::string::const_iterator> rng;
rng = boost::ifind_first(str, std::string("EL"));
return rng;
}
Adjust width and height of iframe to fit with content in it
I figured out another solution after some experimenting. I originally tried the code marked as 'best answer' to this question and it didn't work. My guess is because my iframe in my program at the time was dynamically generated. Here is the code I used (it worked for me):
Javascript inside the iframe that is being loaded:
window.onload = function()
{
parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
};
It is necessary to add 4 or more pixels to the height to remove scroll bars (some weird bug/effect of iframes). The width is even stranger, you are safe to add 18px to the width of the body. Also make sure that you have the css for the iframe body applied (below).
html, body {
margin:0;
padding:0;
display:table;
}
iframe {
border:0;
padding:0;
margin:0;
}
Here is the html for the iframe:
<iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>
Here is all the code within my iframe:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>File Upload</title>
<style type="text/css">
html, body {
margin:0;
padding:0;
display:table;
}
</style>
<script type="text/javascript">
window.onload = function()
{
parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
};
</script>
</head>
<body>
This is a test.<br>
testing
</body>
</html>
I have done testing in chrome and a little in firefox (in windows xp). I still have more testing to do, so please tell me how this works for you.
How might I force a floating DIV to match the height of another floating DIV?
I can't understand why this issue gets pounded into the ground when in 30 seconds you can code a two-column table and solve the problem.
This div column height problem comes up all over a typical layout. Why resort to scripting when a plain old basic HTML tag will do it? Unless there are huge and numerous tables on a layout, I don't buy the argument that tables are significantly slower.
How do I implement charts in Bootstrap?
I would like to suggest you to use HighCharts. It's just awesome and easy to integrate.
Example:
HTML:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Script:
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tokyo',
data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}, {
name: 'New York',
data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]
}, {
name: 'London',
data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]
}, {
name: 'Berlin',
data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
}]
});
});
And here is the fiddle .
Spring Boot REST service exception handling
Although this is an older question, I would like to share my thoughts on this. I hope, that it will be helpful to some of you.
I am currently building a REST API which makes use of Spring Boot 1.5.2.RELEASE with Spring Framework 4.3.7.RELEASE. I use the Java Config approach (as opposed to XML configuration). Also, my project uses a global exception handling mechanism using the @RestControllerAdvice
annotation (see later below).
My project has the same requirements as yours: I want my REST API to return a HTTP 404 Not Found
with an accompanying JSON payload in the HTTP response to the API client when it tries to send a request to an URL which does not exist. In my case, the JSON payload looks like this (which clearly differs from the Spring Boot default, btw.):
{
"code": 1000,
"message": "No handler found for your request.",
"timestamp": "2017-11-20T02:40:57.628Z"
}
I finally made it work. Here are the main tasks you need to do in brief:
- Make sure that the
NoHandlerFoundException
is thrown if API clients
call URLS for which no handler method exists (see Step 1 below).
- Create a custom error class (in my case
ApiError
) which contains all the data that should be returned to the API client (see step 2).
- Create an exception handler which reacts on the
NoHandlerFoundException
and returns a proper error message to the API client (see step 3).
- Write a test for it and make sure, it works (see step 4).
Ok, now on to the details:
Step 1: Configure application.properties
I had to add the following two configuration settings to the project's application.properties
file:
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
This makes sure, the NoHandlerFoundException
is thrown in cases where a client tries to access an URL for which no controller method exists which would be able to handle the request.
Step 2: Create a Class for API Errors
I made a class similar to the one suggested in this article on Eugen Paraschiv's blog. This class represents an API error. This information is
sent to the client in the HTTP response body in case of an error.
public class ApiError {
private int code;
private String message;
private Instant timestamp;
public ApiError(int code, String message) {
this.code = code;
this.message = message;
this.timestamp = Instant.now();
}
public ApiError(int code, String message, Instant timestamp) {
this.code = code;
this.message = message;
this.timestamp = timestamp;
}
// Getters and setters here...
}
Step 3: Create / Configure a Global Exception Handler
I use the following class to handle exceptions (for simplicity, I have removed import statements, logging code and some other, non-relevant pieces of code):
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiError noHandlerFoundException(
NoHandlerFoundException ex) {
int code = 1000;
String message = "No handler found for your request.";
return new ApiError(code, message);
}
// More exception handlers here ...
}
Step 4: Write a test
I want to make sure, the API always returns the correct error messages to the calling client, even in the case of failure. Thus, I wrote a test like this:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SprintBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("dev")
public class GlobalExceptionHandlerIntegrationTest {
public static final String ISO8601_DATE_REGEX =
"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$";
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(roles = "DEVICE_SCAN_HOSTS")
public void invalidUrl_returnsHttp404() throws Exception {
RequestBuilder requestBuilder = getGetRequestBuilder("/does-not-exist");
mockMvc.perform(requestBuilder)
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.code", is(1000)))
.andExpect(jsonPath("$.message", is("No handler found for your request.")))
.andExpect(jsonPath("$.timestamp", RegexMatcher.matchesRegex(ISO8601_DATE_REGEX)));
}
private RequestBuilder getGetRequestBuilder(String url) {
return MockMvcRequestBuilders
.get(url)
.accept(MediaType.APPLICATION_JSON);
}
The @ActiveProfiles("dev")
annotation can be left away. I use it only as I work with different profiles. The RegexMatcher
is a custom Hamcrest matcher I use to better handle timestamp fields. Here's the code (I found it here):
public class RegexMatcher extends TypeSafeMatcher<String> {
private final String regex;
public RegexMatcher(final String regex) {
this.regex = regex;
}
@Override
public void describeTo(final Description description) {
description.appendText("matches regular expression=`" + regex + "`");
}
@Override
public boolean matchesSafely(final String string) {
return string.matches(regex);
}
// Matcher method you can call on this matcher class
public static RegexMatcher matchesRegex(final String string) {
return new RegexMatcher(regex);
}
}
Some further notes from my side:
- In many other posts on StackOverflow, people suggested setting the
@EnableWebMvc
annotation. This was not necessary in my case.
- This approach works well with MockMvc (see test above).
Return different type of data from a method in java?
Method overloading can come in handy here
Like:
<code>
public class myClass
{
int add(int a, int b)
{
return (a + b);
}
String add(String a, String b)
{
return (c + d);
}
public static void main(String args[])
{
myClass ob1 = new myClass);
ob1.add(2, 3);
//will return 5
ob1.add("Hello, ", "World!");
//will return Hello, World!
}
}
Convert np.array of type float64 to type uint8 scaling values
Considering that you are using OpenCV, the best way to convert between data types is to use normalize
function.
img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
However, if you don't want to use OpenCV, you can do this in numpy
def convert(img, target_type_min, target_type_max, target_type):
imin = img.min()
imax = img.max()
a = (target_type_max - target_type_min) / (imax - imin)
b = target_type_max - a * imax
new_img = (a * img + b).astype(target_type)
return new_img
And then use it like this
imgu8 = convert(img16u, 0, 255, np.uint8)
This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040
Insert Data Into Temp Table with Query
This is possible.
Try this way:
Create Global Temporary Table
BossaDoSamba
On Commit Preserve Rows
As
select ArtistName, sum(Songs) As NumberOfSongs
from Spotfy
where ArtistName = 'BossaDoSamba'
group by ArtistName;
How can I set the initial value of Select2 when using AJAX?
Hi was almost quitting this and go back to select 3.5.1. But finally I got the answer!
$('#test').select2({
placeholder: "Select a Country",
minimumResultsForSearch: 2,
ajax: {
url: '...',
dataType: 'json',
cache: false,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data.items
};
}
}
});
var option1 = new Option("new",true, true);
$('#status').append(option1);
$('#status').trigger('change');
Just be sure that the new option is one of the select2 options. I get this by a json.
Query comparing dates in SQL
please try with below query
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
convert(datetime, convert(varchar(10), created_date, 102)) <= convert(datetime,'2013-04-12')
How to have Java method return generic list of any type?
I'm pretty sure you can completely delete the <stuff> , which will generate a warning and you can use an, @ suppress warnings. If you really want it to be generic, but to use any of its elements you will have to do type casting. For instance, I made a simple bubble sort function and it uses a generic type when sorting the list, which is actually an array of Comparable in this case. If you wish to use an item, do something like: System.out.println((Double)arrayOfDoubles[0] + (Double)arrayOfDoubles[1]); because I stuffed Double(s) into Comparable(s) which is polymorphism since all Double(s) inherit from Comparable to allow easy sorting through Collections.sort()
//INDENT TO DISPLAY CODE ON STACK-OVERFLOW
@SuppressWarnings("unchecked")
public static void simpleBubbleSort_ascending(@SuppressWarnings("rawtypes") Comparable[] arrayOfDoubles)
{
//VARS
//looping
int end = arrayOfDoubles.length - 1;//the last index in our loops
int iterationsMax = arrayOfDoubles.length - 1;
//swapping
@SuppressWarnings("rawtypes")
Comparable tempSwap = 0.0;//a temporary double used in the swap process
int elementP1 = 1;//element + 1, an index for comparing and swapping
//CODE
//do up to 'iterationsMax' many iterations
for (int iteration = 0; iteration < iterationsMax; iteration++)
{
//go through each element and compare it to the next element
for (int element = 0; element < end; element++)
{
elementP1 = element + 1;
//if the elements need to be swapped, swap them
if (arrayOfDoubles[element].compareTo(arrayOfDoubles[elementP1])==1)
{
//swap
tempSwap = arrayOfDoubles[element];
arrayOfDoubles[element] = arrayOfDoubles[elementP1];
arrayOfDoubles[elementP1] = tempSwap;
}
}
}
}//END public static void simpleBubbleSort_ascending(double[] arrayOfDoubles)
React Router with optional path parameter
As with regular parameters, declaring an optional parameter is just a matter of the path property of a Route; any parameter that ends with a question mark will be treated as optional:
<Route path="to/page/:pathParam?" component={MyPage}/>
How to URL encode a string in Ruby
I was originally trying to escape special characters in a file name only, not on the path, from a full URL string.
ERB::Util.url_encode
didn't work for my use:
helper.send(:url_encode, "http://example.com/?a=\11\15")
# => "http%3A%2F%2Fexample.com%2F%3Fa%3D%09%0D"
Based on two answers in "Why is URI.escape() marked as obsolete and where is this REGEXP::UNSAFE constant?", it looks like URI::RFC2396_Parser#escape
is better than using URI::Escape#escape
. However, they both are behaving the same to me:
URI.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"
URI::Parser.new.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"
How to solve the memory error in Python
Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError
). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError
.
Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).
If that's not enough, consider converting to a sqlite3
database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.
correct way to define class variables in Python
I think this sample explains the difference between the styles:
james@bodacious-wired:~$cat test.py
#!/usr/bin/env python
class MyClass:
element1 = "Hello"
def __init__(self):
self.element2 = "World"
obj = MyClass()
print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
File "./test.py", line 17, in <module>
print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'
element1 is bound to the class, element2 is bound to an instance of the class.
Can we convert a byte array into an InputStream in Java?
If you use Robert Harder's Base64 utility, then you can do:
InputStream is = new Base64.InputStream(cph);
Or with sun's JRE, you can do:
InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.
There are other Stack Overflow questions about Base64 decoding, such as this one.
How to change the status bar background color and text color on iOS 7?
Write this in your ViewDidLoad Method:
if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
self.edgesForExtendedLayout=UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars=NO;
self.automaticallyAdjustsScrollViewInsets=NO;
}
It fixed status bar color for me and other UI misplacements also to a extent.
Capturing browser logs with Selenium WebDriver using Java
A less elegant solution is taking the log 'manually' from the user data dir:
Set the user data dir to a fixed place:
options = new ChromeOptions();
capabilities = DesiredCapabilities.chrome();
options.addArguments("user-data-dir=/your_path/");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
Get the text from the log file chrome_debug.log located in the path you've entered above.
I use this method since RemoteWebDriver
had problems getting the console logs remotely. If you run your test locally that can be easy to retrieve.
how to create Socket connection in Android?
Here, in this post you will find the detailed code for establishing socket between devices or between two application in the same mobile.
You have to create two application to test below code.
In both application's manifest file, add below permission
<uses-permission android:name="android.permission.INTERNET" />
1st App code: Client Socket
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:id="@+id/tr_send_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="11dp">
<EditText
android:id="@+id/edt_send_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:hint="Enter message"
android:inputType="text" />
<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Send" />
</TableRow>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/tr_send_message"
android:layout_marginTop="25dp"
android:id="@+id/scrollView2">
<TextView
android:id="@+id/tv_reply_from_server"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Created by Girish Bhalerao on 5/4/2017.
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
buttonSend.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
sendMessage(mEditTextSendMessage.getText().toString());
break;
}
}
private void sendMessage(final String msg) {
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Replace below IP with the IP of that device in which server socket open.
//If you change port then change the port number in the server side code also.
Socket s = new Socket("xxx.xxx.xxx.xxx", 9002);
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(msg);
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
final String st = input.readLine();
handler.post(new Runnable() {
@Override
public void run() {
String s = mTextViewReplyFromServer.getText().toString();
if (st.trim().length() != 0)
mTextViewReplyFromServer.setText(s + "\nFrom Server : " + st);
}
});
output.close();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
2nd App Code - Server Socket
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_stop_receiving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP Receiving data"
android:layout_alignParentTop="true"
android:enabled="false"
android:layout_centerHorizontal="true"
android:layout_marginTop="89dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn_stop_receiving"
android:layout_marginTop="35dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="@+id/tv_data_from_client"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
<Button
android:id="@+id/btn_start_receiving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START Receiving data"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp" />
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Girish Bhalerao on 5/4/2017.
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
final Handler handler = new Handler();
private Button buttonStartReceiving;
private Button buttonStopReceiving;
private TextView textViewDataFromClient;
private boolean end = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartReceiving = (Button) findViewById(R.id.btn_start_receiving);
buttonStopReceiving = (Button) findViewById(R.id.btn_stop_receiving);
textViewDataFromClient = (TextView) findViewById(R.id.tv_data_from_client);
buttonStartReceiving.setOnClickListener(this);
buttonStopReceiving.setOnClickListener(this);
}
private void startServerSocket() {
Thread thread = new Thread(new Runnable() {
private String stringData = null;
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(9002);
while (!end) {
//Server is waiting for client here, if needed
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream());
stringData = input.readLine();
output.println("FROM SERVER - " + stringData.toUpperCase());
output.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
updateUI(stringData);
if (stringData.equalsIgnoreCase("STOP")) {
end = true;
output.close();
s.close();
break;
}
output.close();
s.close();
}
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
private void updateUI(final String stringData) {
handler.post(new Runnable() {
@Override
public void run() {
String s = textViewDataFromClient.getText().toString();
if (stringData.trim().length() != 0)
textViewDataFromClient.setText(s + "\n" + "From Client : " + stringData);
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_receiving:
startServerSocket();
buttonStartReceiving.setEnabled(false);
buttonStopReceiving.setEnabled(true);
break;
case R.id.btn_stop_receiving:
//stopping server socket logic you can add yourself
buttonStartReceiving.setEnabled(true);
buttonStopReceiving.setEnabled(false);
break;
}
}
}
How to apply border radius in IE8 and below IE8 browsers?
The border-radius property is supported in IE9+, Firefox 4+, Chrome, Safari 5+, and Opera, because it is CSS3 property.
so, you could use css3pie
first check this demo in IE 8 and download it from here
write your css rule like this
#myAwesomeElement {
border: 1px solid #999;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
behavior: url(path/to/pie_files/PIE.htc);
}
note: added behavior: url(path/to/pie_files/PIE.htc);
in the above rule. within url() you need to specify your PIE.htc file location
SQL Server: the maximum number of rows in table
Largest table I've encountered on SQL Server 8 on Windows2003 was 799 million with 5 columns. But whether or not it's good will is to be measured against the SLA and usage case - e.g. load 50-100,000,000 records and see if it still works.
2D Euclidean vector rotations
Sounds easier to do with the standard classes:
std::complex<double> vecA(0,1);
std::complex<double> i(0,1); // 90 degrees
std::complex<double> r45(sqrt(2.0),sqrt(2.0));
vecA *= i;
vecA *= r45;
Vector rotation is a subset of complex multiplication. To rotate over an angle alpha
, you multiply by std::complex<double> { cos(alpha), sin(alpha) }
Get contentEditable caret index position
This one builds on @alockwood05's answer and provides both get and set functionality for a caret with nested tags inside the contenteditable div as well as the offsets within nodes so that you have a solution that is both serializable and de-serializable by offsets as well.
I'm using this solution in a cross-platform code editor that needs to get the caret start/end position prior to syntax highlighting via a lexer/parser and then set it back immediately afterward.
function countUntilEndContainer(parent, endNode, offset, countingState = {count: 0}) {
for (let node of parent.childNodes) {
if (countingState.done) break;
if (node === endNode) {
countingState.done = true;
countingState.offsetInNode = offset;
return countingState;
}
if (node.nodeType === Node.TEXT_NODE) {
countingState.offsetInNode = offset;
countingState.count += node.length;
} else if (node.nodeType === Node.ELEMENT_NODE) {
countUntilEndContainer(node, endNode, offset, countingState);
} else {
countingState.error = true;
}
}
return countingState;
}
function countUntilOffset(parent, offset, countingState = {count: 0}) {
for (let node of parent.childNodes) {
if (countingState.done) break;
if (node.nodeType === Node.TEXT_NODE) {
if (countingState.count <= offset && offset < countingState.count + node.length)
{
countingState.offsetInNode = offset - countingState.count;
countingState.node = node;
countingState.done = true;
return countingState;
}
else {
countingState.count += node.length;
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
countUntilOffset(node, offset, countingState);
} else {
countingState.error = true;
}
}
return countingState;
}
function getCaretPosition()
{
let editor = document.getElementById('editor');
let sel = window.getSelection();
if (sel.rangeCount === 0) { return null; }
let range = sel.getRangeAt(0);
let start = countUntilEndContainer(editor, range.startContainer, range.startOffset);
let end = countUntilEndContainer(editor, range.endContainer, range.endOffset);
let offsetsCounts = { start: start.count + start.offsetInNode, end: end.count + end.offsetInNode };
let offsets = { start: start, end: end, offsets: offsetsCounts };
return offsets;
}
function setCaretPosition(start, end)
{
let editor = document.getElementById('editor');
let sel = window.getSelection();
if (sel.rangeCount === 0) { return null; }
let range = sel.getRangeAt(0);
let startNode = countUntilOffset(editor, start);
let endNode = countUntilOffset(editor, end);
let newRange = new Range();
newRange.setStart(startNode.node, startNode.offsetInNode);
newRange.setEnd(endNode.node, endNode.offsetInNode);
sel.removeAllRanges();
sel.addRange(newRange);
return true;
}
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
I needed to use this as a cell function (like SUM
or VLOOKUP
) and found that it was easy to:
- Make sure you are in a Macro Enabled Excel File (save as xlsm).
- Open developer tools Alt + F11
- Add Microsoft VBScript Regular Expressions 5.5 as in other answers
Create the following function either in workbook or in its own module:
Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
Dim regex As New VBScript_RegExp_55.RegExp
Dim strInput As String
strInput = myRange.Value
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = matchPattern
End With
REGPLACE = regex.Replace(strInput, outputPattern)
End Function
Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2")
(ex: "A 243" to "A243")
How to set 777 permission on a particular folder?
Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.
Argument Exception "Item with Same Key has already been added"
That Exception is thrown if there is already a key in the dictionary when you try to add the new one.
There must be more than one line in rct3Lines
with the same first word. You can't have 2 entries in the same dictionary with the same key.
You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply
rct3Features[items[0]]=items[1]
but, if not you may want to test if the key already exists with:
if(rect3Features.ContainsKey(items[0]))
{
//Do something
}
else
{
//Do something else
}
How can I select from list of values in Oracle
Starting from Oracle 12.2, you don't need the TABLE
function, you can directly select from the built-in collection.
SQL> select * FROM sys.odcinumberlist(5,2,6,3,78);
COLUMN_VALUE
------------
5
2
6
3
78
SQL> select * FROM sys.odcivarchar2list('A','B','C','D');
COLUMN_VALUE
------------
A
B
C
D
Normalize data in pandas
This is how you do it column-wise:
[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]
Replace comma with newline in sed on MacOS?
If your sed usage tends to be entirely substitution expressions (as mine tends to be), you can also use perl -pe
instead
$ echo 'foo,bar,baz' | perl -pe 's/,/,\n/g'
foo,
bar,
baz
How to use bootstrap-theme.css with bootstrap 3?
For an example of the css styles have a look at: http://getbootstrap.com/examples/theme/
If you want to see how the example looks without the bootstrap-theme.css file open up your browser developer tools and delete the link from the <head> of the example and then you can compare it.
I know this is an old question but posted it just in case anyone is looking for an example of how it looks like I was.
Update
bootstrap.css
= main css framework (grids, basic styles, etc)
bootstrap-theme.css
= extended styling (3D buttons, gradients etc). This file is optional and does not effect the functionality of bootstrap at all, it only enhances the appearance.
Update 2
With the release of v3.2.0 Bootstrap have added an option to view the theme css on the doc pages. If you go to one of the doc pages (css, components, javascript) you should see a "Preview theme" link at the bottom of the side nav which you can use to turn the theme css on and off.
Using sed, Insert a line above or below the pattern?
To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)
sed -i '/pattern/a \
line1 \
line2' inputfile
Output:
#cat inputfile
pattern
line1 line2
To prepend the lines before:
sed -i '/pattern/i \
line1 \
line2' inputfile
Output:
#cat inputfile
line1 line2
pattern
What is the most efficient way to deep clone an object in JavaScript?
Object.assign({},sourceObj)
only clones the object if their property is not having reference type key.
ex
obj={a:"lol",b:["yes","no","maybe"]}
clonedObj = Object.assign({},obj);
clonedObj.b.push("skip")// changes will reflected to the actual obj as well because of its reference type.
obj.b //will also console => yes,no,maybe,skip
So for the deep cloning is not possible to achieve in this way.
The best solution that works is
var obj = Json.stringify(yourSourceObj)
var cloned = Json.parse(obj);
Add ArrayList to another ArrayList in java
The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop. Each iterations NodeList is enlarged by new elements.
After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))
After second loop NodeList has 10 elements (PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd) and list has 2 elements (NodeList (with 10 elements), NodeList (with 10 elements))
To get you expectations you must replace
NodeList.addAll(nodes);
list.add(NodeList)
by
List childrenList = new ArrayList(nodes);
list.add(childrenList);
PS. Your code is not readable, keep Java code conventions to have readble code. For example is hard to recognize if NodeList is a class or object
How to get my activity context?
The best and easy way to get the activity context is putting .this
after the name of the Activity. For example: If your Activity's name is SecondActivity
, its context will be SecondActivity.this
Styling twitter bootstrap buttons
For Bootstrap (at least for version 3.1.1) and LESS, you can use this:
.btn-my-custom {
.button-variant(@color; @background; @border)
}
This is defined in bootstrap/less/buttons.less
.
How to do a JUnit assert on a message in a logger
Using Jmockit (1.21) I was able to write this simple test.
The test makes sure a specific ERROR message is called just once.
@Test
public void testErrorMessage() {
final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger( MyConfig.class );
new Expectations(logger) {{
//make sure this error is happens just once.
logger.error( "Something went wrong..." );
times = 1;
}};
new MyTestObject().runSomethingWrong( "aaa" ); //SUT that eventually cause the error in the log.
}
Delete a dictionary item if the key exists
There is also:
try:
del mydict[key]
except KeyError:
pass
This only does 1 lookup instead of 2. However, except
clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.
How do I cancel a build that is in progress in Visual Studio?
I was hit by an unresponsive build and absolutely nothing would allow me to either kill or cancel the build. Even trying to end the task would trigger a user input window, saying that it could not be ended while the build is still going on (quite ironic because that was precisely the intention, to leave that broken state).
The build was taken care of by MSBuild, so the one way I found is to end its task. When forcing MSBuild.exe to end, VS will wake up and finally see the build as cancelled, allowing you to work again.
Hope this helps someone in the same situation.
Adding external library in Android studio
Android studio doesn't use Maven
, it use Gradle
, you can open your build.gradle
the route should be: /app/build.gradle
and add the Gradle dependency that shows on the repo:
The build.gradle
has a dependencies
section:
dependencies {
//here add your dependency
}
The repo says that you need to add this dependency:
compile 'com.foursquare:foursquare-android-oauth:1.0.3'
only add that line to your dependencies
on buil.gradle
, save the file, and android will rebuild the project, that's all
Pass variables by reference in JavaScript
Actually it is really easy. The problem is understanding that once passing classic arguments, you are scoped into another, read-only zone.
The solution is to pass the arguments using JavaScript's object-oriented design. It is the same as putting the arguments in a global/scoped variable, but better...
function action(){
/* Process this.arg, modification allowed */
}
action.arg = [["empty-array"], "some string", 0x100, "last argument"];
action();
You can also promise stuff up to enjoy the well-known chain:
Here is the whole thing, with promise-like structure
function action(){
/* Process this.arg, modification allowed */
this.arg = ["a", "b"];
}
action.setArg = function(){this.arg = arguments; return this;}
action.setArg(["empty-array"], "some string", 0x100, "last argument")()
Or better yet...
action.setArg(["empty-array"],"some string",0x100,"last argument").call()
Python CSV error: line contains NULL byte
You could just inline a generator to filter out the null values if you want to pretend they don't exist. Of course this is assuming the null bytes are not really part of the encoding and really are some kind of erroneous artifact or bug.
with open(filepath, "rb") as f:
reader = csv.reader( (line.replace('\0','') for line in f) )
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
Shell Script — Get all files modified after <date>
I would simply do the following to backup all new files from 7 days ago
tar --newer $(date -d'7 days ago' +"%d-%b") -zcf thisweek.tgz .
note you can also replace '7 days ago' with anything that suits your need
Can be : date -d'yesterday' +"%d-%b"
Or even : date -d'first Sunday last month' +"%d-%b"
@ variables in Ruby on Rails
A tutorial about What is Variable Scope? presents some details quite well, just enclose the related here.
+------------------+----------------------+
| Name Begins With | Variable Scope |
+------------------+----------------------+
| $ | A global variable |
| @ | An instance variable |
| [a-z] or _ | A local variable |
| [A-Z] | A constant |
| @@ | A class variable |
+------------------+----------------------+
Is there more to an interface than having the correct methods
Normally Interfaces define the interface you should use (as the name says it ;-) ). Sample
public void foo(List l) {
... do something
}
Now your function foo
accepts ArrayList
s, LinkedList
s, ... not only one type.
The most important thing in Java is that you can implement multiple interfaces but you can only extend ONE class! Sample:
class Test extends Foo implements Comparable, Serializable, Formattable {
...
}
is possible but
class Test extends Foo, Bar, Buz {
...
}
is not!
Your code above could also be: IBox myBox = new Rectangle();
. The important thing is now, that myBox ONLY contains the methods/fields from IBox and not the (possibly existing) other methods from Rectangle
.
How to select a single child element using jQuery?
<html>
<title>
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>
<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
<!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->
<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
</asp:Repeater>
</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>
<script>
$(function () {
$('a').click(function() {
$(this).parent().children('.dataContentSectionMessages').slideToggle();
});
});
</script>
</html>
How to revert initial git commit?
Under the conditions stipulated in the question:
- The commit is the first commit in the repository.
- Which means there have been very few commands executed:
- a
git init
,
- presumably some
git add
operations,
- and a
git commit
,
- and that's all!
If those preconditions are met, then the simplest way to undo the initial commit would be:
rm -fr .git
from the directory where you did git init
. You can then redo the git init
to recreate the Git repository, and redo the additions with whatever changes are sensible that you regretted not making the first time, and redo the initial commit.
DANGER! This removes the Git repository directory.
It removes the Git repository directory permanently and irrecoverably, unless you've got backups somewhere. Under the preconditions, you've nothing you want to keep in the repository, so you're not losing anything.
All the files you added are still available in the working directories, assuming you have not modified them yet and have not deleted them, etc. However, doing this is safe only if you have nothing else in your repository at all. Under the circumstances described in the question 'commit repository first time — then regret it', it is safe. Very often, though, it is not safe.
It's also safe to do this to remove an unwanted cloned repository; it does no damage to the repository that it was cloned from. It throws away anything you've done in your copy, but doesn't affect the original repository otherwise.
Be careful, but it is safe and effective when the preconditions are met.
If you've done other things with your repository that you want preserved, then this is not the appropriate technique — your repository no longer meets the preconditions for this to be appropriate.
Logging best practices
Update: For extensions to System.Diagnostics, providing some of the missing listeners you might want, see Essential.Diagnostics on CodePlex (http://essentialdiagnostics.codeplex.com/)
Frameworks
Q: What frameworks do you use?
A: System.Diagnostics.TraceSource, built in to .NET 2.0.
It provides powerful, flexible, high performance logging for applications, however many developers are not aware of its capabilities and do not make full use of them.
There are some areas where additional functionality is useful, or sometimes the functionality exists but is not well documented, however this does not mean that the entire logging framework (which is designed to be extensible) should be thrown away and completely replaced like some popular alternatives (NLog, log4net, Common.Logging, and even EntLib Logging).
Rather than change the way you add logging statements to your application and re-inventing the wheel, just extended the System.Diagnostics framework in the few places you need it.
It seems to me the other frameworks, even EntLib, simply suffer from Not Invented Here Syndrome, and I think they have wasted time re-inventing the basics that already work perfectly well in System.Diagnostics (such as how you write log statements), rather than filling in the few gaps that exist. In short, don't use them -- they aren't needed.
Features you may not have known:
- Using the TraceEvent overloads that take a format string and args can help performance as parameters are kept as separate references until after Filter.ShouldTrace() has succeeded. This means no expensive calls to ToString() on parameter values until after the system has confirmed message will actually be logged.
- The Trace.CorrelationManager allows you to correlate log statements about the same logical operation (see below).
- VisualBasic.Logging.FileLogTraceListener is good for writing to log files and supports file rotation. Although in the VisualBasic namespace, it can be just as easily used in a C# (or other language) project simply by including the DLL.
- When using EventLogTraceListener if you call TraceEvent with multiple arguments and with empty or null format string, then the args are passed directly to the EventLog.WriteEntry() if you are using localized message resources.
- The Service Trace Viewer tool (from WCF) is useful for viewing graphs of activity correlated log files (even if you aren't using WCF). This can really help debug complex issues where multiple threads/activites are involved.
- Avoid overhead by clearing all listeners (or removing Default); otherwise Default will pass everything to the trace system (and incur all those ToString() overheads).
Areas you might want to look at extending (if needed):
- Database trace listener
- Colored console trace listener
- MSMQ / Email / WMI trace listeners (if needed)
- Implement a FileSystemWatcher to call Trace.Refresh for dynamic configuration changes
Other Recommendations:
Use structed event id's, and keep a reference list (e.g. document them in an enum).
Having unique event id's for each (significant) event in your system is very useful for correlating and finding specific issues. It is easy to track back to the specific code that logs/uses the event ids, and can make it easy to provide guidance for common errors, e.g. error 5178 means your database connection string is wrong, etc.
Event id's should follow some kind of structure (similar to the Theory of Reply Codes used in email and HTTP), which allows you to treat them by category without knowing specific codes.
e.g. The first digit can detail the general class: 1xxx can be used for 'Start' operations, 2xxx for normal behaviour, 3xxx for activity tracing, 4xxx for warnings, 5xxx for errors, 8xxx for 'Stop' operations, 9xxx for fatal errors, etc.
The second digit can detail the area, e.g. 21xx for database information (41xx for database warnings, 51xx for database errors), 22xx for calculation mode (42xx for calculation warnings, etc), 23xx for another module, etc.
Assigned, structured event id's also allow you use them in filters.
Q: If you use tracing, do you make use of Trace.Correlation.StartLogicalOperation?
A: Trace.CorrelationManager is very useful for correlating log statements in any sort of multi-threaded environment (which is pretty much anything these days).
You need at least to set the ActivityId once for each logical operation in order to correlate.
Start/Stop and the LogicalOperationStack can then be used for simple stack-based context. For more complex contexts (e.g. asynchronous operations), using TraceTransfer to the new ActivityId (before changing it), allows correlation.
The Service Trace Viewer tool can be useful for viewing activity graphs (even if you aren't using WCF).
Q: Do you write this code manually, or do you use some form of aspect oriented programming to do it? Care to share a code snippet?
A: You may want to create a scope class, e.g. LogicalOperationScope, that (a) sets up the context when created and (b) resets the context when disposed.
This allows you to write code such as the following to automatically wrap operations:
using( LogicalOperationScope operation = new LogicalOperationScope("Operation") )
{
// .. do work here
}
On creation the scope could first set ActivityId if needed, call StartLogicalOperation and then log a TraceEventType.Start message. On Dispose it could log a Stop message, and then call StopLogicalOperation.
Q: Do you provide any form of granularity over trace sources? E.g., WPF TraceSources allow you to configure them at various levels.
A: Yes, multiple Trace Sources are useful / important as systems get larger.
Whilst you probably want to consistently log all Warning & above, or all Information & above messages, for any reasonably sized system the volume of Activity Tracing (Start, Stop, etc) and Verbose logging simply becomes too much.
Rather than having only one switch that turns it all either on or off, it is useful to be able to turn on this information for one section of your system at a time.
This way, you can locate significant problems from the usually logging (all warnings, errors, etc), and then "zoom in" on the sections you want and set them to Activity Tracing or even Debug levels.
The number of trace sources you need depends on your application, e.g. you may want one trace source per assembly or per major section of your application.
If you need even more fine tuned control, add individual boolean switches to turn on/off specific high volume tracing, e.g. raw message dumps. (Or a separate trace source could be used, similar to WCF/WPF).
You might also want to consider separate trace sources for Activity Tracing vs general (other) logging, as it can make it a bit easier to configure filters exactly how you want them.
Note that messages can still be correlated via ActivityId even if different sources are used, so use as many as you need.
Listeners
Q: What log outputs do you use?
This can depend on what type of application you are writing, and what things are being logged. Usually different things go in different places (i.e. multiple outputs).
I generally classify outputs into three groups:
(1) Events - Windows Event Log (and trace files)
e.g. If writing a server/service, then best practice on Windows is to use the Windows Event Log (you don't have a UI to report to).
In this case all Fatal, Error, Warning and (service-level) Information events should go to the Windows Event Log. The Information level should be reserved for these type of high level events, the ones that you want to go in the event log, e.g. "Service Started", "Service Stopped", "Connected to Xyz", and maybe even "Schedule Initiated", "User Logged On", etc.
In some cases you may want to make writing to the event log a built-in part of your application and not via the trace system (i.e. write Event Log entries directly). This means it can't accidentally be turned off. (Note you still also want to note the same event in your trace system so you can correlate).
In contrast, a Windows GUI application would generally report these to the user (although they may also log to the Windows Event Log).
Events may also have related performance counters (e.g. number of errors/sec), and it can be important to co-ordinate any direct writing to the Event Log, performance counters, writing to the trace system and reporting to the user so they occur at the same time.
i.e. If a user sees an error message at a particular time, you should be able to find the same error message in the Windows Event Log, and then the same event with the same timestamp in the trace log (along with other trace details).
(2) Activities - Application Log files or database table (and trace files)
This is the regular activity that a system does, e.g. web page served, stock market trade lodged, order taken, calculation performed, etc.
Activity Tracing (start, stop, etc) is useful here (at the right granuality).
Also, it is very common to use a specific Application Log (sometimes called an Audit Log). Usually this is a database table or an application log file and contains structured data (i.e. a set of fields).
Things can get a bit blurred here depending on your application. A good example might be a web server which writes each request to a web log; similar examples might be a messaging system or calculation system where each operation is logged along with application-specific details.
A not so good example is stock market trades or a sales ordering system. In these systems you are probably already logging the activity as they have important business value, however the principal of correlating them to other actions is still important.
As well as custom application logs, activities also often have related peformance counters, e.g. number of transactions per second.
In generally you should co-ordinate logging of activities across different systems, i.e. write to your application log at the same time as you increase your performance counter and log to your trace system. If you do all at the same time (or straight after each other in the code), then debugging problems is easier (than if they all occur at diffent times/locations in the code).
(3) Debug Trace - Text file, or maybe XML or database.
This is information at Verbose level and lower (e.g. custom boolean switches to turn on/off raw data dumps). This provides the guts or details of what a system is doing at a sub-activity level.
This is the level you want to be able to turn on/off for individual sections of your application (hence the multiple sources). You don't want this stuff cluttering up the Windows Event Log. Sometimes a database is used, but more likely are rolling log files that are purged after a certain time.
A big difference between this information and an Application Log file is that it is unstructured. Whilst an Application Log may have fields for To, From, Amount, etc., Verbose debug traces may be whatever a programmer puts in, e.g. "checking values X={value}, Y=false", or random comments/markers like "Done it, trying again".
One important practice is to make sure things you put in application log files or the Windows Event Log also get logged to the trace system with the same details (e.g. timestamp). This allows you to then correlate the different logs when investigating.
If you are planning to use a particular log viewer because you have complex correlation, e.g. the Service Trace Viewer, then you need to use an appropriate format i.e. XML. Otherwise, a simple text file is usually good enough -- at the lower levels the information is largely unstructured, so you might find dumps of arrays, stack dumps, etc. Provided you can correlated back to more structured logs at higher levels, things should be okay.
Q: If using files, do you use rolling logs or just a single file? How do you make the logs available for people to consume?
A: For files, generally you want rolling log files from a manageability point of view (with System.Diagnostics simply use VisualBasic.Logging.FileLogTraceListener).
Availability again depends on the system. If you are only talking about files then for a server/service, rolling files can just be accessed when necessary. (Windows Event Log or Database Application Logs would have their own access mechanisms).
If you don't have easy access to the file system, then debug tracing to a database may be easier. [i.e. implement a database TraceListener].
One interesting solution I saw for a Windows GUI application was that it logged very detailed tracing information to a "flight recorder" whilst running and then when you shut it down if it had no problems then it simply deleted the file.
If, however it crashed or encountered a problem then the file was not deleted. Either if it catches the error, or the next time it runs it will notice the file, and then it can take action, e.g. compress it (e.g. 7zip) and email it or otherwise make available.
Many systems these days incorporate automated reporting of failures to a central server (after checking with users, e.g. for privacy reasons).
Viewing
Q: What tools to you use for viewing the logs?
A: If you have multiple logs for different reasons then you will use multiple viewers.
Notepad/vi/Notepad++ or any other text editor is the basic for plain text logs.
If you have complex operations, e.g. activities with transfers, then you would, obviously, use a specialized tool like the Service Trace Viewer. (But if you don't need it, then a text editor is easier).
As I generally log high level information to the Windows Event Log, then it provides a quick way to get an overview, in a structured manner (look for the pretty error/warning icons). You only need to start hunting through text files if there is not enough in the log, although at least the log gives you a starting point. (At this point, making sure your logs have co-ordinated entires becomes useful).
Generally the Windows Event Log also makes these significant events available to monitoring tools like MOM or OpenView.
Others --
If you log to a Database it can be easy to filter and sort informatio (e.g. zoom in on a particular activity id. (With text files you can use Grep/PowerShell or similar to filter on the partiular GUID you want)
MS Excel (or another spreadsheet program). This can be useful for analysing structured or semi-structured information if you can import it with the right delimiters so that different values go in different columns.
When running a service in debug/test I usually host it in a console application for simplicity I find a colored console logger useful (e.g. red for errors, yellow for warnings, etc). You need to implement a custom trace listener.
Note that the framework does not include a colored console logger or a database logger so, right now, you would need to write these if you need them (it's not too hard).
It really annoys me that several frameworks (log4net, EntLib, etc) have wasted time re-inventing the wheel and re-implemented basic logging, filtering, and logging to text files, the Windows Event Log, and XML files, each in their own different way (log statements are different in each); each has then implemented their own version of, for example, a database logger, when most of that already existed and all that was needed was a couple more trace listeners for System.Diagnostics. Talk about a big waste of duplicate effort.
Q: If you are building an ASP.NET solution, do you also use ASP.NET Health Monitoring? Do you include trace output in the health monitor events? What about Trace.axd?
These things can be turned on/off as needed. I find Trace.axd quite useful for debugging how a server responds to certain things, but it's not generally useful in a heavily used environment or for long term tracing.
Q: What about custom performance counters?
For a professional application, especially a server/service, I expect to see it fully instrumented with both Performance Monitor counters and logging to the Windows Event Log. These are the standard tools in Windows and should be used.
You need to make sure you include installers for the performance counters and event logs that you use; these should be created at installation time (when installing as administrator). When your application is running normally it should not need have administration privileges (and so won't be able to create missing logs).
This is a good reason to practice developing as a non-administrator (have a separate admin account for when you need to install services, etc). If writing to the Event Log, .NET will automatically create a missing log the first time you write to it; if you develop as a non-admin you will catch this early and avoid a nasty surprise when a customer installs your system and then can't use it because they aren't running as administrator.
How can I quickly sum all numbers in a file?
Just for fun, let's benchmark it:
$ for ((i=0; i<1000000; i++)) ; do echo $RANDOM; done > random_numbers
$ time perl -nle '$sum += $_ } END { print $sum' random_numbers
16379866392
real 0m0.226s
user 0m0.219s
sys 0m0.002s
$ time awk '{ sum += $1 } END { print sum }' random_numbers
16379866392
real 0m0.311s
user 0m0.304s
sys 0m0.005s
$ time { { tr "\n" + < random_numbers ; echo 0; } | bc; }
16379866392
real 0m0.445s
user 0m0.438s
sys 0m0.024s
$ time { s=0;while read l; do s=$((s+$l));done<random_numbers;echo $s; }
16379866392
real 0m9.309s
user 0m8.404s
sys 0m0.887s
$ time { s=0;while read l; do ((s+=l));done<random_numbers;echo $s; }
16379866392
real 0m7.191s
user 0m6.402s
sys 0m0.776s
$ time { sed ':a;N;s/\n/+/;ta' random_numbers|bc; }
^C
real 4m53.413s
user 4m52.584s
sys 0m0.052s
I aborted the sed run after 5 minutes
I've been diving to lua, and it is speedy:
$ time lua -e 'sum=0; for line in io.lines() do sum=sum+line end; print(sum)' < random_numbers
16388542582.0
real 0m0.362s
user 0m0.313s
sys 0m0.063s
and while I'm updating this, ruby:
$ time ruby -e 'sum = 0; File.foreach(ARGV.shift) {|line| sum+=line.to_i}; puts sum' random_numbers
16388542582
real 0m0.378s
user 0m0.297s
sys 0m0.078s
Heed Ed Morton's advice: using $1
$ time awk '{ sum += $1 } END { print sum }' random_numbers
16388542582
real 0m0.421s
user 0m0.359s
sys 0m0.063s
vs using $0
$ time awk '{ sum += $0 } END { print sum }' random_numbers
16388542582
real 0m0.302s
user 0m0.234s
sys 0m0.063s
How to convert local time string to UTC?
This thread seems to be missing an option available since Python 3.6: datetime.astimezone(tz=None)
can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC.
from datetime import datetime, timezone
s = "2008-09-17 14:02:00"
# to datetime object:
dt = datetime.fromisoformat(s) # Python 3.7
# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
dt = dt.astimezone()
print(dt)
# 2008-09-17 14:02:00+02:00
# ...and to UTC:
dtutc = dt.astimezone(timezone.utc)
print(dtutc)
# 2008-09-17 12:02:00+00:00
There is one caveat though, see astimezone(None) gives aware datetime, unaware of DST.
Input type number "only numeric value" validation
I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity
, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.
Sample use:
<input type="number" formControlName="num" placeholder="0" ntvFormValidity>
Directive definition:
import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';
@Directive({
selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {
constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }
/*
- Angular doesn't fire "change" events for invalid <input type="number">
- We have to check the DOM object for browser native invalid state
- Add custom validator that checks native invalidity
*/
ngAfterViewInit() {
var control: FormControl = this.cn.control;
// Bridge native invalid to ng-invalid via Validators
const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
const v_fn = control.validator;
control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
setTimeout(()=>control.updateValueAndValidity(), 0);
}
}
The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.
On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".
I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.
Something like this:
<my-input-number formControlName="num" placeholder="0">
PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers
on the declaration, please let me know so I can update my Directive (and this answer).
Oracle 10g: Extract data (select) from XML (CLOB Type)
Try using xmltype.createxml(xml)
.
As in,
select extract(xmltype.createxml(xml), '//fax').getStringVal() from mytab;
It worked for me.
If you want to improve or manipulate even further.
Try something like this.
Select *
from xmltable(xmlnamespaces('some-name-space' as "ns",
'another-name-space' as "ns1",
),
'/ns/ns1/foo/bar'
passing xmltype.createxml(xml)
columns id varchar2(10) path '//ns//ns1/id',
idboss varchar2(500) path '//ns0//ns1/idboss',
etc....
) nice_xml_table
Hope it helps someone.
RSA encryption and decryption in Python
PKCS#1 OAEP is an asymmetric cipher based on RSA and the OAEP padding
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import PKCS1_OAEP
def rsa_encrypt_decrypt():
key = RSA.generate(2048)
private_key = key.export_key('PEM')
public_key = key.publickey().exportKey('PEM')
message = input('plain text for RSA encryption and decryption:')
message = str.encode(message)
rsa_public_key = RSA.importKey(public_key)
rsa_public_key = PKCS1_OAEP.new(rsa_public_key)
encrypted_text = rsa_public_key.encrypt(message)
#encrypted_text = b64encode(encrypted_text)
print('your encrypted_text is : {}'.format(encrypted_text))
rsa_private_key = RSA.importKey(private_key)
rsa_private_key = PKCS1_OAEP.new(rsa_private_key)
decrypted_text = rsa_private_key.decrypt(encrypted_text)
print('your decrypted_text is : {}'.format(decrypted_text))
CSS 3 slide-in from left transition
Use CSS3 2D transform
to avoid performance issues (mobile)
A common pitfall is to animate left
/top
/right
/bottom
properties instead of using css-transform to achieve the same effect. For a variety of reasons, the semantics of transforms make them easier to offload, but left
/top
/right
/bottom
are much more difficult.
Source: Mozilla Developer Network (MDN)
Demo:
_x000D_
_x000D_
var $slider = document.getElementById('slider');
var $toggle = document.getElementById('toggle');
$toggle.addEventListener('click', function() {
var isOpen = $slider.classList.contains('slide-in');
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');
});
_x000D_
#slider {
position: absolute;
width: 100px;
height: 100px;
background: blue;
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
.slide-in {
animation: slide-in 0.5s forwards;
-webkit-animation: slide-in 0.5s forwards;
}
.slide-out {
animation: slide-out 0.5s forwards;
-webkit-animation: slide-out 0.5s forwards;
}
@keyframes slide-in {
100% { transform: translateX(0%); }
}
@-webkit-keyframes slide-in {
100% { -webkit-transform: translateX(0%); }
}
@keyframes slide-out {
0% { transform: translateX(0%); }
100% { transform: translateX(-100%); }
}
@-webkit-keyframes slide-out {
0% { -webkit-transform: translateX(0%); }
100% { -webkit-transform: translateX(-100%); }
}
_x000D_
<div id="slider" class="slide-in">
<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
</ul>
</div>
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
_x000D_
_x000D_
Uninstall mongoDB from ubuntu
In my case mongodb
packages are named mongodb-org
and mongodb-org-*
So when I type sudo apt purge mongo
then tab
(for auto-completion) I can see all installed packages that start with mongo
.
Another option is to run the following command (which will list all packages that contain mongo
in their names or their descriptions):
dpkg -l | grep mongo
In summary, I would do (to purge all packages that start with mongo
):
sudo apt purge mongo*
and then (to make sure that no mongo packages are left):
dpkg -l | grep mongo
Of course, as mentioned by @alicanozkara, you will need to manually remove some directories like /var/log/mongodb
and /var/lib/mongodb
Running the following find
commands:
sudo find /etc/ -name "*mongo*"
and sudo find /var/ -name "*mongo*"
may also show some files that you may want to remove, like:
/etc/systemd/system/mongodb.service
/etc/apt/sources.list.d/mongodb-org-3.2.list
and:
/var/lib/apt/lists/repo.mongodb.*
You may also want to remove user and group mongodb
, to do so you need to run:
sudo userdel -r mongodb
sudo groupdel mongodb
To check whether mongodb
user/group exists or not, try:
cut -d: -f1 /etc/passwd | grep mongo
cut -d: -f1 /etc/group | grep mongo
How is a tag different from a branch in Git? Which should I use, here?
What you need to realize, coming from CVS, is that you no longer create directories when setting up a branch.
No more "sticky tag" (which can be applied to just one file), or "branch tag".
Branch and tags are two different objects in Git, and they always apply to the all repo.
You would no longer (with SVN this time) have to explicitly structure your repository with:
branches
myFirstBranch
myProject
mySubDirs
mySecondBranch
...
tags
myFirstTag
myProject
mySubDirs
mySecondTag
...
That structure comes from the fact CVS is a revision system and not a version system (see Source control vs. Revision Control?).
That means branches are emulated through tags for CVS, directory copies for SVN.
Your question makes senses if you are used to checkout a tag, and start working in it.
Which you shouldn't ;)
A tag is supposed to represent an immutable content, used only to access it with the guarantee to get the same content every time.
In Git, the history of revisions is a series of commits, forming a graph.
A branch is one path of that graph
x--x--x--x--x # one branch
\
--y----y # another branch
1.1
^
|
# a tag pointing to a commit
- If you checkout a tag, you will need to create a branch to start working from it.
- If you checkout a branch, you will directly see the latest commit it('HEAD') of that branch.
See Jakub Narebski's answer for all the technicalities, but frankly, at this point, you do not need (yet) all the details ;)
The main point is: a tag being a simple pointer to a commit, you will never be able to modify its content. You need a branch.
In your case, each developer working on a specific feature:
- should create their own branch in their respective repository
- track branches from their colleague's repositories (the one working on the same feature)
- pulling/pushing in order to share your work with your peers.
Instead of tracking directly the branches of your colleagues, you could track only the branch of one "official" central repository to which everyone pushes his/her work in order to integrate and share everyone's work for this particular feature.
php error: Class 'Imagick' not found
For all to those having problems with this i did this tutorial:
How to install Imagemagick and Php module Imagick on ubuntu?
i did this 7 simple steps:
Update libraries, and packages
apt-get update
Remove obsolete things
apt-get autoremove
For the libraries of ImageMagick
apt-get install libmagickwand-dev
for the core class Imagick
apt-get install imagemagick
For create the binaries, and conections in beetween
pecl install imagick
Append the extension to your php.ini
echo "extension=imagick.so" >> /etc/php5/apache2/php.ini
Restart Apache
service apache2 restart
I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.
How to force Hibernate to return dates as java.util.Date instead of Timestamp?
I ran into a problem with this as well as my JUnit assertEquals were failing comparing Dates to Hibernate emitted 'java.util.Date' types (which as described in the question are really Timestamps). It turns out that by changing the mapping to 'date' rather than 'java.util.Date' Hibernate generates java.util.Date members. I am using an XML mapping file with Hibernate version 4.1.12.
This version emits 'java.util.Timestamp':
<property name="date" column="DAY" type="java.util.Date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />
This version emits 'java.util.Date':
<property name="date" column="DAY" type="date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />
Note, however, if Hibernate is used to generate the DDL, then these will generate different SQL types (Date for 'date' and Timestamp for 'java.util.Date').
How to convert a String to CharSequence?
That's a good question! You may get into troubles if you invoke API that uses generics and want to assign or return that result with a different subtype of the generic type. Java 8 helps to transform:
List<String> input = new LinkedList<>(Arrays.asList("a", "b", "c"));
List<CharSequence> result;
// result = input; // <-- Type mismatch: cannot convert from List<String> to List<CharSequence>
result = input.stream().collect(Collectors.toList());
System.out.println(result);
how to check if object already exists in a list
Are you sure you need a list in this case? If you are populating the list with many items, performance will suffer with myList.Contains
or myList.Any
; the run-time will be quadratic. You might want to consider using a better data structure. For example,
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class MyClassComparer : EqualityComparer<MyClass>
{
public override bool Equals(MyClass x, MyClass y)
{
if(x == null || y == null)
return x == y;
return x.Property1 == y.Property1 && x.Property2 == y.Property2;
}
public override int GetHashCode(MyClass obj)
{
return obj == null ? 0 : (obj.Property1.GetHashCode() ^ obj.Property2.GetHashCode());
}
}
You could use a HashSet in the following manner:
var set = new HashSet<MyClass>(new MyClassComparer());
foreach(var myClass in ...)
set.Add(myClass);
Of course, if this definition of equality for MyClass
is 'universal', you needn't write an IEqualityComparer
implementation; you could just override GetHashCode
and Equals
in the class itself.
Save the plots into a PDF
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig() # saves the current figure into a pdf page
plt.close()
plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.savefig()
plt.close()
plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x*x, 'ko')
plt.title('Page Three')
pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig
plt.close()
# We can also set the file's metadata via the PdfPages object:
d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = u'Jouni K. Sepp\xe4nen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()
node.js http 'get' request with query string parameters
If you don't want use external package , Just add the following function in your utilities :
var params=function(req){
let q=req.url.split('?'),result={};
if(q.length>=2){
q[1].split('&').forEach((item)=>{
try {
result[item.split('=')[0]]=item.split('=')[1];
} catch (e) {
result[item.split('=')[0]]='';
}
})
}
return result;
}
Then , in createServer
call back , add attribute params
to request
object :
http.createServer(function(req,res){
req.params=params(req); // call the function above ;
/**
* http://mysite/add?name=Ahmed
*/
console.log(req.params.name) ; // display : "Ahmed"
})
In Python script, how do I set PYTHONPATH?
you can set PYTHONPATH
, by os.environ['PATHPYTHON']=/some/path
, then you need to call os.system('python')
to restart the python shell to make the newly added path effective.
How to declare a variable in a template in Angular
Ugly, but:
<div *ngFor="let a of [aVariable]">
<span>{{a}}</span>
</div>
When used with async pipe:
<div *ngFor="let a of [aVariable | async]">
<span>{{a.prop1}}</span>
<span>{{a.prop2}}</span>
</div>
Can I use git diff on untracked files?
Not 100% to the point, but if for some reason you don't want to add your files to the index as suggested by the accepted answer, here is another option:
If the files are untracked, obviously the diff is the whole file, so you can just view them with less:
less $(git ls-files --others --exclude-standard)
Navigate between them with :n
and :p
for next and previous..
Update from the comments: If you need a patch format you can also combine it with git diff
:
git ls-files --others --exclude-standard | xargs -n 1 git --no-pager diff /dev/null | less
You can also redirect the output to a file or use an other diff command in this case.
Getting the last element of a list
If your str()
or list()
objects might end up being empty as so: astr = ''
or alist = []
, then you might want to use alist[-1:]
instead of alist[-1]
for object "sameness".
The significance of this is:
alist = []
alist[-1] # will generate an IndexError exception whereas
alist[-1:] # will return an empty list
astr = ''
astr[-1] # will generate an IndexError exception whereas
astr[-1:] # will return an empty str
Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.
expected assignment or function call: no-unused-expressions ReactJS
In my case the error happened because the new line after the return
statement.
Error : Expected an assignment or function call and instead saw an expression
return
(
<ul>
{
props.numbers.map(number => <li key={number.toString()}>number</li>)
}
</ul>
);
Working OK. No Error
return (
<ul>
{
props.numbers.map(number => <li key={number.toString()}>number</li>)
}
</ul>
);
How do I print bold text in Python?
This depends if you're using linux/unix:
>>> start = "\033[1m"
>>> end = "\033[0;0m"
>>> print "The" + start + "text" + end + " is bold."
The text is bold.
The word text
should be bold.
Convert Variable Name to String?
What are you trying to achieve? There is absolutely no reason to ever do what you describe, and there is likely a much better solution to the problem you're trying to solve..
The most obvious alternative to what you request is a dictionary. For example:
>>> my_data = {'var': 'something'}
>>> my_data['something_else'] = 'something'
>>> print my_data.keys()
['var', 'something_else']
>>> print my_data['var']
something
Mostly as a.. challenge, I implemented your desired output. Do not use this code, please!
#!/usr/bin/env python2.6
class NewLocals:
"""Please don't ever use this code.."""
def __init__(self, initial_locals):
self.prev_locals = list(initial_locals.keys())
def show_new(self, new_locals):
output = ", ".join(list(set(new_locals) - set(self.prev_locals)))
self.prev_locals = list(new_locals.keys())
return output
# Set up
eww = None
eww = NewLocals(locals())
# "Working" requested code
var = {}
print eww.show_new(locals()) # Outputs: var
something_else = 3
print eww.show_new(locals()) # Outputs: something_else
# Further testing
another_variable = 4
and_a_final_one = 5
print eww.show_new(locals()) # Outputs: another_variable, and_a_final_one
How to display an unordered list in two columns?
Modern Browsers
leverage the css3 columns module to support what you are looking for.
http://www.w3schools.com/cssref/css3_pr_columns.asp
CSS:
ul {
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
}
http://jsfiddle.net/HP85j/8/
Legacy Browsers
Unfortunately for IE support you will need a code solution that involves JavaScript and dom manipulation. This means that anytime the contents of the list changes you will need to perform the operation for reordering the list into columns and reprinting. The solution below uses jQuery for brevity.
http://jsfiddle.net/HP85j/19/
HTML:
<div>
<ul class="columns" data-columns="2">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
</ul>
</div>
JavaScript:
(function($){
var initialContainer = $('.columns'),
columnItems = $('.columns li'),
columns = null,
column = 1; // account for initial column
function updateColumns(){
column = 0;
columnItems.each(function(idx, el){
if (idx !== 0 && idx > (columnItems.length / columns.length) + (column * idx)){
column += 1;
}
$(columns.get(column)).append(el);
});
}
function setupColumns(){
columnItems.detach();
while (column++ < initialContainer.data('columns')){
initialContainer.clone().insertBefore(initialContainer);
column++;
}
columns = $('.columns');
}
$(function(){
setupColumns();
updateColumns();
});
})(jQuery);
CSS:
.columns{
float: left;
position: relative;
margin-right: 20px;
}
EDIT:
As pointed out below this will order the columns as follows:
A E
B F
C G
D
while the OP asked for a variant matching the following:
A B
C D
E F
G
To accomplish the variant you simply change the code to the following:
function updateColumns(){
column = 0;
columnItems.each(function(idx, el){
if (column > columns.length){
column = 0;
}
$(columns.get(column)).append(el);
column += 1;
});
}
Copy text from nano editor to shell
I don't know any way to do this directly in nano. However you can use "cat" or "grep" to display lines of your file in the console.
If you use a terminal multiplexer like "screen" you can copy and paste strings like this.
How to convert String to DOM Document object in java?
Either escape the double quotes with \
String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"
or use single quotes instead
String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"
python: sys is not defined
You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:
try:
import datetime
import foo
import sys
except ImportError:
pass
Let's say foo
doesn't exist. Then only datetime
will be imported.
What you can do is import the sys module at the beginning of the file, before the try/except statement:
import sys
try:
import numpy as np
import pyfits as pf
import scipy.ndimage as nd
import pylab as pl
import os
import heapq
from scipy.optimize import leastsq
except ImportError:
print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
sys.exit()
vertical-align image in div
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
JSFiddle demo
Live Example:
_x000D_
_x000D_
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Rest-assured. Is it possible to extract value from request json?
There are several ways. I personally use the following ones:
extracting single value:
String user_Id =
given().
when().
then().
extract().
path("user_id");
work with the entire response when you need more than one:
Response response =
given().
when().
then().
extract().
response();
String userId = response.path("user_id");
extract one using the JsonPath to get the right type:
long userId =
given().
when().
then().
extract().
jsonPath().getLong("user_id");
Last one is really useful when you want to match against the value and the type i.e.
assertThat(
when().
then().
extract().
jsonPath().getLong("user_id"), equalTo(USER_ID)
);
The rest-assured documentation is quite descriptive and full. There are many ways to achieve what you are asking: https://github.com/jayway/rest-assured/wiki/Usage
Use Ant for running program with command line arguments
If you do not want to handle separate properties for each possible argument, I suggest you'd use:
<arg line="${args}"/>
You can check if the property is not set using a specific target with an unless
attribute and inside do:
<input message="Type the desired command line arguments:" addProperty="args"/>
Putting it all together gives:
<target name="run" depends="compile, input-runargs" description="run the project">
<!-- You can use exec here, depending on your needs -->
<java classname="Main">
<arg line="${args}"/>
</java>
</target>
<target name="input-runargs" unless="args" description="prompts for command line arguments if necessary">
<input addProperty="args" message="Type the desired command line arguments:"/>
</target>
You can use it as follows:
ant
ant run
ant run -Dargs='--help'
The first two commands will prompt for the command-line arguments, whereas the latter won't.
Include another HTML file in a HTML file
You can use a polyfill of HTML Imports (https://www.html5rocks.com/en/tutorials/webcomponents/imports/), or that simplified solution
https://github.com/dsheiko/html-import
For example, on the page you import HTML block like that:
<link rel="html-import" href="./some-path/block.html" >
The block may have imports of its own:
<link rel="html-import" href="./some-other-path/other-block.html" >
The importer replaces the directive with the loaded HTML pretty much like SSI
These directives will be served automatically as soon as you load this small JavaScript:
<script async src="./src/html-import.js"></script>
It will process the imports when DOM is ready automatically. Besides, it exposes an API that you can use to run manually, to get logs and so on. Enjoy :)
javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
Working demo
Html.ActionLink as a button or an image, not a link
@using (Html.BeginForm("DeleteMember", "Member", new { id = Model.MemberID }))
{
<input type="submit" value="Delete Member" onclick = "return confirm('Are you sure you want to delete the member?');" />
}
Copy entire contents of a directory to another using php
My pruned version of @Kzoty answer.
Thank you Kzoty.
Usage
Helper::copy($sourcePath, $targetPath);
class Helper {
static function copy($source, $target) {
if (!is_dir($source)) {//it is a file, do a normal copy
copy($source, $target);
return;
}
//it is a folder, copy its files & sub-folders
@mkdir($target);
$d = dir($source);
$navFolders = array('.', '..');
while (false !== ($fileEntry=$d->read() )) {//copy one by one
//skip if it is navigation folder . or ..
if (in_array($fileEntry, $navFolders) ) {
continue;
}
//do copy
$s = "$source/$fileEntry";
$t = "$target/$fileEntry";
self::copy($s, $t);
}
$d->close();
}
}
Modifying a file inside a jar
You can use the u
option for jar
From the Java Tutorials:
jar uf jar-file input-file(s)
"Any files already in the archive having the same pathname as a file being added will be overwritten."
See Updating a JAR File.
Much better than making the whole jar all over again. Invoking this from within your program sounds possible too. Try Running Command Line in Java
Generate random string/characters in JavaScript
Random unicode string
This method will return a random string with any of the supported unicode characters, which is not 100% what OP asks for, but what I was looking for:
function randomUnicodeString(length){
return Array.from({length: length}, ()=>{
return String.fromCharCode(Math.floor(Math.random() * (65536)))
}).join('')
}
Rationale
This is the top result of google when searching for "random string javascript", but OP asks for a-zA-Z0-9 only.
JavaScript Editor Plugin for Eclipse
JavaScript that allows for syntax checking
JSHint-Eclipse
and autosuggestions for .js files in Eclipse?
- Use JSDoc more as JSDT has nice support for the standard, so you will get more suggestions for your own code.
- There is new TernIDE that provide additional hints for .js and AngulatJS .html. Get them together as Anide from
http://www.nodeclipse.org/updates/anide/
As Nodeclipse lead, I am always looking for what is available in Eclipse ecosystem. Nodeclipse site has even more links,
and I am inviting to collaborate on the JavaScript tools on GitHub
Getting data posted in between two dates
May this helpful to you....
With Join of Three Tables
public function get_details_beetween_dates()
{
$from = $this->input->post('fromdate');
$to = $this->input->post('todate');
$this->db->select('users.first_name, users.last_name, users.email, groups.name as designation, dailyinfo.amount as Total_Fine, dailyinfo.date as Date_of_Fine, dailyinfo.desc as Description')
->from('users')
->where('dailyinfo.date >= ',$from)
->where('dailyinfo.date <= ',$to)
->join('users_groups','users.id = users_groups.user_id')
->join('dailyinfo','users.id = dailyinfo.userid')
->join('groups','groups.id = users_groups.group_id');
/*
$this->db->select('date, amount, desc')
->from('dailyinfo')
->where('dailyinfo.date >= ',$from)
->where('dailyinfo.date <= ',$to);
*/
$q = $this->db->get();
$array['userDetails'] = $q->result();
return $array;
}
download csv file from web api in angular js
Try it like :
File.save(csvInput, function (content) {
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/csv,' + encodeURI(content);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.csv';
hiddenElement.click();
});
based on the most excellent answer in this question
How to import js-modules into TypeScript file?
I'm currently taking some legacy codebases and introducing minimal TypeScript changes to see if it helps our team. Depending on how strict you want to be with TypeScript, this may or may not be an option for you.
The most helpful way for us to get started was to extend our tsconfig.json
file with this property:
// tsconfig.json excerpt:
{
...
"compilerOptions": {
...
"allowJs": true,
...
}
...
}
This change lets our JS files that have JSDoc type hints get compiled. Also our IDEs (JetBrains IDEs and VS Code) can provide code-completion and Intellisense.
References:
Python json.loads shows ValueError: Extra data
This may also happen if your JSON file is not just 1 JSON record.
A JSON record looks like this:
[{"some data": value, "next key": "another value"}]
It opens and closes with a bracket [ ], within the brackets are the braces { }. There can be many pairs of braces, but it all ends with a close bracket ].
If your json file contains more than one of those:
[{"some data": value, "next key": "another value"}]
[{"2nd record data": value, "2nd record key": "another value"}]
then loads() will fail.
I verified this with my own file that was failing.
import json
guestFile = open("1_guests.json",'r')
guestData = guestFile.read()
guestFile.close()
gdfJson = json.loads(guestData)
This works because 1_guests.json has one record []. The original file I was using all_guests.json had 6 records separated by newline. I deleted 5 records, (which I already checked to be bookended by brackets) and saved the file under a new name. Then the loads statement worked.
Error was
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 10 column 1 (char 261900 - 6964758)
PS. I use the word record, but that's not the official name. Also, if your file has newline characters like mine, you can loop through it to loads() one record at a time into a json variable.
Trying to start a service on boot on Android
The other answers look good, but I thought I'd wrap everything up into one complete answer.
You need the following in your AndroidManifest.xml
file:
In your <manifest>
element:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
In your <application>
element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver
):
<receiver android:name="com.example.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
(you don't need the android:enabled
, exported
, etc., attributes: the Android defaults are correct)
In MyBroadcastReceiver.java
:
package com.example;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
context.startService(startServiceIntent);
}
}
From the original question:
- it's not clear if the
<receiver>
element was in the <application>
element
- it's not clear if the correct fully-qualified (or relative) class name for the
BroadcastReceiver
was specified
- there was a typo in the
<intent-filter>
Javascript swap array elements
Here's a compact version
swaps value at i1 with i2 in arr
arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))
Twitter Bootstrap - add top space between rows
There is a trick for adding margin automatically only for the 2nd+ row in the container.
.container-row-margin .row + .row {
margin-top: 1rem;
}
Adding the .container-row-margin
to the container, results in:
Complete HTML:
<div class="bg-secondary text-white">
div outside of the container.
</div>
<div class="container container-row-margin">
<div class="row">
<div class="col col-4 bg-warning">
Row without top margin
</div>
</div>
<div class="row">
<div class="col col-4 bg-primary text-white">
Row with top margin
</div>
</div>
<div class="row">
<div class="col col-4 bg-primary text-white">
Row with top margin
</div>
</div>
</div>
<div class="bg-secondary text-white">
div outside of the container.
</div>
Taken from official samples.
Difference between @click and v-on:click Vuejs
v-bind
and v-on
are two frequently used directives in vuejs html template.
So they provided a shorthand notation for the both of them as follows:
You can replace v-on:
with @
v-on:click='someFunction'
as:
@click='someFunction'
Another example:
v-on:keyup='someKeyUpFunction'
as:
@keyup='someKeyUpFunction'
Similarly, v-bind
with :
v-bind:href='var1'
Can be written as:
:href='var1'
Hope it helps!
Create Generic method constraining T to an Enum
This is my implementation. Basically, you can setup any attribute and it works.
public static class EnumExtensions
{
public static string GetDescription(this Enum @enum)
{
Type type = @enum.GetType();
FieldInfo fi = type.GetField(@enum.ToString());
DescriptionAttribute[] attrs =
fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
if (attrs.Length > 0)
{
return attrs[0].Description;
}
return null;
}
}
How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
The FULLY WORKING SOLUTION for both Android
or React-native
users facing this issue just add this
android:usesCleartextTraffic="true"
in AndroidManifest.xml file like this:
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
in between <application>
.. </application>
tag like this:
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"/>
</application>
How to test if a list contains another list?
Dave answer is good. But I suggest this implementation which is more efficient and doesn't use nested loops.
def contains(small_list, big_list):
"""
Returns index of start of small_list in big_list if big_list
contains small_list, otherwise -1.
"""
loop = True
i, curr_id_small= 0, 0
while loop and i<len(big_list):
if big_list[i]==small_list[curr_id_small]:
if curr_id_small==len(small_list)-1:
loop = False
else:
curr_id_small += 1
else:
curr_id_small = 0
i=i+1
if not loop:
return i-len(small_list)
else:
return -1
What steps are needed to stream RTSP from FFmpeg?
You can use FFserver to stream a video using RTSP.
Just change console syntax to something like this:
ffmpeg -i space.mp4 -vcodec libx264 -tune zerolatency -crf 18 http://localhost:1234/feed1.ffm
Create a ffserver.config
file (sample) where you declare HTTPPort
, RTSPPort
and SDP stream. Your config file could look like this (some important stuff might be missing):
HTTPPort 1234
RTSPPort 1235
<Feed feed1.ffm>
File /tmp/feed1.ffm
FileMaxSize 2M
ACL allow 127.0.0.1
</Feed>
<Stream test1.sdp>
Feed feed1.ffm
Format rtp
Noaudio
VideoCodec libx264
AVOptionVideo flags +global_header
AVOptionVideo me_range 16
AVOptionVideo qdiff 4
AVOptionVideo qmin 10
AVOptionVideo qmax 51
ACL allow 192.168.0.0 192.168.255.255
</Stream>
With such setup you can watch the stream with i.e. VLC by typing:
rtsp://192.168.0.xxx:1235/test1.sdp
Here is the FFserver documentation.
HTML5 LocalStorage: Checking if a key exists
The MDN documentation shows how the getItem
method is implementated:
Object.defineProperty(oStorage, "getItem", {
value: function (sKey) { return sKey ? this[sKey] : null; },
writable: false,
configurable: false,
enumerable: false
});
If the value isn't set, it returns null
. You are testing to see if it is undefined
. Check to see if it is null
instead.
if(localStorage.getItem("username") === null){
Using generic std::function objects with member functions in one class
A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.
Because your std::function
signature specifies that your function doesn't take any arguments (<void(void)>
), you must bind the first (and the only) argument.
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
If you want to bind a function with parameters, you need to specify placeholders:
using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);
Or, if your compiler supports C++11 lambdas:
std::function<void(int,int)> f = [=](int a, int b) {
this->doSomethingArgs(a, b);
}
(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)
How to count certain elements in array?
I believe what you are looking for is functional approach
const arr = ['a', 'a', 'b', 'g', 'a', 'e'];
const count = arr.filter(elem => elem === 'a').length;
console.log(count); // Prints 3
elem === 'a' is the condition, replace it with your own.
PPT to PNG with transparent background
I just tried to make a transparent image with powerpoint after failing miserably with other online systems. I was successful. Amazing.
First I used word art to give me typefaces which convert well to PNG or JPEG. The ordinary text in powerpoint does not convert well. It gets fuzzy. Anyway, I typed in my words in white (my choice of colour as i wanted it against a navy blue background), arranged it how i wanted, then right clicked and selected format shape to remove lines, then shadow to set the transparency.
I took the transparency to 100%. It came out fine. i then right clicked to save as png. Opened the image with MS Picture manager and resized the image to my suiting. It did not come out with the powerpoint white background at all. Once resized, i dropped the image against my navy blue background and it was like magic.
How to merge 2 List<T> and removing duplicate values from it in C#
Have you had a look at Enumerable.Union
This method excludes duplicates from the return set. This is different
behavior to the Concat
method, which returns all the elements
in the input sequences including
duplicates.
List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();
// ulist output : 1, 12, 5, 7, 9
What is SYSNAME data type in SQL Server?
FWIW, you can pass a table name to useful system SP's like this, should you wish to explore a database that way :
DECLARE @Table sysname; SET @Table = 'TableName';
EXEC sp_fkeys @Table;
EXEC sp_help @Table;
Filter by Dates in SQL
Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.
Passing an Object from an Activity to a Fragment
Get reference from the following example.
1. In fragment:
Create a reference variable for the class whose object you want in the fragment. Simply create a setter method for the reference variable and call the setter before replacing fragment from the activity.
MyEmployee myEmp;
public void setEmployee(MyEmployee myEmp)
{
this.myEmp = myEmp;
}
2. In activity:
//we need to pass object myEmp to fragment myFragment
MyEmployee myEmp = new MyEmployee();
MyFragment myFragment = new MyFragment();
myFragment.setEmployee(myEmp);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_layout, myFragment);
ft.commit();
Split string into strings by length?
The string splitting is required in many cases like where you have to sort the characters of the string given, replacing a character with an another character etc. But all these operations can be performed with the following mentioned string splitting methods.
The string splitting can be done in two ways:
Slicing the given string based on the length of split.
Converting the given string to a list with list(str) function, where characters of the string breakdown to form the the elements of a list. Then do the required operation and join them with 'specified character between the characters of the original string'.join(list) to get a new processed string.
How to store a datetime in MySQL with timezone info
None of the answers here quite hit the nail on the head.
How to store a datetime in MySQL with timezone info
Use two columns: DATETIME
, and a VARCHAR
to hold the time zone information, which may be in several forms:
A timezone or location such as America/New_York
is the highest data fidelity.
A timezone abbreviation such as PST
is the next highest fidelity.
A time offset such as -2:00
is the smallest amount of data in this regard.
Some key points:
- Avoid
TIMESTAMP
because it's limited to the year 2038, and MySQL relates it to the server timezone, which is probably undesired.
- A time offset should not be stored naively in an
INT
field, because there are half-hour and quarter-hour offsets.
If it's important for your use case to have MySQL compare or sort these dates chronologically, DATETIME
has a problem:
'2009-11-10 11:00:00 -0500'
is before '2009-11-10 10:00:00 -0700'
in terms of "instant in time", but they would sort the other way when inserted into a DATETIME
.
You can do your own conversion to UTC. In the above example, you would then have
'2009-11-10 16:00:00'
and '2009-11-10 17:00:00'
respectively, which would sort correctly. When retrieving the data, you would then use the timezone info to revert it to its original form.
One recommendation which I quite like is to have three columns:
local_time DATETIME
utc_time DATETIME
time_zone VARCHAR(X)
where X is appropriate for what kind of data you're storing there. (I would choose 64 characters for timezone/location.)
An advantage to the 3-column approach is that it's explicit: with a single DATETIME
column, you can't tell at a glance if it's been converted to UTC before insertion.
Regarding the descent of accuracy through timezone/abbreviation/offset:
- If you have the user's timezone/location such as
America/Juneau
, you can know accurately what the wall clock time is for them at any point in the past or future (barring changes to the way Daylight Savings is handled in that location). The start/end points of DST, and whether it's used at all, are dependent upon location, so this is the only reliable way.
- If you have a timezone abbreviation such as MST, (Mountain Standard Time) or a plain offset such as
-0700
, you will be unable to predict a wall clock time in the past or future. For example, in the United States, Colorado and Arizona both use MST, but Arizona doesn't observe DST. So if the user uploads his cat photo at 14:00 -0700
during the winter months, was he in Arizona or California? If you added six months exactly to that date, would it be 14:00
or 13:00
for the user?
These things are important to consider when your application has time, dates, or scheduling as core function.
References:
Rails 4 image-path, image-url and asset-url no longer work in SCSS files
In case anyone arrives looking for how to generate a relative path from the rails console
ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
Or the controller
include ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
Why is access to the path denied?
When a user tries to connect to your Web site, IIS assigns the connection to the IUSER_ComputerName account, where ComputerName is the name of the server on which IIS is running. By default, the IUSER_ComputerName account is a member of the Guests group. This group has security restrictions. Try to grand access to IUSER_ComputerName to that folder
Here is very good described answer about IIS security
Hope this helps
Re-assign host access permission to MySQL user
Similar issue where I was getting permissions failed. On my setup, I SSH in only. So What I did to correct the issue was
sudo MySQL
SELECT User, Host FROM mysql.user WHERE Host <> '%';
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User | Host |
+-------+-------------+
| root | 169.254.0.% |
| foo | 192.168.0.% |
| bar | 192.168.0.% |
+-------+-------------+
4 rows in set (0.00 sec)
I need these users moved to 'localhost'. So I issued the following:
UPDATE mysql.user SET host = 'localhost' WHERE user = 'foo';
UPDATE mysql.user SET host = 'localhost' WHERE user = 'bar';
Run SELECT User, Host FROM mysql.user WHERE Host <> '%'; again and we see:
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User | Host |
+-------+-------------+
| root | 169.254.0.% |
| foo | localhost |
| bar | localhost |
+-------+-------------+
4 rows in set (0.00 sec)
And then I was able to work normally again. Hope that helps someone.
$ mysql -u foo -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Run function in script from command line (Node JS)
Sometimes you want to run a function via CLI, sometimes you want to require
it from another module. Here's how to do both.
// file to run
const runMe = () => {}
if (require.main === module) {
runMe()
}
module.exports = runMe
iOS (iPhone, iPad, iPodTouch) view real-time console log terminal
Two options:
libimobiledevice is installable via homebrew and works great. Its idevicesyslog
tool works similarly to deviceconsole
(below), and it supports wirelessly viewing your device's syslog (!)
I've written more about that on Tumblr tl;dr:
brew install libimobiledevice
idevice_id --list // list available device UDIDs
idevicesyslog -u <device udid>
with the device connected via USB or available on the local wireless network.
(Keeping for the historical record, from 2013:) deviceconsole from rpetrich is a much less wacked-out solution than ideviceconsole above. My fork of it builds and runs in Xcode 5 out of the box, and the Build action will install the binary to /usr/local/bin
for ease of use.
As an additional helpful bit of info, I use it in the following style which makes it easy to find the device I want in my shell history and removes unnecessary >
lines that deviceconsole
prints out.
deviceconsole -d -u <device UDID> | uniq -u && echo "<device name>"
How to call a method with a separate thread in Java?
Sometime ago, I had written a simple utility class that uses JDK5 executor service and executes specific processes in the background. Since doWork() typically would have a void return value, you may want to use this utility class to execute it in the background.
See this article where I had documented this utility.
How to export plots from matplotlib with transparent background?
Use the matplotlib savefig
function with the keyword argument transparent=True
to save the image as a png file.
In [30]: x = np.linspace(0,6,31)
In [31]: y = np.exp(-0.5*x) * np.sin(x)
In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]
In [33]: savefig('demo.png', transparent=True)
Result:
Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display
command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.
Add a Progress Bar in WebView
I have added few lines in your code and now its working fine with progress bar.
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main );
// Makes Progress bar Visible
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
webview = (WebView) findViewById(R.id.webview);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
setTitle("Loading...");
setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
setTitle(R.string.app_name);
}
});
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");
Why can't decimal numbers be represented exactly in binary?
As we have been discussing, in floating point arithmetic, the decimal 0.1 cannot be perfectly represented in binary.
Floating point and integer representations provide grids or lattices for the numbers represented. As arithmetic is done, the results fall off the grid and have to be put back onto the grid by rounding. Example is 1/10 on a binary grid.
If we use binary coded decimal representation as one gentleman suggested, would we be able to keep numbers on the grid?
How to stop "setInterval"
You have to store the timer id of the interval when you start it, you will use this value later to stop it, using the clearInterval
function:
$(function () {
var timerId = 0;
$('textarea').focus(function () {
timerId = setInterval(function () {
// interval function body
}, 1000);
});
$('textarea').blur(function () {
clearInterval(timerId);
});
});
500 Internal Server Error for php file not for html
500 Internal Server Error is shown if your php code has fatal errors but error displaying is switched off. You may try this to see the error itself instead of 500 error page:
In your php file:
ini_set('display_errors', 1);
In .htaccess file:
php_flag display_errors 1
How to cache data in a MVC application
Here's an improvement to Hrvoje Hudo's answer. This implementation has a couple of key improvements:
- Cache keys are created automatically based on the function to update data and the object passed in that specifies dependencies
- Pass in time span for any cache duration
- Uses a lock for thread safety
Note that this has a dependency on Newtonsoft.Json to serialize the dependsOn object, but that can be easily swapped out for any other serialization method.
ICache.cs
public interface ICache
{
T GetOrSet<T>(Func<T> getItemCallback, object dependsOn, TimeSpan duration) where T : class;
}
InMemoryCache.cs
using System;
using System.Reflection;
using System.Runtime.Caching;
using Newtonsoft.Json;
public class InMemoryCache : ICache
{
private static readonly object CacheLockObject = new object();
public T GetOrSet<T>(Func<T> getItemCallback, object dependsOn, TimeSpan duration) where T : class
{
string cacheKey = GetCacheKey(getItemCallback, dependsOn);
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
{
lock (CacheLockObject)
{
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.Add(duration));
}
}
return item;
}
private string GetCacheKey<T>(Func<T> itemCallback, object dependsOn) where T: class
{
var serializedDependants = JsonConvert.SerializeObject(dependsOn);
var methodType = itemCallback.GetType();
return methodType.FullName + serializedDependants;
}
}
Usage:
var order = _cache.GetOrSet(
() => _session.Set<Order>().SingleOrDefault(o => o.Id == orderId)
, new { id = orderId }
, new TimeSpan(0, 10, 0)
);
MySQL vs MongoDB 1000 reads
On Single Server, MongoDb would not be any faster than mysql MyISAM on both read and write, given table/doc
sizes are small 1 GB to 20 GB.
MonoDB will be faster on Parallel Reduce on Multi-Node clusters, where Mysql can NOT scale horizontally.
Querying a linked sql server
If linked server name is IP address following code is true:
select * from [1.2.3.4,1433\MSSQLSERVER].test.dbo.Table1
It's just, note [] around IP address section.
How to set the height of an input (text) field in CSS?
You should use font-size for controlling the height, it is widely supported amongst browsers.
And in order to add spacing, you should use padding.
Forexample,
.inputField{
font-size: 30px;
padding-top: 10px;
padding-bottom: 10px;
}
How to get start and end of day in Javascript?
Using the luxon.js library, same can be achieved using startOf and endOf methods by passing the 'day' as parameter
var DateTime = luxon.DateTime;
DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z
DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
remove .toUTC() if you need only the local time
and you may ask why not moment.js, answer is here for that.
Environment variables in Mac OS X
If you want to change environment variables permanently on macOS, set them in /etc/paths
. Note, this file is read-only by default, so you'll have to chmod for write permissions.
How to completely uninstall python 2.7.13 on Ubuntu 16.04
This is what I have after doing purge of all the python versions and reinstalling only 3.6.
root@esp32:/# python
Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
root@esp32:/# python3
Python 3.8.0 (default, Dec 15 2019, 14:19:02)
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
Also the pip and pip3 commands are totally f up:
root@esp32:/# pip
Traceback (most recent call last):
File "/usr/local/bin/pip", line 7, in <module>
from pip._internal.cli.main import main
File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
sys.stderr.write(f"ERROR: {exc}")
^
SyntaxError: invalid syntax
root@esp32:/# pip3
Traceback (most recent call last):
File "/usr/local/bin/pip3", line 7, in <module>
from pip._internal.cli.main import main
File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
sys.stderr.write(f"ERROR: {exc}")
^
SyntaxError: invalid syntax
I am totally noob at Linux, I just wanted to update Python from 2.x to 3.x so that Platformio could upgrade and now I messed up everything it seems.
Cannot overwrite model once compiled Mongoose
Here is one more reason why this can happen. Perhaps this can help someone else. Notice the difference, Members vs Member. They must be the same...
export default mongoose.models.Members || mongoose.model('Member', FamilySchema)
Change to:
export default mongoose.models.Member || mongoose.model('Member', FamilySchema)
How should I edit an Entity Framework connection string?
No, you can't edit the connection string in the designer. The connection string is not part of the EDMX file it is just referenced value from the configuration file and probably because of that it is just readonly in the properties window.
Modifying configuration file is common task because you sometimes wants to make change without rebuilding the application. That is the reason why configuration files exist.
moment.js 24h format
_x000D_
_x000D_
//Format 24H use HH:mm_x000D_
let currentDate = moment().format('YYYY-MM-DD HH:mm')_x000D_
console.log(currentDate)_x000D_
_x000D_
//example of current time with defined Time zone +1_x000D_
let currentDateTm = moment().utcOffset('+0100').format('YYYY-MM-DD HH:mm')_x000D_
console.log(currentDateTm)
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_
How can I output leading zeros in Ruby?
Use the %
operator with a string:
irb(main):001:0> "%03d" % 5
=> "005"
The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:
irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"
Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C
function printf
, but similar formating functions are available in perl, ruby, python, java, php, etc.
How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
Jquery to get the id of selected value from dropdown
First set a custom attribute into your option for example nameid
(you can set non-standardized attribute of an HTML element, it's allowed):
'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'
then you can easily get attribute value using jquery .attr()
:
$('option:selected').attr("nameid")
For Example:
<select id="jobSel" class="longcombo" onchange="GetNameId">
<option nameid="32" value="1">test1</option>
<option nameid="67" value="1">test2</option>
<option nameid="45" value="1">test3</option>
</select>
Jquery:
function GetNameId(){
alert($('#jobSel option:selected').attr("nameid"));
}
How to create a label inside an <input> element?
The common approach is to use the default value as a label, and then remove it when the field gains the focus.
I really dislike this approach as it has accessibility and usability implications.
Instead, I would start by using a standard element next to the field.
Then, if JavaScript is active, set a class on an ancestor element which causes some new styles to apply that:
- Relatively position a div that contains the input and label
- Absolutely position the label
- Absolutely position the input on top of the label
- Remove the borders of the input and set its background-color to transparent
Then, and also whenever the input loses the focus, I test to see if the input has a value. If it does, ensure that an ancestor element has a class (e.g. "hide-label"), otherwise ensure that it does not have that class.
Whenever the input gains the focus, set that class.
The stylesheet would use that classname in a selector to hide the label (using text-indent: -9999px; usually).
This approach provides a decent experience for all users, including those with JS disabled and those using screen readers.
What does character set and collation mean exactly?
A character encoding is a way to encode characters so that they fit in memory. That is, if the charset is ISO-8859-15, the euro symbol, €, will be encoded as 0xa4, and in UTF-8, it will be 0xe282ac.
The collation is how to compare characters, in latin9, there are letters as e é è ê f
, if sorted by their binary representation, it will go e f é ê è
but if the collation is set to, for example, French, you'll have them in the order you thought they would be, which is all of e é è ê
are equal, and then f
.
how to automatically scroll down a html page?
You can use two different techniques to achieve this.
The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;
).
The second is setting the link to point to a specific id in the page e.g.
<a href="mypage.html#sectionOne">section one</a>
Then if in your target page you'll have that ID the page will be scrolled automatically.
Check Whether a User Exists
I suggest to use id command as it tests valid user existence wrt passwd file entry which is not necessary means the same:
if [ `id -u $USER_TO_CHECK 2>/dev/null || echo -1` -ge 0 ]; then
echo FOUND
fi
Note: 0 is root uid.
How to use custom packages
First, be sure to read and understand the "How to write Go code" document.
The actual answer depends on the nature of your "custom package".
If it's intended to be of general use, consider employing the so-called "Github code layout". Basically, you make your library a separate go get
-table project.
If your library is for internal use, you could go like this:
- Place the directory with library files under the directory of your project.
- In the rest of your project, refer to the library using its path relative to the root of your workspace containing the project.
To demonstrate:
src/
myproject/
mylib/
mylib.go
...
main.go
Now, in the top-level main.go
, you could import "myproject/mylib"
and it would work OK.
How can I list (ls) the 5 last modified files in a directory?
The accepted answer lists only the filenames, but to get the top 5 files one can also use:
ls -lht | head -6
where:
-l
outputs in a list format
-h
makes output human readable (i.e. file sizes appear in kb, mb, etc.)
-t
sorts output by placing most recently modified file first
head -6
will show 5 files because ls
prints the block size in the first line of output.
I think this is a slightly more elegant and possibly more useful approach.
Example output:
total 26960312
-rw-r--r--@ 1 user staff 1.2K 11 Jan 11:22 phone2.7.py
-rw-r--r--@ 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf
-rw-r--r--@ 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf
-rw-r--r--@ 1 user staff 502K 8 Jan 10:20 lab-01.pdf
-rw-rw-rw-@ 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv
How to get the current working directory using python 3?
Using pathlib you can get the folder in which the current file is located. __file__
is the pathname of the file from which the module was loaded.
Ref: docs
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
Doc ref: link
Using an array as needles in strpos
I'm writing a new answer which hopefully helps anyone looking for similar to what I am.
This works in the case of "I have multiple needles and I'm trying to use them to find a singled-out string". and this is the question I came across to find that.
$i = 0;
$found = array();
while ($i < count($needle)) {
$x = 0;
while ($x < count($haystack)) {
if (strpos($haystack[$x], $needle[$i]) !== false) {
array_push($found, $haystack[$x]);
}
$x++;
}
$i++;
}
$found = array_count_values($found);
The array $found
will contain a list of all the matching needles, the item of the array with the highest count value will be the string(s) you're looking for, you can get this with:
print_r(array_search(max($found), $found));