Although it's too late , But here is my experience .
Whenever you get your maven project from a source controller or just copying your project from one machine to another , you need to update the dependencies .
For this Right-click on Project on project explorer -> Maven -> Update Project.
Please consider checking the "Force update of snapshot/releases"
checkbox.
If you have not your dependencies in m2/repository then you need internet connection to get from the remote maven repository.
In case you have get from the source controller and you have not any unit test , It's probably your test folder does not include in the source controller in the first place , so you don't have those in the new repository.so you need to create those folders manually.
I have had both these cases .
Use
if(isset($_POST['submit'])) // name of your submit button
To answer your additional question how disable views caching:
You can do this by automatically delete the files in the folder for each request with the command php artisan view:clear
mentioned by DilipGurung. Here is an example Middleware class from https://stackoverflow.com/a/38598434/2311074
<?php
namespace App\Http\Middleware;
use Artisan;
use Closure;
class ClearViewCache
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (env('APP_DEBUG') || env('APP_ENV') === 'local')
Artisan::call('view:clear');
return $next($request);
}
}
However you may note that Larevel will recompile the files in the /app/storage/views folder whenever the time on the views files is earlier than the time on the PHP blade files for the layout. THus, I cannot really think of a scenario where this would be necessary to do.
Code that calls COM object dlls (for example, to read proprietary data files), may work fine in a user interface but hang mysteriously from a service. The reason is that as of .Net 2.0 user interfaces assume STA (thread-safe) while services assume MTA ((before that, services assumed STA). Having to create an STA thread for every COM call in a service can add significant overhead.
I use printf, is shorter as it doesn't need flags to do the work:
printf "\rMy static $myvars composed text"
You can create config once and use it everywhere.
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'Authorization': 'Bearer '+token}
});
instance.get('/path')
.then(response => {
return response.data;
})
Just check my scripts it's working well:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
#list img{
width: auto;
height: 100px;
margin: 10px ;
}
FAST "FROM" AND "TO" METHODS
I am late to the party, but I compounded previous answers and improved over them. I think these two methods are faster than any others posted so far. I was able to convert 1,000,000 numbers from and to base 36 in under 400ms in a single core machine.
Example below is for base 62. Change the BaseChars
array to convert from and to any other base.
private static readonly char[] BaseChars =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
private static readonly Dictionary<char, int> CharValues = BaseChars
.Select((c,i)=>new {Char=c, Index=i})
.ToDictionary(c=>c.Char,c=>c.Index);
public static string LongToBase(long value)
{
long targetBase = BaseChars.Length;
// Determine exact number of characters to use.
char[] buffer = new char[Math.Max(
(int) Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];
var i = buffer.Length;
do
{
buffer[--i] = BaseChars[value % targetBase];
value = value / targetBase;
}
while (value > 0);
return new string(buffer, i, buffer.Length - i);
}
public static long BaseToLong(string number)
{
char[] chrs = number.ToCharArray();
int m = chrs.Length - 1;
int n = BaseChars.Length, x;
long result = 0;
for (int i = 0; i < chrs.Length; i++)
{
x = CharValues[ chrs[i] ];
result += x * (long)Math.Pow(n, m--);
}
return result;
}
EDIT (2018-07-12)
Fixed to address the corner case found by @AdrianBotor (see comments) converting 46655 to base 36. This is caused by a small floating-point error calculating Math.Log(46656, 36)
which is exactly 3, but .NET returns 3 + 4.44e-16
, which causes an extra character in the output buffer.
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage("images/background.png"),
fit: BoxFit.cover
),
),
this also works inside a container.
Back in Feb 2012, there was a very interesting thread on the Git mailing list from Joshua Redstone, a Facebook software engineer testing Git on a huge test repository:
The test repo has 4 million commits, linear history and about 1.3 million files.
Tests that were run show that for such a repo Git is unusable (cold operation lasting minutes), but this may change in the future. Basically the performance is penalized by the number of stat()
calls to the kernel FS module, so it will depend on the number of files in the repo, and the FS caching efficiency. See also this Gist for further discussion.
Let me explain the difference between process and threads first.
A process can have {1..N} number of threads. A small explanation on virtual memory and virtual processor.
Virtual memory
Used as a swap space so that a process thinks that it is sitting on the primary memory for execution.
Virtual processor
The same concept as virtual memory except this is for processor. To a process, it will look it's the only thing that is using the processor.
OS will take care of allocating the virtual memory and virtual processor to a process and performing the swap between processes and doing execution.
All the threads within a process will share the same virtual memory. But, each thread will have their individual virtual processor assigned to them so that they can be executed individually.
Thus saving the memory as well as utilizing the CPU to its potential.
Some people have commented about readability, saying "Oh it doesn't help readability that much, who cares?"
Suppose you need a check before the main code:
if precondition_fails(message): continue
''' main code here '''
Note you can do this after the main code was written without changing that code in anyway. If you diff the code, only the added line with "continue" will be highlighted since there are no spacing changes to the main code.
Imagine if you have to do a breakfix of production code, which turns out to simply be adding a line with continue. It's easy to see that's the only change when you review the code. If you start wrapping the main code in if/else, diff will highlight the newly indented code, unless you ignore spacing changes, which is dangerous particularly in Python. I think unless you've been in the situation where you have to roll out code on short notice, you might not fully appreciate this.
This solved my problem : Sample alter table statement to change the ownership.
ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;
I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60
returns nothing. The command find . -mmin -60 |xargs ls -l
, however, returns every file in the directory which is consistent with what happens when ls -l
is run without an argument.
To make sure that ls -l
is only run when a file is found, try:
find . -mmin -60 -type f -exec ls -l {} +
This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module
whose name matched my filename appropriately, rather than just defining a class:
In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))
module DevelopmentMailInterceptor
class DevelopmentMailInterceptor
def self.delivering_email(message)
message.subject = "intercepted for: #{message.to} #{message.subject}"
message.to = "[email protected]"
end
end
end
works, but it doesn't load if I hadn't put the class inside a module.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
I successfully use the following method in one file,
But come up with exactly the same error again... Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
"user.dir" is the current working directory, not the home directory It is all described here.
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also, by using \\
instead of File.separator, you will lose portability with *nix system which uses /
for file separator.
If you want to add the elements with index, you could instead use an array.
String [] test = new String[length];
test[0] = "add";
I had to run the following command:
sudo apt-get autoremove phpmyadmin
Then I cleared my cache and it worked!
Take a look at Arrays.sort()
See LINQ: How to get the latest/last record with a group by clause
var firstItemsInGroup = from b in mainButtons
group b by b.category into g
select g.First();
I assume that mainButtons are already sorted correctly.
If you need to specify custom sort order, use OrderBy override with Comparer.
var firstsByCompareInGroups = from p in rows
group p by p.ID into grp
select grp.OrderBy(a => a, new CompareRows()).First();
See an example in my post "Select First Row In Group using Custom Comparer"
The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.
The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?
As of Spring 3.0, Spring offers support for JSR-330 dependency injection annotations (@Inject
, @Named
, @Singleton
).
There is a separate section in the Spring documentation about them, including comparisons to their Spring equivalents.
In the "give a man a fish, feed him for a day; teach a man to fish, get rid of him for the whole weekend" vein,
g++ --helpshows compiler options. The g++ -v option helps:
-v Display the programs invoked by the compiler
Look through the output for bogus paths. In my case the original command:
g++ -v "d:/UW_Work/EasyUnit/examples/1-BasicUnitTesting/main.cpp"
generated output including this little gem:
-iprefix c:\olimexods\yagarto\arm-none-eabi\bin\../lib/gcc/arm-none-eabi/4.5.1/
which would explain the "no such file or directory" message.
The "../lib/gcc/arm-none-eabi/4.5.1/" segment is coming from built-in specs:
g++ -dumpspecs
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));
//Output : C
items.forEach(item->{
System.out.println(item);
System.out.println(item.toLowerCase());
}
});
Whatever you do, make sure not to trust data sent from the client. $_SERVER['REMOTE_ADDR']
contains the real IP address of the connecting party. That is the most reliable value you can find.
However, they can be behind a proxy server in which case the proxy may have set the $_SERVER['HTTP_X_FORWARDED_FOR']
, but this value is easily spoofed. For example, it can be set by someone without a proxy, or the IP can be an internal IP from the LAN behind the proxy.
This means that if you are going to save the $_SERVER['HTTP_X_FORWARDED_FOR']
, make sure you also save the $_SERVER['REMOTE_ADDR']
value. E.g. by saving both values in different fields in your database.
If you are going to save the IP to a database as a string, make sure you have space for at least 45 characters. IPv6 is here to stay and those addresses are larger than the older IPv4 addresses.
(Note that IPv6 usually uses 39 characters at most but there is also a special IPv6 notation for IPv4 addresses which in its full form can be up to 45 characters. So if you know what you are doing you can use 39 characters, but if you just want to set and forget it, use 45).
You can use json2csharp.com to Convert your json to object model
var model = JsonConvert.DeserializeObject<RootObject>(json);
using NewtonJsonHere, It will generate something like this:
public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}
public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}
public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}
public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}
Then you can deserialize as:
var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
yes we can do this using nth-child like so
div:nth-child(n + 8) {
background: red;
}
This will make the 8th div child onwards become red. Hope this helps...
Also, if someone ever says "hey, they can't be done with styled using css, use JS!!!" doubt them immediately. CSS is extremely flexible nowadays
Example :: http://jsfiddle.net/uWrLE/1/
In the example the first 7 children are blue, then 8 onwards are red...
I prefer to destruct object values into array:
[...Object.values(dataObject)]
var dataObject = {
object1: {id: 1, name: "Fred"},
object2: {id: 2, name: "Wilma"},
object3: {id: 3, name: "Pebbles"}
};
var dataArray = [...Object.values(dataObject)];
>>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2))
The limitations of a 32-bit JVM on a 64-bit OS will be exactly the same as the limitations of a 32-bit JVM on a 32-bit OS. After all, the 32-bit JVM will be running In a 32-bit virtual machine (in the virtualization sense) so it won't know that it's running on a 64-bit OS/machine.
The one advantage to running a 32-bit JVM on a 64-bit OS versus a 32-bit OS is that you can have more physical memory, and therefore will encounter swapping/paging less frequently. This advantage is only really fully realized when you have multiple processes, however.
I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:
(1 - (oldNumber / newNumber)) * 100
So, the percentage difference from 30 to 40 is:
(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)
The percentage difference from 40 to 30 is:
(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)
In php, I use a function like this:
function calculatePercentage($oldFigure, $newFigure) {
if (($oldFigure != 0) && ($newFigure != 0)) {
$percentChange = (1 - $oldFigure / $newFigure) * 100;
}
else {
$percentChange = null;
}
return $percentChange;
}
There is certainly a shorter notation, but that was my approach:
gulp.task('check_env', function () {
return new Promise(function (resolve, reject) {
// gulp --dev
var env = process.argv[3], isDev;
if (env) {
if (env == "--dev") {
log.info("Dev Mode on");
isDev = true;
} else {
log.info("Dev Mode off");
isDev = false;
}
} else {
if (variables.settings.isDev == true) {
isDev = true;
} else {
isDev = false;
}
}
resolve();
});
});
If you want to set the env based to the actual Git branch (master/develop):
gulp.task('set_env', function (cb) {
exec('git rev-parse --abbrev-ref HEAD', function (err, stdout, stderr) {
git__branch = stdout.replace(/(\r\n|\n|\r)/gm, "");
if (git__branch == "develop") {
log.info("?Develop Branch");
isCompressing = false;
} else if (git__branch == "master") {
log.info("Master Branch");
isCompressing = true;
} else {
//TODO: check for feature-* branch
log.warn("Unknown " + git__branch + ", maybe feat?");
//isCompressing = variables.settings.isCompressing;
}
log.info(stderr);
cb(err);
});
return;
})
P.s. For the log I added the following:
var log = require('fancy-log');
In Case you need it, thats my default Task:
gulp.task('default',
gulp.series('set_env', gulp.parallel('build_scss', 'minify_js', 'minify_ts', 'minify_html', 'browser_sync_func', 'watch'),
function () {
}));
Suggestions for optimization are welcome.
I Think it's worth mentioning that in some cases, this would work:
$( document ).ajaxComplete(function() {
// Do Stuff
});
With CSS:
selector { cursor: none; }
An example:
<div class="nocursor">_x000D_
Some stuff_x000D_
</div>_x000D_
<style type="text/css">_x000D_
.nocursor { cursor:none; }_x000D_
</style>
_x000D_
To set this on an element in Javascript, you can use the style
property:
<div id="nocursor"><!-- some stuff --></div>
<script type="text/javascript">
document.getElementById('nocursor').style.cursor = 'none';
</script>
If you want to set this on the whole body:
<script type="text/javascript">
document.body.style.cursor = 'none';
</script>
Make sure you really want to hide the cursor, though. It can really annoy people.
995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.
Receiving 0 bytes from EndRecieve
means that the socket has been closed, as does most exceptions that EndRecieve
will throw.
You need to start dealing with those situations.
Never ever ignore exceptions, they are thrown for a reason.
Update
There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.
What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.
As for the receive callback a more proper way of handling it is something like this (semi pseudo code):
public void OnDataReceived(IAsyncResult asyn)
{
BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);
try
{
SocketPacket client = (SocketPacket)asyn.AsyncState;
int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
if (bytesReceived == 0)
{
HandleDisconnect(client);
return;
}
}
catch (Exception err)
{
HandleDisconnect(client);
}
try
{
string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);
//do your handling here
}
catch (Exception err)
{
// Your logic threw an exception. handle it accordinhly
}
try
{
client.thisSocket.BeginRecieve(.. all parameters ..);
}
catch (Exception err)
{
HandleDisconnect(client);
}
}
the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.
Rather than preg_replace
, you could always use PHP's filter functions using the filter_var()
function with FILTER_SANITIZE_STRING
.
Try with command find. Specify the directory hardcoded or as argument. Then initiate find to search all files inside the directory. Check if return of find is null. Echo the data of find
#!/bin/bash
_DIR="/home/user/test/"
#_DIR=$1
_FIND=$(find $_DIR -type f )
if [ -n "$_FIND" ]
then
echo -e "$_DIR contains files or subdirs with files \n\n "
echo "$_FIND"
else
echo "empty (or does not exist)"
fi
Would it not be better to use java.util.Observable
and java.util.Observer
that will cause the table to update?
If you want to run a script to a database:
mysql -u user -p data_base_name_here < db.sql
background: url("../image/b21.jpg") no-repeat center center fixed;
background-size: 100% 100%;
height: 100%;
position: absolute;
width: 100%;
Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.
The solution is setting a height to the vertical scrollable element. For example:
#container article {
flex: 1 1 auto;
overflow-y: auto;
height: 0px;
}
The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px;
that it is exactly the same as: min-height: 100px;
#container article {
flex: 1 1 auto;
overflow-y: auto;
height: 100px; /* == min-height: 100px*/
}
So the best solution if you want a min-height
in the vertical scroll:
#container article {
flex: 1 1 auto;
overflow-y: auto;
min-height: 100px;
}
If you just want full vertical scroll in case there is no enough space to see the article:
#container article {
flex: 1 1 auto;
overflow-y: auto;
min-height: 0px;
}
The final code: http://jsfiddle.net/ch7n6/867/
Found out that this breaks some applications, the better way to do it is
In addition to symlink, on more recent distros and filesystems, as root you can also use bind-mount:
mkdir /home/username
mount --bind --verbose /extra-home/username /home/username
This is useful for allowing access "through" the /home directory to subdirs via daemons that are otherwise configured to avoid pathing through symlinks (apache, ftpd, etc.).
You have to remember (or init script) to bind upon restarts, of course.
An example init script in /etc/fstab
is
/extra-home/username /home/username none defaults,bind 0 0
URL safe Base64 Encoding/Decoding
public static class Base64Url
{
public static string Encode(string text)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).TrimEnd('=').Replace('+', '-')
.Replace('/', '_');
}
public static string Decode(string text)
{
text = text.Replace('_', '/').Replace('-', '+');
switch (text.Length % 4)
{
case 2:
text += "==";
break;
case 3:
text += "=";
break;
}
return Encoding.UTF8.GetString(Convert.FromBase64String(text));
}
}
Over a certain message of size, it messes up the content when setting through $mail->Body.
You can test it, if it works well with small messages, but doesn't work with larger (over 4-6 kB), then this is the problem.
It seems to be the problem of $mail->Body, so you can get around this by setting the HTML body manually via $mail->MsgHTML($message). And then you can try to only add the non-html body by $mail->AltBody.
Hope that I could help, feel free to provide more details, information.
^[ _]*[A-Z0-9][A-Z0-9 _]*$
You can optionally have some spaces or underscores up front, then you need one letter or number, and then an arbitrary number of numbers, letters, spaces or underscores after that.
Something that contains only spaces and underscores will fail the [A-Z0-9]
portion.
As a one-liner function:
def is_leap_year(year):
"""Determine whether a year is a leap year."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
It's similar to the Mark's answer, but short circuits at the first test (note the parenthesis).
Alternatively, you can use the standard library's calendar.isleap
, which has exactly the same implementation:
from calendar import isleap
print(isleap(1900))
Though this is an old post and have many answers, but here I have my version of code to upload the file to sharepoint 2013 using CSOM(c#)
I hope if you are working with downloading and uploading files then you know how to create Clientcontext
object and Web
object
/* Assuming you have created ClientContext object and Web object*/
string listTitle = "List title where you want your file to upload";
string filePath = "your file physical path";
List oList = web.Lists.GetByTitle(listTitle);
clientContext.Load(oList.RootFolder);//to load the folder where you will upload the file
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.Overwrite = true;
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = fileName;
File fileToUpload = fileCollection.Add(fileInfo);
clientContext.ExecuteQuery();
fileToUpload.CheckIn("your checkin comment", CheckinType.MajorCheckIn);
if (oList.EnableMinorVersions)
{
fileToUpload.Publish("your publish comment");
clientContext.ExecuteQuery();
}
if (oList.EnableModeration)
{
fileToUpload.Approve("your approve comment");
}
clientContext.ExecuteQuery();
And here is the code for download
List oList = web.Lists.GetByTitle("ListNameWhereFileExist");
clientContext.Load(oList);
clientContext.Load(oList.RootFolder);
clientContext.Load(oList.RootFolder.Files);
clientContext.ExecuteQuery();
FileCollection fileCollection = oList.RootFolder.Files;
File SP_file = fileCollection.GetByUrl("fileNameToDownloadWithExtension");
clientContext.Load(SP_file);
clientContext.ExecuteQuery();
var Local_stream = System.IO.File.Open("c:/testing/" + SP_file.Name, System.IO.FileMode.CreateNew);
var fileInformation = File.OpenBinaryDirect(clientContext, SP_file.ServerRelativeUrl);
var Sp_Stream = fileInformation.Stream;
Sp_Stream.CopyTo(Local_stream);
Still there are different ways I believe that can be used to upload and download.
This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd
to another (existing) directory and then cd
back; the simplest would be: cd; cd -
.
works for me:
<target name="build2-jar" depends="compile" >
<jar destfile="./myJjar.jar">
<fileset dir="./WebContent/WEB-INF/lib" includes="hibernate*.jar,mysql*.jar" />
<fileset dir="./WebContent/WEB-INF/classes" excludes="**/controlador/*.class,**/form/*.class,**/orm/*.class,**/reporting/*.class,**/org/w3/xmldsig/*.class"/>
</jar>
Is there also a way to pass coords directly to google maps to display?
You can use the geo URI
prefix:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:" + latitude + "," + longitude));
startActivity(intent);
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
Bootstrap does not document the media queries very well. Those variables of @screen-sm
, @screen-md
, @screen-lg
are actually referring to LESS variables and not simple CSS.
When you customize Bootstrap you can change the media query breakpoints and when it compiles the @screen-xx variables are changed to whatever pixel width you defined as screen-xx. This is how a framework like this can be coded once and then customized by the end user to fit their needs.
A similar question on here that might provide more clarity: Bootstrap 3.0 Media queries
In your CSS, you will still have to use traditional media queries to override or add to what Bootstrap is doing.
In regards to your second question, that is not a typo. Once the screen goes below 768px the framework becomes completely fluid and resizes at any device width, removing the need for breakpoints. The breakpoint at 480px exists because there are specific changes that occur to the layout for mobile optimization.
To see this in action, go to this example on their site (http://getbootstrap.com/examples/navbar-fixed-top/), and resize your window to see how it treats the design after 768px.
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.
Combine the SUBSTRING()
, LEFT()
, and CHARINDEX()
functions.
SELECT LEFT(SUBSTRING(YOUR_FIELD,
CHARINDEX(';', YOUR_FIELD) + 1, 100),
CHARINDEX('[', YOUR_FIELD) - 1)
FROM YOUR_TABLE;
This assumes your field length will never exceed 100, but you can make it smarter to account for that if necessary by employing the LEN()
function. I didn't bother since there's enough going on in there already, and I don't have an instance to test against, so I'm just eyeballing my parentheses, etc.
<th nowrap="nowrap">
or
<th style="white-space:nowrap;">
or
<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>
Here you can find every thing you need:
http://web.eecs.umich.edu/~sugih/courses/eecs487/glut-howto/#win
Every time you call e.nextElement()
you take the next object from the iterator. You have to check e.hasMoreElement()
between each call.
Example:
while(e.hasMoreElements()){
String param = e.nextElement();
System.out.println(param);
}
Check out this link it has a example code to encrypt/decrypt data using AES256CBC using EVP API.
https://github.com/saju/misc/blob/master/misc/openssl_aes.c
Also you can check the use of AES256 CBC in a detailed open source project developed by me at https://github.com/llubu/mpro
The code is detailed enough with comments and if you still need much explanation about the API itself i suggest check out this book Network Security with OpenSSL by Viega/Messier/Chandra (google it you will easily find a pdf of this..) read chapter 6 which is specific to symmetric ciphers using EVP API.. This helped me a lot actually understanding the reasons behind using various functions and structures of EVP.
and if you want to dive deep into the Openssl crypto library, i suggest download the code from the openssl website (the version installed on your machine) and then look in the implementation of EVP and aeh api implementation.
One more suggestion from the code you posted above i see you are using the api from aes.h instead use EVP. Check out the reason for doing this here OpenSSL using EVP vs. algorithm API for symmetric crypto nicely explained by Daniel in one of the question asked by me..
Just use this function.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let index = CategorytableView.indexPathForSelectedRow
let indexNumber = index?.row
let VC = segue.destination as! DestinationViewController
VC.value = self.data
}
For your requirement, Popen function of subprocess python module is the answer. For example,
import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout
In 6.1.0-beta.1 KeyValuePipe was introduced https://github.com/angular/angular/pull/24319
<div *ngFor="let item of {'b': 1, 'a': 1} | keyvalue">
{{ item.key }} - {{ item.value }}
</div>
Another approach is to create NgForIn
directive that will be used like:
<div *ngFor="let key in obj">
<b>{{ key }}</b>: {{ obj[key] }}
</div>
ngforin.directive.ts
@Directive({
selector: '[ngFor][ngForIn]'
})
export class NgForIn<T> extends NgForOf<T> implements OnChanges {
@Input() ngForIn: any;
ngOnChanges(changes: NgForInChanges): void {
if (changes.ngForIn) {
this.ngForOf = Object.keys(this.ngForIn) as Array<any>;
const change = changes.ngForIn;
const currentValue = Object.keys(change.currentValue);
const previousValue = change.previousValue ? Object.keys(change.previousValue) : undefined;
changes.ngForOf = new SimpleChange(previousValue, currentValue, change.firstChange);
super.ngOnChanges(changes);
}
}
}
There are a couple of options I can think of.
array[100]
without having to walk through 1-99
first. And it might not be that handy for you to use either.It is hard to say what option would be best in your situation. Simply creating a large array is ofcourse one of the easiest solutions and shouldn't give you much problems unless it's really large.
NOTE - it looks like the question has changed some. The answer to the question of how you call an instance method from a static method is that you can't without passing an instance in as an argument or instantiating that instance inside the static method.
What follows is mostly to answer "how do you call a static method from another static method":
Bear in mind that there is a difference between static methods and class methods in Python. A static method takes no implicit first argument, while a class method takes the class as the implicit first argument (usually cls
by convention). With that in mind, here's how you would do that:
If it's a static method:
test.dosomethingelse()
If it's a class method:
cls.dosomethingelse()
It was weird that no one suggested KVM.
It is gonna provide you almost native performance and it is built-in Linux. Go and check it out.
you will feel like u are using mac only and then install Xcode there u may even choose to directly boot into the OSX GUI instead of Linux one on startup
Here what I DO on MY PC I install all software that i usually used in G: partian not C: if my operating system is fall (win 10) , Do not need to reinstall them again and lost time , Then How windows work it update PATH automatic if you install any new programe or pice of softwore ,
SO
I must update PATH like these HERE! all my software i usually used 1- I created folder called Programe Files 2- I install all my programe data in these folder 3-and then going to PATH and add it Dont forget ;
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;G:\HashiCorp\Vagrant\bin;G:\xampp\php;G:\xampp\mysql\bin;G:\Program Files (x86)\heroku\bin;G:\Program Files (x86)\Git\bin;G:\Program Files (x86)\composer;G:\Program Files (x86)\nodejs;G:\Program Files (x86)\Sublime Text 3;G:\Program Files (x86)\Microsoft VS Code\bin;G:\Program Files (x86)\cygwin64\bin
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
try it it is working fine
<%:Html.ActionLink("Details","Details","Product", new {id=item.dateID },null)%>
I'm not sure how stuck you are:
You must have a web server (Windows comes with one called IIS, but it may not be installed)
http://localhost/
in your browser and see what happens. If nothing happens it means that you may not have IIS installed. See Installing IIS Installing your application
Once you have done that, you can more or less just copy your application to c:\wwwroot\inetpub\
. Read Installing ASP.NET Applications (IIS 6.0) for more information
Accessing the web site from another machine
In theory, once you have a web server running, and the application installed, you only need the IP address
of your web server to access the application.
To find your IP address try:
Start
-> Run
-> type cmd
(hit ENTER
) -> type ipconfig
(hit ENTER
)
Once
you can access your website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application.
If you put your application in a directory called NewApp
, you will need to type something like http://your_ip_address/NewApp/default.aspx
Turn off your firewall
If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.
Unfortunately, git branch -a
and git branch -r
do not show you all remote branches, if you haven't executed a "git fetch".
git remote show origin
works consistently all the time. Also git show-ref
shows all references in the Git repository. However, it works just like the git branch
command.
Just tRy this
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex; /* NEW, Spec - Firefox, Chrome, Opera */
this worked for me
I'm not sure if this is what you ask, but you can check gradle version of your project here in android studio:
(left pane must be in project view, not android for this path) app->gradle->wrapper->gradle-wrapper.properties
it has a line like this, indicating the gradle version:
distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-all.zip
There is also a table at the end of this page that shows gradle and gradle plug-in versions supported by each android studio version. (you can check your android studio by checking help->about as you may already know)
Specifying the absolute path to the library should work fine:
g++ /my/dir/libfoo.so.0 ...
Did you remember to remove the -lfoo
once you added the absolute path?
You could change the database structure such that all subject rows become a column variable (like spreadsheet). This makes such analysis much easier
The difference between encodeURI()
and encodeURIComponent()
are exactly 11 characters encoded by encodeURIComponent but not by encodeURI:
I generated this table easily with console.table in Google Chrome with this code:
var arr = [];_x000D_
for(var i=0;i<256;i++) {_x000D_
var char=String.fromCharCode(i);_x000D_
if(encodeURI(char)!==encodeURIComponent(char)) {_x000D_
arr.push({_x000D_
character:char,_x000D_
encodeURI:encodeURI(char),_x000D_
encodeURIComponent:encodeURIComponent(char)_x000D_
});_x000D_
}_x000D_
}_x000D_
console.table(arr);
_x000D_
classname.getResourceAsStream() loads a file via the classloader of classname. If the class came from a jar file, that is where the resource will be loaded from.
FileInputStream is used to read a file from the filesystem.
Well, first you need to select the elements with a function like getElementById
.
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];
getElementById
only returns one node, but getElementsByClassName
returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0]
is for—it's just like an array).
Then, you can change the html with .textContent
.
targetDiv.textContent = "Goodbye world!";
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];_x000D_
targetDiv.textContent = "Goodbye world!";
_x000D_
<div id="foo">_x000D_
<div class="bar">_x000D_
Hello world!_x000D_
</div>_x000D_
</div>
_x000D_
if you just type
$ git update
on bash git will inform you that 'update' command is no longer working and will display the correct command which is 'update-git-for-windows'
but still the update will continue you just have to press " y "
if you are having issues on it run the bashh as administrator or add the 'git.exe' path to the "allowed apps through controlled folder access".
This works, but all the children of the element with this class will also become transparent, without any way of preventing that.
.css-class-name {
opacity:0.8;
}
Im not do not know all of the technical language but I could not find the answer anywhere so I came up with this and it worked... Good Luck!
$time = date("Y/m/d h:i:s");
$sql = "INSERT INTO *yourtablenamehere* ('dt') VALUES ('$time')";
No, I don't believe there is any way to forward-declare a function in Python.
Imagine you are the Python interpreter. When you get to the line
print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)])
either you know what cmp_configs is or you don't. In order to proceed, you have to know cmp_configs. It doesn't matter if there is recursion.
Use following layerlist
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" android:padding="10dp">
<corners
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
</item>
<item android:drawable="@drawable/image_name_here" />
</layer-list>
Here is what I ended up doing to work around the error.
First, I set up the database recovery model as SIMPLE. More information here.
Then, by deleting some old files I was able to make 5GB of free space which gave the log file more space to grow.
I reran the DELETE statement sucessfully without any warning.
I thought that by running the DELETE statement the database would inmediately become smaller thus freeing space in my hard drive. But that was not true. The space freed after a DELETE statement is not returned to the operating system inmediatedly unless you run the following command:
DBCC SHRINKDATABASE (MyDb, 0);
GO
More information about that command here.
By the way, in Notepad++ there's built-in plugin that can handle this:
TextFX -> TextFX Edit -> Delete Blank Lines
(first press CTRL+A to select all).
You can also try: (I tried this and it worked for me)
SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;
You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.
The System.exit(0)
will terminates the currently running Java Virtual Machine.
Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.
It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!
To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.
Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.
If you give your table a unique id, its easier:
<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
onmouseup="checkMultipleSelection(this,event);">
<table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table"
cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="width:50px; text-align:left;">09:15 AM</td>
<td style="width:50px; text-align:left;">Item001</td>
<td style="width:50px; text-align:left;">10</td>
<td style="width:50px; text-align:left;">Address1</td>
<td style="width:50px; text-align:left;">46545465</td>
<td style="width:50px; text-align:left;">ref1</td>
</tr>
</table>
</div>
var multiselect =
document.getElementById(
'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
).rows[0].cells,
timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];
//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];
The password_hash() function in PHP is an inbuilt function , used to create a new password hash with different algorithms and options. the function uses a strong hashing algorithm.
the function take 2 mandetory parametres ($password and $algorithm,) and 1 optional parameter ($options).
$strongPassword = password_hash( $password, $algorithm, $options )
Algoristrong textthms allowed right now for password_hash() are :
PASSWORD_DEFAULT
PASSWORD_BCRYPT
ASSWORD_ARGON2I
PASSWORD_ARGON2ID
example : echo password_hash("abcDEF", PASSWORD_DEFAULT);
answer : $2y$10$KwKceUaG84WInAif5ehdZOkE4kHPWTLp0ZK5a5OU2EbtdwQ9YIcGy
answer :$2y$10$SNly5bFzB/R6OVbBMq1bj.yiOZdsk6Mwgqi4BLR2sqdCvMyv/AyL2
to use the BCRYPT as password, use option cost =12 in an array , also change 1st parameter $password to some strong password like "wgt167yuWBGY@#1987__"
Example: echo password_hash("wgt167yuWBGY@#1987__", PASSWORD_BCRYPT ,['cost' => 12]);
Answer : $2y$12$TjSggXiFSidD63E.QP8PJOds2texJfsk/82VaNU8XRZ/niZhzkJ6S
Add authorization header and click pencil button to enter username and passwords
This only converts the tabs without changing anything else:
Edit -> Convert Indents -> To Spaces
EDIT Feb 1, 2013. Due to the popularity of this answer and the changes to jQuery in version 1.9 (and 2.0) regarding properties and attributes, I added some notes and a fiddle to see how it works when accessing properties/attributes on input, buttons and some selects. The fiddle here: http://jsfiddle.net/pVBU8/1/
get all the inputs:
var allInputs = $(":input");
get all the inputs type:
allInputs.attr('type');
get the values:
allInputs.val();
NOTE: .val() is NOT the same as :checked for those types where that is relevent. use:
.attr("checked");
EDIT Feb 1, 2013 - re: jQuery 1.9 use prop() not attr() as attr will not return proper values for properties that have changed.
.prop('checked');
or simply
$(this).checked;
to get the value of the check - whatever it is currently. or simply use the ':checked' if you want only those that ARE checked.
EDIT: Here is another way to get type:
var allCheckboxes=$('[type=checkbox]');
EDIT2: Note that the form of:
$('input:radio');
is perferred over
$(':radio');
which both equate to:
$('input[type=radio]');
but the "input" is desired so it only gets the inputs and does not use the universal '*" when the form of $(':radio')
is used which equates to $('*:radio');
EDIT Aug 19, 2015: preference for the $('input[type=radio]');
should be used as that then allows modern browsers to optimize the search for a radio input.
EDIT Feb 1, 2013 per comment re: select elements @dariomac
$('select').prop("type");
will return either "select-one" or "select-multiple" depending upon the "multiple" attribute and
$('select')[0].type
returns the same for the first select if it exists. and
($('select')[0]?$('select')[0].type:"howdy")
will return the type if it exists or "howdy" if it does not.
$('select').prop('type');
returns the property of the first one in the DOM if it exists or "undefined" if none exist.
$('select').type
returns the type of the first one if it exists or an error if none exist.
Check your array index to see if it's accessed out of bound.
Once I accessed categories[0]. Later I changed the array name from categories to category but forgot to change the access point--from categories[0] to category[0], thus I also get this error.
JavaScript does a poor debug message. In your case, I reckon probably the access gets out of bound.
(In Chrome 35+ the "Emulation" tab is present by default. Also, the console is available from any primary tab.)
This option is not (yet?) available in the console tab.
Portland group have a commercial product called CUDA x86, it is hybrid compiler which creates CUDA C/ C++ code which can either run on GPU or use SIMD on CPU, this is done fully automated without any intervention for the developer. Hope this helps.
Can I just ask about the long term need for this facility - is it for debuging purposes?
If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.
Just my opinion, but I prefer the debugger approach - for code and databases.
I think i understand what the reason of your error. First you click auto AUTO INCREMENT field then select it as a primary key.
The Right way is First You have to select it as a primary key then you have to click auto AUTO INCREMENT field.
Very easy. Thanks
Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.
Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.
Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.
One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)
The correct solution is
Dim copyToRow: copyToRow = 5
Rows(copyToRow & ":" & copyToRow).Select
If you're using .NET 4, there is a special folder enumeration ProgramFilesX86:
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
Omit the double quotes from your first query.
... LIKE '%\n%'
Since :last-child
is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child
is supported, as it's defined in the CSS2.1 specification.
One possible solution is to simply give the last child a class name and style that class.
Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child
pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.
let str = "Hello World"
console.log(str.substring(1, 3)) // el -> Excludes the last index
console.log(str.substr(1, 3)) // ell -> Includes the last index
If You're using php5.6 and Ubuntu 18.04 Then run these two commands in your terminal your errors will be solved definitely.
sudo apt-get install php5.6-gd
then restart your apache server by this command.
sudo service apache2 restart
If you need the exact functionality of the back button in your custom button, why not just call yourActivity.onBackPressed() that way if you override the functionality of the backbutton your custom button will behave the same.
Stan's answer was the best one. But it also have a problem, when you use the controller with a Tab Bar and change the controller's title, you could change the Tab Bar's title too.So the best answer is change the view_controller.navigationItem.title only and use the view_controller.navigationItem.title in the function. Answer is here:(With ARC and add them into view's viewDidLoad)
static NSString * back_button_title=@"Back"; //or whatever u want
if (![view_controller.navigationItem.title isEqualToString:back_button_title]){
UILabel* custom_title_view = [[UILabel alloc] initWithFrame:CGRectZero];
custom_title_view.text = view_controller.navigationItem.title; // original title
custom_title_view.font = [UIFont boldSystemFontOfSize:20];
custom_title_view.backgroundColor = [UIColor clearColor];
custom_title_view.textColor = [UIColor whiteColor];
custom_title_view.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
custom_title_view.shadowOffset = CGSizeMake(0, -1);
[custom_title_view sizeToFit];
view_controller.navigationItem.titleView = custom_title_view;
view_controller.navigationItem.title = back_button_title;
}
In myself use, I make it a function like this, just have the feature with one line code in the viewDidLoad.
+ (void)makeSubViewHaveBackButton:(UIViewController*) view_controller{
static NSString * back_button_title=@"Back"; //or whatever u want
if (![view_controller.navigationItem.title isEqualToString:back_button_title]){
UILabel* custom_title_view = [[UILabel alloc] initWithFrame:CGRectZero];
custom_title_view.text = view_controller.navigationItem.title; // original title
custom_title_view.font = [UIFont boldSystemFontOfSize:20];
custom_title_view.backgroundColor = [UIColor clearColor];
custom_title_view.textColor = [UIColor whiteColor];
custom_title_view.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
custom_title_view.shadowOffset = CGSizeMake(0, -1);
[custom_title_view sizeToFit];
view_controller.navigationItem.titleView = custom_title_view;
view_controller.navigationItem.title = back_button_title;
}
}
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.
Here my two cents, which permits casting up and down, and adds customizable precision:
def convertFloatToDecimal(f=0.0, precision=2):
'''
Convert a float to string of decimal.
precision: by default 2.
If no arg provided, return "0.00".
'''
return ("%." + str(precision) + "f") % f
def formatFileSize(size, sizeIn, sizeOut, precision=0):
'''
Convert file size to a string representing its value in B, KB, MB and GB.
The convention is based on sizeIn as original unit and sizeOut
as final unit.
'''
assert sizeIn.upper() in {"B", "KB", "MB", "GB"}, "sizeIn type error"
assert sizeOut.upper() in {"B", "KB", "MB", "GB"}, "sizeOut type error"
if sizeIn == "B":
if sizeOut == "KB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size/1024.0**2), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0**3), precision)
elif sizeIn == "KB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0**2), precision)
elif sizeIn == "MB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0**2), precision)
elif sizeOut == "KB":
return convertFloatToDecimal((size*1024.0), precision)
elif sizeOut == "GB":
return convertFloatToDecimal((size/1024.0), precision)
elif sizeIn == "GB":
if sizeOut == "B":
return convertFloatToDecimal((size*1024.0**3), precision)
elif sizeOut == "KB":
return convertFloatToDecimal((size*1024.0**2), precision)
elif sizeOut == "MB":
return convertFloatToDecimal((size*1024.0), precision)
Add TB
, etc, as you wish.
Since a for
loop is a statement (as is print
, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write
method on sys.stdout
along with the join
method.
x = lambda x: sys.stdout.write("\n".join(x) + "\n")
Use the TextBox's Exit
event handler:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Logincode_Click
End Sub
You can simply return a ResponseEntity with the appropriate header:
@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public ResponseEntity updateDataThatDoesntRequireClientToBeNotified(...){
....
return new ResponseEntity(HttpStatus.OK)
}
It works best....
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
I'm assuming you just want to find out how much trouble you're getting yourself into prior to actually attempting the merge...and resetting to the last commit after a failed merge is relatively easy so I wouldn't be surprised if that is the intended approach.
That said, if you really don't want to touch your existing files in the working tree - you could create a patch and test it against the target branch. This also has the benefit of showing exactly what changes were made to which files - just open up the patch file in a text editor.
git checkout -b mycrazybranch
[change some stuff...]
git add .
git commit -m "changed some stuff"
git format-patch master --stdout > crazy.patch
git checkout master
git apply crazy.patch --check
[all good! cleanup...]
rm crazy.patch
As you can see, this will create a patch file, you can then test it with --check and see if there are any errors, then remove the patch file.
As a CS student, you might have heard about Mathematical induction. The recursive solution of Tower of Hanoi works analogously - only different part is to really get not lost with B and C as were the full tower ends up.
The major difference is time-out, WCF Service has timed-out when there is no response, but web-service does not have this property.
You need to give a function to be called after the time delay as the second argument to after
:
after(delay_ms, callback=None, *args)
Registers an alarm callback that is called after a given time.
So what you really want to do is this:
tiles_letter = ['a', 'b', 'c', 'd', 'e']
def add_letter():
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
root.after(0, add_letter) # add_letter will run as soon as the mainloop starts.
root.mainloop()
You also need to schedule the function to be called again by repeating the call to after
inside the callback function, since after
only executes the given function once. This is also noted in the documentation:
The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself
Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter
, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter
to make sure the list isn't empty, and just return
if it is:
def add_letter():
if not tiles_letter:
return
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
Live-Demo: repl.it
Simple Explanation.
If you want to convert your PC (running Windows) into Mac, you can do either of these:
(1) You can simply install a Mac theme on your Windows. So, your PC feels more like Mac, but you can't actually run any Mac programs.
(SIMULATION)
(or)
(2) You can program your PC to run like Mac (I'm not sure if this is possible :P ). Now you can even run Mac programs successfully and expect the same output as on Mac.
(EMULATION)
In the first case, you can experience Mac, but you can't expect the same output as on Mac.
In the second case, you can expect the same output as on Mac, but still the fact remains that it is only a PC.
A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common
only returns a tuple. I often couple this with a json output for handy log files:
from collections import Counter, OrderedDict
x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())
With the output:
OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
"c": 7,
"a": 5,
"b": 3
}
Based on the answer by 'Cassio Borghi'. With this method, there is no need to change the XAML at all.
DataGridTextColumn colNameStatus2 = new DataGridTextColumn();
colNameStatus2.Header = "Status";
colNameStatus2.MinWidth = 100;
colNameStatus2.Binding = new Binding("Status");
grdComputer_Servives.Columns.Add(colNameStatus2);
Style style = new Style(typeof(TextBlock));
Trigger running = new Trigger() { Property = TextBlock.TextProperty, Value = "Running" };
Trigger stopped = new Trigger() { Property = TextBlock.TextProperty, Value = "Stopped" };
stopped.Setters.Add(new Setter() { Property = TextBlock.BackgroundProperty, Value = Brushes.Blue });
running.Setters.Add(new Setter() { Property = TextBlock.BackgroundProperty, Value = Brushes.Green });
style.Triggers.Add(running);
style.Triggers.Add(stopped);
colNameStatus2.ElementStyle = style;
foreach (var Service in computerResult)
{
var RowName = Service;
grdComputer_Servives.Items.Add(RowName);
}
Here's an example of using text-overflow:
.text {_x000D_
display: block;_x000D_
width: 100px;_x000D_
overflow: hidden;_x000D_
white-space: nowrap;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<span class="text">Hello world this is a long sentence</span>
_x000D_
Suppose the two segments have endpoints A,B and C,D. The numerically robust way to determine intersection is to check the sign of the four determinants:
| Ax-Cx Bx-Cx | | Ax-Dx Bx-Dx |
| Ay-Cy By-Cy | | Ay-Dy By-Dy |
| Cx-Ax Dx-Ax | | Cx-Bx Dx-Bx |
| Cy-Ay Dy-Ay | | Cy-By Dy-By |
For intersection, each determinant on the left must have the opposite sign of the one to the right, but there need not be any relationship between the two lines. You are basically checking each point of a segment against the other segment to make sure they lie on opposite sides of the line defined by the other segment.
See here: http://www.cs.cmu.edu/~quake/robust.html
The following code works for me.
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
method implementation:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
Following chrome options worked for me for headless chrome:
IN JAVA:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--window-size=1920,1080");
chromeOptions.setHeadless(true);
driver = new ChromeDriver(chromeOptions);
driver.get("your-site");
driver.manage().window().maximize();
selenium-java: 3.8.1
chromedriver: 2.43
Chrome: v69-71
You could use list comprehensions to bring the item in your tuple into a list:
conn = mysql.connector.connect()
cursor = conn.cursor()
sql = "SELECT column_name FROM db.table_name;"
cursor.execute(sql)
results = cursor.fetchall()
# bring the first item of the tuple in your results here
item_0_in_result = [_[0] for _ in results]
public class CustomAdapter extends BaseAdapter{
ArrayList<BookPojo> data;
Context ctx;
int index=0;
public CustomAdapter(ArrayList<BookPojo> data, Context ctx) {
super();
this.data = data;
this.ctx = ctx;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertview, ViewGroup parent) {
// TODO Auto-generated method stub
View v=convertview;
if(v==null){
LayoutInflater vi=LayoutInflater.from(ctx);
v=vi.inflate(R.layout.messgeview,null);
}
RelativeLayout rlmessage=(RelativeLayout)v.findViewById(R.id.rlmessgeview);
TextView tvisdn=(TextView)v.findViewById(R.id.tvisdn);
TextView tvtitle=(TextView)v.findViewById(R.id.tvtitle);
TextView tvauthor=(TextView)v.findViewById(R.id.tvauthor);
TextView tvprice=(TextView)v.findViewById(R.id.tvprice);
BookPojo bpj=data.get(position);
tvisdn.setText(bpj.isdn+"");
tvtitle.setText(bpj.title);
tvauthor.setText(bpj.author);
tvprice.setText(bpj.price+"");
if(index%2==0)
{
rlmessage.setBackgroundColor(Color.BLUE);
}
else
{
rlmessage.setBackgroundColor(Color.YELLOW);
}
index++;
return v;
}
}
All I'm really interested in is the ownership and permissions information for the first level subdirectories.
I found a easy solution while playing my fish, which fits your need perfectly.
ll `ls`
or
ls -l $(ls)
Another solution would be the usage of std::make_move_iterator to build a new vector (C++11 )
int main(){
std::map<std::string, int> map;
//Populate map
std::vector<std::pair<std::string, int>> v {std::make_move_iterator(begin(map)),
std::make_move_iterator(end(map))};
// Create a vector with the map parameters
sort(begin(v), end(v),
[](auto p1, auto p2){return p1.second > p2.second;});
// Using sort + lambda function to return an ordered vector
// in respect to the int value that is now the 2nd parameter
// of our newly created vector v
}
Daemon thread is like daemon process which is responsible for managing resources,a daemon thread is created by the Java VM to serve the user threads. example updating system for unix,unix is daemon process. child of daemon thread is always daemon thread,so by default daemon is false.you can check thread as daemon or user by using "isDaemon()" method. so daemon thread or daemon process are basically responsible for managing resources. for example when you starting jvm there is garbage collector running that is daemon thread whose priority is 1 that is lowest,which is managing memory. jvm is alive as long as user thread is alive,u can not kill daemon thread.jvm is responsible to kill daemon threads.
Let's change tütü's code
private void disableEnableControls(boolean enable, ViewGroup vg){
for (int i = 0; i < vg.getChildCount(); i++){
View child = vg.getChildAt(i);
if (child instanceof ViewGroup){
disableEnableControls(enable, (ViewGroup)child);
} else {
child.setEnabled(enable);
}
}
}
I think, there is no point in just making viewgroup disable. If you want to do it, there is another way I have used for exactly the same purpose. Create view as a sibling of your groupview :
<View
android:visibility="gone"
android:id="@+id/reservation_second_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:background="#66ffffff"
android:clickable="false" />
and at run-time, make it visible. Note: your groupview's parent layout should be either relative or frame layout. Hope this will help.
The jargon file has this to say about the definition of tail recursion:
tail recursion /n./
If you aren't sick of it already, see tail recursion.
Here's a gist I put together. I was wondering the same and this helped improve my understanding. Open this up in an Xcode Playground to see what's going on.
protocol YelpRequestDelegate {
func getYelpData() -> AnyObject
func processYelpData(data: NSData) -> NSData
}
class YelpAPI {
var delegate: YelpRequestDelegate?
func getData() {
println("data being retrieved...")
let data: AnyObject? = delegate?.getYelpData()
}
func processYelpData(data: NSData) {
println("data being processed...")
let data = delegate?.processYelpData(data)
}
}
class Controller: YelpRequestDelegate {
init() {
var yelpAPI = YelpAPI()
yelpAPI.delegate = self
yelpAPI.getData()
}
func getYelpData() -> AnyObject {
println("getYelpData called")
return NSData()
}
func processYelpData(data: NSData) -> NSData {
println("processYelpData called")
return NSData()
}
}
var controller = Controller()
Mongodb and Mongoose are two completely different things!
Mongodb is the database itself, while Mongoose is an object modeling tool for Mongodb
EDIT: As pointed out MongoDB is the npm package, thanks!
If you want to bind a string to the src
attribute, you should wrap it on single quotes:
<img v-bind:src="'/static/img/clear.gif'">
<!-- or shorthand -->
<img :src="'/static/img/clear.gif'">
IMO you do not need to bind a string, you could use the simple way:
<img src="/static/img/clear.gif">
Check an example about the image preload here: http://codepen.io/pespantelis/pen/RWVZxL
I had this error and found a few solutions:
Looking at your connection string, it looks valid. I found this blog post, the problem here is that they were using Integrated Security. If you are running on IIS, your IIS user needs access to the database.
If you are using Entity Framework with Transactions, Entity Framework automatically opens and closes a connection with each database call. So when using transactions, you are attempting to spread a transaction out over multiple connections. This elevates to MSDTC.
(See this reference for more information.)
Changing my code to the following fixed it:
using (DatabaseEntities context = new DatabaseEntities())
{
context.Connection.Open();
// the rest
}
Why use regex for that. String
implements IEnumerable<char>
, so you can just use LINQ.
test.Count(c => c == '&')
To simplify the answare let's look on the following code:
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
private:
int m_id;
static int count;
public:
A() {count++; m_id = count;}
A(int id) { m_id = id; }
~A() {cout<< "Destructor A " <<m_id<<endl; }
};
int A::count = 0;
void f1()
{
A* arr = new A[10];
//delete operate only one constructor, and crash!
delete arr;
//delete[] arr;
}
int main()
{
f1();
system("PAUSE");
return 0;
}
The output is: Destructor A 1 and then it's crashing (Expression: _BLOCK_TYPE_IS_VALID(phead- nBlockUse)).
We need to use: delete[] arr; becuse it's delete the whole array and not just one cell!
try to use delete[] arr; the output is: Destructor A 10 Destructor A 9 Destructor A 8 Destructor A 7 Destructor A 6 Destructor A 5 Destructor A 4 Destructor A 3 Destructor A 2 Destructor A 1
The same principle is for an array of pointers:
void f2()
{
A** arr = new A*[10];
for(int i = 0; i < 10; i++)
{
arr[i] = new A(i);
}
for(int i = 0; i < 10; i++)
{
delete arr[i];//delete the A object allocations.
}
delete[] arr;//delete the array of pointers
}
if we'll use delete arr instead of delete[] arr. it will not delete the whole pointers in the array => memory leak of pointer objects!
As @Sarfraz already mentioned CSS, I'll just add HTML5 to the mix.
You can use the HTML5 placeholder
attribute:
<input type="text" placeholder="Placeholder text blah blah." />
Copy this script to notepad and save as .vbs file. Drag&Drop .js files on this script.
ps. This will work only on windows.
set objArgs = Wscript.Arguments
set objFso = CreateObject("Scripting.FileSystemObject")
content = ""
'Iterate through all the arguments passed
for i = 0 to objArgs.count
on error resume next
'Try and treat the argument like a folder
Set folder = objFso.GetFolder(objArgs(i))
'If we get an error, we know it is a file
if err.number <> 0 then
'This is not a folder, treat as file
content = content & ReadFile(objArgs(i))
else
'No error? This is a folder, process accordingly
for each file in folder.Files
content = content & ReadFile(file.path)
next
end if
on error goto 0
next
'Get system Temp folder path
set tempFolderPath = objFso.GetSpecialFolder(2)
'Generate a random filename to use for a temporary file
strTempFileName = objFso.GetTempName
'Create temporary file in Temp folder
set objTempFile = tempFolderPath.CreateTextFile(strTempFileName)
'Write content from JavaScript files to temporary file
objTempFile.WriteLine(content)
objTempFile.Close
'Open temporary file in Notepad
set objShell = CreateObject("WScript.Shell")
objShell.Run("Notepad.exe " & tempFolderPath & "\" & strTempFileName)
function ReadFile(strFilePath)
'If file path ends with ".js", we know it is JavaScript file
if Right(strFilePath, 3) = ".js" then
set objFile = objFso.OpenTextFile(strFilePath, 1, false)
'Read entire contents of a JavaScript file and returns it as a string
ReadFile = objFile.ReadAll & vbNewLine
objFile.Close
else
'Return empty string
ReadFile = ""
end if
end function
You can also use update_or_create just like get_or_create and here is the pattern I follow for update_or_create assuming a model Person with id (key), name, age, is_manager as attributes -
update_values = {"is_manager": False}
new_values = {"name": "Bob", "age": 25, "is_manager":True}
obj, created = Person.objects.update_or_create(identifier='id',
defaults=update_values)
if created:
obj.update(**new_values)
That flag is dangerous!! Leaves your file system open for access. Documents originating from anywhere, local or web, should not, by default, have any access to local file:/// resources.
Much better solution is to run a little http server locally.
--- For Windows ---
The easiest is to install http-server globally using node's package manager:
npm install -g http-server
Then simply run http-server
in any of your project directories:
Eg. d:\my_project> http-server
Starting up http-server, serving ./
Available on:
http:169.254.116.232:8080
http:192.168.88.1:8080
http:192.168.0.7:8080
http:127.0.0.1:8080
Hit CTRL-C to stop the server
Or as prusswan suggested, you can also install Python under windows, and follow the instructions below.
--- For Linux ---
Since Python is usually available in most linux distributions, just run python -m SimpleHTTPServer
in your project directory, and you can load your page on http://localhost:8000
In Python 3 the SimpleHTTPServer
module has been merged into http.server
, so the new command is python3 -m http.server
.
Easy, and no security risk of accidentally leaving your browser open vulnerable.
Even shorter version of the solution from Dominic Zukiewicz:
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.
I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit
tries to fit a function f
that you must know to a set of points.
This is a simple 3 degree polynomial fit using numpy.polyfit
and poly1d
, the first performs a least squares polynomial fit and the second calculates the new points:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
window.location.reload() // without passing true as argument
works for me.
The trick is to read the declaration backwards (right-to-left):
const int a = 1; // read as "a is an integer which is constant"
int const a = 1; // read as "a is a constant integer"
Both are the same thing. Therefore:
a = 2; // Can't do because a is constant
The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:
const char *s; // read as "s is a pointer to a char that is constant"
char c;
char *const t = &c; // read as "t is a constant pointer to a char"
*s = 'A'; // Can't do because the char is constant
s++; // Can do because the pointer isn't constant
*t = 'A'; // Can do because the char isn't constant
t++; // Can't do because the pointer is constant
Tool: Using Proguard in your application it can be restricted to reverse engineering your application
There'a an add-in for Visual Studio 2008 that converts the end of line format when a file is saved. You can download it here: http://grebulon.com/software/stripem.php
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});
I received this error when I tried to launch app from Xcode as I figured I had selected distribution profile only. Build was successful so I created .ipa file. I used testflightapp.com to run the app. You can use iTunes as well.
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
This happens to me every time I add a pod to the podfile.
I constantly try and find the problem but I just go round in circles again and again!
The error messages range, however the way to fix it is the same every time!
Comment out(#) ALL of the pods in the podfile and run pod install in terminal.
Then...
Uncomment out all of the pods in the podfile and run pod install again.
This has worked for me every single time!
In the end, the difference between try, except
and testing len(sys.argv)
isn't all that significant. They're both a bit hackish compared to argparse
.
This occurs to me, though -- as a sort of low-budget argparse:
arg_names = ['command', 'x', 'y', 'operation', 'option']
args = dict(zip(arg_names, sys.argv))
You could even use it to generate a namedtuple
with values that default to None
-- all in four lines!
Arg_list = collections.namedtuple('Arg_list', arg_names)
args = Arg_list(*(args.get(arg, None) for arg in arg_names))
In case you're not familiar with namedtuple
, it's just a tuple that acts like an object, allowing you to access its values using tup.attribute
syntax instead of tup[0]
syntax.
So the first line creates a new namedtuple
type with values for each of the values in arg_names
. The second line passes the values from the args
dictionary, using get
to return a default value when the given argument name doesn't have an associated value in the dictionary.
The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:
set rowcount @top
select * from sometable
set rowcount 0
Hope this helps
Oisin.
(edited to replace @@rowcount with rowcount - thanks augustlights)
I typed
git checkout <branch_name>
and got
Branch <branch_name> set up to track remote branch <branch_name> from origin.
Switched to a new branch '<branch_name>'
There is no sentence caps option in CSS. The other answers suggesting text-transform: capitalize
are incorrect as that option capitalizes each word.
Here's a crude way to accomplish it if you only want the first letter of each element to be uppercase, but it's definitely nowhere near actual sentence caps:
p {
text-transform: lowercase;
}
p:first-letter {
text-transform: uppercase;
}
<p>THIS IS AN EXAMPLE SENTENCE.</p>
<p>THIS IS ANOTHER EXAMPLE SENTENCE.
AND THIS IS ANOTHER, BUT IT WILL BE ENTIRELY LOWERCASE.</p>
"Resetting" styles for a specific element isn't possible, you'll have to overwrite all styles you don't want/need. If you do this with CSS directly or using JQuery to apply the styles (depends on what's easier for you, but I wouldn't recommend using JavaScript/JQuery for this, as it's completely unnecessary).
If your div is some kind of "widget" that can be included into other sites, you could try to wrap it into an iframe. This will "reset" the styles, because its content is another document, but maybe this affects how your widget works (or maybe breaks it completely) so this might not be possible in your case.
this works fine, but file name does not display anymore.
$(document).ready(function(){ $("img.attach2").click(function(){ $("input.attach1").click(); return false; }); });
You can do it in two ways, choose what suits your requirement:
Method I.) Replacing using line number. You can use built-in function enumerate()
in this case:
First, in read mode get all data in a variable
with open("your_file.txt",'r') as f:
get_all=f.readlines()
Second, write to the file (where enumerate comes to action)
with open("your_file.txt",'w') as f:
for i,line in enumerate(get_all,1): ## STARTS THE NUMBERING FROM 1 (by default it begins with 0)
if i == 2: ## OVERWRITES line:2
f.writelines("Mage\n")
else:
f.writelines(line)
Method II.) Using the keyword you want to replace:
Open file in read mode and copy the contents to a list
with open("some_file.txt","r") as f:
newline=[]
for word in f.readlines():
newline.append(word.replace("Warrior","Mage")) ## Replace the keyword while you copy.
"Warrior" has been replaced by "Mage", so write the updated data to the file:
with open("some_file.txt","w") as f:
for line in newline:
f.writelines(line)
This is what the output will be in both cases:
Dan Dan
Warrior ------> Mage
500 500
1 1
0 0
TextView
comes with 4 compound drawables, one for each of left, top, right and bottom.
In your case, you do not need the LinearLayout
and ImageView
at all. Just add android:drawableLeft="@drawable/up_count_big"
to your TextView
.
See TextView#setCompoundDrawablesWithIntrinsicBounds for more info.
I'd recommend using Python's with
statement for managing resources that need to be cleaned up. The problem with using an explicit close()
statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a finally
block to prevent a resource leak when an exception occurs.
To use the with
statement, create a class with the following methods:
def __enter__(self)
def __exit__(self, exc_type, exc_value, traceback)
In your example above, you'd use
class Package:
def __init__(self):
self.files = []
def __enter__(self):
return self
# ...
def __exit__(self, exc_type, exc_value, traceback):
for file in self.files:
os.unlink(file)
Then, when someone wanted to use your class, they'd do the following:
with Package() as package_obj:
# use package_obj
The variable package_obj will be an instance of type Package (it's the value returned by the __enter__
method). Its __exit__
method will automatically be called, regardless of whether or not an exception occurs.
You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the with
clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the __enter__
and __exit__
methods. Then, the Package class would be defined strictly inside the __enter__
method and returned. That way, the caller never could instantiate the Package class without using a with
statement:
class PackageResource:
def __enter__(self):
class Package:
...
self.package_obj = Package()
return self.package_obj
def __exit__(self, exc_type, exc_value, traceback):
self.package_obj.cleanup()
You'd use this as follows:
with PackageResource() as package_obj:
# use package_obj
You can use zip
:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
... print x, y
...
1 a
2 b
3 c
rounded(_:)
method as blueprinted in the FloatingPoint
protocolThe FloatingPoint
protocol (to which e.g. Double
and Float
conforms) blueprints the rounded(_:)
method
func rounded(_ rule: FloatingPointRoundingRule) -> Self
Where FloatingPointRoundingRule
is an enum enumerating a number of different rounding rules:
case awayFromZero
Round to the closest allowed value whose magnitude is greater than or equal to that of the source.
case down
Round to the closest allowed value that is less than or equal to the source.
case toNearestOrAwayFromZero
Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.
case toNearestOrEven
Round to the closest allowed value; if two values are equally close, the even one is chosen.
case towardZero
Round to the closest allowed value whose magnitude is less than or equal to that of the source.
case up
Round to the closest allowed value that is greater than or equal to the source.
We make use of similar examples to the ones from @Suragch's excellent answer to show these different rounding options in practice.
.awayFromZero
Round to the closest allowed value whose magnitude is greater than or equal to that of the source; no direct equivalent among the C functions, as this uses, conditionally on sign of self
, ceil
or floor
, for positive and negative values of self
, respectively.
3.000.rounded(.awayFromZero) // 3.0
3.001.rounded(.awayFromZero) // 4.0
3.999.rounded(.awayFromZero) // 4.0
(-3.000).rounded(.awayFromZero) // -3.0
(-3.001).rounded(.awayFromZero) // -4.0
(-3.999).rounded(.awayFromZero) // -4.0
.down
Equivalent to the C floor
function.
3.000.rounded(.down) // 3.0
3.001.rounded(.down) // 3.0
3.999.rounded(.down) // 3.0
(-3.000).rounded(.down) // -3.0
(-3.001).rounded(.down) // -4.0
(-3.999).rounded(.down) // -4.0
.toNearestOrAwayFromZero
Equivalent to the C round
function.
3.000.rounded(.toNearestOrAwayFromZero) // 3.0
3.001.rounded(.toNearestOrAwayFromZero) // 3.0
3.499.rounded(.toNearestOrAwayFromZero) // 3.0
3.500.rounded(.toNearestOrAwayFromZero) // 4.0
3.999.rounded(.toNearestOrAwayFromZero) // 4.0
(-3.000).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.001).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.499).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.500).rounded(.toNearestOrAwayFromZero) // -4.0
(-3.999).rounded(.toNearestOrAwayFromZero) // -4.0
This rounding rule can also be accessed using the zero argument rounded()
method.
3.000.rounded() // 3.0
// ...
(-3.000).rounded() // -3.0
// ...
.toNearestOrEven
Round to the closest allowed value; if two values are equally close, the even one is chosen; equivalent to the C rint
(/very similar to nearbyint
) function.
3.499.rounded(.toNearestOrEven) // 3.0
3.500.rounded(.toNearestOrEven) // 4.0 (up to even)
3.501.rounded(.toNearestOrEven) // 4.0
4.499.rounded(.toNearestOrEven) // 4.0
4.500.rounded(.toNearestOrEven) // 4.0 (down to even)
4.501.rounded(.toNearestOrEven) // 5.0 (up to nearest)
.towardZero
Equivalent to the C trunc
function.
3.000.rounded(.towardZero) // 3.0
3.001.rounded(.towardZero) // 3.0
3.999.rounded(.towardZero) // 3.0
(-3.000).rounded(.towardZero) // 3.0
(-3.001).rounded(.towardZero) // 3.0
(-3.999).rounded(.towardZero) // 3.0
If the purpose of the rounding is to prepare to work with an integer (e.g. using Int
by FloatPoint
initialization after rounding), we might simply make use of the fact that when initializing an Int
using a Double
(or Float
etc), the decimal part will be truncated away.
Int(3.000) // 3
Int(3.001) // 3
Int(3.999) // 3
Int(-3.000) // -3
Int(-3.001) // -3
Int(-3.999) // -3
.up
Equivalent to the C ceil
function.
3.000.rounded(.up) // 3.0
3.001.rounded(.up) // 4.0
3.999.rounded(.up) // 4.0
(-3.000).rounded(.up) // 3.0
(-3.001).rounded(.up) // 3.0
(-3.999).rounded(.up) // 3.0
FloatingPoint
to verify the C functions equivalence to the different FloatingPointRoundingRule
rulesIf we'd like, we can take a look at the source code for FloatingPoint
protocol to directly see the C function equivalents to the public FloatingPointRoundingRule
rules.
From swift/stdlib/public/core/FloatingPoint.swift.gyb we see that the default implementation of the rounded(_:)
method makes us of the mutating round(_:)
method:
public func rounded(_ rule: FloatingPointRoundingRule) -> Self { var lhs = self lhs.round(rule) return lhs }
From swift/stdlib/public/core/FloatingPointTypes.swift.gyb we find the default implementation of round(_:)
, in which the equivalence between the FloatingPointRoundingRule
rules and the C rounding functions is apparent:
public mutating func round(_ rule: FloatingPointRoundingRule) { switch rule { case .toNearestOrAwayFromZero: _value = Builtin.int_round_FPIEEE${bits}(_value) case .toNearestOrEven: _value = Builtin.int_rint_FPIEEE${bits}(_value) case .towardZero: _value = Builtin.int_trunc_FPIEEE${bits}(_value) case .awayFromZero: if sign == .minus { _value = Builtin.int_floor_FPIEEE${bits}(_value) } else { _value = Builtin.int_ceil_FPIEEE${bits}(_value) } case .up: _value = Builtin.int_ceil_FPIEEE${bits}(_value) case .down: _value = Builtin.int_floor_FPIEEE${bits}(_value) } }
I got much better solution .
here is my directive , I have injected on object reference in directive and has extend that by adding invoke function in directive code .
app.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
/*The object that passed from the cntroller*/
objectToInject: '=',
},
templateUrl: 'templates/myTemplate.html',
link: function ($scope, element, attrs) {
/*This method will be called whet the 'objectToInject' value is changes*/
$scope.$watch('objectToInject', function (value) {
/*Checking if the given value is not undefined*/
if(value){
$scope.Obj = value;
/*Injecting the Method*/
$scope.Obj.invoke = function(){
//Do something
}
}
});
}
};
});
Declaring the directive in the HTML with a parameter:
<my-directive object-to-inject="injectedObject"></ my-directive>
my Controller:
app.controller("myController", ['$scope', function ($scope) {
// object must be empty initialize,so it can be appended
$scope.injectedObject = {};
// now i can directly calling invoke function from here
$scope.injectedObject.invoke();
}];
I moved Android folder path to another path and taked this error.
I resolved to this problem in below.
I was changed to Gradle path in system variables. But not path in user variables. You must change to path in system variables
Check to see if the key-value pair is actually showing up in the request:
In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers
Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like:
F12: Developer Tools > Sources Tab > YourJavascriptSrc.js
and check your code.
But as other answers have said:
xhttp.setRequestHeader(key, value);
should add a key-value pair to your request header, just make sure to place it after your open()
and before your send()
You can close the connection with
mongoose.connection.close()
The line
Object EchoServer0;
says that you are allocating an Object
named EchoServer0
. This has nothing to do with the class EchoServer0
. Furthermore, the object is not initialized, so EchoServer0
is null
. Classes and identifiers have separate namespaces. This will actually compile:
String String = "abc"; // My use of String String was deliberate.
Please keep to the Java naming standards: classes begin with a capital letter, identifiers begin with a small letter, constants and enum
s are all-capitals.
public final String ME = "Eric Jablow";
public final double GAMMA = 0.5772;
public enum Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET}
public COLOR background = Color.RED;
Here is the correct test of the device, without depending on the orientation
- (BOOL)isIPhone5
{
CGSize size = [[UIScreen mainScreen] bounds].size;
if (MIN(size.width,size.height) == 320 && MAX(size.width,size.height == 568)) {
return YES;
}
return NO;
}
<script type="text/javascript">
$(document).ready(function(){
$('.appBanner').fadeOut('slow');
});
</script>
or
<script type="text/javascript">
$(document).ready(function(){
$('.appBanner').hide();
});
</script>
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
<a [routerLink]="" (click)="openSite(SiteUrl)">{{SiteUrl}}</a>
and in your Component.ts
openSite(siteUrl) {
window.open("//" + siteUrl, '_blank');
}
It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.
Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.
If you really want to dig into it, I'd look at the source. Here's the header comment:
"""
client module for memcached (memory cache daemon)
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
This should give you a feel for how this module operates::
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
mc.set("some_key", "Some value")
value = mc.get("some_key")
mc.set("another_key", 3)
mc.delete("another_key")
mc.set("key", "1") # note that the key used for incr/decr must be a string.
mc.incr("key")
mc.decr("key")
The standard way to use memcache with a database is like this::
key = derive_key(obj)
obj = mc.get(key)
if not obj:
obj = backend_api.get(...)
mc.set(key, obj)
# we now have obj, and future passes through this code
# will use the object from the cache.
Detailed Documentation
======================
More detailed documentation is available in the L{Client} class.
"""
The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!
Two notes from experience which might be helpful:
You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.
If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.
a piece of cake. i did it for string but, it's not much different
Click on this link to see which version your BROWSER is using: http://jsfiddle.net/Ac6CT/
You should be able filter by using script tags to each JS version.
<script type="text/javascript">
var jsver = 1.0;
</script>
<script language="Javascript1.1">
jsver = 1.1;
</script>
<script language="Javascript1.2">
jsver = 1.2;
</script>
<script language="Javascript1.3">
jsver = 1.3;
</script>
<script language="Javascript1.4">
jsver = 1.4;
</script>
<script language="Javascript1.5">
jsver = 1.5;
</script>
<script language="Javascript1.6">
jsver = 1.6;
</script>
<script language="Javascript1.7">
jsver = 1.7;
</script>
<script language="Javascript1.8">
jsver = 1.8;
</script>
<script language="Javascript1.9">
jsver = 1.9;
</script>
<script type="text/javascript">
alert(jsver);
</script>
My Chrome reports 1.7
Blatantly stolen from: http://javascript.about.com/library/bljver.htm
Try jQuery's delegate()
function, like so:
$(document).ready(function(){
$("div.custList table").delegate('tr', 'click', function() {
alert("You clicked my <tr>!");
//get <td> element values here!!??
});
});
A delegate works in the same way as live()
except that live()
cannot be applied to chained items, whereas delegate()
allows you to specify an element within an element to act on.
This will do it:
window.history.pushState(null,null,'https://www.google.com');
the error for Response.END(); is because you are using a asp update panel or any control that using javascript, try to use control native from asp or html without javascript or scriptmanager or scripting and try again
The consequence of this is that you may need a rather insane-looking query, e. g.,
SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID] AS lngRecordID
,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName] AS vcrSourceWorkbookName
,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName] AS vcrImportFileName
,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime] AS dtmLastWriteTime
,[dbo].[tblTimeSheetExportFiles].[lngNRecords] AS lngNRecords
,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk] AS lngSizeOnDisk
,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity] AS lngLastIdentity
,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
,MIN ( [tblTimeRecords].[dtmActivity_Date] ) AS dtmPeriodFirstWorkDate
,MAX ( [tblTimeRecords].[dtmActivity_Date] ) AS dtmPeriodLastWorkDate
,SUM ( [tblTimeRecords].[decMan_Hours_Actual] ) AS decHoursWorked
,SUM ( [tblTimeRecords].[decAdjusted_Hours] ) AS decHoursBilled
FROM [dbo].[tblTimeSheetExportFiles]
LEFT JOIN [dbo].[tblTimeRecords]
ON [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
GROUP BY [dbo].[tblTimeSheetExportFiles].[lngRecordID]
,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]
Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.
I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
lets see how we make this
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
here's how it works
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
this is the params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
This function would suit if you have to append many element, if there is any way to improve this answer please let me know.
edit:
Here is a working demo
This can be highly customized to suit your project!
They are used in a similar way but they have a few differences. Here is a link to the TemplateBinding documentation: http://msdn.microsoft.com/en-us/library/ms742882.aspx
You can use a simple regular expression:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
Or you can use the below functions too, according your needs. They are developed by the PHPJS Project.
is_int()
=> Check if variable type is integer and if its content is integer
is_float()
=> Check if variable type is float and if its content is float
ctype_digit()
=> Check if variable type is string and if its content has only decimal digits
Update 1
Now it checks negative numbers too, thanks for @ChrisBartley comment!
Here's an option if you have multiple records for each Customer and are looking for the latest balance for each (say they are dated records):
SELECT ID, BALANCE FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateModified DESC) as RowNum, ID, BALANCE
FROM CUSTOMERS
) C
WHERE RowNum = 1
OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.
#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif
Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:
BARNABY_API int add(){
}
This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.
use #undef UNICODE
at the top of your main file.
I'm not quite sure if I'm allowed to answer a question that was asked like 2 years ago as this is my first answer on stackoverflow but, here's my solution;
If you once retrieved the date from your MySQL database, split it and then use the splitted values.
$(document).ready(function () {
var datefrommysql = $('.date-from-mysql').attr("date");
var arraydate = datefrommysql.split('.');
var yearfirstdigit = arraydate[2][2];
var yearlastdigit = arraydate[2][3];
var day = arraydate[0];
var month = arraydate[1];
$('.formatted-date').text(day + "/" + month + "/" + yearfirstdigit + yearlastdigit);
});
Here's a fiddle.
I like the approach from Fusion, but there's a small error in it. Like that it is correct:
function closest(array, number) {
var num = 0;
for (var i = array.length - 1; i >= 0; i--) {
if(Math.abs(number - array[i]) < Math.abs(number - array[num])){
num = i;
}
}
return array[num];
}
It it also a bit faster because it uses the improved for
loop.
At the end I wrote my function like this:
var getClosest = function(number, array) {
var current = array[0];
var difference = Math.abs(number - current);
var index = array.length;
while (index--) {
var newDifference = Math.abs(number - array[index]);
if (newDifference < difference) {
difference = newDifference;
current = array[index];
}
}
return current;
};
I tested it with console.time()
and it is slightly faster than the other function.
I installed xampp bundle with apache, php and mysql
in ubuntu. There my.cnf
file is located in /opt/lampp/etc/
folder. Hope it'll help somebody.
Or the KISS answer for short lists:
[(i, j) for i in list1 for j in list2]
Not as performant as itertools but you're using python so performance is already not your top concern...
I like all the other answers too!
I had this error message show up for me because I was using the network on the main thread and new versions of Android have a "strict" policy to prevent that. To get around it just throw whatever network connection call into an AsyncTask.
Example:
AsyncTask<CognitoCachingCredentialsProvider, Integer, Void> task = new AsyncTask<CognitoCachingCredentialsProvider, Integer, Void>() {
@Override
protected Void doInBackground(CognitoCachingCredentialsProvider... params) {
AWSSessionCredentials creds = credentialsProvider.getCredentials();
String id = credentialsProvider.getCachedIdentityId();
credentialsProvider.refresh();
Log.d("wooohoo", String.format("id=%s, token=%s", id, creds.getSessionToken()));
return null;
}
};
task.execute(credentialsProvider);
I would suggest using the members of string, but with an explicit encoding:
byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");
By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes()
etc:
EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.
Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.
EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset
instead. Using Guava I'd really use:
byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
Why do not use it?
$scope.get_location=function(url_str){
var parser = document.createElement('a');
parser.href =url_str;//"http://example.com:3000/pathname/?search=test#hash";
var info={
protocol:parser.protocol,
hostname:parser.hostname, // => "example.com"
port:parser.port, // => "3000"
pathname:parser.pathname, // => "/pathname/"
search:parser.search, // => "?search=test"
hash:parser.hash, // => "#hash"
host:parser.host, // => "example.com:3000"
}
return info;
}
alert( JSON.stringify( $scope.get_location("http://localhost:257/index.php/deploy/?asd=asd#asd"),null,4 ) );
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.