Reading string from input with space character?
While the above mentioned methods do work, but each one has it's own kind of problems.
You can use getline()
or getdelim()
, if you are using posix supported platform.
If you are using windows and minigw as your compiler, then it should be available.
getline()
is defined as :
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
In order to take input, first you need to create a pointer to char type.
#include <stdio.h>
#include<stdlib.h>
// s is a pointer to char type.
char *s;
// size is of size_t type, this number varies based on your guess of
// how long the input is, even if the number is small, it isn't going
// to be a problem
size_t size = 10;
int main(){
// allocate s with the necessary memory needed, +1 is added
// as its input also contains, /n character at the end.
s = (char *)malloc(size+1);
getline(&s,&size,stdin);
printf("%s",s);
return 0;
}
Sample Input:Hello world to the world!
Output:Hello world to the world!\n
One thing to notice here is, even though allocated memory for s is 11 bytes,
where as input size is 26 bytes, getline reallocates s
using realloc()
.
So it doesn't matter how long your input is.
size
is updated with no.of bytes read, as per above sample input size
will be 27
.
getline()
also considers \n
as input.So your 's' will hold '\n' at the end.
There is also more generic version of getline()
, which is getdelim()
, which takes one more extra argument, that is delimiter
.
getdelim()
is defined as:
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
Linux man page
Reading a string with scanf
An array "decays" into a pointer to its first element, so scanf("%s", string)
is equivalent to scanf("%s", &string[0])
. On the other hand, scanf("%s", &string)
passes a pointer-to-char[256]
, but it points to the same place.
Then scanf
, when processing the tail of its argument list, will try to pull out a char *
. That's the Right Thing when you've passed in string
or &string[0]
, but when you've passed in &string
you're depending on something that the language standard doesn't guarantee, namely that the pointers &string
and &string[0]
-- pointers to objects of different types and sizes that start at the same place -- are represented the same way.
I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)
How do you allow spaces to be entered using scanf?
/*reading string which contains spaces*/
#include<stdio.h>
int main()
{
char *c,*p;
scanf("%[^\n]s",c);
p=c; /*since after reading then pointer points to another
location iam using a second pointer to store the base
address*/
printf("%s",p);
return 0;
}
How to prevent scanf causing a buffer overflow in C?
Most of the time a combination of fgets
and sscanf
does the job. The other thing would be to write your own parser, if the input is well formatted. Also note your second example needs a bit of modification to be used safely:
#define LENGTH 42
#define str(x) # x
#define xstr(x) str(x)
/* ... */
int nc = scanf("%"xstr(LENGTH)"[^\n]%*[^\n]", array);
The above discards the input stream upto but not including the newline (\n
) character. You will need to add a getchar()
to consume this. Also do check if you reached the end-of-stream:
if (!feof(stdin)) { ...
and that's about it.
Reading numbers from a text file into an array in C
There are two problems in your code:
- the return value of
scanf
must be checked
- the
%d
conversion does not take overflows into account (blindly applying *10 + newdigit
for each consecutive numeric character)
The first value you got (-104204697
) is equals to 5623125698541159
modulo 2^32
; it is thus the result of an overflow (if int
where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.
The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf
, the number of items successfully matched):
#include <stdio.h>
int main(int argc, char *argv[]) {
int i, j;
short unsigned digitArray[16];
i = 0;
while (
i != sizeof(digitArray) / sizeof(digitArray[0])
&& 1 == scanf("%1hu", digitArray + i)
) {
i++;
}
for (j = 0; j != i; j++) {
printf("%hu\n", digitArray[j]);
}
return 0;
}
Reading in double values with scanf in c
Use this line of code when scanning the second value:
scanf(" %lf", &b);
also replace all %ld with %lf.
It's a problem related with input stream buffer. You can also use fflush(stdin); after the first scanning to clear the input buffer and then the second scanf will work as expected. An alternate way is place a getch(); or getchar(); function after the first scanf line.
printf not printing on console
As others have pointed out, output can be buffered within your program before a console or shell has a chance to see it.
On unix-like systems, including macs, stdout
has line-based buffering by default. This means that your program empties its stdout
buffer as soon as it sees a newline.
However, on windows, newlines are no longer special, and full buffering is used. Windows doesn't support line buffering at all; see the msdn page on setvbuf.
So on windows, a good approach is to completely shut off stdout
buffering like so:
setvbuf (stdout, NULL, _IONBF, 0);
How can I read an input string of unknown length?
Safer and faster (doubling capacity) version:
char *readline(char *prompt) {
size_t size = 80;
char *str = malloc(sizeof(char) * size);
int c;
size_t len = 0;
printf("%s", prompt);
while (EOF != (c = getchar()) && c != '\r' && c != '\n') {
str[len++] = c;
if(len == size) str = realloc(str, sizeof(char) * (size *= 2));
}
str[len++]='\0';
return realloc(str, sizeof(char) * len);
}
Read int values from a text file in C
A simple solution using fscanf
:
void read_ints (const char* file_name)
{
FILE* file = fopen (file_name, "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
}
How to read string from keyboard using C?
You need to have the pointer to point somewhere to use it.
Try this code:
char word[64];
scanf("%s", word);
This creates a character array of lenth 64 and reads input to it. Note that if the input is longer than 64 bytes the word array overflows and your program becomes unreliable.
As Jens pointed out, it would be better to not use scanf for reading strings. This would be safe solution.
char word[64]
fgets(word, 63, stdin);
word[63] = 0;
Reading a string with spaces with sscanf
Since you want the trailing string from the input, you can use %n
(number of characters consumed thus far) to get the position at which the trailing string starts. This avoids memory copies and buffer sizing issues, but comes at the cost that you may need to do them explicitly if you wanted a copy.
const char *input = "19 cool kid";
int age;
int nameStart = 0;
sscanf(input, "%d %n", &age, &nameStart);
printf("%s is %d years old\n", input + nameStart, age);
outputs:
cool kid is 19 years old
How do you read scanf until EOF in C?
Your code loops until it reads a single word, then exits. So if you give it multiple words it will read the first and exit, while if you give it an empty input, it will loop forever. In any case, it will only print random garbage from uninitialized memory. This is apparently not what you want, but what do you want? If you just want to read and print the first word (if it exists), use if:
if (scanf("%15s", word) == 1)
printf("%s\n", word);
If you want to loop as long as you can read a word, use while:
while (scanf("%15s", word) == 1)
printf("%s\n", word);
Also, as others have noted, you need to give the word array a size that is big enough for your scanf:
char word[16];
Others have suggested testing for EOF instead of checking how many items scanf matched. That's fine for this case, where scanf can't fail to match unless there's an EOF, but is not so good in other cases (such as trying to read integers), where scanf might match nothing without reaching EOF (if the input isn't a number) and return 0.
edit
Looks like you changed your question to match my code which works fine when I run it -- loops reading words until EOF is reached and then exits. So something else is going on with your code, perhaps related to how you are feeding it input as suggested by David
sscanf in Python
If the separators are ':', you can split on ':', and then use x.strip() on the strings to get rid of any leading or trailing whitespace. int() will ignore the spaces.
What is the difference between sscanf or atoi to convert a string to an integer?
When there is no concern about invalid string input or range issues, use the simplest: atoi()
Otherwise, the method with best error/range detection is neither atoi()
, nor sscanf()
.
This good answer all ready details the lack of error checking with atoi()
and some error checking with sscanf()
.
strtol()
is the most stringent function in converting a string to int
. Yet it is only a start. Below are detailed examples to show proper usage and so the reason for this answer after the accepted one.
// Over-simplified use
int strtoi(const char *nptr) {
int i = (int) strtol(nptr, (char **)NULL, 10);
return i;
}
This is the like atoi()
and neglects to use the error detection features of strtol()
.
To fully use strtol()
, there are various features to consider:
Detection of no conversion: Examples: "xyz"
, or ""
or "--0"
? In these cases, endptr
will match nptr
.
char *endptr;
int i = (int)strtol(nptr, &endptr, 10);
if (nptr == endptr) return FAIL_NO_CONVERT;
Should the whole string convert or just the leading portion: Is "123xyz"
OK?
char *endptr;
int i = (int)strtol(nptr, &endptr, 10);
if (*endptr != '\0') return FAIL_EXTRA_JUNK;
Detect if value was so big, the the result is not representable as a long
like "999999999999999999999999999999"
.
errno = 0;
long L = strtol(nptr, &endptr, 10);
if (errno == ERANGE) return FAIL_OVERFLOW;
Detect if the value was outside the range of than int
, but not long
. If int
and long
have the same range, this test is not needed.
long L = strtol(nptr, &endptr, 10);
if (L < INT_MIN || L > INT_MAX) return FAIL_INT_OVERFLOW;
Some implementations go beyond the C standard and set errno
for additional reasons such as errno to EINVAL in case no conversion was performed or EINVAL
The value of the Base parameter is not valid.. The best time to test for these errno
values is implementation dependent.
Putting this all together: (Adjust to your needs)
#include <errno.h>
#include <stdlib.h>
int strtoi(const char *nptr, int *error_code) {
char *endptr;
errno = 0;
long i = strtol(nptr, &endptr, 10);
#if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
if (errno == ERANGE || i > INT_MAX || i < INT_MIN) {
errno = ERANGE;
i = i > 0 : INT_MAX : INT_MIN;
*error_code = FAIL_INT_OVERFLOW;
}
#else
if (errno == ERANGE) {
*error_code = FAIL_OVERFLOW;
}
#endif
else if (endptr == nptr) {
*error_code = FAIL_NO_CONVERT;
} else if (*endptr != '\0') {
*error_code = FAIL_EXTRA_JUNK;
} else if (errno) {
*error_code = FAIL_IMPLEMENTATION_REASON;
}
return (int) i;
}
Note: All functions mentioned allow leading spaces, an optional leading sign character and are affected by locale change. Additional code is required for a more restrictive conversion.
Note: Non-OP title change skewed emphasis. This answer applies better to original title "convert string to integer sscanf or atoi"
How to read numbers separated by space using scanf
int main()
{
char string[200];
int g,a,i,G[20],A[20],met;
gets(string);
g=convert_input(G,string);
for(i=0;i<=g;i++)
printf("\n%d>>%d",i,G[i]);
return 0;
}
int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
temp=0;
while(string[i]!=' ' && string[i]!='\0')
temp=temp*10 + (string[i++]-'0') ;
if(string[i]==' ')
i++;
K[j++]=temp;
}
return j-1;
}
What is the format specifier for unsigned short int?
From the Linux manual page:
h A following integer conversion corresponds to a short int or unsigned short int argument, or a fol-
lowing n conversion corresponds to a pointer to a short int argument.
So to print an unsigned short integer, the format string should be "%hu"
.
How to scanf only integer?
- You take
scanf()
.
- You throw it in the bin.
- You use
fgets()
to get an entire line.
- You use
strtol()
to parse the line as an integer, checking if it consumed the entire line.
char *end;
char buf[LINE_MAX];
do {
if (!fgets(buf, sizeof buf, stdin))
break;
// remove \n
buf[strlen(buf) - 1] = 0;
int n = strtol(buf, &end, 10);
} while (end != buf + strlen(buf));
Reading file using fscanf() in C
scanf()
and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:
#include <stdio.h>
#include <errno.h>
#include <stdbool.h>
int main(void)
{
char item[9], status;
FILE *fp;
if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
printf("No such file\n");
exit(1);
}
while (true) {
int ret = fscanf(fp, "%s %c", item, &status);
if(ret == 2)
printf("\n%s \t %c", item, status);
else if(errno != 0) {
perror("scanf:");
break;
} else if(ret == EOF) {
break;
} else {
printf("No match.\n");
}
}
printf("\n");
if(feof(fp)) {
puts("EOF");
}
return 0;
}
How to read from input until newline is found using scanf()?
//increase char array size if u want take more no. of characters.
#include <stdio.h>
int main()
{
char s[10],s1[10];
scanf("\n");//imp for below statement to work
scanf("%[^\n]%c",s);//to take input till the you click enter
scanf("%s",s1);//to take input till a space
printf("%s",s);
printf("%s",s1);
return 0;
}
How to do scanf for single char in C
Here is a similiar thing that I would like to share,
while you're working on Visual Studio you could get an error like:
'scanf': function or variable may be unsafe. Consider using scanf_s
instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS
To prevent this, you should write it in the following format
A single character may be read as follows:
char c;
scanf_s("%c", &c, 1);
When multiple characters for non-null terminated strings are read, integers are used as the width specification and the buffer size.
char c[4];
scanf_s("%4c", &c, _countof(c));
Get Excel sheet name and use as variable in macro
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
How can I generate an MD5 hash?
I do not know if this is relevant for anyone reading this, but I just had the problem that I wanted to
- download a file from a given URL and
- compare its MD5 to a known value.
I wanted to do it with JRE classes only (no Apache Commons or similar). A quick web search did not show me sample code snippets doing both at the same time, only each task separately. Because this requires to read the same file twice, I figured it might be worth the while to write some code which unifies both tasks, calculating the checksum on the fly while downloading the file. This is my result (sorry if it is not perfect Java, but I guess you get the idea anyway):
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.DigestOutputStream; // new
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
void downloadFile(String fromURL, String toFile, BigInteger md5)
throws IOException, NoSuchAlgorithmException
{
ReadableByteChannel in = Channels.newChannel(new URL(fromURL).openStream());
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
WritableByteChannel out = Channels.newChannel(
//new FileOutputStream(toFile)); // old
new DigestOutputStream(new FileOutputStream(toFile), md5Digest)); // new
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); // 1 MB
while (in.read(buffer) != -1) {
buffer.flip();
//md5Digest.update(buffer.asReadOnlyBuffer()); // old
out.write(buffer);
buffer.clear();
}
BigInteger md5Actual = new BigInteger(1, md5Digest.digest());
if (! md5Actual.equals(md5))
throw new RuntimeException(
"MD5 mismatch for file " + toFile +
": expected " + md5.toString(16) +
", got " + md5Actual.toString(16)
);
}
making a paragraph in html contain a text from a file
You'll want to use either JavaScript or a server-side language like PHP, ASP...etc
(supposedly can be done with HTML <embed>
tag, which makes sense, but I haven't used, since PHP...etc is so simple/common)
Javascript can work: Here's a link to someone doing something similar via javascript on stackoverflow: How do I load the contents of a text file into a javascript variable?
PHP (as example of server-side language) is the easiest way to go though:
<div><p><?php include('myFile.txt'); ?></p></div>
To use this (if you're unfamiliar with PHP), you can:
1) check if you have php on your server
2) change the file extension of your .html file to .php
3) paste the code from my PHP example somewhere in the body of your newly-renamed PHP file
selenium get current url after loading a page
Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:
WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
foo(driver,startURL);
/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
String previousURL = driver.getCurrentUrl();
driver.findElement(By.xpath("//*[@id='someID']")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
ExpectedCondition e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return (d.getCurrentUrl() != previousURL);
}
};
wait.until(e);
currentURL = driver.getCurrentUrl();
System.out.println(currentURL);
}
OWIN Security - How to Implement OAuth2 Refresh Tokens
Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:
private string ComputeHash(Guid input)
{
byte[] source = input.ToByteArray();
var encoder = new SHA256Managed();
byte[] encoded = encoder.ComputeHash(source);
return Convert.ToBase64String(encoded);
}
In CreateAsync
:
var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());
ReceiveAsync
:
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
Guid token;
if (Guid.TryParse(context.Token, out token))
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
{
context.SetTicket(ticket);
}
}
}
Use of "this" keyword in formal parameters for static methods in C#
This is an extension method. See here for an explanation.
Extension methods allow developers to add new methods to the public
contract of an existing CLR type, without having to sub-class it or
recompile the original type. Extension Methods help blend the
flexibility of "duck typing" support popular within dynamic languages
today with the performance and compile-time validation of
strongly-typed languages.
Extension Methods enable a variety of useful scenarios, and help make
possible the really powerful LINQ query framework... .
it means that you can call
MyClass myClass = new MyClass();
int i = myClass.Foo();
rather than
MyClass myClass = new MyClass();
int i = Foo(myClass);
This allows the construction of fluent interfaces as stated below.
Set LIMIT with doctrine 2?
$query_ids = $this->getEntityManager()
->createQuery(
"SELECT e_.id
FROM MuzichCoreBundle:Element e_
WHERE [...]
GROUP BY e_.id")
->setMaxResults(5)
->setMaxResults($limit)
;
HERE in the second query the result of the first query should be passed ..
$query_select = "SELECT e
FROM MuzichCoreBundle:Element e
WHERE e.id IN (".$query_ids->getResult().")
ORDER BY e.created DESC, e.name DESC"
;
$query = $this->getEntityManager()
->createQuery($query_select)
->setParameters($params)
->setMaxResults($limit);
;
$resultCollection = $query->getResult();
JavaScript dictionary with names
I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement:
var myMappings = {
"Name": 0.1,
"Phone": 0.1,
"Address": 0.5,
"Zip": 0.1,
"Comments": 0.2
};
for (var col in myMappings) {
alert((myMappings[col] * 100) + "%");
}
How to upgrade Angular CLI to the latest version
If you have any difficulties managing your global CLI version it is better to use NVM: MAC, Windows.
To update the local CLI in your Angular project follow this steps:
Starting from CLI v6 you can just run ng update
in order to get your dependencies updated automatically to a new version.
ng update @angular/cli
With ng update
sometimes you might want to add --force
flag.
You can also pass --all
flag to upgrade all packages at the same time.
ng update --all --force
If you want just to migrate CLI just run this:
ng update @angular/cli --migrateOnly
You can also pass flag --from=from
- version from which to migrate from, e.g --from=1.7.4
. This flag is only available with a single package being updated, and only on migration only.
After update is done make sure that the version of typescript you got
installed supported by your current angular version,
otherwise you might need to downgrade the typescript version. Also bear in mind that usually the latest version of angular won't support the latest version of the typescript.
Checkout Angular CLI / Angular / NodeJS / Typescript
compatibility versions here
Also checkout this guide Updating your Angular projects and update.angular.io
OLD ANSWER:
All you need to do is to diff with angular-cli-diff and apply the changes in your current project.
Here is the steps:
- Say you go from 1.4. to 1.5 then you do https://github.com/cexbrayat/angular-cli-diff/compare/1.4.0...1.5.0
- click on
File changed
tab
- Apply the changes to your current project.
npm install
/ yarn
- Test all
npm scripts
(more details here: https://stackoverflow.com/a/45431592/415078)
Spring RestTemplate GET with parameters
If you pass non-parametrized params for RestTemplate, you'll have one Metrics for everyone single different URL that you pass, considering the parameters. You would like to use parametrized urls:
http://my-url/action?param1={param1}¶m2={param2}
instead of
http://my-url/action?param1=XXXX¶m2=YYYY
The second case is what you get by using UriComponentsBuilder class.
One way to implement the first behavior is the following:
Map<String, Object> params = new HashMap<>();
params.put("param1", "XXXX");
params.put("param2", "YYYY");
String url = "http://my-url/action?%s";
String parametrizedArgs = params.keySet().stream().map(k ->
String.format("%s={%s}", k, k)
).collect(Collectors.joining("&"));
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> entity = new HttpEntity<>(headers);
restTemplate.exchange(String.format(url, parametrizedArgs), HttpMethod.GET, entity, String.class, params);
How are echo and print different in PHP?
As the PHP.net manual suggests, take a read of this discussion.
One major difference is that echo
can take multiple parameters to output. E.g.:
echo 'foo', 'bar'; // Concatenates the 2 strings
print('foo', 'bar'); // Fatal error
If you're looking to evaluate the outcome of an output statement (as below) use print
. If not, use echo
.
$res = print('test');
var_dump($res); //bool(true)
Asynchronous method call in Python?
The native Python way for asynchronous calls in 2021 with Python 3.9 suitable also for Jupyter / Ipython Kernel
Camabeh's answer is the way to go since Python 3.3.
async def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
This will work in Jupyter Notebook / Jupyter Lab but throw an error:
RuntimeError: This event loop is already running
Due to Ipython's usage of event loops we need something called nested asynchronous loops which is not yet implemented in Python. Luckily there is nest_asyncio to deal with the issue. All you need to do is:
!pip install nest_asyncio # use ! within Jupyter Notebook, else pip install in shell
import nest_asyncio
nest_asyncio.apply()
(Based on this thread)
Only when you call loop.close()
it throws another error as it probably refers to Ipython's main loop.
RuntimeError: Cannot close a running event loop
I'll update this answer as soon as someone answered to this github issue.
What do "branch", "tag" and "trunk" mean in Subversion repositories?
First of all, as @AndrewFinnell and @KenLiu point out, in SVN the directory names themselves mean nothing -- "trunk, branches and tags" are simply a common convention that is used by most repositories. Not all projects use all of the directories (it's reasonably common not to use "tags" at all), and in fact, nothing is stopping you from calling them anything you'd like, though breaking convention is often confusing.
I'll describe probably the most common usage scenario of branches and tags, and give an example scenario of how they are used.
Trunk: The main development area. This is where your next major release of the code lives, and generally has all the newest features.
Branches: Every time you release a major version, it gets a branch created. This allows you to do bug fixes and make a new release without having to release the newest - possibly unfinished or untested - features.
Tags: Every time you release a version (final release, release candidates (RC), and betas) you make a tag for it. This gives you a point-in-time copy of the code as it was at that state, allowing you to go back and reproduce any bugs if necessary in a past version, or re-release a past version exactly as it was. Branches and tags in SVN are lightweight - on the server, it does not make a full copy of the files, just a marker saying "these files were copied at this revision" that only takes up a few bytes. With this in mind, you should never be concerned about creating a tag for any released code. As I said earlier, tags are often omitted and instead, a changelog or other document clarifies the revision number when a release is made.
For example, let's say you start a new project. You start working in "trunk", on what will eventually be released as version 1.0.
- trunk/ - development version, soon to be 1.0
- branches/ - empty
Once 1.0.0 is finished, you branch trunk into a new "1.0" branch, and create a "1.0.0" tag. Now work on what will eventually be 1.1 continues in trunk.
- trunk/ - development version, soon to be 1.1
- branches/1.0 - 1.0.0 release version
- tags/1.0.0 - 1.0.0 release version
You come across some bugs in the code, and fix them in trunk, and then merge the fixes over to the 1.0 branch. You can also do the opposite, and fix the bugs in the 1.0 branch and then merge them back to trunk, but commonly projects stick with merging one-way only to lessen the chance of missing something. Sometimes a bug can only be fixed in 1.0 because it is obsolete in 1.1. It doesn't really matter: you only want to make sure that you don't release 1.1 with the same bugs that have been fixed in 1.0.
- trunk/ - development version, soon to be 1.1
- branches/1.0 - upcoming 1.0.1 release
- tags/1.0.0 - 1.0.0 release version
Once you find enough bugs (or maybe one critical bug), you decide to do a 1.0.1 release. So you make a tag "1.0.1" from the 1.0 branch, and release the code. At this point, trunk will contain what will be 1.1, and the "1.0" branch contains 1.0.1 code. The next time you release an update to 1.0, it would be 1.0.2.
- trunk/ - development version, soon to be 1.1
- branches/1.0 - upcoming 1.0.2 release
- tags/1.0.0 - 1.0.0 release version
- tags/1.0.1 - 1.0.1 release version
Eventually you are almost ready to release 1.1, but you want to do a beta first. In this case, you likely do a "1.1" branch, and a "1.1beta1" tag. Now, work on what will be 1.2 (or 2.0 maybe) continues in trunk, but work on 1.1 continues in the "1.1" branch.
- trunk/ - development version, soon to be 1.2
- branches/1.0 - upcoming 1.0.2 release
- branches/1.1 - upcoming 1.1.0 release
- tags/1.0.0 - 1.0.0 release version
- tags/1.0.1 - 1.0.1 release version
- tags/1.1beta1 - 1.1 beta 1 release version
Once you release 1.1 final, you do a "1.1" tag from the "1.1" branch.
You can also continue to maintain 1.0 if you'd like, porting bug fixes between all three branches (1.0, 1.1, and trunk). The important takeaway is that for every main version of the software you are maintaining, you have a branch that contains the latest version of code for that version.
Another use of branches is for features. This is where you branch trunk (or one of your release branches) and work on a new feature in isolation. Once the feature is completed, you merge it back in and remove the branch.
- trunk/ - development version, soon to be 1.2
- branches/1.1 - upcoming 1.1.0 release
- branches/ui-rewrite - experimental feature branch
The idea of this is when you're working on something disruptive (that would hold up or interfere with other people from doing their work), something experimental (that may not even make it in), or possibly just something that takes a long time (and you're afraid if it holding up a 1.2 release when you're ready to branch 1.2 from trunk), you can do it in isolation in branch. Generally you keep it up to date with trunk by merging changes into it all the time, which makes it easier to re-integrate (merge back to trunk) when you're finished.
Also note, the versioning scheme I used here is just one of many. Some teams would do bug fix/maintenance releases as 1.1, 1.2, etc., and major changes as 1.x, 2.x, etc. The usage here is the same, but you may name the branch "1" or "1.x" instead of "1.0" or "1.0.x". (Aside, semantic versioning is a good guide on how to do version numbers).
Extracting text from HTML file using Python
Beautiful soup does convert html entities. It's probably your best bet considering HTML is often buggy and filled with unicode and html encoding issues. This is the code I use to convert html to raw text:
import BeautifulSoup
def getsoup(data, to_unicode=False):
data = data.replace(" ", " ")
# Fixes for bad markup I've seen in the wild. Remove if not applicable.
masssage_bad_comments = [
(re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1)),
(re.compile('<!WWWAnswer T[=\w\d\s]*>'), lambda match: '<!--' + match.group(0) + '-->'),
]
myNewMassage = copy.copy(BeautifulSoup.BeautifulSoup.MARKUP_MASSAGE)
myNewMassage.extend(masssage_bad_comments)
return BeautifulSoup.BeautifulSoup(data, markupMassage=myNewMassage,
convertEntities=BeautifulSoup.BeautifulSoup.ALL_ENTITIES
if to_unicode else None)
remove_html = lambda c: getsoup(c, to_unicode=True).getText(separator=u' ') if c else ""
JavaScript: Create and destroy class instance through class method
1- There is no way to actually destroy an object in javascript, but using delete
, we could remove a reference from an object:
var obj = {};
obj.mypointer = null;
delete obj.mypointer;
2- The important point about the delete
keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete
keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.
3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}]
overriding the value of the array like array = []
would remove the references to the two objects inside the array and those two objects would be marked as collectible.
4- for your solution the easiest way is just this:
var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;
As mentioned above, either setting storage.instance = null
or delete storage.instance
would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null
then the storage object still has a property called instance (with the value null). If you delete storage.instance
then the storage object no longer has a property named instance.
and WHAT ABOUT destroy method ??
the paradoxical point here is if you use instance.destroy
in the destroy function you have no access to the actual instance
pointer, and it won't let you delete it.
The only way is to pass the reference to the destroy function and then delete it:
// Class constructor
var Class = function () {
this.destroy = function (baseObject, refName) {
delete baseObject[refName];
};
};
// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined
BUT if I were you I would simply stick to the first solution and delete the object like this:
storage.instance = null;
// OR
delete storage.instance;
WOW it was too much :)
Remove category & tag base from WordPress url - without a plugin
Whilst you dismiss it as a solution, the plugin is by far the easiest and most consistent method and they don't change any WordPress default files.
http://wordpress.org/plugins/wp-no-category-base/
It hasn't needed to be updated for a year, so it is not exactly creating any problems with updates.
There is no simple hand rolled solution that will do all of this that does not just replicate what the plugin does from within your own functions.php
- Better and logical permalinks like myblog.com/my-category/ and myblog.com/my-category/my-post/.
- Simple plugin - barely adds any overhead.
- Works out of the box - no setup needed. No need to modify
WordPress files.
- Doesn't require other plugins to work.
- Compatible with sitemap plugins.
- Works with multiple sub-categories.
- Works with WordPress Multisite.
- Redirects old category permalinks to the new ones (301 redirect, good for SEO).
Plus you get the benefit that if WordPress does change, then the plugin will be updated to work whilst you would then have to figure out how to fix your own code on your own.
Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'
I had same issue but problem went off after going back and fixing DbContext
incorrect syntax issue such as it should have been ExampleDbContextClass: DbContext
whereas I had missed DbContext
part in Context Class where you define your DbSet
. Also, I verified following dependencies are needed in order to achieve connection to SqlServer.
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
Also verify that Version you install is less than your project's current version to be on safe side. Such as if your project is using 3.1 do not try to use newer one which would be for example 3.1.9. I had issue with that too.
How can I select rows by range?
Assuming id
is the primary key of table :
SELECT * FROM table WHERE id BETWEEN 10 AND 50
For first 20 results
SELECT * FROM table order by id limit 20;
Cannot use Server.MapPath
Firt add a reference to System.web
, if you don't have. Do that in the References folder.
You can then use Hosting.HostingEnvironment.MapPath(path);
Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now
For people who have this problem today(to example to switch from 2.8.0 to 2.10.0), move to file gradle-wrapper.properties and set distributionUrl with the value you need.
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
I changed 2.8.0 to 2.10.0 and dont forget to Sync after
Pandas: Convert Timestamp to datetime.date
You can convert a datetime.date object into a pandas Timestamp like this:
#!/usr/bin/env python3
# coding: utf-8
import pandas as pd
import datetime
# create a datetime data object
d_time = datetime.date(2010, 11, 12)
# create a pandas Timestamp object
t_stamp = pd.to_datetime('2010/11/12')
# cast `datetime_timestamp` as Timestamp object and compare
d_time2t_stamp = pd.to_datetime(d_time)
# print to double check
print(d_time)
print(t_stamp)
print(d_time2t_stamp)
# since the conversion succeds this prints `True`
print(d_time2t_stamp == t_stamp)
How do I install Maven with Yum?
I've just learned of a handy packaging tool called fpm recently. Stumbling upon this question I thought I might give it a try. Turns out, after reading @OrwellHindenberg's answer, it's easy to package maven into an RPM with fpm.
yum install -y gcc make rpm-build ruby-devel rubygems
gem install fpm
create a project directory and layout the directory structure of the package
mkdir maven-build
cd maven-build
mkdir -p etc/profile.d opt
create a file that we'll install to /etc/profile.d/maven.sh
, we'll store this under the newly created etc/profile.d directory as maven.sh, with the following contents
export M3_HOME=/opt/apache-maven-3.1.0
export M3=$M3_HOME/bin
export PATH=$M3:$PATH
download and unpack the latest maven in the opt directory
wget http://www.eng.lsu.edu/mirrors/apache/maven/maven-3/3.1.0/binaries/apache-maven-3.1.0-bin.tar.gz
tar -xzf apache-maven-3.1.0-bin.tar.gz -C opt
finally, build the RPM
fpm -n maven-3.1.0 -s dir -t rpm etc opt
Now you can install maven through rpm
$ rpm -Uvh maven-3.1.0-1.0-1.x86_64.rpm
Preparing... ########################################### [100%]
1:maven-3.1.0 ########################################### [100%]
and viola
$ which mvn
/opt/apache-maven-3.1.0/bin/mvn
not quite yum but closer to home ;)
MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?
Alright so after trying every solution out there to solve this exact issues on a wordpress blog, I might have done something either really stupid or genius... With no idea why there's an increase in Mysql connections, I used the php script below in my header to kill all sleeping processes..
So every visitor to my site helps in killing the sleeping processes..
<?php
$result = mysql_query("SHOW processlist");
while ($myrow = mysql_fetch_assoc($result)) {
if ($myrow['Command'] == "Sleep") {
mysql_query("KILL {$myrow['Id']}");}
}
?>
Print array without brackets and commas
Basically, don't use ArrayList.toString()
- build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray
when it's not actually an array, by the way.)
Double free or corruption after queue::push
Let's talk about copying objects in C++.
Test t;
, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.
Trouble comes when you push t
into your queue using q.push(t)
. If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.
When we take a look at std::queue::push
method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test
object to make a new Test
.
Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray
is just a memory address; when the value of myArray
is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.
How do I fix it?
The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:
Test(const Test& other){
myArray = new int[10];
memcpy( myArray, other.myArray, 10 );
}
Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.
We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:
Test& operator= (const Test& other){
if (this != &other) {
memcpy( myArray, other.myArray, 10 );
}
return *this;
}
The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.
C Program to find day of week given date
This is my implementation. It's very short and includes error checking. If you want dates before 01-01-1900, you could easily change the anchor to the starting date of the Gregorian calendar.
#include <stdio.h>
int main(int argv, char** arv) {
int month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char* day[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int d, m, y, i;
printf("Fill in a date after 01-01-1900 as dd-mm-yyyy: ");
scanf("%d-%d-%d", &d, &m, &y);
// correction for leap year
if (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0))
month[1] = 29;
if (y < 1900 || m < 1 || m > 12 || d < 1 || d > month[m - 1]) {
printf("This is an invalid date.\n");
return 1;
}
for (i = 1900; i < y; i++)
if (i % 4 == 0 && (i % 100 != 0 || i % 400 == 0))
d += 366;
else
d += 365;
for (i = 0; i < m - 1; i++)
d += month[i];
printf("This is a %s.\n", day[d % 7]);
return 0;
}
Enable CORS in Web API 2
To enable CORS,
1.Go to App_Start folder.
2.add the namespace 'using System.Web.Http.Cors';
3.Open the WebApiConfig.cs file and type the following in a static method.
_x000D_
_x000D_
config.EnableCors(new EnableCorsAttribute("https://localhost:44328",headers:"*", methods:"*"));
_x000D_
_x000D_
_x000D_
getting integer values from textfield
As You're getting values from textfield as jTextField3.getText();
.
As it is a textField
it will return you string format as its format says:
String getText()
Returns the text contained in this TextComponent.
So, convert your String
to Integer
as:
int jml = Integer.parseInt(jTextField3.getText());
instead of directly setting
int jml = jTextField3.getText();
Select all columns except one in MySQL?
It is good practice to specify the columns that you are querying even if you query all the columns.
So I would suggest you write the name of each column in the statement (excluding the one you don't want).
SELECT
col1
, col2
, col3
, col..
, col53
FROM table
How to Inspect Element using Safari Browser
In your Safari menu bar click Safari > Preferences & then select the Advanced tab.
Select: "Show Develop menu in menu bar"
Now you can click Develop in your menu bar and choose Show Web Inspector
You can also right-click and press "Inspect element".
How to view table contents in Mysql Workbench GUI?
You have to open database connection, not workbench file with schema. It looks a bit wierd, but it makes sense when you realize what you are editing.
So, go to home tab, double click database connection (create it if you don't have it yet) and have fun.
Change Bootstrap tooltip color
This is already been answered right but i think i should give my opinion too.
Like cozen says this is a border, and for it to work you must specify the classes to format this in the same way that bootstrap specifies it. So, you can do this
.tooltip .tooltip-inner {background-color: #00a8c4; color: black;}
.tooltip.top .tooltip-arrow {border-top-color: #00a8c4;}
or you can do the next one, just for the tooltip-arrow but you must add the !important, so that it overwrites the bootstrap css
.tooltip-arrow {border-top-color: #00a8c4!important;}
Django DoesNotExist
I have found the solution to this issue using ObjectDoesNotExist on this way
from django.core.exceptions import ObjectDoesNotExist
......
try:
# try something
except ObjectDoesNotExist:
# do something
After this, my code works as I need
Thanks any way, your post help me to solve my issue
Convert String to equivalent Enum value
Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration
class), you can use the valueOf
method of java.lang.Enum
subclass:
MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");
Vertical rulers in Visual Studio Code
With Visual Studio Code 1.27.2:
When I go to File > Preference > Settings, I get the following tab
I type rulers in Search settings and I get the following list of settings
Clicking on the first Edit in settings.json, I can edit the user settings
Clicking on the pen icon that appears to the left of the setting in Default user settings I can copy it on the user settings and edit it
With Visual Studio Code 1.38.1, the screenshot shown on the third point changes to the following one.
The panel for selecting the default user setting values isn't shown anymore.
Regular expression for decimal number
In .NET, I recommend to dynamically build the regular expression with the decimal separator of the current cultural context:
using System.Globalization;
...
NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
Regex re = new Regex("^(?\\d+("
+ Regex.Escape(nfi.CurrencyDecimalSeparator)
+ "\\d{1,2}))$");
You might want to pimp the regexp by allowing 1000er separators the same way as the decimal separator.
Java: how to convert HashMap<String, Object> to array
If you have HashMap<String, SomeObject> hashMap
then:
hashMap.values().toArray();
Will return an Object[]
. If instead you want an array of the type SomeObject
, you could use:
hashMap.values().toArray(new SomeObject[0]);
Python functions call by reference
Technically python do not pass arguments by value: all by reference. But ... since python has two types of objects: immutable and mutable, here is what happens:
Immutable arguments are effectively passed by value: string, integer, tuple are all immutable object types. While they are technically "passed by reference" (like all parameters), since you can't change them in-place inside the function it looks/behaves as if it is passed by value.
Mutable arguments are effectively passed by reference: lists or dictionaries are passed by its pointers. Any in-place change inside the function like (append or del) will affect the original object.
This is how Python is designed: no copies and all are passed by reference. You can explicitly pass a copy.
def sort(array):
# do sort
return array
data = [1, 2, 3]
sort(data[:]) # here you passed a copy
Last point I would like to mention which is a function has its own scope.
def do_any_stuff_to_these_objects(a, b):
a = a * 2
del b['last_name']
number = 1 # immutable
hashmap = {'first_name' : 'john', 'last_name': 'legend'} # mutable
do_any_stuff_to_these_objects(number, hashmap)
print(number) # 1 , oh it should be 2 ! no a is changed inisde the function scope
print(hashmap) # {'first_name': 'john'}
Access-Control-Allow-Origin error sending a jQuery Post to Google API's
If you have this error trying to consume a service that you can't add the header Access-Control-Allow-Origin *
in that application, but you can put in front of the server a reverse proxy, the error can avoided with a header rewrite.
Assuming the application is running on the port 8080 (public domain at www.mydomain.com), and you put the reverse proxy in the same host at port 80, this is the configuration for Nginx reverse proxy:
server {
listen 80;
server_name www.mydomain.com;
access_log /var/log/nginx/www.mydomain.com.access.log;
error_log /var/log/nginx/www.mydomain.com.error.log;
location / {
proxy_pass http://127.0.0.1:8080;
add_header Access-Control-Allow-Origin *;
}
}
Force page scroll position to top at page refresh in HTML
To reset window scroll back to top, $(window).scrollTop(0)
in the beforeunload event does the tricks, however, I tested in Chrome 80 it will go back to the old location after the reload.
To prevent that, set the history.scrollRestoration
to "manual"
.
//Reset scroll top
history.scrollRestoration = "manual";
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});
Access non-numeric Object properties by index?
The only way I can think of doing this is by creating a method that gives you the property using Object.keys();
.
var obj = {
dog: "woof",
cat: "meow",
key: function(n) {
return this[Object.keys(this)[n]];
}
};
obj.key(1); // "meow"
Demo: http://jsfiddle.net/UmkVn/
It would be possible to extend this to all objects using Object.prototype;
but that isn't usually recommended.
Instead, use a function helper:
var object = {
key: function(n) {
return this[ Object.keys(this)[n] ];
}
};
function key(obj, idx) {
return object.key.call(obj, idx);
}
key({ a: 6 }, 0); // 6
Creating SVG elements dynamically with javascript inside HTML
Add this to html:
<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>
Try this function and adapt for you program:
var svgNS = "http://www.w3.org/2000/svg";
function createCircle()
{
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);
myCircle.setAttributeNS(null,"cy",100);
myCircle.setAttributeNS(null,"r",50);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","none");
document.getElementById("mySVG").appendChild(myCircle);
}
Javascript Print iframe contents only
I was stuck trying to implement this in typescript, all of the above would not work. I had to first cast the element in order for typescript to have access to the contentWindow.
let iframe = document.getElementById('frameId') as HTMLIFrameElement;
iframe.contentWindow.print();
Eclipse shows errors but I can't find them
I had a red X on a folder, but not on any of the files inside it. The only thing that fixed it was clicking and dragging some of the files from the problem folder into another folder, and then performing Maven -> Update Project
. I could then drag the files back without the red X returning.
GUI-based or Web-based JSON editor that works like property explorer
Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.
Based on JSON Schema
Commercial (No endorsement intended or implied, may or may not meet requirement)
jQuery
YAML
See Also
How to change legend title in ggplot
I didn't dig in much into this but because you used fill=cond in ggplot(),
+ labs(color='NEW LEGEND TITLE')
might not have worked. However it you replace color by fill, it works!
+ labs(fill='NEW LEGEND TITLE')
This worked for me in ggplot2_2.1.0
Replace console output in Python
Below code will count Message from 0 to 137 each 0.3 second replacing previous number.
Number of symbol to backstage = number of digits.
stream = sys.stdout
for i in range(137):
stream.write('\b' * (len(str(i)) + 10))
stream.write("Message : " + str(i))
stream.flush()
time.sleep(0.3)
Scala list concatenation, ::: vs ++
:::
works only with lists, while ++
can be used with any traversable. In the current implementation (2.9.0), ++
falls back on :::
if the argument is also a List
.
RegEx for matching UK Postcodes
I've been looking for a UK postcode regex for the last day or so and stumbled on this thread. I worked my way through most of the suggestions above and none of them worked for me so I came up with my own regex which, as far as I know, captures all valid UK postcodes as of Jan '13 (according to the latest literature from the Royal Mail).
The regex and some simple postcode checking PHP code is posted below. NOTE:- It allows for lower or uppercase postcodes and the GIR 0AA anomaly but to deal with the, more than likely, presence of a space in the middle of an entered postcode it also makes use of a simple str_replace to remove the space before testing against the regex. Any discrepancies beyond that and the Royal Mail themselves don't even mention them in their literature (see http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf and start reading from page 17)!
Note: In the Royal Mail's own literature (link above) there is a slight ambiguity surrounding the 3rd and 4th positions and the exceptions in place if these characters are letters. I contacted Royal Mail directly to clear it up and in their own words "A letter in the 4th position of the Outward Code with the format AANA NAA has no exceptions and the 3rd position exceptions apply only to the last letter of the Outward Code with the format ANA NAA." Straight from the horse's mouth!
<?php
$postcoderegex = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
$postcode2check = str_replace(' ','',$postcode2check);
if (preg_match($postcoderegex, $postcode2check)) {
echo "$postcode2check is a valid postcode<br>";
} else {
echo "$postcode2check is not a valid postcode<br>";
}
?>
I hope it helps anyone else who comes across this thread looking for a solution.
Play multiple CSS animations at the same time
You can indeed run multiple animations simultaneously, but your example has two problems. First, the syntax you use only specifies one animation. The second style rule hides the first. You can specify two animations using syntax like this:
-webkit-animation-name: spin, scale
-webkit-animation-duration: 2s, 4s
as in this fiddle (where I replaced "scale" with "fade" due to the other problem explained below... Bear with me.): http://jsfiddle.net/rwaldin/fwk5bqt6/
Second, both of your animations alter the same CSS property (transform) of the same DOM element. I don't believe you can do that. You can specify two animations on different elements, the image and a container element perhaps. Just apply one of the animations to the container, as in this fiddle: http://jsfiddle.net/rwaldin/fwk5bqt6/2/
Compare two columns using pandas
I think the closest to the OP's intuition is an inline if statement:
df['que'] = (df['one'] if ((df['one'] >= df['two']) and (df['one'] <= df['three']))
What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?
Format with Currency format string
=Format(Fields!Price.Value, "C")
It will give you 2 decimal places with "$" prefixed.
You can find other format strings on MSDN: Adding Style and Formatting to a ReportViewer Report
Note: The MSDN article has been archived to the "VS2005_General" document, which is no longer directly accessible online. Here is the excerpt of the formatting strings referenced:
Formatting Numbers
The following table lists common .NET Framework number formatting
strings.
Format string, Name
C or c Currency
D or d Decimal
E or e Scientific
F or f Fixed-point
G or g General
N or n Number
P or p Percentage
R or r Round-trip
X or x Hexadecimal
You can modify many of the format strings to include a precision
specifier that defines the number of digits to the right of the
decimal point. For example, a formatting string of D0 formats the
number so that it has no digits after the decimal point. You
can also use custom formatting strings, for example, #,###.
Formatting Dates
The following table lists common .NET Framework date formatting
strings.
Format string, Name
d Short date
D Long date
t Short time
T Long time
f Full date/time (short time)
F Full date/time (long time)
g General date/time (short time)
G General date/time (long time)
M or m Month day
R or r RFC1123 pattern
Y or y Year month
You can also a use custom formatting strings; for example, dd/MM/yy.
For more information about .NET Framework
formatting strings, see Formatting Types.
Django DB Settings 'Improperly Configured' Error
In my case, I got this when trying to run Django tests through PyCharm. I think it is because PyCharm does not load the initial Django project settings, i.e. those that manage.py shell
runs initially. One can add them to the start of the testing script or just run the tests using manage.py test
.
Versions:
- Python 3.5 (in virtualenv)
- PyCharm 2016.3.2 Professional
- Django 1.10
Using async/await for multiple tasks
I just want to add to all great answers above,
that if you write a library it's a good practice to use ConfigureAwait(false)
and get better performance, as said here.
So this snippet seems to be better:
public static async Task DoWork()
{
int[] ids = new[] { 1, 2, 3, 4, 5 };
await Task.WhenAll(ids.Select(i => DoSomething(1, i))).ConfigureAwait(false);
}
A full fiddle link here.
Hidden Features of Xcode
My favorites have to be these general editor shortcuts:
- ? + 0 returns you back to your editor from debug mode.
- ? + Shift + R takes you from debug mode to editor view (project mode)
- ? + Shift + E "maximizes" the editor (This is very useful when you have build results, etc. displayed above your editor and you just want to make your source editor taller)
- Ctrl + 2 displays an outline of your current code
- ? + Return runs the application
- ? + Shift + Return ends the application
Select multiple columns in data.table by their numeric indices
It's a bit verbose, but i've gotten used to using the hidden .SD
variable.
b<-data.table(a=1,b=2,c=3,d=4)
b[,.SD,.SDcols=c(1:2)]
It's a bit of a hassle, but you don't lose out on other data.table features (I don't think), so you should still be able to use other important functions like join tables etc.
Removing index column in pandas when reading a csv
When reading to and from your CSV file include the argument index=False
so for example:
df.to_csv(filename, index=False)
and to read from the csv
df.read_csv(filename, index=False)
This should prevent the issue so you don't need to fix it later.
How to reset a timer in C#?
All the timers have the equivalent of Start() and Stop() methods, except System.Threading.Timer.
So an extension method such as...
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
...is one way to go about it.
Comparing two branches in Git?
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
How to use underscore.js as a template engine?
I wanted to share one more important finding.
use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.
We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance
curl.h no such file or directory
sudo apt-get install curl-devel
sudo apt-get install libcurl-dev
(will install the default alternative)
OR
sudo apt-get install libcurl4-openssl-dev
(the OpenSSL variant)
OR
sudo apt-get install libcurl4-gnutls-dev
(the gnutls variant)
Is it possible to create a File object from InputStream
If you do not want to use other library, here is a simple function to convert InputStream
to OutputStream
.
public static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Now you can easily write an Inputstream
into file by using FileOutputStream
-
FileOutputStream out = new FileOutputStream(outFile);
copyStream (inputStream, out);
out.close();
What to do on TransactionTooLargeException
I found the root cause of this (we got both "adding window failed" and file descriptor leak as mvds says).
There is a bug in BitmapFactory.decodeFileDescriptor()
of Android 4.4.
It only occurs when inPurgeable
and inInputShareable
of BitmapOptions
are set to true
. This causes many problem in many places interact with files.
Note that the method is also called from MediaStore.Images.Thumbnails.getThumbnail()
.
Universal Image Loader is affected by this issue. Picasso and Glide seems to be not affected.
https://github.com/nostra13/Android-Universal-Image-Loader/issues/1020
Why is Spring's ApplicationContext.getBean considered bad?
The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.
Think of the container as something is invisible to your code, magically providing for its needs, without being asked.
Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.
How much data can a List can hold at the maximum?
It depends on the List
implementation. Since you index arrays with int
s, an ArrayList
can't hold more than Integer.MAX_VALUE
elements. A LinkedList
isn't limited in the same way, though, and can contain any amount of elements.
How to check if ping responded or not in a batch file
The following checklink.cmd
program is a good place to start. It relies on the fact that you can do a single-shot ping and that, if successful, the output will contain the line:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
By extracting tokens 5 and 7 and checking they're respectively "Received"
and "1,"
, you can detect the success.
@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=down
for /f "tokens=5,6,7" %%a in ('ping -n 1 !ipaddr!') do (
if "x%%b"=="xunreachable." goto :endloop
if "x%%a"=="xReceived" if "x%%c"=="x1," set state=up
)
:endloop
echo.Link is !state!
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal
Call it with the name (or IP address) you want to test:
checklink 127.0.0.1
checklink localhost
checklink nosuchaddress
Take into account that, if your locale is not English, you must replace Received
with the corresponding keyword in your locale, for example recibidos
for Spanish. Do a test ping to discover what keyword is used in your locale.
To only notify you when the state changes, you can use:
@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=down
for /f "tokens=5,7" %%a in ('ping -n 1 !ipaddr!') do (
if "x%%a"=="xReceived" if "x%%b"=="x1," set state=up
)
if not !state!==!oldstate! (
echo.Link is !state!
set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal
However, as Gabe points out in a comment, you can just use ERRORLEVEL
so the equivalent of that second script above becomes:
@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
if not !state!==!oldstate! (
echo.Link is !state!
set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal
How do you move a file?
If I'm not wrong starting from version 1.5 SVN can track moved files\folders. In TortoiseSVN use can move file via drag&drop.
Border around specific rows in a table?
The only other way I can think of to do it is to enclose each of the rows you need a border around in a nested table. That will make the border easier to do but will potentially creat other layout issues, you'll have to manually set the width on table cells etc.
Your approach may well be the best one depending on your other layout rerquirements and the suggested approach here is just a possible alternative.
<table cellspacing="0">
<tr>
<td>no border</td>
<td>no border here either</td>
</tr>
<tr>
<td>
<table style="border: thin solid black">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>four</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">once again no borders</td>
</tr>
<tr>
<td>
<table style="border: thin solid black">
<tr>
<td>hello</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">world</td>
</tr>
</table>
Oracle date to string conversion
If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):
SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1
The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.
Recursive sub folder search and return files in a list python
If you don't mind installing an additional light library, you can do this:
pip install plazy
Usage:
import plazy
txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)
The result should look something like this:
['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']
It works on both Python 2.7 and Python 3.
Github: https://github.com/kyzas/plazy#list-files
Disclaimer: I'm an author of plazy
.
Reading Properties file in Java
Based on your exception, the InputStream
is null, this means the class loader is not finding your properties file. I'm guessing that myProp.properties is in the root of your project, if that's the case, you need a preceding slash:
InputStream stream = loader.getResourceAsStream("/myProp.properties");
Android Studio 3.0 Flavor Dimension Issue
If you have simple flavors (free/pro, demo/full etc.) then add to build.gradle file:
android {
...
flavorDimensions "version"
productFlavors {
free{
dimension "version"
...
}
pro{
dimension "version"
...
}
}
By dimensions you can create "flavors in flavors". Read more.
Fast way to concatenate strings in nodeJS/JavaScript
The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.
Tested with the following code:
function a(){
var s = "hello";
var p = "world";
s = s + p;
return s;
}
function b(){
var s = new Buffer("hello");
var p = new Buffer("world");
s = Buffer.concat([s,p]);
return s;
}
var times = 100000;
var t1 = new Date();
for( var i = 0; i < times; i++){
a();
}
var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
b();
}
var t3 = new Date();
console.log("Buffer took: " + (t3-t2) + " ms.");
Output:
Normal took: 4 ms.
Buffer took: 458 ms.
Can't find how to use HttpContent
For JSON Post:
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);
Non-JSON:
var stringContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("field1", "value1"),
new KeyValuePair<string, string>("field2", "value2"),
});
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);
https://blog.pedrofelix.org/2012/01/16/the-new-system-net-http-classes-message-content/
Creating your own header file in C
#ifndef MY_HEADER_H
# define MY_HEADER_H
//put your function headers here
#endif
MY_HEADER_H
serves as a double-inclusion guard.
For the function declaration, you only need to define the signature, that is, without parameter names, like this:
int foo(char*);
If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.
This declares the function foo
which accepts a char*
and returns an int
.
In your source file, you would have:
#include "my_header.h"
int foo(char* name) {
//do stuff
return 0;
}
docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC
It's clearly a proxy issue: docker proxies https connections to the wrong place. Bear in mind that docker proxy settings may be different from the operating system (and curl) ones. Here's how I managed to solve the issue:
First of all, find out where are you proxying your docker https requests:
# docker info | grep Proxy
Http Proxy: http://<my.proxy.server>:8080
Https Proxy: https://<my.proxy.server>:8080
No Proxy: localhost,127.0.0.1
and double check your https settings.
In my case, I realized that the "Https proxy" was set to https://...
instead of http://...
, so I corrected it in /etc/sysconfig/docker
file (I'm using RHEL7) and, after a docker restart with:
# systemctl restart docker
the proxy variable shows up succesfully updated:
# docker info | grep Proxy
Http Proxy: http://<my.proxy.server>:8080
Https Proxy: http://<my.proxy.server>:8080
No Proxy: localhost,127.0.0.1
and everything works fine :-)
Can Mysql Split a column?
It seems to work:
substring_index ( substring_index ( context,',',1 ), ',', -1)
substring_index ( substring_index ( context,',',2 ), ',', -1)
substring_index ( substring_index ( context,',',3 ), ',', -1)
substring_index ( substring_index ( context,',',4 ), ',', -1)
it means 1st value, 2nd, 3rd, etc.
Explanation:
The inner substring_index
returns the first n values that are comma separated. So if your original string is "34,7,23,89", substring_index( context,',', 3)
returns "34,7,23".
The outer substring_index
takes the value returned by the inner substring_index
and the -1
allows you to take the last value. So you get "23" from the "34,7,23".
Instead of -1
if you specify -2
, you'll get "7,23", because it took the last two values.
Example:
select * from MyTable where substring_index(substring_index(prices,',',1),',',-1)=3382;
Here, prices
is the name of a column in MyTable
.
Spring default behavior for lazy-init
When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".
If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".
Does "display:none" prevent an image from loading?
Yes it will render faster, slightly, only because it doesn't have to render the image and is one less element to sort on the screen.
If you don't want it loaded, leave a DIV empty where you can load html into it later containing an <img>
tag.
Try using firebug or wireshark as I've mentioned before and you'll see that the files DO get transferred even if display:none
is present.
Opera is the only browser which will not load the image if the display is set to none. Opera has now moved to webkit and will render all images even if their display is set to none.
Here is a testing page that will prove it:
http://www.quirksmode.org/css/displayimg.html
How to completely remove a dialog on close
I use this function in all my js projects
You call it:
hideAndResetModals("#IdModalDialog")
You define if:
function hideAndResetModals(modalID)
{
$(modalID).modal('hide');
clearValidation(modalID); //You implement it if you need it. If not, you can remote this line
$(modalID).on('hidden.bs.modal', function ()
{
$(modalID).find('form').trigger('reset');
});
}
Adding text to ImageView in Android
You can also use a TextView and set the background image to what you wanted in the ImageView
. Furthermore if you were using the ImageView
as a button you can set it to click-able
Here is some basic code for a TextView
that shows an image with text on top of it.
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/your_image"
android:text="your text here" />
Android Camera : data intent returns null
When we capture the image from Camera in Android then Uri
or data.getdata()
becomes null. We have two solutions to resolve this issue.
- Retrieve the Uri path from the Bitmap Image
- Retrieve the Uri path from cursor.
This is how to retrieve the Uri from the Bitmap Image. First capture image through Intent that will be the same for both methods:
// Capture Image
captureImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, reqcode);
}
}
});
Now implement OnActivityResult
, which will be the same for both methods:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==reqcode && resultCode==RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// Show Uri path based on Image
Toast.makeText(LiveImage.this,"Here "+ tempUri, Toast.LENGTH_LONG).show();
// Show Uri path based on Cursor Content Resolver
Toast.makeText(this, "Real path for URI : "+getRealPathFromURI(tempUri), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Failed To Capture Image", Toast.LENGTH_SHORT).show();
}
}
Now create all above methods to create the Uri from Image and Cursor methods:
Uri path from Bitmap Image:
private Uri getImageUri(Context applicationContext, Bitmap photo) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(LiveImage.this.getContentResolver(), photo, "Title", null);
return Uri.parse(path);
}
Uri from Real path of saved image:
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]
I was having the same problem using my class SharedModule.
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [MyService]
}
}
}
Then I changed it putting directly in the app.modules this way
@NgModule({declarations: [
AppComponent,
NaviComponent],imports: [BrowserModule,RouterModule.forRoot(ROUTES),providers: [MoviesService],bootstrap: [MyService] })
Obs: I'm using "@angular/core": "^6.0.2".
I hope its help you.
ConfigurationManager.AppSettings - How to modify and save?
Perhaps you should look at adding a Settings File. (e.g. App.Settings)
Creating this file will allow you to do the following:
string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";
This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!
The result is a Application or User contextual setting.
Have a look in the "add new item" menu for the setting file.
Is it possible to create a temporary table in a View and drop it after select?
No, a view consists of a single SELECT
statement. You cannot create or drop tables in a view.
Maybe a common table expression (CTE) can solve your problem. CTEs are temporary result sets that are defined within the execution scope of a single statement and they can be used in views.
Example (taken from here) - you can think of the SalesBySalesPerson
CTE as a temporary table:
CREATE VIEW vSalesStaffQuickStats
AS
WITH SalesBySalesPerson (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS
(
SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT E.EmployeeID,
EmployeeOrders = OS.NumberOfOrders,
EmployeeLastOrderDate = OS.MostRecentOrderDate,
E.ManagerID,
ManagerOrders = OM.NumberOfOrders,
ManagerLastOrderDate = OM.MostRecentOrderDate
FROM HumanResources.Employee AS E
INNER JOIN SalesBySalesPerson AS OS ON E.EmployeeID = OS.SalesPersonID
LEFT JOIN SalesBySalesPerson AS OM ON E.ManagerID = OM.SalesPersonID
GO
Performance considerations
Which are more performant, CTE or temporary tables?
Fastest way to remove first char in a String
The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo".
The first option needs a bit more work to understand than the third - I would view the Substring
option as the most common and readable.
(Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data
itself.)
I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring
to probably be the fastest here, simply because Substring
always ends up creating a string from a single chunk of the original input, whereas Remove
has to at least potentially glue together a start chunk and an end chunk.
TCPDF Save file to folder?
If you still get
TCPDF ERROR: Unable to create output file: myfile.pdf
you can avoid TCPDF's file saving logic by putting PDF data to a variable and saving this string to a file:
$pdf_string = $pdf->Output('pseudo.pdf', 'S');
file_put_contents('./mydir/myfile.pdf', $pdf_string);
In AVD emulator how to see sdcard folder? and Install apk to AVD?
- switch to DDMS perspective
- select the emulator in devices list, whose sdcard you want to explore.
- open File Explorer tab on right hand side.
- expand tree structure. mnt/sdcard/
refer to image below
To install apk manually:
copy your apk to to sdk/platform-tools folder and run following command in the same folder
adb install apklocation.apk
Fastest way to serialize and deserialize .NET objects
Having an interest in this, I decided to test the suggested methods with the closest "apples to apples" test I could. I wrote a Console app, with the following code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace SerializationTests
{
class Program
{
static void Main(string[] args)
{
var count = 100000;
var rnd = new Random(DateTime.UtcNow.GetHashCode());
Console.WriteLine("Generating {0} arrays of data...", count);
var arrays = new List<int[]>();
for (int i = 0; i < count; i++)
{
var elements = rnd.Next(1, 100);
var array = new int[elements];
for (int j = 0; j < elements; j++)
{
array[j] = rnd.Next();
}
arrays.Add(array);
}
Console.WriteLine("Test data generated.");
var stopWatch = new Stopwatch();
Console.WriteLine("Testing BinarySerializer...");
var binarySerializer = new BinarySerializer();
var binarySerialized = new List<byte[]>();
var binaryDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
foreach (var array in arrays)
{
binarySerialized.Add(binarySerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("BinaryFormatter: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in binarySerialized)
{
binaryDeserialized.Add(binarySerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("BinaryFormatter: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Testing ProtoBuf serializer...");
var protobufSerializer = new ProtoBufSerializer();
var protobufSerialized = new List<byte[]>();
var protobufDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
foreach (var array in arrays)
{
protobufSerialized.Add(protobufSerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("ProtoBuf: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in protobufSerialized)
{
protobufDeserialized.Add(protobufSerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("ProtoBuf: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Testing NetSerializer serializer...");
var netSerializerSerializer = new ProtoBufSerializer();
var netSerializerSerialized = new List<byte[]>();
var netSerializerDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
foreach (var array in arrays)
{
netSerializerSerialized.Add(netSerializerSerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("NetSerializer: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in netSerializerSerialized)
{
netSerializerDeserialized.Add(netSerializerSerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("NetSerializer: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine("Press any key to end.");
Console.ReadKey();
}
public class BinarySerializer
{
private static readonly BinaryFormatter Formatter = new BinaryFormatter();
public byte[] Serialize(object toSerialize)
{
using (var stream = new MemoryStream())
{
Formatter.Serialize(stream, toSerialize);
return stream.ToArray();
}
}
public T Deserialize<T>(byte[] serialized)
{
using (var stream = new MemoryStream(serialized))
{
var result = (T)Formatter.Deserialize(stream);
return result;
}
}
}
public class ProtoBufSerializer
{
public byte[] Serialize(object toSerialize)
{
using (var stream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(stream, toSerialize);
return stream.ToArray();
}
}
public T Deserialize<T>(byte[] serialized)
{
using (var stream = new MemoryStream(serialized))
{
var result = ProtoBuf.Serializer.Deserialize<T>(stream);
return result;
}
}
}
public class NetSerializer
{
private static readonly NetSerializer Serializer = new NetSerializer();
public byte[] Serialize(object toSerialize)
{
return Serializer.Serialize(toSerialize);
}
public T Deserialize<T>(byte[] serialized)
{
return Serializer.Deserialize<T>(serialized);
}
}
}
}
The results surprised me; they were consistent when run multiple times:
Generating 100000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 336.8392ms.
BinaryFormatter: Deserializing took 208.7527ms.
Testing ProtoBuf serializer...
ProtoBuf: Serializing took 2284.3827ms.
ProtoBuf: Deserializing took 2201.8072ms.
Testing NetSerializer serializer...
NetSerializer: Serializing took 2139.5424ms.
NetSerializer: Deserializing took 2113.7296ms.
Press any key to end.
Collecting these results, I decided to see if ProtoBuf or NetSerializer performed better with larger objects. I changed the collection count to 10,000 objects, but increased the size of the arrays to 1-10,000 instead of 1-100. The results seemed even more definitive:
Generating 10000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 285.8356ms.
BinaryFormatter: Deserializing took 206.0906ms.
Testing ProtoBuf serializer...
ProtoBuf: Serializing took 10693.3848ms.
ProtoBuf: Deserializing took 5988.5993ms.
Testing NetSerializer serializer...
NetSerializer: Serializing took 9017.5785ms.
NetSerializer: Deserializing took 5978.7203ms.
Press any key to end.
My conclusion, therefore, is: there may be cases where ProtoBuf and NetSerializer are well-suited to, but in terms of raw performance for at least relatively simple objects... BinaryFormatter is significantly more performant, by at least an order of magnitude.
YMMV.
select count(*) from table of mysql in php
$howmanyuser_query=$conn->query('SELECT COUNT(uno) FROM userentry;');
$howmanyuser=$howmanyuser_query->fetch_array(MYSQLI_NUM);
echo $howmanyuser[0];
after the so many hours excellent :)
Laravel 5 Eloquent where and or in Clauses
Also, if you have a variable,
CabRes::where('m_Id', 46)
->where('t_Id', 2)
->where(function($q) use ($variable){
$q->where('Cab', 2)
->orWhere('Cab', $variable);
})
->get();
VBA Excel 2-Dimensional Arrays
Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.
This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.
A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.
A VBA 'Array to Range' function
Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)
' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.
' This subroutine saves repetitive coding for a common VBA and Excel task.
' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.
On Error Resume Next
'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code
Dim rngOutput As Excel.Range
Dim iRowCount As Long
Dim iColCount As Long
Dim iRow As Long
Dim iCol As Long
Dim arrTemp As Variant
Dim iDimensions As Integer
Dim iRowOffset As Long
Dim iColOffset As Long
Dim iStart As Long
Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
rngTarget.ClearContents
End If
Application.EnableEvents = True
If IsEmpty(InputArray) Then
Exit Sub
End If
If TypeName(InputArray) = "Range" Then
InputArray = InputArray.Value
End If
' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
rngTarget.Cells(1, 1).Value2 = InputArray
Exit Sub
End If
iDimensions = ArrayDimensions(InputArray)
If iDimensions < 1 Then
rngTarget.Value = CStr(InputArray)
ElseIf iDimensions = 1 Then
iRowCount = UBound(InputArray) - LBound(InputArray)
iStart = LBound(InputArray)
iColCount = 1
If iRowCount > (655354 - rngTarget.Row) Then
iRowCount = 655354 + iStart - rngTarget.Row
ReDim Preserve InputArray(iStart To iRowCount)
End If
iRowCount = UBound(InputArray) - LBound(InputArray)
iColCount = 1
' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
arrTemp(iRow, 1) = InputArray(iRow)
Next
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
rngOutput.Value2 = arrTemp
Set rngTarget = rngOutput
End With
Erase arrTemp
ElseIf iDimensions = 2 Then
iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)
iStart = LBound(InputArray, 1)
If iRowCount > (65534 - rngTarget.Row) Then
iRowCount = 65534 - rngTarget.Row
InputArray = ArrayTranspose(InputArray)
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
InputArray = ArrayTranspose(InputArray)
End If
iStart = LBound(InputArray, 2)
If iColCount > (254 - rngTarget.Column) Then
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
End If
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))
Err.Clear
Application.EnableEvents = False
rngOutput.Value2 = InputArray
Application.EnableEvents = True
If Err.Number <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Formula = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
If Left(InputArray(iRow, iCol), 1) = "=" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "+" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "*" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Value2 = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsObject(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
ElseIf IsArray(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
ElseIf IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
If Len(InputArray(iRow, iCol)) > 255 Then
' Block-write operations fail on strings exceeding 255 chars. You *have*
' to go back and check, and write this masterpiece one cell at a time...
InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Text = InputArray
End If 'err<>0
If Err <> 0 Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
iRowOffset = LBound(InputArray, 1) - 1
iColOffset = LBound(InputArray, 2) - 1
For iRow = 1 To iRowCount
If iRow Mod 100 = 0 Then
Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
End If
For iCol = 1 To iColCount
rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
Next iCol
Next iRow
Application.StatusBar = False
Application.ScreenUpdating = True
End If 'err<>0
Set rngTarget = rngOutput ' resizes the range This is useful, *most* of the time
End With
End If
End Sub
You will need the source for ArrayDimensions:
This API declaration is required in the module header:
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Any, _
Source As Any, _
ByVal Length As Long)
...And here's the function itself:
Private Function ArrayDimensions(arr As Variant) As Integer
'-----------------------------------------------------------------
' will return:
' -1 if not an array
' 0 if an un-dimmed array
' 1 or more indicating the number of dimensions of a dimmed array
'-----------------------------------------------------------------
' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
' Code written by Chris Rae, 25/5/00
' Originally published by R. B. Smissaert.
' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax
Dim ptr As Long
Dim vType As Integer
Const VT_BYREF = &H4000&
'get the real VarType of the argument
'this is similar to VarType(), but returns also the VT_BYREF bit
CopyMemory vType, arr, 2
'exit if not an array
If (vType And vbArray) = 0 Then
ArrayDimensions = -1
Exit Function
End If
'get the address of the SAFEARRAY descriptor
'this is stored in the second half of the
'Variant parameter that has received the array
CopyMemory ptr, ByVal VarPtr(arr) + 8, 4
'see whether the routine was passed a Variant
'that contains an array, rather than directly an array
'in the former case ptr already points to the SA structure.
'Thanks to Monte Hansen for this fix
If (vType And VT_BYREF) Then
' ptr is a pointer to a pointer
CopyMemory ptr, ByVal ptr, 4
End If
'get the address of the SAFEARRAY structure
'this is stored in the descriptor
'get the first word of the SAFEARRAY structure
'which holds the number of dimensions
'...but first check that saAddr is non-zero, otherwise
'this routine bombs when the array is uninitialized
If ptr Then
CopyMemory ArrayDimensions, ByVal ptr, 2
End If
End Function
Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module
statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.
Excel telling me my blank cells aren't blank
'Select non blank cells
Selection.SpecialCells(xlCellTypeConstants, 23).Select
' REplace tehse blank look like cells to something uniqu
Selection.Replace What:="", Replacement:="TOBEDELETED", LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'now replace this uique text to nothing and voila all will disappear
Selection.Replace What:="TOBEDELETED", Replacement:="", LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
How to SSH into Docker?
These files will successfully open sshd and run service so you can ssh in locally. (you are using cyberduck aren't you?)
Dockerfile
FROM swiftdocker/swift
MAINTAINER Nobody
RUN apt-get update && apt-get -y install openssh-server supervisor
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
EXPOSE 22
CMD ["/usr/bin/supervisord"]
supervisord.conf
[supervisord]
nodaemon=true
[program:sshd]
command=/usr/sbin/sshd -D
to build / run start daemon / jump into shell.
docker build -t swift3-ssh .
docker run -p 2222:22 -i -t swift3-ssh
docker ps # find container id
docker exec -i -t <containerid> /bin/bash
key_load_public: invalid format
@uvsmtid Your post finally lead me into the right direction
:
simply deleting (actually renaming) the public key file id_rsa.pub
solved the problem for me, that git was working though nagging about invalid format.
Not quite sure, yet the file is not actually needed, since the pub key can be extracted from private key file id_rsa
anyway.
How to write Unicode characters to the console?
This works for me:
Console.OutputEncoding = System.Text.Encoding.Default;
To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:
Open Command Prompt;
Right click on the top bar of the Command Prompt;
Click Properties;
If the font is set to Raster Fonts, change it to Lucida Console.
How to find the length of a string in R
See ?nchar
. For example:
> nchar("foo")
[1] 3
> set.seed(10)
> strn <- paste(sample(LETTERS, 10), collapse = "")
> strn
[1] "NHKPBEFTLY"
> nchar(strn)
[1] 10
Possible to change where Android Virtual Devices are saved?
The environmental variable ANDROID_AVD_HOME
can be used to define the directory in which the AVD Manager shall look for AVD INI files and can therefore be used to change the location of the virtual devices;
The default value is %USERPROFILE%\.android\avd
on Windows (or ~/.android/avd
on Linux).
One can also create a link for the whole directory %USERPROFILE%\.android
on Windows (or a sym-link for directory ~/.android
on Linux).
When moving AVDs, the path
entry in AVD INI file needs to be updated accordingly.
Twitter Bootstrap 3: how to use media queries?
If you're using LESS or SCSS/SASS and you're using a LESS/SCSS version of Bootstrap, you can use variables as well, provided you have access to them. A LESS translation of @full-decent's answer would be as follows:
@media(max-width: @screen-xs-max){}
@media(min-width: @screen-sm-min){} /* deprecated: @screen-tablet, or @screen-sm */
@media(min-width: @screen-md-min){} /* deprecated: @screen-desktop, or @screen-md */
@media(min-width: @screen-lg-min){} /* deprecated: @screen-lg-desktop, or @screen-lg */
There are also variables for @screen-sm-max
and @screen-md-max
, which are 1 pixel less than @screen-md-min
and @screen-lg-min
, respectively, typically for use with @media(max-width)
.
EDIT: If you're using SCSS/SASS, variables start with a $
instead of a @
, so it'd be $screen-xs-max
etc.
jQuery convert line breaks to br (nl2br equivalent)
This JavaScript function considers whether to use insert or replace to handle the swap.
(Insert or replace HTML line breaks)
/**
* This function is same as PHP's nl2br() with default parameters.
*
* @param {string} str Input text
* @param {boolean} replaceMode Use replace instead of insert
* @param {boolean} isXhtml Use XHTML
* @return {string} Filtered text
*/
function nl2br (str, replaceMode, isXhtml) {
var breakTag = (isXhtml) ? '<br />' : '<br>';
var replaceStr = (replaceMode) ? '$1'+ breakTag : '$1'+ breakTag +'$2';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);
}
Demo - JSFiddle
JavaScript nl2br & br2nl functions
What function is to replace a substring from a string in C?
The optimizer should eliminate most of the local variables. The tmp pointer is there to make sure strcpy doesn't have to walk the string to find the null. tmp points to the end of result after each call. (See Shlemiel the painter's algorithm for why strcpy can be annoying.)
// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep (the string to remove)
int len_with; // length of with (the string to replace rep with)
int len_front; // distance between rep and end of last rep
int count; // number of replacements
// sanity checks and initialization
if (!orig || !rep)
return NULL;
len_rep = strlen(rep);
if (len_rep == 0)
return NULL; // empty rep causes infinite loop during count
if (!with)
with = "";
len_with = strlen(with);
// count the number of replacements needed
ins = orig;
for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
}
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}
Can't load AMD 64-bit .dll on a IA 32-bit platform
If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.
Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)
Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.
If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...
Common sources of unterminated string literal
Try a "binary search". Delete half the code and try again. If the error is still there, delete half the remaining code. If the error is not there, put what you deleted back in, and delete half of that. Repeat.
You should be able to narrow it down to a few line fairly quickly. My experience has been that at this point, you will notice some stupid malformed string.
It may be expedient to perform this on a saved version of the HTML output to the browser, if you're not sure which server-side resource the error is in.
How to change font size in html?
You can do this by setting a style in your paragraph tag. For example if you wanted to change the font size to 28px.
<p style="font-size: 28px;"> Hello, World! </p>
You can also set the color by setting:
<p style="color: blue;"> Hello, World! </p>
However, if you want to preview font sizes and colors (which I recommend doing) before you add them to your website and use them. I recommend testing them out beforehand so you pick a good font size and color that contrasts well with the background. I recommend using this site if you wish to do so, couldn't find anything else: http://fontpreview.herokuapp.com/
How to save and load cookies using Python + Selenium WebDriver
When you need cookies from session to session, there is another way to do it. Use the Chrome options user-data-dir in order to use folders as profiles. I run:
# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")
Here you can do the logins that check for human interaction. I do this and then the cookies I need now every time I start the Webdriver with that folder everything is in there. You can also manually install the Extensions and have them in every session.
The second time I run, all the cookies are there:
# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") # Now you can see the cookies, the settings, extensions, etc., and the logins done in the previous session are present here.
The advantage is you can use multiple folders with different settings and cookies, Extensions without the need to load, unload cookies, install and uninstall Extensions, change settings, change logins via code, and thus no way to have the logic of the program break, etc.
Also, this is faster than having to do it all by code.
How to get substring from string in c#?
Here is example of getting substring from 14 character to end of string. You can modify it to fit your needs
string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
//get substring where 14 is start index
string substring = text.Substring(14);
Only local connections are allowed Chrome and Selenium webdriver
Here you are a working stack:
Some previous notes:
1) Run sudo Xvfb :10 -ac &
2) Run export DISPLAY=:10
3) Run java -jar "YOUR_PATH_TO/selenium-server-standalone-2.53.1.jar" -Dwebdriver.chrome.driver="YOUR_PATH_TO/chromedriver.2.27" -Dwebdriver.chrome.whitelistedIps="localhost"
Calculating text width
$.fn.textWidth = function(){
var w = $('body').append($('<span stlye="display:none;" id="textWidth"/>')).find('#textWidth').html($(this).html()[0]).width();
$('#textWidth').remove();
console.log(w);
return w;
};
almost a one liner.
Gives you the with of the first character
Get Hard disk serial Number
Use "vol" shell command and parse serial from it's output, like this.
Works at least in Win7
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CheckHD
{
class HDSerial
{
const string MY_SERIAL = "F845-BB23";
public static bool CheckSerial()
{
string res = ExecuteCommandSync("vol");
const string search = "Number is";
int startI = res.IndexOf(search, StringComparison.InvariantCultureIgnoreCase);
if (startI > 0)
{
string currentDiskID = res.Substring(startI + search.Length).Trim();
if (currentDiskID.Equals(MY_SERIAL))
return true;
}
return false;
}
public static string ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
return result;
}
catch (Exception)
{
// Log the exception
return null;
}
}
}
}
How to set character limit on the_content() and the_excerpt() in wordpress
wp_trim_words()
This function trims text to a certain number of words and returns the trimmed text.
$excerpt = wp_trim_words( get_the_content(), 40, '<a href="'.get_the_permalink().'">More Link</a>');
Get truncated string with specified width using mb_strimwidth()
php function.
$excerpt = mb_strimwidth( strip_tags(get_the_content()), 0, 100, '...' );
Using add_filter()
method of WordPress on the_content
filter hook.
add_filter( "the_content", "limit_content_chr" );
function limit_content_chr( $content ){
if ( 'post' == get_post_type() ) {
return mb_strimwidth( strip_tags($content), 0, 100, '...' );
} else {
return $content;
}
}
Using custom php function to limit content characters.
function limit_content_chr( $content, $limit=100 ) {
return mb_strimwidth( strip_tags($content), 0, $limit, '...' );
}
// using above function in template tags
echo limit_content_chr( get_the_content(), 50 );
What are the differences between Mustache.js and Handlebars.js?
One more subtle difference is the treatment of falsy values in {{#property}}...{{/property}}
blocks. Most mustache implementations will just obey JS falsiness here, not rendering the block if property
is ''
or '0'.
Handlebars will render the block for ''
and 0
, but not other falsy values. This can cause some trouble when migrating templates.
Angular 2: Get Values of Multiple Checked Checkboxes
<input type="checkbox" name="options" value="option" (change)="updateChecked(option, $event)" />
export class MyComponent {
checked: boolean[] = [];
updateChecked(option, event) {
this.checked[option]=event; // or `event.target.value` not sure what this event looks like
}
}
Round up double to 2 decimal places
@Rounded, A swift 5.1 property wrapper
Example :
struct GameResult {
@Rounded(rule: NSDecimalNumber.RoundingMode.up,scale: 4)
var score: Decimal
}
var result = GameResult()
result.score = 3.14159265358979
print(result.score) // 3.1416
Why is my JQuery selector returning a n.fn.init[0], and what is it?
Another approach(Inside of $function
to asure that the each
is executed on document ready
):
var ids = [1,2];
$(function(){
$('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
if(ids.indexOf($(item).data('id')) > -1){
$(item).prop("checked", "checked");
}
});
});
What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?
Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the length:0
means that it doesn't find any element based on your search criteria.
About n.fn.init[0]
, lets look at the core of the Jquery Library:
var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
};
Looks familiar, right?, now in a minified version of jquery, this should looks like:
var n = function( selector, context ) {
return new n.fn.init( selector, context );
};
So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.
Form Submit jQuery does not work
Because when you call $( "#form_id" ).submit();
it triggers the external submit handler which prevents the default action, instead use
$( "#form_id" )[0].submit();
or
$form.submit();//declare `$form as a local variable by using var $form = this;
When you call the dom element's submit method programatically, it won't trigger the submit handlers attached to the element
reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
number_format() with MySQL
You need this:
CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
Check if a varchar is a number (TSQL)
Wade73's answer for decimals doesn't quite work. I've modified it to allow only a single decimal point.
declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar)
values
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......');
-- This shows that Wade73's answer allows some non-numeric values to slip through.
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber
from
@MyTable
) t order by IsNumber;
-- Notice the addition of "and MyVar not like N'%.%.%'".
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' then 1 else 0 end as IsNumber
from
@MyTable
) t
order by IsNumber;
$.widget is not a function
I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.
No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.
A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.
Printing 1 to 1000 without loop or conditionals
I missed all the fun, all the good C++ answers have already been posted !
This is the weirdest thing I could come up with, I wouldn't bet it's legal C99 though :p
#include <stdio.h>
int i = 1;
int main(int argc, char *argv[printf("%d\n", i++)])
{
return (i <= 1000) && main(argc, argv);
}
Another one, with a little cheating :
#include <stdio.h>
#include <boost/preprocessor.hpp>
#define ECHO_COUNT(z, n, unused) n+1
#define FORMAT_STRING(z, n, unused) "%d\n"
int main()
{
printf(BOOST_PP_REPEAT(1000, FORMAT_STRING, ~), BOOST_PP_ENUM(LOOP_CNT, ECHO_COUNT, ~));
}
Last idea, same cheat :
#include <boost/preprocessor.hpp>
#include <iostream>
int main()
{
#define ECHO_COUNT(z, n, unused) BOOST_PP_STRINGIZE(BOOST_PP_INC(n))"\n"
std::cout << BOOST_PP_REPEAT(1000, ECHO_COUNT, ~) << std::endl;
}
What does DIM stand for in Visual Basic and BASIC?
Dim
have had different meanings attributed to it.
I've found references about Dim
meaning "Declare In Memory", the more relevant reference is a document on Dim Statement published Oracle as part of the Siebel VB Language Reference. Of course, you may argue that if you do not declare the variables in memory where do you do it? Maybe "Declare in Module" is a good alternative considering how Dim
is used.
In my opinion, "Declare In Memory" is actually a mnemonic, created to make easier to learn how to use Dim
. I see "Declare in Memory" as a better meaning as it describes what it does in current versions of the language, but it is not the proper meaning.
In fact, at the origins of Basic Dim
was only used to declare arrays. For regular variables no keyword was used, instead their type was inferred from their name. For instance, if the name of the variable ends with $
then it is a string (this is something that you could see even in method names up to VB6, for example Mid$
). And so, you used Dim
only to give dimension to the arrays (notice that ReDim
resizes arrays).
Really, Does It Matter? I mean, it is a keyword it has its meaning inside an artificial language. It doesn't have to be a word in English or any other natural language. So it could just mean whatever you want, all that matters is that it works.
Anyhow, that is not completely true. As BASIC is part of our culture, and understanding why it came to be as it is - I hope - will help improve our vision of the world.
I sit in from of my computer with a desire to help preserve this little piece of our culture that seems lost, replaced by our guessing of what it was. And so, I have dug MSDN both current and the old CDs from the 1998 version. I have also searched the documention for the old QBasic [Had to use DOSBox] and managed to get some Darthmouth manual, all to find how they talk about Dim
. For my disappointment, they don't say what does Dim
stand for, and only say how it is used.
But before my hope was dim, I managed to find this BBC Microcomputer System Used Guide (that claims to be from 1984, and I don't want to doubt it). The BBC Microcomputer used a variant of BASIC called BBC BASIC and it is described in the document. Even though, it doesn't say what does Dim
stand for, it says (on page 104):
... you can dimension N$ to have as many entries as you want. For
example, DIM N$(1000) would create a string array with space for 1000
different names.
As I said, it doesn't say that Dim
stands for dimension, but serves as proof to show that associating Dim
with Dimension
was a common thing at the time of writing that document.
Now, I got a rewarding surprise later on (at page 208), the title for the section that describes the DIM keyword (note: that is not listed in the contents) says:
DIM dimension of an array
So, I didn't get the quote "Dim stands for..." but I guess it is clear that any decent human being that is able to read those document will consider that Dim
means dimension.
With renewed hope, I decided to search about how Dim
was chosen. Again, I didn't find an account on the subject, still I was able to find a definitive quote:
Before you can use an array, you must define it in a DIM (dimension) statement.
You can find this as part of the True BASIC Online User's Guides at the web page of True BASIC inc, a company founded by Thomas Eugene Kurtz, co-author of BASIC.
So, In reallity, Dim
is a shorthand for DIMENSION
, and yes. That existed in FORTRAN before, so it is likely that it was picked by influence of FORTRAN as Patrick McDonald said in his answer.
Dim sum as string = "this is not a chinese meal" REM example usage in VB.NET ;)
Html.Textbox VS Html.TextboxFor
Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.
1: @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)
will both produce
<input id="Name" name="Name" type="text" />
So what does that mean in terms of use?
Generally two things:
- The typed
TextBoxFor
will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
- Using the typed
TextBoxFor
version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.
It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.
Javascript change Div style
function abc() {
var color = document.getElementById("test").style.color;
color = (color=="red") ? "black" : "red" ;
document.getElementById("test").style.color= color;
}
How can I detect keydown or keypress event in angular.js?
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.
Set variable in jinja
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
How to set a:link height/width with css?
Your problem is probably that a
elements are display: inline
by nature. You can't set the width and height of inline elements.
You would have to set display: block
on the a
, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left
so they line up side by side anyway.
Authentication issues with WWW-Authenticate: Negotiate
Putting this information here for future readers' benefit.
You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
ASP.Net MVC - Read File from HttpPostedFileBase without save
A slight change to Thangamani Palanisamy answer, which allows the Binary reader to be disposed and corrects the input length issue in his comments.
string result = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
result = System.Text.Encoding.UTF8.GetString(binData);
}
How to make the Facebook Like Box responsive?
Colin's example for me clashed with the like button. So I adapted it to only target the Like Box.
.fb-like-box, .fb-like-box span, .fb-like-box span iframe[style] { width: 100% !important; }
Tested in most modern browsers.
How to show text on image when hovering?
This is what I use to make the text appear on hover:
_x000D_
_x000D_
* {_x000D_
box-sizing: border-box_x000D_
}_x000D_
_x000D_
div {_x000D_
position: relative;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
border-radius: 50%;_x000D_
overflow: hidden;_x000D_
text-align: center_x000D_
}_x000D_
_x000D_
img {_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
position: absolute;_x000D_
border-radius: 50%_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
opacity: 0;_x000D_
transition:opacity 2s;_x000D_
}_x000D_
_x000D_
heading {_x000D_
line-height: 40px;_x000D_
font-weight: bold;_x000D_
font-family: "Trebuchet MS";_x000D_
text-align: center;_x000D_
position: absolute;_x000D_
display: block_x000D_
}_x000D_
_x000D_
div p {_x000D_
z-index: -1;_x000D_
width: 420px;_x000D_
line-height: 20px;_x000D_
display: inline-block;_x000D_
padding: 200px 0px;_x000D_
vertical-align: middle;_x000D_
font-family: "Trebuchet MS";_x000D_
height: 450px_x000D_
}
_x000D_
<div>_x000D_
<img src="https://68.media.tumblr.com/20b34e8d12d4230f9b362d7feb148c57/tumblr_oiwytz4dh41tf8vylo1_1280.png">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing <br>elit. Reiciendis temporibus iure dolores aspernatur excepturi <br> corporis nihil in suscipit, repudiandae. Totam._x000D_
</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_
JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")
You should never use the unidirectional @OneToMany
annotation because:
- It generates inefficient SQL statements
- It creates an extra table which increases the memory footprint of your DB indexes
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
Arithmetic overflow error converting numeric to data type numeric
My guess is that you're trying to squeeze a number greater than 99999.99 into your decimal fields. Changing it to (8,3) isn't going to do anything if it's greater than 99999.999 - you need to increase the number of digits before the decimal. You can do this by increasing the precision (which is the total number of digits before and after the decimal). You can leave the scale the same unless you need to alter how many decimal places to store. Try decimal(9,2)
or decimal(10,2)
or whatever.
You can test this by commenting out the insert #temp
and see what numbers the select statement is giving you and see if they are bigger than your column can handle.
Get all files modified in last 30 days in a directory
A couple of issues
- You're not limiting it to files, so when it finds a matching directory it will list every file within it.
- You can't use
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
.
+30
is older
than 30 days, -30
would be modified in last 30 days.
-exec
really isn't needed, you could list everything with various -printf
options.
Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease
I made it work by upgrading the WebApi package to the prerelease version using nuget:
PM> Microsoft.AspNet.WebApi -Pre
In order to force the project using the latest version of WebApi, some modifications to the root Web.config were necessary:
1) Webpages Version from 2.0.0.0 to 3.0.0.0
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
</appSettings>
2) Binding redirect to 5.0.0.0 for System.Web.Http and System.Net.Http.Formatting
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
I think that's it
PS: Solution highly inspired from WebAPI OData 5.0 Beta - Accessing GlobalConfiguration throws Security Error
How do I download and save a file locally on iOS using objective C?
I think a much easier way is to use ASIHTTPRequest. Three lines of code can accomplish this:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];
Link to Reference
UPDATE: I should mention that ASIHTTPRequest is no longer maintained. The author has specifically advised people to use other framework instead, like AFNetworking
Pointer to incomplete class type is not allowed
One thing to check for...
If your class is defined as a typedef:
typedef struct myclass { };
Then you try to refer to it as struct myclass
anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:
typedef struct mystruct {}...
struct mystruct *myvar = value;
Instead use...
mystruct *myvar = value;
Common mistake.
Popup Message boxes
Ok, SO Basically I think I have a simple and effective solution.
package AnotherPopUpMessage;
import javax.swing.JOptionPane;
public class AnotherPopUp {
public static void main(String[] args) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(null, "Again? Where do all these come from?",
"PopUp4", JOptionPane.CLOSED_OPTION);
}
}
Pointers in JavaScript?
Late answer but I have come across a way of passing primitive values by reference by means of closures. It is rather complicated to create a pointer, but it works.
function ptr(get, set) {
return { get: get, set: set };
}
function helloWorld(namePtr) {
console.log(namePtr.get());
namePtr.set('jack');
console.log(namePtr.get())
}
var myName = 'joe';
var myNamePtr = ptr(
function () { return myName; },
function (value) { myName = value; }
);
helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack
In ES6, the code can be shortened to use lambda expressions:
var myName = 'joe';
var myNamePtr = ptr(=> myName, v => myName = v);
helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack
How do I use installed packages in PyCharm?
You should never need to modify the path directly, either through environment variables or sys.path
. Whether you use the os (ex. apt-get
), or pip
in a virtualenv, packages will be installed to a location already on the path.
In your example, GNU Radio is installed to the system Python 2's standard site-packages
location, which is already in the path. Pointing PyCharm at the correct interpreter is enough; if it isn't there is something else wrong that isn't apparent. It may be that /usr/bin/python
does not point to the same interpreter that GNU Radio was installed in; try pointing specifically at the python2.7
binary. Or, PyCharm used to be somewhat bad at detecting packages; File > Invalidate Caches > Invalidate and Restart
would tell it to rescan.
This answer will cover how you should set up a project environment, install packages in different scenarios, and configure PyCharm. I refer multiple times to the Python Packaging User Guide, written by the same group that maintains the official Python packaging tools.
The correct way to develop a Python application is with a virtualenv. Packages and version are installed without affecting the system or other projects. PyCharm has a built-in interface to create a virtualenv and install packages. Or you can create it from the command line and then point PyCharm at it.
$ cd MyProject
$ python2 -m virtualenv env
$ . env/bin/activate
$ pip install -U pip setuptools # get the latest versions
$ pip install flask # install other packages
In your PyCharm project, go to File > Settings > Project > Project Interpreter
. If you used virtualenvwrapper
or PyCharm to create the env, then it should show up in the menu. If not, click the gear, choose Add Local
, and locate the Python binary in the env. PyCharm will display all the packages in the selected env.
In some cases, such as with GNU Radio, there is no package to install with pip
, the package was installed system-wide when you install the rest of GNU Radio (ex. apt-get install gnuradio
). In this case, you should still use a virtualenv, but you'll need to make it aware of this system package.
$ python2 -m virtualenv --system-site-packages env
Unfortunately it looks a little messy, because all system packages will now appear in your env, but they are just links, you can still safely install or upgrade packages without affecting the system.
In some cases, you will have multiple local packages you're developing, and will want one project to use the other package. In this case you might think you have to add the local package to the other project's path, but this is not the case. You should install your package in development mode. All this requires is adding a setup.py
file to your package, which will be required anyway to properly distribute and deploy the package later.
Minimal setup.py
for your first project:
from setuptools import setup, find_packages
setup(
name='mypackage',
version='0.1',
packages=find_packages(),
)
Then install it in your second project's env:
$ pip install -e /path/to/first/project
Get image dimensions
You can use the getimagesize
function like this:
list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " . $height;