tar -pczf <target_file.tar.gz> --exclude /path/to/exclude --exclude /another/path/to/exclude/* /path/to/include/ /another/path/to/include/*
Tested in Ubuntu 19.10.
=
after exclude
is optional. You can use =
instead of space after keyword exclude
if you like.exclude
must be placed before the source.Global Gzip in HttpModule
If you don't have access to the final IIS instance (shared hosting...) you can create a HttpModule that adds this code to every HttpApplication.Begin_Request event :
HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
Testing
Kudos, no solution is done without testing. I like to use the Firefox plugin "Liveheaders" it shows all the information about every http message between the browser and server, including compression, file size (which you could compare to the file size on the server).
If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule
that gets added this code to every HttpApplication.Begin_Request
event:-
HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
import gzip
f = gzip.open('file.txt.gz', 'rb')
file_content = f.read()
f.close()
find /my/dir/ -printf "%P\n" | tar -czf mydir.tgz --no-recursion -C /my/dir/ -T -
With some conditions (archive only files, dirs and symlinks):
find /my/dir/ -printf "%P\n" -type f -o -type l -o -type d | tar -czf mydir.tgz --no-recursion -C /my/dir/ -T -
The below unfortunately includes a parent directory ./
in the archive:
tar -czf mydir.tgz -C /my/dir .
You can move all the files out of that directory by using the --transform
configuration option, but that doesn't get rid of the .
directory itself. It becomes increasingly difficult to tame the command.
You could use $(find ...)
to add a file list to the command (like in magnus' answer), but that potentially causes a "file list too long" error. The best way is to combine it with tar's -T
option, like this:
find /my/dir/ -printf "%P\n" -type f -o -type l -o -type d | tar -czf mydir.tgz --no-recursion -C /my/dir/ -T -
Basically what it does is list all files (-type f
), links (-type l
) and subdirectories (-type d
) under your directory, make all filenames relative using -printf "%P\n"
, and then pass that to the tar command (it takes filenames from STDIN using -T -
). The -C
option is needed so tar knows where the files with relative names are located. The --no-recursion
flag is so that tar doesn't recurse into folders it is told to archive (causing duplicate files).
If you need to do something special with filenames (filtering, following symlinks etc), the find
command is pretty powerful, and you can test it by just removing the tar
part of the above command:
$ find /my/dir/ -printf "%P\n" -type f -o -type l -o -type d
> textfile.txt
> documentation.pdf
> subfolder2
> subfolder
> subfolder/.gitignore
For example if you want to filter PDF files, add ! -name '*.pdf'
$ find /my/dir/ -printf "%P\n" -type f ! -name '*.pdf' -o -type l -o -type d
> textfile.txt
> subfolder2
> subfolder
> subfolder/.gitignore
The command uses printf
(available in GNU find
) which tells find
to print its results with relative paths. However, if you don't have GNU find
, this works to make the paths relative (removes parents with sed
):
find /my/dir/ -type f -o -type l -o -type d | sed s,^/my/dir/,, | tar -czf mydir.tgz --no-recursion -C /my/dir/ -T -
Ran into this problem using the same .htaccess configuration. I realized that my server was serving javascript files as text/javascript
instead of application/javascript
. Once I added text/javascript
to the AddOutputFilterByType
declaration, gzip started working.
As to why javascript was being served as text/javascript
: there was an AddType 'text/javascript' js
declaration at the top of my root .htaccess file. After removing it (it had been added in error), javascript starting serving as application/javascript
.
This is basically the same solution as @andy-wilkinson provided, but as of Spring Boot 1.0 the customize(...) method has a ConfigurableEmbeddedServletContainer parameter.
Another thing that is worth mentioning is that Tomcat only compresses content types of text/html
, text/xml
and text/plain
by default. Below is an example that supports compression of application/json
as well:
@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer servletContainer) {
((TomcatEmbeddedServletContainerFactory) servletContainer).addConnectorCustomizers(
new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
httpProtocol.setCompression("on");
httpProtocol.setCompressionMinSize(256);
String mimeTypes = httpProtocol.getCompressableMimeTypes();
String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
}
}
);
}
};
}
If you want to do a real test extract of a tar file without extracting to disk, use the -O option. This spews the extract to standard output instead of the filesystem. If the tar file is corrupt, the process will abort with an error.
Example of failed tar ball test...
$ echo "this will not pass the test" > hello.tgz
$ tar -xvzf hello.tgz -O > /dev/null
gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error exit delayed from previous errors
$ rm hello.*
Working Example...
$ ls hello*
ls: hello*: No such file or directory
$ echo "hello1" > hello1.txt
$ echo "hello2" > hello2.txt
$ tar -cvzf hello.tgz hello[12].txt
hello1.txt
hello2.txt
$ rm hello[12].txt
$ ls hello*
hello.tgz
$ tar -xvzf hello.tgz -O
hello1.txt
hello1
hello2.txt
hello2
$ ls hello*
hello.tgz
$ tar -xvzf hello.tgz
hello1.txt
hello2.txt
$ ls hello*
hello1.txt hello2.txt hello.tgz
$ rm hello*
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
This is because of
String outStr = obj.toString("UTF-8");
Send the byte[]
which you can get from your ByteArrayOutputStream
and use it as such in your ByteArrayInputStream
to construct your GZIPInputStream
. Following are the changes which need to be done in your code.
byte[] compressed = compress(string); //In the main method
public static byte[] compress(String str) throws Exception {
...
...
return obj.toByteArray();
}
public static String decompress(byte[] bytes) throws Exception {
...
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
...
}
The problem is that you do not have bzip2 installed. The tar program relies upon this external program to do compression. For installing bzip2, it depends on the system you are using. For example, with Ubuntu that would be on Ubuntu
sudo apt-get install bzip2
The GNU tar program does not know how to compress an existing file such as user-logs.tar (bzip2 does that). The tar program can use external compression programs gzip, bzip2, xz by opening a pipe to those programs, sending a tar archive via the pipe to the compression utility, which compresses the data which it reads from tar and writes the result to the filename which the tar program specifies.
Alternatively, the tar and compression utility could be the same program. BSD tar does its compression using lib archive (they're not really distinct except in name).
gzip -dc archive.tar.gz | tar -xf - -C /destination
or, with GNU tar
tar xzf archive.tar.gz -C /destination
It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.
Most browsers can decompress gzip on the fly. That might be a better option than a javascript implementation.
Try:
ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz
Then Try:
ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm
This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.
I had the same issue. It was damaged the archive file...
The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.
If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.
On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).
You can also use the tar flag "--use-compress-program=" to tell tar what compression program to use.
For example use:
tar -c --use-compress-program=pigz -f tar.file dir_to_zip
If the mysql dump was a .gz file, you need to gunzip to uncompress the file by typing $ gunzip mysqldump.sql.gz
This will uncompress the .gz file and will just store mysqldump.sql in the same location.
Type the following command to import sql data file:
$ mysql -u username -p -h localhost test-database < mysqldump.sql password: _
There is an easier solution to this problem.
You just need to add a t
to the mode so it becomes wt
. This causes Python to open the file as a text file and not binary. Then everything will just work.
The complete program becomes this:
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
outfile.write(plaintext)
How about this?
node-compress
A streaming compression / gzip module for node.js
To install, ensure that you have libz installed, and run:
node-waf configure
node-waf build
This will put the compress.node binary module in build/default.
...
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
In my case, I change a lot an specific JS file and I need it to be in its last version in all browsers where is being used.
I do not have a specific version number for this file, so I simply hash the current date and time (hour and minute) and pass it as the version number:
<script src="/js/panel/app.js?v={{ substr(md5(date("Y-m-d_Hi")),10,18) }}"></script>
I need it to be loaded every minute, but you can decide when it should be reloaded.
tar -zcvf compressFileName.tar.gz folderToCompress
everything in folderToCompress will go to compressFileName
Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName
mod_deflate requires fewer resources on your server, although you may pay a small penalty in terms of the amount of compression.
If you are serving many small files, I'd recommend benchmarking and load testing your compressed and uncompressed solutions - you may find some cases where enabling compression will not result in savings.
Visual Studio 2017 / 2019
For anyone looking for an answer for a newer version of Visual Studio, install the Editor Guidelines plugin, then right-click in the editor and select this:
Hi We sort of had the same problem if I understand you well. So check what pysftp version you're using. If it's the latest one which is 0.2.9 downgrade to 0.2.8. Check this out. https://github.com/Yenthe666/auto_backup/issues/47
For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.
#include <gtest/gtest.h>
const bool skip_some_test = true;
bool some_test_was_run = false;
void someTest() {
EXPECT_TRUE(!skip_some_test);
some_test_was_run = true;
}
TEST(BasicTest, Sanity) {
EXPECT_EQ(1, 1);
if(!skip_some_test) {
someTest();
EXPECT_TRUE(some_test_was_run);
}
}
This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.
Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.
As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.
The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.
You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.
A DATE
column does not have a format. You cannot specify a format for it.
You can use DateStyle
to control how PostgreSQL emits dates, but it's global and a bit limited.
Instead, you should use to_char
to format the date when you query it, or format it in the client application. Like:
SELECT to_char("date", 'DD/MM/YYYY') FROM mytable;
e.g.
regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');
to_char
------------
01/04/2014
(1 row)
ES6 style allows you to use new features, such as super
keyword. super
keyword it's all about parent class context, when you are using ES6 classes syntax. As a very simple example, checkout:
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
Bar.classMethod(); // 'hello, too'
Also, you can use super
to call parent constructor:
class Foo {}
class Bar extends Foo {
constructor(num) {
let tmp = num * 2; // OK
this.num = num; // ReferenceError
super();
this.num = num; // OK
}
}
And of course you can use it to access parent class properties super.prop
.
So, use ES6 and be happy.
Copying the ".txt" file from one folder to another is very simple and question contains the logic. Only missing part is substituting with right information as below:
import os, shutil, glob
src_fldr = r"Source Folder/Directory path"; ## Edit this
dst_fldr = "Destiantion Folder/Directory path"; ## Edit this
try:
os.makedirs(dst_fldr); ## it creates the destination folder
except:
print "Folder already exist or some error";
below lines of code will copy the file with *.txt extension files from src_fldr to dst_fldr
for txt_file in glob.glob(src_fldr+"\\*.txt"):
shutil.copy2(txt_file, dst_fldr);
Most commonly, you'd use:
import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding
Python provides other distributions if you need.
If you have numpy
imported already, you can used its equivalent:
import numpy as np
np.random.uniform(a, b) # range [a, b)
Again, if you need another distribution, numpy
provides the same distributions as python, as well as many additional ones.
In addition to all of the great answers, there is a concept called lazy loading:
Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed.
Using it properly, you can reduce the loading time of your application. And Kotlin way of it's implementation is by lazy()
which loads the needed value to your variable whenever it's needed.
But lateinit is used when you are sure a variable won't be null or empty and will be initialized before you use it -e.g. in onResume()
method for android- and so you don't want to declare it as a nullable type.
You can convert an std object to array like this:
$objectToArray = (array)$object;
Jun 10 2015: Note from the author of gulp-uglifyjs
:
DEPRECATED: This plugin has been blacklisted as it relies on Uglify to concat the files instead of using gulp-concat, which breaks the "It should do one thing" paradigm. When I created this plugin, there was no way to get source maps to work with gulp, however now there is a gulp-sourcemaps plugin that achieves the same goal. gulp-uglifyjs still works great and gives very granular control over the Uglify execution, I'm just giving you a heads up that other options now exist.
Feb 18 2015: gulp-uglify
and gulp-concat
both work nicely with gulp-sourcemaps
now. Just make sure to set the newLine
option correctly for gulp-concat
; I recommend \n;
.
Original Answer (Dec 2014): Use gulp-uglifyjs instead. gulp-concat
isn't necessarily safe; it needs to handle trailing semi-colons correctly. gulp-uglify
also doesn't support source maps. Here's a snippet from a project I'm working on:
gulp.task('scripts', function () {
gulp.src(scripts)
.pipe(plumber())
.pipe(uglify('all_the_things.js',{
output: {
beautify: false
},
outSourceMap: true,
basePath: 'www',
sourceRoot: '/'
}))
.pipe(plumber.stop())
.pipe(gulp.dest('www/js'))
});
Use git reflog
to find the hashes of previously checked out commits.
A shortcut command to get to your last checked out branch (not sure if this work correctly with detached HEAD and intermediate commits though) is git checkout -
Many of the answers here are great, but for those that just want a simple one line to the point answer without having to set up aliases or anything extra, here it is:
git log --all --decorate --oneline --graph
Not everyone would be doing a git log
all the time, but when you need it just remember:
"A Dog" = git log --all --decorate --oneline --graph
You add the .ico in your resource as bobobobo said and then in your main dialog's constructor you modify:
m_hIcon = AfxGetApp()->LoadIcon(ICON_ID_FROM_RESOURCE.H);
With Git 2.22 (Q2 2019), you will have a simpler approach: git branch --show-current
.
See commit 0ecb1fc (25 Oct 2018) by Daniels Umanovskis (umanovskis
).
(Merged by Junio C Hamano -- gitster
-- in commit 3710f60, 07 Mar 2019)
branch
: introduce--show-current
display option
When called with
--show-current
,git branch
will print the current branch name and terminate.
Only the actual name gets printed, withoutrefs/heads
.
In detached HEAD state, nothing is output.
Intended both for scripting and interactive/informative use.
Unlikegit branch --list
, no filtering is needed to just get the branch name.
See the original discussion on the Git mailing list in Oct. 2018, and the actual pathc.
You forgot to mention the name of your database (is it "my"?).
ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE my SET OFFLINE;
ALTER DATABASE my MODIFY FILE
(
Name = my_Data,
Filename = 'D:\DATA\my.MDF'
);
ALTER DATABASE my MODIFY FILE
(
Name = my_Log,
Filename = 'D:\DATA\my_1.LDF'
);
Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:
ALTER DATABASE my SET ONLINE;
ALTER DATABASE my SET MULTI_USER;
This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.
If you use "=", a replica is created for the original arraylist in the second one, but the reference is same so if you change in one list , the other one will also get modified. Use this instead of "="
List_Of_Array1.addAll(List_Of_Array);
He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!
<?php
$data['may_1_2002']=
Array(
'title_id_32'=>'Good morning',
'title_id_21'=>'Blue sky',
'title_id_3'=>'Summer',
'date'=>'1 May 2002'
);
$data['may_2_2002']=
Array(
'title_id_34'=>'Leaves',
'title_id_20'=>'Old times',
'date'=>'2 May 2002 '
);
echo '<pre>';
print_r($data);
?>
public void EndTask(string taskname)
{
string processName = taskname.Replace(".exe", "");
foreach (Process process in Process.GetProcessesByName(processName))
{
process.Kill();
}
}
//EndTask("notepad");
Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.
After trying a variety of methods, I figured that the NTFS volume creation time of the system volume is probably the best proxy. While there are tools to check this (see this link ) I wanted a method without an additional utility. I settled on the creation date of "C:\System Volume Information" and it seemed to check out in various cases.
One-line of PowerShell to get it is:
([DateTime](Get-Item -Force 'C:\System Volume Information\').CreationTime).ToString('MM/dd/yyyy')
Response.Write("<script> try {this.submit();} catch(e){} </script>");
useTimezone is an older workaround. MySQL team rewrote the setTimestamp/getTimestamp code fairly recently, but it will only be enabled if you set the connection parameter useLegacyDatetimeCode=false and you're using the latest version of mysql JDBC connector. So for example:
String url =
"jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false
If you download the mysql-connector source code and look at setTimestamp, it's very easy to see what's happening:
If use legacy date time code = false, newSetTimestampInternal(...) is called. Then, if the Calendar passed to newSetTimestampInternal is NULL, your date object is formatted in the database's time zone:
this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
this.tsdf.setTimeZone(this.connection.getServerTimezoneTZ());
timestampString = this.tsdf.format(x);
It's very important that Calendar is null - so make sure you're using:
setTimestamp(int,Timestamp).
... NOT setTimestamp(int,Timestamp,Calendar).
It should be obvious now how this works. If you construct a date: January 5, 2011 3:00 AM in America/Los_Angeles (or whatever time zone you want) using java.util.Calendar and call setTimestamp(1, myDate), then it will take your date, use SimpleDateFormat to format it in the database time zone. So if your DB is in America/New_York, it will construct the String '2011-01-05 6:00:00' to be inserted (since NY is ahead of LA by 3 hours).
To retrieve the date, use getTimestamp(int) (without the Calendar). Once again it will use the database time zone to build a date.
Note: The webserver time zone is completely irrelevant now! If you don't set useLegacyDatetimecode to false, the webserver time zone is used for formatting - adding lots of confusion.
Note:
It's possible MySQL my complain that the server time zone is ambiguous. For example, if your database is set to use EST, there might be several possible EST time zones in Java, so you can clarify this for mysql-connector by telling it exactly what the database time zone is:
String url =
"jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false&serverTimezone=America/New_York";
You only need to do this if it complains.
To make @Raghavendra's answer more specific:
Once you've downloaded 2 zip files,
copy ALL the contents of "win64_11gR2_database_2of2.zip -> Database -> Stage -> Components" folder to "win64_11gR2_database_1of2.zip -> Database -> Stage -> Components" folder.
You'll still get the same warning, however, the installation will run completely without generating any errors.
There's a far more simpler solution to tackle this.
The reason why you get ValueError: Index contains duplicate entries, cannot reshape
is because, once you unstack "Location
", then the remaining index columns "id
" and "date
" combinations are no longer unique.
You can avoid this by retaining the default index column (row #) and while setting the index using "id
", "date
" and "location
", add it in "append
" mode instead of the default overwrite mode.
So use,
e.set_index(['id', 'date', 'location'], append=True)
Once this is done, your index columns will still have the default index along with the set indexes. And unstack
will work.
Let me know how it works out.
I was having the same issue, and for me it worked by simply concatenating https:${image.getAttribute('src')}
First of all, have only one id="test"
Secondly, try this:
if ($('[name="test"]').is(':checked'))
@Context ServletContext ctx;
@Context private HttpServletResponse response;
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/download/{filename}")
public StreamingOutput download(@PathParam("filename") String fileName) throws Exception {
final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");
return new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException,
WebApplicationException {
Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output));
}
};
}
Can you change the if condition to this:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
You need to analyze the JSON calls using Wireshark, so you will see if you include the charset in the formation of the JSON page or not, for example:
0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK. 0010 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 .Content -Type: t 0020 65 78 74 2f 68 74 6d 6c 0d 0a 43 61 63 68 65 2d ext/html ..Cache- 0030 43 6f 6e 74 72 6f 6c 3a 20 6e 6f 2d 63 61 63 68 Control: no-cach
0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK. 0010 0a 43 61 63 68 65 2d 43 6f 6e 74 72 6f 6c 3a 20 .Cache-C ontrol: 0020 6e 6f 2d 63 61 63 68 65 0d 0a 43 6f 6e 74 65 6e no-cache ..Conten 0030 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 68 74 6d t-Type: text/htm 0040 6c 3b 20 63 68 61 72 73 65 74 3d 49 53 4f 2d 38 l; chars et=ISO-8 0050 38 35 39 2d 31 0d 0a 43 6f 6e 6e 65 63 74 69 6f 859-1..C onnectio
Why is that? because we can not put on the page of JSON a goal like this:
In my case I use the manufacturer Connect Me 9210 Digi:
It worked for me without having to convert the data passed by JSON for UTF-8 and then redo the conversion on the page ...
I found an unorthodox way to accomplish this.
Just put the script page in an iframe. Doing so allows the page to be refreshed, seemingly even on older browsers without the "confirm form resubmission" message ever appearing.
I believe you're looking for the @filename
syntax, e.g.:
strip new lines
curl --data "@/path/to/filename" http://...
keep new lines
curl --data-binary "@/path/to/filename" http://...
curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary
in place of --data
In my case, the file ~/.curlrc had a wrong proxy configured.
It is ALWAYS preferable to use const, instead of #define. That's because const is treated by the compiler and #define by the preprocessor. It is like #define itself is not part of the code (roughly speaking).
Example:
#define PI 3.1416
The symbolic name PI may never be seen by compilers; it may be removed by the preprocessor before the source code even gets to a compiler. As a result, the name PI may not get entered into the symbol table. This can be confusing if you get an error during compilation involving the use of the constant, because the error message may refer to 3.1416, not PI. If PI were defined in a header file you didn’t write, you’d have no idea where that 3.1416 came from.
This problem can also crop up in a symbolic debugger, because, again, the name you’re programming with may not be in the symbol table.
Solution:
const double PI = 3.1416; //or static const...
The extension is available but not installed in this database.
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Sometimes offsetHeight will return zero because the element you've created has not been rendered in the Dom yet. I wrote this function for such circumstances:
function getHeight(element)
{
var e = element.cloneNode(true);
e.style.visibility = "hidden";
document.body.appendChild(e);
var height = e.offsetHeight + 0;
document.body.removeChild(e);
e.style.visibility = "visible";
return height;
}
In my case I had to compare column E and I.
I used conditional formatting with new rule. Formula was "=IF($E1<>$I1,1,0)" for highlights in orange and "=IF($E1=$I1,1,0)" to highlight in green.
Next problem is how many columns you want to highlight. If you open Conditional Formatting Rules Manager you can edit for each rule domain of applicability: Check "Applies to"
In my case I used "=$E:$E,$I:$I" for both rules so I highlight only two columns for differences - column I and column E.
Default migration generator does not handle default values (column modifiers are supported but do not include default
or null
), but you could create your own generator.
You can also manually update the migration file prior to running rake db:migrate
by adding the options to add_column
:
add_column :tweet, :retweets_count, :integer, :null => false, :default => 0
... and read Rails API
Try Ehcache? It allows you to plug in your own caching expiry algorithms so you could control your peek functionality.
You can serialize to disk, database, across a cluster etc...
For me, the viewport meta tag actually caused a horizontal scroll issue on the Blackberry.
I removed content="initial-scale=1.0; maximum-scale=1.0;
from the viewport tag and it fixed the issue. Below is my current viewport tag:
<meta name="viewport" content="user-scalable=0;"/>
Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.
Assuming your repository is called "my_repo", and it is stored in C:\svn_repos:
Create a file called "passwd" in "C:\svn_repos\my_repo\conf". This file should look like:
[Users]
username = password
john = johns_password
steve = steves_password
In C:\svn_repos\my_repo\conf\svnserve.conf set:
[general]
password-db = passwd
auth-access=read
auth-access=write
This will force users to log in to read or write to this repository.
Follow these steps for each repository, only including the appropriate users in the passwd
file for each repository.
I was facing the same issue.
I wanted to catch all the errors at a central place and transform them.
Following is the code for how I handled it.
Create the following class which implements ExceptionMapper
and add @Provider
annotation on this class. This will handle all the exceptions.
Override toResponse
method and return the Response object populated with customised data.
//ExceptionMapperProvider.java
/**
* exception thrown by restful endpoints will be caught and transformed here
* so that client gets a proper error message
*/
@Provider
public class ExceptionMapperProvider implements ExceptionMapper<Throwable> {
private final ErrorTransformer errorTransformer = new ErrorTransformer();
public ExceptionMapperProvider() {
}
@Override
public Response toResponse(Throwable throwable) {
//transforming the error using the custom logic of ErrorTransformer
final ServiceError errorResponse = errorTransformer.getErrorResponse(throwable);
final ResponseBuilder responseBuilder = Response.status(errorResponse.getStatus());
if (errorResponse.getBody().isPresent()) {
responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
responseBuilder.entity(errorResponse.getBody().get());
}
for (Map.Entry<String, String> header : errorResponse.getHeaders().entrySet()) {
responseBuilder.header(header.getKey(), header.getValue());
}
return responseBuilder.build();
}
}
// ErrorTransformer.java
/**
* Error transformation logic
*/
public class ErrorTransformer {
public ServiceError getErrorResponse(Throwable throwable) {
ServiceError serviceError = new ServiceError();
//add you logic here
serviceError.setStatus(getStatus(throwable));
serviceError.setBody(getBody(throwable));
serviceError.setHeaders(getHeaders(throwable));
}
private String getStatus(Throwable throwable) {
//your logic
}
private Optional<String> getBody(Throwable throwable) {
//your logic
}
private Map<String, String> getHeaders(Throwable throwable) {
//your logic
}
}
//ServiceError.java
/**
* error data holder
*/
public class ServiceError {
private int status;
private Map<String, String> headers;
private Optional<String> body;
//setters and getters
}
angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs
In your case you need to find a div with ID or class name. for class name you can use
var elems =$element.find('div') //returns all the div's in the $elements
angular.forEach(elems,function(v,k)){
if(angular.element(v).hasClass('class-name')){
console.log(angular.element(v));
}}
or you can use much simpler way by query selector
angular.element(document.querySelector('#id'))
angular.element(elem.querySelector('.classname'))
it is not as flexible as jQuery but what
git branch -d branch1 branch2 branch3
already works, but will be faster with Git 2.31 (Q1 2021).
Before, when removing many branches and tags, the code used to do so one ref at a time.
There is another API it can use to delete multiple refs, and it makes quite a lot of performance difference when the refs are packed.
See commit 8198907 (20 Jan 2021) by Phil Hord (phord
).
(Merged by Junio C Hamano -- gitster
-- in commit f6ef8ba, 05 Feb 2021)
8198907795
:usedelete_refs
when deleting tags or branchesAcked-by: Elijah Newren
Signed-off-by: Phil Hord
'
git tag -d
'(man) accepts one or more tag refs to delete, but each deletion is done by callingdelete_ref
on eachargv
.
This is very slow when removing from packed refs.
Usedelete_refs
instead so all the removals can be done inside a single transaction with a single update.Do the same for '
git branch -d
'(man).Since
delete_refs
performs all the packed-refs delete operations inside a single transaction, if any of the deletes fail then all them will be skipped.
In practice, none of them should fail since we verify the hash of each one before callingdelete_refs
, but some network error or odd permissions problem could have different results after this change.Also, since the file-backed deletions are not performed in the same transaction, those could succeed even when the packed-refs transaction fails.
After deleting branches, remove the branch config only if the branch ref was removed and was not subsequently added back in.
A manual test deleting 24,000 tags took about 30 minutes using
delete_ref
.
It takes about 5 seconds usingdelete_refs
.
I get this problem once, using a not official Apple cable.
Hope it helps.
To get the value from a textarea with an id you just have to do
Edited
$("#area1").val();
If you are having more than one element with the same id in the document then the HTML is invalid.
Dim wsh as new wshshell
chdir "Directory of Batch File"
wsh.run "Full Path of Batch File",vbnormalfocus, true
Done Son
holder.checkbox.setTag(row_id);
and
holder.checkbox.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
int row_id = (Integer) v.getTag();
checkboxes.put(row_id, c.isChecked());
}
});
I personally prefer the +
operator than append
:
for i in range(0, n):
list1 += [[i]]
But this is creating a new list every time, so might not be the best if performance is critical.
This is the safest solution:
git stash
Now you can do whatever you want without fear of conflicts.
For instance:
git checkout origin/master
If you want to include the remote changes in the master branch you can do:
git reset --hard origin/master
This will make you branch "master" to point to "origin/master".
In new version of jquery, could done it via following steps:
serializeArray()
push()
or similar methods to add additional params to the array,$.param(arr)
to get serialized string, which could be used as jquery ajax's data
param.Example code:
var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
// ...
}
I've been working on a function to work within a library for a client, and have been having a lot of trouble keeping the UI responsive during the sorts (even with only a few hundred results).
The function has to resort the entire table each AJAX pagination, as new data may require injection further up. This is what I had so far:
table
is the ID of the table being sorted.sort-attribute
, sort-direction
and the column attribute column
are all pre-set.Using some of the details above I managed to improve performance a bit.
function sorttable(table) {
var context = $('#' + table), tbody = $('#' + table + ' tbody'), sortfield = $(context).data('sort-attribute'), c, dir = $(context).data('sort-direction'), index = $(context).find('thead th[data-column="' + sortfield + '"]').index();
if (!sortfield) {
sortfield = $(context).data('id-attribute');
};
switch (dir) {
case "asc":
tbody.find('tr').sort(function (a, b) {
var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
// if a < b return 1
return sortvala < sortvalb ? 1
// else if a > b return -1
: sortvala > sortvalb ? -1
// else they are equal - return 0
: 0;
}).appendTo(tbody);
break;
case "desc":
default:
tbody.find('tr').sort(function (a, b) {
var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
// if a < b return 1
return sortvala > sortvalb ? 1
// else if a > b return -1
: sortvala < sortvalb ? -1
// else they are equal - return 0
: 0;
}).appendTo(tbody);
break;
}
In principle the code works perfectly, but it's painfully slow... are there any ways to improve performance?
An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.
select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo)
limit 1
My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...
SQLer
Here is the simplest way to track your mouse position
Html
<body id="mouse-position" ></body>
js
document.querySelector('#mouse-position').addEventListener('mousemove', (e) => {
console.log("mouse move X: ", e.clientX);
console.log("mouse move X: ", e.screenX);
}, );
EDITED MARCH 2019 now with programmatic pin color,
PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS
no longer relies on deprecated Charts API
var pinColor = "#FFFFFF";
var pinLabel = "A";
// Pick your pin (hole or no hole)
var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
var labelOriginHole = new google.maps.Point(12,15);
var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
var labelOriginFilled = new google.maps.Point(12,9);
var markerImage = { // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
path: pinSVGFilled,
anchor: new google.maps.Point(12,17),
fillOpacity: 1,
fillColor: pinColor,
strokeWeight: 2,
strokeColor: "white",
scale: 2,
labelOrigin: labelOriginFilled
};
var label = {
text: pinLabel,
color: "white",
fontSize: "12px",
}; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
this.marker = new google.maps.Marker({
map: map.MapObject,
//OPTIONAL: label: label,
position: this.geographicCoordinates,
icon: markerImage,
//OPTIONAL: animation: google.maps.Animation.DROP,
});
Assuming $WORKING_DIR
is set to the directory... this one-liner should do it:
if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi
(otherwise just replace with your directory)
I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:
HostingEnvironment.MapPath("~/Data/data.html")
Have you checked the equals method for the mockable class? If this one returns always true or you test the same instance against the same instance and the equal method is not overwritten (and therefor only checks against the references), then it returns true.
here's bash code for SCP with a .pem key file. Just save it to a script.sh file then run with 'sh script.sh'
Enjoy
#!/bin/bash
#Error function
function die(){
echo "$1"
exit 1
}
Host=ec2-53-298-45-63.us-west-1.compute.amazonaws.com
User=ubuntu
#Directory at sent destination
SendDirectory=scp
#File to send at host
FileName=filetosend.txt
#Key file
Key=MyKeyFile.pem
echo "Aperture in Process...";
#The code that will send your file scp
scp -i $Key $FileName $User@$Host:$SendDirectory || \
die "@@@@@@@Houston we have problem"
echo "########Aperture Complete#########";
You could use Number.toLocaleString()
:
var number = 1557564534;_x000D_
document.body.innerHTML = number.toLocaleString();_x000D_
// 1,557,564,534
_x000D_
Turned out there was some extra code in the AppModel that was messing things up:
in beforeFind
and afterFind
:
App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");
I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.
This is a direct string representation techniques : I see a lot of solutions mentioned, but I think most are looking at split. Split however does it at every occurrence of "." . What you would rather be looking for is partition.
string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]
FYI My Motorola Xyboard had an "Off" icon at the top of developer options. Once I tapped that it worked.
Spark 2.2+
Spark 2.2 introduces typedLit
to support Seq
, Map
, and Tuples
(SPARK-19254) and following calls should be supported (Scala):
import org.apache.spark.sql.functions.typedLit
df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withColumn("some_struct", typedLit(("foo", 1, 0.3)))
df.withColumn("some_map", typedLit(Map("key1" -> 1, "key2" -> 2)))
Spark 1.3+ (lit
), 1.4+ (array
, struct
), 2.0+ (map
):
The second argument for DataFrame.withColumn
should be a Column
so you have to use a literal:
from pyspark.sql.functions import lit
df.withColumn('new_column', lit(10))
If you need complex columns you can build these using blocks like array
:
from pyspark.sql.functions import array, create_map, struct
df.withColumn("some_array", array(lit(1), lit(2), lit(3)))
df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))
df.withColumn("some_map", create_map(lit("key1"), lit(1), lit("key2"), lit(2)))
Exactly the same methods can be used in Scala.
import org.apache.spark.sql.functions.{array, lit, map, struct}
df.withColumn("new_column", lit(10))
df.withColumn("map", map(lit("key1"), lit(1), lit("key2"), lit(2)))
To provide names for structs
use either alias
on each field:
df.withColumn(
"some_struct",
struct(lit("foo").alias("x"), lit(1).alias("y"), lit(0.3).alias("z"))
)
or cast
on the whole object
df.withColumn(
"some_struct",
struct(lit("foo"), lit(1), lit(0.3)).cast("struct<x: string, y: integer, z: double>")
)
It is also possible, although slower, to use an UDF.
Note:
The same constructs can be used to pass constant arguments to UDFs or SQL functions.
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.
First Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create a pointer that points to random memory address
*ptr = 20; //Dereference that pointer,
// and assign a value to random memory address.
//Depending on external (not inside your program) state
// this will either crash or SILENTLY CORRUPT another
// data structure in your program.
printf("%d", *ptr); //Print contents of same random memory address
// May or may not crash, depending on who owns this address
return 0;
}
Second Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create pointer to random memory address
int q = 50; //Create local variable with contents int 50
ptr = &q; //Update address targeted by above created pointer to point
// to local variable your program properly created
printf("%d", *ptr); //Happily print the contents of said local variable (q)
return 0;
}
The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.
Using it before is creating code that depends on uninitialized memory which will at best crash but at worst work sometimes, because the random memory address happens to be inside the memory space your program already owns. God help you if it overwrites a data structure you are using elsewhere in your program.
It's important to keep in mind that the MapReduce framework in Hadoop allows us only to
suggest the number of Map tasks for a job
which like Praveen pointed out above will correspond to the number of input splits for the task. Unlike it's behavior for the number of reducers (which is directly related to the number of files output by the MapReduce job) where we can
demand that it provide n reducers.
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Running it like this produces:
% echo "1 2" | test.py
6
I suspect IDLE is simply passing a single string to your script. The first input()
is slurping the entire string. Notice what happens if you put some print statements in after the calls to input()
:
width = input()
print(width)
height = input()
print(height)
Running echo "1 2" | test.py
produces
1 2
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 5, in <module>
height = input()
EOFError: EOF when reading a line
Notice the first print statement prints the entire string '1 2'
. The second call to input()
raises the EOFError
(end-of-file error).
So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input()
once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what
width, height = map(int, input().split())
does.
Note, there are other ways to pass input to your program. If you had run test.py
in a terminal, then you could have typed 1
and 2
separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1
and 2
programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with
test.py 1 2
To export a single file from a remote:
git archive --remote=ssh://host/pathto/repo.git HEAD README.md | tar -x
This will download the file README.md
to your current directory.
If you want the contents of the file exported to STDOUT:
git archive --remote=ssh://host/pathto/repo.git HEAD README.md | tar -xO
You can provide multiple paths at the end of the command.
You've already got the correct answer from Gursel Koca but I believe that there's a good chance that this is not what you really want to do. How about parsing the key-values instead?
import java.util.Enumeration;
import java.util.Hashtable;
class SplitIt {
public static void main(String args[]) {
String person = "name=john age=13 year=2001";
for (String p : person.split("\\s")) {
String[] keyValue = p.split("=");
System.out.println(keyValue[0] + " = " + keyValue[1]);
}
}
}
output:
name = john
age = 13
year = 2001
Instead of using align-self: center
use align-items: center
.
There's no need to change flex-direction
or use text-align
.
Here's your code, with one adjustment, to make it all work:
ul {
height: 100%;
}
li {
display: flex;
justify-content: center;
/* align-self: center; <---- REMOVE */
align-items: center; /* <---- NEW */
background: silver;
width: 100%;
height: 20%;
}
The align-self
property applies to flex items. Except your li
is not a flex item because its parent – the ul
– does not have display: flex
or display: inline-flex
applied.
Therefore, the ul
is not a flex container, the li
is not a flex item, and align-self
has no effect.
The align-items
property is similar to align-self
, except it applies to flex containers.
Since the li
is a flex container, align-items
can be used to vertically center the child elements.
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
html, body {_x000D_
height: 100%;_x000D_
}_x000D_
ul {_x000D_
height: 100%;_x000D_
}_x000D_
li {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
/* align-self: center; */_x000D_
align-items: center;_x000D_
background: silver;_x000D_
width: 100%;_x000D_
height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
<li>This is the text</li>_x000D_
</ul>
_x000D_
Technically, here's how align-items
and align-self
work...
The align-items
property (on the container) sets the default value of align-self
(on the items). Therefore, align-items: center
means all flex items will be set to align-self: center
.
But you can override this default by adjusting the align-self
on individual items.
For example, you may want equal height columns, so the container is set to align-items: stretch
. However, one item must be pinned to the top, so it is set to align-self: flex-start
.
How is the text a flex item?
Some people may be wondering how a run of text...
<li>This is the text</li>
is a child element of the li
.
The reason is that text that is not explicitly wrapped by an inline-level element is algorithmically wrapped by an inline box. This makes it an anonymous inline element and child of the parent.
From the CSS spec:
9.2.2.1 Anonymous inline boxes
Any text that is directly contained inside a block container element must be treated as an anonymous inline element.
The flexbox specification provides for similar behavior.
Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.
Hence, the text in the li
is a flex item.
What you need is something called Document Listener. See How to Write a Document Listener.
I have uploaded the project you can directly open in eclipse and run that's all https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA
Thank You
The reason is that php cannot find the correct path of mysql.sock
.
Please make sure that your mysql is running first.
Then, please confirm that which path is the mysql.sock
located, for example /tmp/mysql.sock
then add this path string to php.ini:
Finally, restart Apache.
I recently used the following in an application that is working well for my needs.
.htaccess
<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On
# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>
index.php
foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
// Figure out what you want to do with the URL parts.
}
$.datepicker.setDefaults({
closeText: "??",
prevText: "<??",
nextText: "??>",
currentText: "??",
monthNames: [ "??","??","??","??","??","??",
"??","??","??","??","???","???" ],
monthNamesShort: [ "??","??","??","??","??","??",
"??","??","??","??","???","???" ],
dayNames: [ "???","???","???","???","???","???","???" ],
dayNamesShort: [ "??","??","??","??","??","??","??" ],
dayNamesMin: [ "?","?","?","?","?","?","?" ],
weekHeader: "?",
dateFormat: "yy-mm-dd",
firstDay: 1,
isRTL: false,
showMonthAfterYear: true,
yearSuffix: "?"
});
the i18n code could be copied from https://github.com/jquery/jquery-ui/tree/master/ui/i18n
In order to center text in md files you can use the center tag like html tag:
<center>Centered text</center>
For bootstrap 4 if you are using Sass here is the variable to edit
// Grid containers
//
// Define the maximum width of `.container` for different screen sizes.
$container-max-widths: (
sm: 540px,
md: 720px,
lg: 960px,
xl: 1140px
) !default;
To override this variable I declared $container-max-widths without the !default in my .sass file before importing bootstrap.
Note : I only needed to change the xl value so I didn't care to think about breakpoints.
child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.
so you can solve your problem using child_process.spawn as used below.
var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('code ' + code.toString());
});
The graphicx
package provides the command \resizebox{width}{height}{object}
:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}
UPDATE
You can use Apache Commons Codec (version 1.7+) to do this job for you.
DigestUtils.sha1Hex(stringToConvertToSHexRepresentation)
Thanks to @Jon Onstott for this suggestion.
Old Answer
Convert your Byte Array to Hex String. Real's How To tells you how.
return byteArrayToHexString(md.digest(convertme))
and (copied from Real's How To)
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
BTW, you may get more compact representation using Base64. Apache Commons Codec API 1.4, has this nice utility to take away all the pain. refer here
brew install rbenv ruby-build
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile
rbenv install 2.6.5
rbenv global 2.6.5
ruby -v
Unfortunately we need to run docker-compose logs
separately from docker-compose run
. In order to get this to work reliably we need to suppress the docker-compose run
exit status then redirect the log and exit with the right status.
#!/bin/bash
set -euo pipefail
docker-compose run app | tee app.log || failed=yes
docker-compose logs --no-color > docker-compose.log
[[ -z "${failed:-}" ]] || exit 1
Both methods ensure that your process doesn't end before all of your threads have ended.
The join method has your thread of the main
function explicitly wait for all threads that are to be "joined".
The pthread_exit
method terminates your main
function and thread in a controlled way. main
has the particularity that ending main
otherwise would be terminating your whole process including all other threads.
For this to work, you have to be sure that none of your threads is using local variables that are declared inside them main
function. The advantage of that method is that your main
doesn't have to know all threads that have been started in your process, e.g because other threads have themselves created new threads that main
doesn't know anything about.
This problem was due to the use of AngularJS 1.1.5 (which was unstable, and obviously had some bug or different implementation of the routing than it was in 1.0.7)
turning it back to 1.0.7 solved the problem instantly.
have tried the 1.2.0rc1 version, but have not finished testing as I had to rewrite some of the router functionality since they took it out of the core.
anyway, this problem is fixed when using AngularJS vs 1.0.7.
I realize this is an old question, but I came across it when doing something similar.
Using SASS, you have a very elegant way to convert RGBA to hex ARGB: ie-hex-str
. I've used it here in a mixin.
@mixin ie8-rgba ($r, $g, $b, $a){
$rgba: rgba($r, $g, $b, $a);
$ie8-rgba: ie-hex-str($rgba);
.lt-ie9 &{
background-color: transparent;
filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#{$ie8-rgba}', endColorstr='#{$ie8-rgba}');
}
}
.transparent{
@include ie8-rgba(88,153,131,.8);
background-color: rgba(88,153,131,.8);
}
outputs:
.transparent {_x000D_
background-color: rgba(88, 153, 131, 0.8);_x000D_
}_x000D_
.lt-ie9 .transparent {_x000D_
background-color: transparent;_x000D_
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#CC589983', endColorstr='#CC589983');_x000D_
zoom: 1;_x000D_
}
_x000D_
If you want to detect links with http:// OR without http:// OR ftp OR other possible cases like removing trailing punctuation at the end, take a look at this code.
https://jsfiddle.net/AndrewKang/xtfjn8g3/
A simple way to use that is to use NPM
npm install --save url-knife
One more idea for you. Create a rake task that calls rails server with the -p.
task "start" => :environment do
system 'rails server -p 3001'
end
then call rake start
instead of rails server
If you are here because your pytorch always gives False
for torch.cuda.is_available()
that's probably because you installed your pytorch version without GPU support. (Eg: you coded up in laptop then testing on server).
The solution is to uninstall and install pytorch again with the right command from pytorch downloads page. Also refer this pytorch issue.
malloc()
and calloc()
are functions from the C standard library that allow dynamic memory allocation, meaning that they both allow memory allocation during runtime.
Their prototypes are as follows:
void *malloc( size_t n);
void *calloc( size_t n, size_t t)
There are mainly two differences between the two:
Behavior: malloc()
allocates a memory block, without initializing it, and reading the contents from this block will result in garbage values. calloc()
, on the other hand, allocates a memory block and initializes it to zeros, and obviously reading the content of this block will result in zeros.
Syntax: malloc()
takes 1 argument (the size to be allocated), and calloc()
takes two arguments (number of blocks to be allocated and size of each block).
The return value from both is a pointer to the allocated block of memory, if successful. Otherwise, NULL will be returned indicating the memory allocation failure.
Example:
int *arr;
// allocate memory for 10 integers with garbage values
arr = (int *)malloc(10 * sizeof(int));
// allocate memory for 10 integers and sets all of them to 0
arr = (int *)calloc(10, sizeof(int));
The same functionality as calloc()
can be achieved using malloc()
and memset()
:
// allocate memory for 10 integers with garbage values
arr= (int *)malloc(10 * sizeof(int));
// set all of them to 0
memset(arr, 0, 10 * sizeof(int));
Note that malloc()
is preferably used over calloc()
since it's faster. If zero-initializing the values is wanted, use calloc()
instead.
Converting a Java Keystore into PEM Format
The most precise answer of all must be that this is NOT possible.
A Java keystore is merely a storage facility for cryptographic keys and certificates while PEM is a file format for X.509 certificates only.
There is an open-source javascript plugin that does just that, but for any browser - debugout.js
Debugout.js records and save console.logs so your application can access them. Full disclosure, I wrote it. It formats different types appropriately, can handle nested objects and arrays, and can optionally put a timestamp next to each log. You can also toggle live-logging in one place, and without having to remove all your logging statements.
Use entrySet
,
/**
*Output:
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08
B's new balance: 1123.22
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MainClass {
public static void main(String args[]) {
HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("A", new Double(3434.34));
hm.put("B", new Double(123.22));
hm.put("C", new Double(1378.00));
hm.put("D", new Double(99.22));
hm.put("E", new Double(-19.08));
Set<Map.Entry<String, Double>> set = hm.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
double balance = hm.get("B");
hm.put("B", balance + 1000);
System.out.println("B's new balance: " + hm.get("B"));
}
}
see complete example here:
I'm going to take a stab in the dark and guess you're talking about Windows. In a nutshell, kernel mode has full access to hardware, but user mode doesn't. For instance, many if not most device drivers are written in kernel mode because they need to control finer details of their hardware.
See also this wikibook.
The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.
Your criticism is entirely justified.
I discuss this problem in detail here:
Closing over the loop variable considered harmful
Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.
I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.
The for
loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.
For all databases query sys.sysprocesses
SELECT * FROM sys.sysprocesses WHERE open_tran = 1
For the current database use:
DBCC OPENTRAN
The same problem was coming for my phone and this resolved the problem:
Go to Application Manager
/ Apps
from Settings.
Select Google Play Services
.
Click Uninstall Updates
button to the right of the Force Stop
button.
Once the updates are uninstalled, you should see Disable
button
which means you are done.
You will see lots of free space available now.
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
If you have a specific integer timestamp to insert/update, you can use PHP date() function with your timestamp as second arg :
date("Y-m-d H:i:s", $myTimestamp)
To make an unit test specifically on the abstract class, you should derive it for testing purpose, test base.method() results and intended behaviour when inheriting.
You test a method by calling it so test an abstract class by implementing it...
A handle is like a primary key value of a record in a database.
edit 1: well, why the downvote, a primary key uniquely identifies a database record, and a handle in the Windows system uniquely identifies a window, an opened file, etc, That's what I'm saying.
Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
if you are on linux, edit the /etc/php/php.ini
(or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment
;extension=imap.so
so that it becomes like this:
extension=imap.so
Then, restart the apache by
# /etc/rc.d/httpd restart
You have more going on than you said. I ran the following expanded test from your example:
public class test {
public static void main(String[] args) {
Object[][] someArray = new Object[5][];
someArray[0] = new Object[10];
someArray[1] = null;
someArray[2] = new Object[1];
someArray[3] = null;
someArray[4] = new Object[5];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i] != null) {
System.out.println("not null");
} else {
System.out.println("null");
}
}
}
}
and got the expected output:
$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null
Are you possibly trying to check the lengths of someArray[index]?
Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error
Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart
I followed the suggestion and added the logging.properties file. And below was my reason of failure:
java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded
The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.
It may be helpful for someone to know that this was happening on OpenShift JBoss gear.
There are several ways you can achieve this. This sets the size of the history file to 0:
export HISTFILESIZE=0
This sets the history file to /dev/null
, effectively disabling it:
export HISTFILE=/dev/null
For individual commands, you can prefix the command with a space and it won't be saved in the history file. Note that this requires you have the ignorespace
value included in the $HISTCONTROL
environment variable (man bash and search for ignorespace
for more details).
I think it's worth mentioning how the Underscore's _.each() works internally. The _.each(list, iteratee) checks if the passed list is an array object, or an object.
In the case that the list is an array, iteratee arguments will be a list element and index as in the following example:
var a = ['I', 'like', 'pancakes', 'a', 'lot', '.'];
_.each( a, function(v, k) { console.log( k + " " + v); });
0 I
1 like
2 pancakes
3 a
4 lot
5 .
On the other hand, if the list argument is an object the iteratee will take a list element and a key:
var o = {name: 'mike', lastname: 'doe', age: 21};
_.each( o, function(v, k) { console.log( k + " " + v); });
name mike
lastname doe
age 21
For reference this is the _.each() code from Underscore.js 1.8.3
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
Simply restart the Android Studio. In my case, I was offline before starting the Android Studio, but online when I did restart.
Below code is for getting data from online server using GET method and okHTTP library for android kotlin...
Log.e("Main",response.body!!.string())
in above line !! is the thing using which you can get the json from response body
val client = OkHttpClient()
val request: Request = Request.Builder()
.get()
.url("http://172.16.10.126:8789/test/path/jsonpage")
.addHeader("", "")
.addHeader("", "")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle this
Log.e("Main","Try again latter!!!")
}
override fun onResponse(call: Call, response: Response) {
// Handle this
Log.e("Main",response.body!!.string())
}
})
I agree with user3158900, and I only differ slightly in the way I use it:
{{Form::label('sports', 'Sports')}}
{{Form::select('sports',$aSports,null,array('multiple'=>'multiple','name'=>'sports[]'))}}
However, in my experience the 3rd parameter of the select is a string only, so for repopulating data for a multi-select I have had to do something like this:
<select multiple="multiple" name="sports[]" id="sports">
@foreach($aSports as $aKey => $aSport)
@foreach($aItem->sports as $aItemKey => $aItemSport)
<option value="{{$aKey}}" @if($aKey == $aItemKey)selected="selected"@endif>{{$aSport}}</option>
@endforeach
@endforeach
</select>
Use @RequestParam
@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){
Item i = itemDao.findOne(itemid);
String itemName = i.getItemName();
String price = i.getPrice();
return i;
}
I use:
from pathlib import Path
import platform
import tempfile
tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())
This is because on MacOS, i.e. Darwin, tempfile.gettempdir()
and os.getenv('TMPDIR')
return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'
; it is one that I do not always want.
For Windows users.
This happens because the MondgDB server is stopped. to fix this you can,
1 search for Services ,for that search using the left bottom corner search option.
2 then there is a gear icon named with 'Services'.
3 after clicking that you will get a window with lot of services
4 scroll down and you will find 'MongoDB server (MongoDB)'.
5 so you will see that there is an option to start the service.
6 start it.
1 then open your command prompt.
2 type mongod
now you can connect to your server.
this steps also working fine if your sql server service down. (find sql server services)
I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
...
let headers = {"Content-Type": "application/json"};
if (token) {
headers["Authorization"] = `Token ${token}`;
}
return fetch("/api/instruments/", {headers,})
.then(res => {
...
I was running apache.
What solved this problem for me was changing WSGIPassAuthorization
to 'On'
in wsgi.conf
.
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config
, I did this:
container_commands:
01wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.
I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.
# Enable TCP/IP
Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable
# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433
# Modify TCP/IP properties to enable an IP address
$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }
# Restart SQL Server
Restart-Service 'MSSQL$SQLEXPRESS'
Beside using loop and for comprehension, you could also use map
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
The code marked @Before
is executed before each test, while @BeforeClass
runs once before the entire test fixture. If your test class has ten tests, @Before
code will be executed ten times, but @BeforeClass
will be executed only once.
In general, you use @BeforeClass
when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass
into @Before
, but your test run may take longer. Note that the code marked @BeforeClass
is run as static initializer, therefore it will run before the class instance of your test fixture is created.
In JUnit 5, the tags @BeforeEach
and @BeforeAll
are the equivalents of @Before
and @BeforeClass
in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.
Try this: Create a plain div
without any style or content outside of the red div
. Now you can use a loop over all styles of the plain div
and assign then to your inner div
to reset all styles.
Of course this doesn't work if someone assigns styles to all div
s (i.e. without using a class. CSS would be div { ... }
).
The usual solution for problems like this is to give your div
a distinct class. That way, web designers of the sites can adjust the styling of your div
to fit into the rest of the design.
Use a variable as an object key
let key = 'myKey';
let data = {[key] : 'name1'; }
In your version rand() % 10000
will yield an integer between 0
and 9999
. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.
It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG
double r2()
{
return (double)rand() / (double)RAND_MAX ;
}
Use (double)rand() / (double)((unsigned)RAND_MAX + 1)
if exclusion of 1.0 was intentional.
The major difference is that
Ternary Operator expression expr1 ?: expr3
returns expr1
if expr1
evaluates to
TRUE
but on the other hand Null Coalescing Operator expression (expr1) ?? (expr2)
evaluates to expr1
if expr1
is not NULL
Ternary
Operator expr1 ?: expr3
emit a notice if the left-hand side
value (expr1)
does not exist but on the other hand Null Coalescing Operator (expr1) ?? (expr2)
In particular, does not emit a notice if the left-hand side value (expr1)
does
not exist, just like isset()
.
TernaryOperator is left associative
((true ? 'true' : false) ? 't' : 'f');
Null Coalescing Operator is right associative
($a ?? ($b ?? $c));
Now lets explain the difference between by example :
Ternary Operator (?:)
$x='';
$value=($x)?:'default';
var_dump($value);
// The above is identical to this if/else statement
if($x){
$value=$x;
}
else{
$value='default';
}
var_dump($value);
Null Coalescing Operator (??)
$value=($x)??'default';
var_dump($value);
// The above is identical to this if/else statement
if(isset($x)){
$value=$x;
}
else{
$value='default';
}
var_dump($value);
Here is the table that explain the difference and similarity between '??'
and ?:
Special Note : null coalescing operator and ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; and return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.
extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<RadioGroup
android:id="@+id/radio_group_list_selector"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#80000000"
android:padding="4dp" >
<RadioButton
android:id="@+id/radioPopular"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="@string/Popular"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:button="@null"
android:background="@drawable/shape_radiobutton"
android:textColor="@drawable/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioAZ"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/AZ"
android:layout_weight="1"
android:button="@null"
android:background="@drawable/shape_radiobutton2"
android:textColor="@drawable/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioCategory"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/Category"
android:layout_weight="1"
android:button="@null"
android:background="@drawable/shape_radiobutton2"
android:textColor="@drawable/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioNearBy"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/NearBy"
android:layout_weight="1"
android:button="@null"
android:background="@drawable/shape_radiobutton3"
android:textColor="@drawable/textcolor_radiobutton" />
</RadioGroup>
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
android:scrollbars="vertical" />
I just used the following:
import unicodedata
message = unicodedata.normalize("NFKD", message)
Check what documentation says about it:
unicodedata.normalize(form, unistr) Return the normal form form for the Unicode string unistr. Valid values for form are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).
For each character, there are two normal forms: normal form C and normal form D. Normal form D (NFD) is also known as canonical decomposition, and translates each character into its decomposed form. Normal form C (NFC) first applies a canonical decomposition, then composes pre-combined characters again.
In addition to these two forms, there are two additional normal forms based on compatibility equivalence. In Unicode, certain characters are supported which normally would be unified with other characters. For example, U+2160 (ROMAN NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I). However, it is supported in Unicode for compatibility with existing character sets (e.g. gb2312).
The normal form KD (NFKD) will apply the compatibility decomposition, i.e. replace all compatibility characters with their equivalents. The normal form KC (NFKC) first applies the compatibility decomposition, followed by the canonical composition.
Even if two unicode strings are normalized and look the same to a human reader, if one has combining characters and the other doesn’t, they may not compare equal.
Solves it for me. Simple and easy.
Alciende's answer didn't quite work for me in Safari for whatever reason just now, but did after a minor modification:
function textAreaAdjust(o) {
o.style.height = "1px";
setTimeout(function() {
o.style.height = (o.scrollHeight)+"px";
}, 1);
}
Hope this helps someone
http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.
try {
// your code
} catch (Exception1 | Exception2 ex) {
// Handle 2 exceptions in Java 7
}
I'm making study cards, and this thread was helpful, just wanted to put in my two cents.
The isinstance
built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:
def my_print(text, begin, end):
"Print 'text' in UPPER between 'begin' and 'end' in lower"
try:
print begin.lower() + text.upper() + end.lower()
except (AttributeError, TypeError):
raise AssertionError('Input variables should be strings')
This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)
Try below code,
$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
$fh = fopen($cookieFile, "w");
fwrite($fh, "");
fclose($fh);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
$response = curl_exec($ch);
}
curl_close($ch);
$result = json_decode($response, true);
echo '<pre>';
var_dump($result);
echo'</pre>';
I hope this will help you.
Best regards, Dasitha.
Ok solved it.
Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting
In my app.js routing config:
$routeProvider.when('/pages/:name', {
templateUrl: '/pages/home.html',
controller: CMSController
});
Then in my CMS controller:
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
$.get($route.current.templateUrl, function (data) {
$scope.$apply(function () {
$('#views').html($compile(data)($scope));
});
});
...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
With #views being my <div id="views" ng-view></div>
So now it works with standard routing and dynamic routing.
To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio
into my browser and hey presto portfolio.html was displayed....
Updated Added $apply and $compile to the html so that dynamic content can be injected.
I also want to do the same thing: migrate a db from a standalone redis instance to a another redis instances(redis sentinel).
Because the data is not critical(session data), i will give https://github.com/yaauie/redis-copy a try.
One tiny addition to JB Jansen's answer - in the main readdir()
loop I'd add this:
if (dir->d_type == DT_REG)
{
printf("%s\n", dir->d_name);
}
Just checking if it's really file, not (sym)link, directory, or whatever.
NOTE: more about struct dirent
in libc
documentation.
Where it says "Accept requests from these HTTP referrers (websites) (Optional)" you don't need to have any referrer listed. So click the X beside localhost on this page but continue to use your key.
It should then work after a few minutes.
Changes made can sometimes take a few minutes to take effect so wait a few minutes before testing again.
In addition to MR Chandru"s answer above, do these steps after configuring XAMPP:
C:\xampp
xampp-control.exe
, the XAMPP Control PanelC:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
or
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
The XAMPP Control Panel should now auto-start whenever you reboot Windows.
As the Python documentation says:
sys.maxsize
The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.
In my computer (Linux x86_64):
>>> import sys
>>> print sys.maxsize
9223372036854775807
I think this might help.
SELECT datetime(strftime('%s','now'), 'unixepoch', 'localtime');
create a filter.js and you can make this as reusable
angular.module('yourmodule').filter('date', function($filter)
{
return function(input)
{
if(input == null){ return ""; }
var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
return _date.toUpperCase();
};
});
view
<span>{{ d.time | date }}</span>
or in controller
var filterdatetime = $filter('date')( yourdate );
You could use get
twice:
example_dict.get('key1', {}).get('key2')
This will return None
if either key1
or key2
does not exist.
Note that this could still raise an AttributeError
if example_dict['key1']
exists but is not a dict (or a dict-like object with a get
method). The try..except
code you posted would raise a TypeError
instead if example_dict['key1']
is unsubscriptable.
Another difference is that the try...except
short-circuits immediately after the first missing key. The chain of get
calls does not.
If you wish to preserve the syntax, example_dict['key1']['key2']
but do not want it to ever raise KeyErrors, then you could use the Hasher recipe:
class Hasher(dict):
# https://stackoverflow.com/a/3405143/190597
def __missing__(self, key):
value = self[key] = type(self)()
return value
example_dict = Hasher()
print(example_dict['key1'])
# {}
print(example_dict['key1']['key2'])
# {}
print(type(example_dict['key1']['key2']))
# <class '__main__.Hasher'>
Note that this returns an empty Hasher when a key is missing.
Since Hasher
is a subclass of dict
you can use a Hasher in much the same way you could use a dict
. All the same methods and syntax is available, Hashers just treat missing keys differently.
You can convert a regular dict
into a Hasher
like this:
hasher = Hasher(example_dict)
and convert a Hasher
to a regular dict
just as easily:
regular_dict = dict(hasher)
Another alternative is to hide the ugliness in a helper function:
def safeget(dct, *keys):
for key in keys:
try:
dct = dct[key]
except KeyError:
return None
return dct
So the rest of your code can stay relatively readable:
safeget(example_dict, 'key1', 'key2')
Suppose we haven't used the "@" operator then our code would look like this:
$fileHandle = fopen($fileName, $writeAttributes);
And what if the file we are trying to open is not found? It will show an error message.
To suppress the error message we are using the "@" operator like:
$fileHandle = @fopen($fileName, $writeAttributes);
If you are using Sql Server Management Studio 2008 there are certain data fields you can view in the object explorer details window. Simply browse to and select the tables folder. In the details view you are able to right-click the column titles and add fields to the "report". Your mileage may vary if you are on SSMS 2008 express.
Hold down Ctrl+Shift+P (or cmd on Mac), select "Change Language Mode" and there it is.
But I still can't find a way to make VS Code recognized files with specific extension as some certain language.
Sub HighlightSpecificValue()
'PURPOSE: Highlight all cells containing a specified values
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
'What value do you want to find?
fnd = InputBox("I want to hightlight cells containing...", "Highlight")
'End Macro if Cancel Button is Clicked or no Text is Entered
If fnd = vbNullString Then Exit Sub
Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)
enter code here
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)
'Test to see if anything was found
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Else
GoTo NothingFound
End If
Set rng = FoundCell
'Loop until cycled through all unique finds
Do Until FoundCell Is Nothing
'Find next cell with fnd value
Set FoundCell = myRange.FindNext(after:=FoundCell)
'Add found cell to rng range variable
Set rng = Union(rng, FoundCell)
'Test to see if cycled through to first found cell
If FoundCell.Address = FirstFound Then Exit Do
Loop
'Highlight Found cells yellow
rng.Interior.Color = RGB(255, 255, 0)
Dim fnd1 As String
fnd1 = "Rah"
'Condition highlighting
Set FoundCell = myRange.FindNext(after:=FoundCell)
If FoundCell.Value("rah") Then
rng.Interior.Color = RGB(255, 0, 0)
ElseIf FoundCell.Value("Nav") Then
rng.Interior.Color = RGB(0, 0, 255)
End If
'Report Out Message
MsgBox rng.Cells.Count & " cell(s) were found containing: " & fnd
Exit Sub
'Error Handler
NothingFound:
MsgBox "No cells containing: " & fnd & " were found in this worksheet"
End Sub
Here's how:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
For comparison between two times use time.Sub()
// utc life
loc, _ := time.LoadLocation("UTC")
// setup a start and end time
createdAt := time.Now().In(loc).Add(1 * time.Hour)
expiresAt := time.Now().In(loc).Add(4 * time.Hour)
// get the diff
diff := expiresAt.Sub(createdAt)
fmt.Printf("Lifespan is %+v", diff)
The program outputs:
Lifespan is 3h0m0s
Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.
npm install jquery --save
Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.
// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;
// You can use it now
$('body').css('background-color', 'orange');
// Here you can add the code for different plugins
I solved this exact problem today and stumbled onto this unanswered question by chance during the process.
First, ensure you've properly setup Firebase for Android as documented here: https://firebase.google.com/docs/android/setup. Then, make sure you are compiling the latest version of the Firebase APIs (9.2.0) and the Google Play Services APIs (9.2.0) that you are using. My gradle dependencies look something like this:
dependencies {
...
compile 'com.google.android.gms:play-services-location:9.2.0'
compile 'com.google.firebase:firebase-core:9.2.0'
compile 'com.google.firebase:firebase-auth:9.2.0'
compile 'com.google.firebase:firebase-messaging:9.2.0'
}
Hope this helps!
Jquery code which contains simple ajax :
$("#product").on("input", function(event) {
var data=$("#nameform").serialize();
$.post("./__partails/search-productbyCat.php",data,function(e){
$(".result").empty().append(e);
});
});
Html elements you can use any element:
<form id="nameform">
<input type="text" name="product" id="product">
</form>
php Code:
$pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
$Catagoryf=$_POST['product'];
$pricef=$_POST['price'];
$colorf=$_POST['color'];
$stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
$stmtcat->execute(array($Catagoryf));
while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
$iddb=$result['ID'];
$namedb=$result['Name'];
$pricedb=$result['Price'];
$colordb=$result['Color'];
echo "<tr>";
echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>';
echo "<td><pre>$pricedb</pre></td>";
echo "<td><pre> $colordb</pre>";
echo "</tr>";
The easy way
Info.plist
First things first. You need to add your descriptive string in the info.plist file for the keys NSLocationWhenInUseUsageDescription
or NSLocationAlwaysUsageDescription
depending on what kind of service you are requesting
Code
import Foundation
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
let manager: CLLocationManager
var locationManagerClosures: [((userLocation: CLLocation) -> ())] = []
override init() {
self.manager = CLLocationManager()
super.init()
self.manager.delegate = self
}
//This is the main method for getting the users location and will pass back the usersLocation when it is available
func getlocationForUser(userLocationClosure: ((userLocation: CLLocation) -> ())) {
self.locationManagerClosures.append(userLocationClosure)
//First need to check if the apple device has location services availabel. (i.e. Some iTouch's don't have this enabled)
if CLLocationManager.locationServicesEnabled() {
//Then check whether the user has granted you permission to get his location
if CLLocationManager.authorizationStatus() == .NotDetermined {
//Request permission
//Note: you can also ask for .requestWhenInUseAuthorization
manager.requestWhenInUseAuthorization()
} else if CLLocationManager.authorizationStatus() == .Restricted || CLLocationManager.authorizationStatus() == .Denied {
//... Sorry for you. You can huff and puff but you are not getting any location
} else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
// This will trigger the locationManager:didUpdateLocation delegate method to get called when the next available location of the user is available
manager.startUpdatingLocation()
}
}
}
//MARK: CLLocationManager Delegate methods
@objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
manager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
//Because multiple methods might have called getlocationForUser: method there might me multiple methods that need the users location.
//These userLocation closures will have been stored in the locationManagerClosures array so now that we have the users location we can pass the users location into all of them and then reset the array.
let tempClosures = self.locationManagerClosures
for closure in tempClosures {
closure(userLocation: newLocation)
}
self.locationManagerClosures = []
}
}
Usage
self.locationManager = LocationManager()
self.locationManager.getlocationForUser { (userLocation: CLLocation) -> () in
print(userLocation)
}
In Java 8:
List<WorldLocation> locations = new ArrayList<>();
.getMap(locations.stream().toArray(WorldLocation[]::new));
Each type of integer has a different range of storage capacity
Type Capacity
Int16 -- (-32,768 to +32,767)
Int32 -- (-2,147,483,648 to +2,147,483,647)
Int64 -- (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
As stated by James Sutherland in his answer:
int
andInt32
are indeed synonymous;int
will be a little more familiar looking,Int32
makes the 32-bitness more explicit to those reading your code. I would be inclined to use int where I just need 'an integer',Int32
where the size is important (cryptographic code, structures) so future maintainers will know it's safe to enlarge anint
if appropriate, but should take care changingInt32
variables in the same way.The resulting code will be identical: the difference is purely one of readability or code appearance.
This is something I wind up looking for repeatedly, even though I wrote myself a nice little function a while ago. So, I figured others might benefit from having it and maybe I'll even find it here, myself. hahaha
It's pretty simple to paste into your script and use. Just pass it a folder object.
I think it requires PowerShell 3 just because of the -directory flag on the Get-ChildItem command, but I'm sure it can be easily adapted, if need be.
function Get-TreeSize ($folder = $null)
{
#Function to get recursive folder size
$result = @()
$folderResult = "" | Select-Object FolderPath, FolderName, SizeKB, SizeMB, SizeGB, OverThreshold
$contents = Get-ChildItem $folder.FullName -recurse -force -erroraction SilentlyContinue -Include * | Where-Object {$_.psiscontainer -eq $false} | Measure-Object -Property length -sum | Select-Object sum
$sizeKB = [math]::Round($contents.sum / 1000,3) #.ToString("#.##")
$sizeMB = [math]::Round($contents.sum / 1000000,3) #.ToString("#.##")
$sizeGB = [math]::Round($contents.sum / 1000000000,3) #.ToString("#.###")
$folderResult.FolderPath = $folder.FullName
$folderResult.FolderName = $folder.BaseName
$folderResult.SizeKB = $sizeKB
$folderresult.SizeMB = $sizeMB
$folderresult.SizeGB = $sizeGB
$result += $folderResult
return $result
}
#Use the function like this for a single directory
$topDir = get-item "C:\test"
Get-TreeSize ($topDir)
#Use the function like this for all top level folders within a direcotry
#$topDir = gci -directory "\\server\share\folder"
$topDir = Get-ChildItem -directory "C:\test"
foreach ($folderPath in $topDir) {Get-TreeSize $folderPath}
You will need to get the textbox via javascript when moving the mouse over it and change its type
to text
. And when moving it out, you will want to change it back to password
. No chance of doing this in pure CSS.
HTML:
<input type="password" name="password" id="myPassword" size="30" />
<img src="theicon" onmouseover="mouseoverPass();" onmouseout="mouseoutPass();" />
JS:
function mouseoverPass(obj) {
var obj = document.getElementById('myPassword');
obj.type = "text";
}
function mouseoutPass(obj) {
var obj = document.getElementById('myPassword');
obj.type = "password";
}
If you don't want to use CSS try this one between your rows:
<tr>
<td class="divider"><hr /></td>
</tr>
Cheers!!
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
Though I am 3/4 of a month late, you still execute the following after your where clauses are defined... $this->db->get("tbl_name");
Just in case anyone comes looking a solution for this problem.
The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.
$1
, $2
, $3
, ... are the positional parameters."$@"
is an array-like construct of all positional parameters, {$1, $2, $3 ...}
."$*"
is the IFS expansion of all positional parameters, $1 $2 $3 ...
.$#
is the number of positional parameters.$-
current options set for the shell.$$
pid of the current shell (not subshell).$_
most recent parameter (or the abs path of the command to start the current shell immediately after startup).$IFS
is the (input) field separator.$?
is the most recent foreground pipeline exit status.$!
is the PID of the most recent background command.$0
is the name of the shell or shell script.Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.
For a comprehensive index, please see the Reference Manual Variable Index.
If you're using Guava, you can take a functional approach and do the following
FluentIterable.from(list).find(new Predicate<MyObject>() {
public boolean apply(MyObject input) {
return "John".equals(input.getName());
}
}).Any();
which looks a little verbose. However the predicate is an object and you can provide different variants for different searches. Note how the library itself separates the iteration of the collection and the function you wish to apply. You don't have to override equals()
for a particular behaviour.
As noted below, the java.util.Stream framework built into Java 8 and later provides something similar.
The includes
(formerly called contains
and include
) method compares objects by reference (or more precisely, with ===
). Because the two object literals of {"b": 2}
in your example represent different instances, they are not equal. Notice:
({"b": 2} === {"b": 2})
> false
However, this will work because there is only one instance of {"b": 2}
:
var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true
On the other hand, the where
(deprecated in v4) and find
methods compare objects by their properties, so they don't require reference equality. As an alternative to includes
, you might want to try some
(also aliased as any
):
_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true
All previous examples will raise an exception in case your string is not long enough.
Another approach is to use
'yourstring'.ljust(100)[:100].strip()
.
This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.
You must use Rect.width()
and Rect.Height()
which returned from getTextBounds()
instead. That works for me.
Based on First answer here is the complete image selection options:
Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
|PNG|*.PNG;*.png
|JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
|Bitmap(.BMP,.bmp)|*.BMP;*.bmp
|GIF|*.GIF;*.gif
|TIF|*.tif;*.tiff
|ICO|*.ico;*.ICO";
I imagine that trygetvalue is doing something more like:
if(myDict.ReallyOptimisedVersionofContains(someKey))
{
someVal = myDict[someKey];
return true;
}
return false;
So hopefully no try/catch anywhere.
I think it is just a method of convenience really. I generally use it as it saves a line of code or two.
I assume your header is fixed because you want it to stay at the top of the page even when the user scrolls down, but you dont want it covering the container. Setting position: fixed
removes the element from the linear layout of the page however, so you would need to either set the top margin of the "next" element to be the same as the height of the header, or (if for whatever reason you don't want to do that), put a placeholder element which takes up space in the page flow, but would appear underneath where the header shows up.
Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):
CREATE TABLE "dbo"."TableName"
(
id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
name varchar(20),
);
the insert statement should list all columns except the id column (it will be filled with autoincremented value):
INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');
and the result of
SELECT id, name FROM "dbo"."TableName";
will be
id name
--------------------------
1 alpha
2 beta
I have a project that uses generators a lot and needed this to be automatic, so I copied the index_name
function from the rails source to override it. I added this in config/initializers/generated_index_name.rb
:
# make indexes shorter for postgres
require "active_record/connection_adapters/abstract/schema_statements"
module ActiveRecord
module ConnectionAdapters # :nodoc:
module SchemaStatements
def index_name(table_name, options) #:nodoc:
if Hash === options
if options[:column]
"ix_#{table_name}_on_#{Array(options[:column]) * '__'}".slice(0,63)
elsif options[:name]
options[:name]
else
raise ArgumentError, "You must specify the index name"
end
else
index_name(table_name, index_name_options(options))
end
end
end
end
end
It creates indexes like ix_assignments_on_case_id__project_id
and just truncates it to 63 characters if it's still too long. That's still going to be non-unique if the table name is very long, but you can add complications like shortening the table name separately from the column names or actually checking for uniqueness.
Note, this is from a Rails 5.2 project; if you decide to do this, copy the source from your version.
Try to use ES6 syntax of set timeout. Normal javascript setTimeout() won't work in react js
setTimeout(
() => this.setState({ position: 100 }),
5000
);
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select
Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.
= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}
I have created function to disable previous date, disable flexible weekend days (Like Saturday, Sunday)
We are using beforeShowDay method of jQuery UI datepicker plugin.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
var NotBeforeToday = function(date) {_x000D_
var now = new Date(); //this gets the current date and time_x000D_
if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6) )_x000D_
return [true,""];_x000D_
if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
return [true,""];_x000D_
if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
return [true,""];_x000D_
return [false,""];_x000D_
}_x000D_
_x000D_
_x000D_
jQuery("#datepicker").datepicker({_x000D_
beforeShowDay: NotBeforeToday_x000D_
});
_x000D_
Here today's date is 15th Sept. I have disabled Saturday and Sunday.
There are libraries that provide safe arithmetic operations, which check integer overflow/underflow . For example, Guava's IntMath.checkedAdd(int a, int b) returns the sum of a
and b
, provided it does not overflow, and throws ArithmeticException
if a + b
overflows in signed int
arithmetic.
you can use np.int_
:
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> np.int_(x)
array([[1, 2],
[1, 2]])
open command prompt and run the following commands (assuming python 2.7):
cd c:\Python27\scripts\
pip install opencv-python
the above works for me for python 2.7 on windows 10 64 bit
Since the previous answers don't appear to work in with Visual Styles. You'll probably need to create your own class or extend the progress bar:
public class NewProgressBar : ProgressBar
{
public NewProgressBar()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rec = e.ClipRectangle;
rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;
if(ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);
rec.Height = rec.Height - 4;
e.Graphics.FillRectangle(Brushes.Red, 2, 2, rec.Width, rec.Height);
}
}
EDIT: Updated code to make the progress bar use the visual style for the background
I tried updating all of my SDKs by just going into the Project Structure > Platform Settings > SDKs and changing the Java SDK, but that didn't work, so I had to recreate the configurations from scratch.
Here's how to create your SDKs with the latest Java:
In resume, there are many options to find out if an element is empty:
1- Using html
:
if (!$.trim($('p#element').html())) {
// paragraph with id="element" is empty, your code goes here
}
2- Using text
:
if (!$.trim($('p#element').text())) {
// paragraph with id="element" is empty, your code goes here
}
3- Using is(':empty')
:
if ($('p#element').is(':empty')) {
// paragraph with id="element" is empty, your code goes here
}
4- Using length
if (!$('p#element').length){
// paragraph with id="element" is empty, your code goes here
}
In addiction if you are trying to find out if an input element is empty you can use val
:
if (!$.trim($('input#element').val())) {
// input with id="element" is empty, your code goes here
}
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention.
Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
.
So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
Specifically relating to the error you're getting, you can't do something like this in PHP for a nullable field in MySQL:
$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';
Because null in PHP will equate to an empty string which is not the same as a NULL value in MysQL. Instead you want to do this:
$sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';
Of course you don't have to use is_null but I figure that it demonstrates the point a little better. Probably safer to use empty() or something like that. And if $col2 happens to be a string which you would enclose in double quotes in the query, don't forget not to include those around the 'NULL' string, otherwise it wont work.
Hope that helps!
=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")
There is a special security expression in spring security:
hasAnyRole(list of roles) - true if the user has been granted any of the roles specified (given as a comma-separated list of strings).
I have never used it but I think it is exactly what you are looking for.
Example usage:
<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
...
</security:authorize>
Here is a link to the reference documentation where the standard spring security expressions are described. Also, here is a discussion where I described how to create custom expression if you need it.
You're looking for a hash based collection (like a Dictionary or Hashset) which the ObservableCollection is not. The best solution might be to derive from a hash based collection and implement INotifyCollectionChanged which will give you the same behavior as an ObservableCollection.
You can use Safari to debug the iOS version of your app without having to enable "Debug JS Remotely", Just follow the following steps:
1. Enable Develop menu in Safari: Preferences ? Advanced ? Select "Show Develop menu in menu bar"
2. Select your app's JSContext: Develop ? {Your Simulator} ? Automatically Show Web Inspector for JS JSContext
3. Safari's Web Inspector should open which has a Console and a Debugger
just enhancing above solution.. so header it self resize its width in order to accommodate lengthy string like 12345
private void advancedDataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
var grid = sender as DataGridView;
var rowIdx = (e.RowIndex + 1).ToString();
var centerFormat = new StringFormat()
{
// right alignment might actually make more sense for numbers
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
//get the size of the string
Size textSize = TextRenderer.MeasureText(rowIdx, this.Font);
//if header width lower then string width then resize
if (grid.RowHeadersWidth < textSize.Width + 40)
{
grid.RowHeadersWidth = textSize.Width + 40;
}
var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}
You can also use, if you want to preserve exit error status, and have a readable file with one command per line:
my_command1 || exit $?
my_command2 || exit $?
This, however will not print any additional error message. But in some cases, the error will be printed by the failed command anyway.
Updated for Swift 3
yourButtonName.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
Instead of - fd.append( 'userfile', $('#userfile')[0].files[0]);
Use - fd.append( 'file', $('#userfile')[0].files[0]);
for a solution that uses ncurses
with working code and initialization of ncurses see getchar() returns the same value (27) for up and down arrow keys
Very late to the game, but this is a version of Chris Pratt's answer that protects against race conditions while sacrificing performance, by using a transaction
block and select_for_update()
@receiver(pre_save, sender=MyModel)
@transaction.atomic
def do_something_if_changed(sender, instance, **kwargs):
try:
obj = sender.objects.select_for_update().get(pk=instance.pk)
except sender.DoesNotExist:
pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
else:
if not obj.some_field == instance.some_field: # Field has changed
# do something
var t = document.getElementById("table"),
d = t.getElementsByTagName("tr"),
r = d.getElementsByTagName("td");
needs to be:
var t = document.getElementById("table"),
tableRows = t.getElementsByTagName("tr"),
r = [], i, len, tds, j, jlen;
for ( i =0, len = tableRows.length; i<len; i++) {
tds = tableRows[i].getElementsByTagName('td');
for( j = 0, jlen = tds.length; j < jlen; j++) {
r.push(tds[j]);
}
}
Because getElementsByTagName
returns a NodeList
an Array-like structure. So you need to loop through the return nodes and then populate you r
like above.
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
You're correct. Subdomains are still considered separate domains when using iframes. It's possible to pass messages using postMessage(...)
, but other JS APIs are intentionally made inaccessible.
It's also still possible to get the URL depending on the context. See other answers for more details.
The easiest solution I found is to just rename the php folder version as such:
That way only two of them will be read by MAMP. Done!
Since version 1.7.0, NumPy has a choice
function that supports probability distributions.
from numpy.random import choice
draw = choice(list_of_candidates, number_of_items_to_pick,
p=probability_distribution)
Note that probability_distribution
is a sequence in the same order of list_of_candidates
. You can also use the keyword replace=False
to change the behavior so that drawn items are not replaced.
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes, you could make the display resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
Now I am using the browser kit like this:
{
border-radius: 7px;
-webkit-border-radius: 7px;
-moz-border-radius: 7px;
}
To get a border on just one side of a drawable, apply a negative inset
to the other 3 sides (causing those borders to be drawn off-screen).
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetTop="-2dp"
android:insetBottom="-2dp"
android:insetLeft="-2dp">
<shape android:shape="rectangle">
<stroke android:width="2dp" android:color="#FF0000" />
<solid android:color="#000000" />
</shape>
</inset>
This approach is similar to naykah's answer, but without the use of a layer-list
.
I will post the new "way" with androidx
in a short answer (because in some case you does not need custom registry or contract). If you want more informations see : https://developer.android.com/training/basics/intents/result
Important : there is actually a bug with the backward compatibility of androidx so you have to add fragment_version
in your gradle file. Otherwise you will get an exception "New result API error : Can only use lower 16 bits for requestCode".
dependencies {
def activity_version = "1.2.0-beta01"
// Java language implementation
implementation "androidx.activity:activity:$activity_version"
// Kotlin
implementation "androidx.activity:activity-ktx:$activity_version"
def fragment_version = "1.3.0-beta02"
// Java language implementation
implementation "androidx.fragment:fragment:$fragment_version"
// Kotlin
implementation "androidx.fragment:fragment-ktx:$fragment_version"
// Testing Fragments in Isolation
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
Now you just have to add this member variable of your activity. This use a predefined registry and generic contract.
public class MyActivity extends AppCompatActivity{
...
/**
* Activity callback API.
*/
// https://developer.android.com/training/basics/intents/result
private ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
switch (result.getResultCode()) {
case Activity.RESULT_OK:
Intent intent = result.getData();
// Handle the Intent
Toast.makeText(MyActivity.this, "Activity returned ok", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MyActivity.this, "Activity canceled", Toast.LENGTH_SHORT).show();
break;
}
}
});
Before new API you had :
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity .this, EditActivity.class);
startActivityForResult(intent, Constants.INTENT_EDIT_REQUEST_CODE);
}
});
You may notice that the request code is now generated (and holded) by the google framework. Your code become.
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity .this, EditActivity.class);
mStartForResult.launch(intent);
}
});
Hope my answer will help some people !
Generate a random integer between from
(inclusive) and to
(exclusive)
import java.util.Random
val random = Random()
fun rand(from: Int, to: Int) : Int {
return random.nextInt(to - from) + from
}
You have number of ways doing it on Windows:
Press CTRL + L
import os
cls = lambda: os.system('cls')
cls()
cls = lambda: print('\n'*100)
cls()
The public
keyword is used only when declaring a class method.
Since you're declaring a simple function and not a class you need to remove public
from your code.