Scrum is a very specific set of practices. Agile describes a family of practices, everything from Extreme Programming to Scrum and almost anything else that uses short iterations can claim Agile. That may not have originally been the case when the term was coined, but it certainly is by now.
Scrum is just one of the many iterative and incremental agile software development methods. You can find here a very detailed description of the process.
In the SCRUM methodology, a Sprint is the basic unit of development. Each Sprint starts with a planning meeting, where the tasks for the sprint are identified and an estimated commitment for the sprint goal is made. A Sprint ends with a review or retrospective meeting where the progress is reviewed and lessons for the next sprint are identified. During each Sprint, the team creates finished portions of a Product.
In the Agile methods each iteration involves a team working through a full software development cycle, including planning, requirements analysis, design, coding, unit testing, and acceptance testing when a working product is demonstrated to stakeholders.
So if in a SCRUM Sprint you perform all the software development phases (from requirement analysis to acceptance testing), and in my opinion you should, you can say SCRUM Sprints correspond to AGILE Iterations.
EDIT: Kanbanize is a commercial product and offers a 30 day free trial.
Disclosing: I am a co-founder of http://kanbanize.com/
Mark, I understand your desire to find the perfect application with all these features inside, but I really doubt that you will get it for free. There's a bunch of super cool apps (including Kanbanize) out there, but none of them is completely free.
Be careful what you call a Kanban board and what not, though. Trello is definitely NOT a kanban system (no WIP limits, no analytics, etc.). It is a great visual management system, but not a Kanban one.
Finally, to answer your question, tools that deserve attention in my opinion are: Kanbanize (of course), LeanKit, KanbanTool, Kanbanery and probably a few others. My personal bias is that LeanKit is the most advanced to date followed by Kanbanize and KanbanTool.
I hope that helps.
Some important and successfully executed software projects like Google Chrome and Mozilla Firefox are fine examples of both iterative and incremental software development.
I will quote fine ars technica article which describes this approach: http://arstechnica.com/information-technology/2010/07/chrome-team-sets-six-week-cadence-for-new-major-versions/
According to Chrome program manager Anthony Laforge, the increased pace is designed to address three main goals. One is to get new features out to users faster. The second is make the release schedule predictable and therefore easier to plan which features will be included and which features will be targeted for later releases. Third, and most counterintuitive, is to cut the level of stress for Chrome developers. Laforge explains that the shorter, predictable time periods between releases are more like "trains leaving Grand Central Station." New features that are ready don't have to wait for others that are taking longer to complete—they can just hop on the current release "train." This can in turn take the pressure off developers to rush to get other features done, since another release train will be coming in six weeks. And they can rest easy knowing their work isn't holding the train from leaving the station.<<
According to my experience
ref: https://en.wikipedia.org/wiki/Scrum_(software_development)
I've had good luck with the SWF::File library on CPAN, and particularly the dumpswf.plx tool that comes with that distribution. It generates Perl code that, when run, regenerates your SWF.
Open database properties --> options and set Database read-only to False.
Did the trick for me...
Here is an instructions for the problem:
You can evaluate Visual Studio for free up to 30 days.
To Unlock Visual Studio using an online subscription
Link Microsoft account to Visual Studio 2015
I have encountered this problem:
Possible solution can be found at the link above.
This message indicates that while your subscription may still be valid, the license token Visual Studio uses to keep your subscription up to date hasn’t been refreshed and has gone stale due to one of the following reasons: You have not used Visual Studio or have had no internet connection for an extend period of time. You signed out of Visual Studio.
To achieve your current need, you need to fire below query
> insert overwrite table student
> select *from student
> where id <> 1;
This will delete current table and create new table with same name with all rows except the rows that you want to exclude/delete
I tried this on Hive 1.2.1
push
does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action){
console.log(arr);
switch (action.type){
case ADD_ITEM :
return {
...state,
arr:[...state.arr, action.newItem]
}
default:return state
}
}
Firstly, PHP doesn't have multi-dimensional arrays, it has arrays of arrays.
Secondly, you can write a function that will do it:
function declare($m, $n, $value = 0) {
return array_fill(0, $m, array_fill(0, $n, $value));
}
Open CMD or Powershell in Administrator mode, then run...
netstat -ab
The output should be able to point you in the direction of which process is holding port 8080. Entry may likely be 127.0.0.1:8080
You may still have a running instance of Tomcat at port 8080
.
You can either use Stop-Process
in PowerShell or taskKill
in CMD to stop that process and should be able to execute the program at that point.
The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:
git push origin master
Which will create this new master branch for you. Little things like this are very confusing with git.
If this didn't fix your issue then it's probably a gitolite-related issue:
Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:
repo phonegap
RW+ = myusername otherusername
repo gitolite-admin
RW+ = myusername
Please make sure you're setting your conf file correctly.
Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.
Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.
The greps can be chained. For example:
tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"
public string Hash(byte [] temp)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(temp);
return Convert.ToBase64String(hash);
}
}
EDIT:
You could also specify the encoding when converting the byte array to string as follows:
return System.Text.Encoding.UTF8.GetString(hash);
or
return System.Text.Encoding.Unicode.GetString(hash);
The simplest solution is to go to your XML layout containing your webview. Change your android:layout_width and android:layout_height from "wrap_content" to "match_parent".
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"/>
I think there's no foolproof way to do it. For example, consider the following:
$t = "A+B";
Is that an URL encoded "A B" or does it need to be encoded to "A%2BB"?
Just use this code, If you want values of [Category] and [CreationDate] columns
SELECT [Category], MAX([CreationDate]) FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
Or use this code, If you want only values of [Category] column.
SELECT [Category] FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
You'll have all the distinct records what ever you want.
For me I wanted a regex which supports a strings as preceding. Basically, the motive is to support some foreign countries postal format as it should be an alphanumeric with spaces allowed.
So I ended up by writing custom regex as below.
/^([a-z]+[\s]*[0-9]+[\s]*)+$/i
Here, I gave * in [\s]*
as it is not mandatory to have a space. A postal code may or may not contains space in my case.
Here you can add one month for the first day of current month than delete 1 day from that day.
DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
You can also try my ubuntu repository: https://launchpad.net/~mmk2410/+archive/ubuntu/intellij-idea
To use it just run the following commands:
sudo apt-add-repository ppa:mmk2410/intellij-idea
sudo apt-get update
The community edition can then installed with
sudo apt-get install intellij-idea-community
and the ultimate edition with
sudo apt-get install intellij-idea-ultimate
Yes, you can Make a Batch file with the following code:
cd \Desktop
echo $Shell = New-Object -ComObject Shell.Application >>FILENAME.ps1
echo $RecBin = $Shell.Namespace(0xA) >>FILENAME.ps1
echo $RecBin.Items() ^| %%{Remove-Item $_.Path -Recurse -Confirm:$false} >>FILENAME.ps1
REM The actual lines being writen are right, exept for the last one, the actual thigs being writen are "$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}"
But since | and % screw things up, i had to make some changes.
Powershell.exe -executionpolicy remotesigned -File C:\Desktop\FILENAME.ps1
This basically creates a powershell script that empties the trash in the \Desktop directory, then runs it.
If you are looking for a pattern in a directory recursively, you can either first save it to file.
ls -1R ./ | list-of-files.txt
And then grep that, or pipe it to the grep search
ls -1R | grep --color -rE '[A-Z]|'
This will look of listing all files, but colour the ones with uppercase letters. If you remove the last | you will only see the matches.
I use this to find images named badly with upper case for example, but normal grep does not show the path for each file just once per directory so this way I can see context.
I think that this construct: if exists (select...
is specific for MS SQL. In MySQL EXISTS
predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
You can rewrite the above lines of code like this:
DELIMITER $$
CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
BEGIN
DECLARE count_prim INT;
DECLARE count_sec INT;
SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;
if (count_prim > 0) then
set resultado = 0;
elseif (count_sec > 0) then
set resultado = -1;
else
set resultado = -2;
end if;
SELECT resultado;
END
See the answer to this question on address validating with regex: regex street address match
The problem is, street addresses vary so much in formatting that it's hard to code against them. If you are trying to validate addresses, finding if one isn't valid based on its format is mighty hard to do. This would return the following address (253 N. Cherry St. ), anything with its same format:
\d{1,5}\s\w.\s(\b\w*\b\s){1,2}\w*\.
This allows 1-5 digits for the house number, a space, a character followed by a period (for N. or S.), 1-2 words for the street name, finished with an abbreviation (like st. or rd.).
Because regex is used to see if things meet a standard or protocol (which you define), you probably wouldn't want to allow for the addresses provided above, especially the first one with the dash, since they aren't very standard. you can modify my above code to allow for them if you wish--you could add
(-?)
to allow for a dash but not require one.
In addition, http://rubular.com/ is a quick and interactive way to learn regex. Try it out with the addresses above.
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
.... but how do we find the equivalent class in the second List to pass to the method below;
This is your actual problem; you must have at least one immutable property, a id or something like that, to identify corresponding objects in both lists. If you do not have such a property you, cannot solve the problem without errors. You can just try to guess corresponding objects by searching for minimal or logical changes.
If you have such an property, the solution becomes really simple.
Enumerable.Join(
listA, listB,
a => a.Id, b => b.Id,
(a, b) => CompareTwoClass_ReturnDifferences(a, b))
thanks to you both danbruc and Noldorin for your feedback. both Lists will be the same length and in the same order. so the method above is close, but can you modify this method to pass the enum.Current to the method i posted above?
Now I am confused ... what is the problem with that? Why not just the following?
for (Int32 i = 0; i < Math.Min(listA.Count, listB.Count); i++)
{
yield return CompareTwoClass_ReturnDifferences(listA[i], listB[i]);
}
The Math.Min() call may even be left out if equal length is guaranted.
Noldorin's implementation is of course smarter because of the delegate and the use of enumerators instead of using ICollection.
Ran into this issue while trying to create an index on a perfectly valid database. Turns out it will throw this error (in addition to other reasons described here) if the sqlite temp_store_directory
variable/directory is unwritable.
Solution: change temp_store_directory
with c.execute(f'PRAGMA temp_store_directory = "{writable_directory}"')
. Note that this pragma is being deprecated and I am not yet sure what the replacement will be.
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
There is a much easier way to get the smooth scroll effect without javascript. In your CSS just target the entire html tag and give it scroll-behavior: smooth;
html {_x000D_
scroll-behavior: smooth;_x000D_
}_x000D_
_x000D_
a {_x000D_
text-decoration: none;_x000D_
color: black;_x000D_
} _x000D_
_x000D_
#down {_x000D_
margin-top: 100%;_x000D_
padding-bottom: 25%;_x000D_
}
_x000D_
<html>_x000D_
<a href="#down">Click Here to Smoothly Scroll Down</a>_x000D_
<div id="down">_x000D_
<h1>You are down!</h1>_x000D_
</div>_x000D_
</html
_x000D_
The "scroll-behavior" is telling the page how it should scroll and is so much easier than using javascript. Javascript will give you more options on speed and the smoothness but this will deliver without all of the confusing code.
The inline-block
display style seems to do what you want. Note that the <nobr>
tag is deprecated, and should not be used. Non-breaking white space is doable in CSS. Here's how I would alter your example style rules:
div { display: inline-block; white-space: nowrap; }
.success { background-color: #ccffcc; }
Alter your stylesheet, remove the <nobr>
tags from your source, and give it a try. Note that display: inline-block
does not work in every browser, though it tends to only be problematic in older browsers (newer versions should support it to some degree). My personal opinion is to ignore coding for broken browsers. If your code is standards compliant, it should work in all of the major, modern browsers. Anyone still using IE6 (or earlier) deserves the pain. :-)
tar -cvzf tarlearn.tar.gz --remove-files mytemp/*
If the folder is mytemp then if you apply the above it will zip and remove all the files in the folder but leave it alone
tar -cvzf tarlearn.tar.gz --remove-files --exclude='*12_2008*' --no-recursion mytemp/*
You can give exclude patterns and also specify not to look into subfolders too
If you have multiple headers then you might want to use the following:
curl -X POST --header "Content-Type:application/json" --header "X-Auth:AuthKey" --data @hello.json Your_url
Here's an example that let's you set the color of the background. If you don't want to use float, then you might need to set the width and height manually. But even that really depends on the surrounding CSS/HTML.
<style>
#color {
background-color: red;
float: left;
}#opacity {
opacity : 0.4;
filter: alpha(opacity=40);
}
</style>
<div id="color">
<div id="opacity">
<img src="image.jpg" />
</div>
</div>
Put the modal and javascript into the partial view. Then call the partial view in your page. This will handle form submission too.
Partial View
<div id="confirmDialog" class="modal fade" data-backdrop="false">
<div class="modal-dialog" data-backdrop="false">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Missing Service Order</h4>
</div>
<div class="modal-body">
<p>You have not entered a Service Order. Do you want to continue?</p>
</div>
<div class="modal-footer">
<input id="btnSubmit" type="submit" class="btn btn-primary"
value="Submit" href="javascript:"
onClick="document.getElementById('Coordinate').submit()" />
<button type="button" class="btn btn-default" data-
dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
Javascript
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#Coordinate").on('submit',
function (e) {
if ($("#ServiceOrder").val() == '') {
e.preventDefault();
$('#confirmDialog').modal('show');
}
});
});
</script>
Then just call your partial inside the form of your page.
Create.cshtml
@using (Html.BeginForm("Edit","Home",FormMethod.Post, new {id ="Coordinate"}))
{
//Form Code
@Html.Partial("ConfirmDialog")
}
I chose to strip these characters out of the string by doing this -
ini_set('mbstring.substitute_character', "none");
$text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');
awk, sed, pipe, that's heavy
set `cat /etc/*release`; echo $1
This will open the link in a new tab in Chrome and Firefox, and possibly more browsers I haven't tested:
var popup = $window.open("about:blank", "_blank"); // the about:blank is to please Chrome, and _blank to please Firefox
popup.location = 'newpage.html';
It basically opens a new empty tab, and then sets the location of that empty tab. Beware that it is a sort of a hack, since browser tab/window behavior is really the domain, responsibility and choice of the Browser and the User.
The second line can be called in a callback (after you've done some AJAX request for example), but then the browser would not recognize it as a user-initiated click-event, and may block the popup.
You may wish to create an array and use that instead of the read-only filelist.
var myReadWriteList = new Array();
// user selects files later...
// then as soon as convenient...
myReadWriteList = FileListReadOnly;
After that point do your uploading against your list instead of the built in list. I am not sure of the context you are working in but I am working with a jquery plugin I found and what I had to do was take the plugin's source and put it in the page using <script>
tags. Then above the source I added my array so that it can act as a global variable and the plugin could reference it.
Then it was just a matter of swapping out the references.
I think this would allow you to also add drag & drop as again, if the built in list is read-only then how else could you get the dropped files into the list?
:))
Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.
inside templateHTML.html:
<form action="#" method="get">
<input type="text" value="8" name="mytextbox" size="1"/>
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
inside view.py:
import mypythoncode
def request_page(request):
if(request.GET.get('mybtn')):
mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')
You can use LiteWare.Configuration library for that. It is very similar to .NET Framework original ConfigurationManager
and works for .NET Core/Standard. Code-wise, you'll end up with something like:
string cacheDirectory = ConfigurationManager.AppSettings.GetValue<string>("CacheDirectory");
ulong cacheFileSize = ConfigurationManager.AppSettings.GetValue<ulong>("CacheFileSize");
Disclaimer: I am the author of LiteWare.Configuration.
Edit: you should now use brew services start mongodb
, as in Gergo's answer...
When you install/upgrade mongodb, brew will tell you what to do:
To have launchd start mongodb at login:
ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don't want/need launchctl, you can just run:
mongod
It works perfectly.
The main thread is the UI thread, and you cannot do an operation in the main thread which may block the user interaction. You can solve this in two ways:
Force to do the task in the main thread like this
StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(threadPolicy);
Or create a simple handler and update the main thread if you want.
Runnable runnable;
Handler newHandler;
newHandler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
try {
//update UI
} catch (Exception e) {
e.printStackTrace();
}
}
};
newHandler.post(runnable);
And to stop the thread use:
newHandler.removeCallbacks(runnable);
For more information check this out: Painless threading
The problem is due to the input element box model. I just recently found a nice solution to the issue when trying to keep my input at 100% for mobile devices.
Wrap your input with another element, a div for example. Then apply the styling you want for your input to that the wrapper div. For example:
<div class="input-wrapper">
<input type="text" />
</div>
.input-wrapper {
border-raius:5px;
padding:10px;
}
.input-wrapper input[type=text] {
width:100%;
font-size:16px;
}
Give .input-wrapper rounded corner padding etc, whatever you want for your input, then give the input width 100%. You have your input padded nicely with a border etc but without the annoying overflow!
var obj = {_x000D_
key1: 'value1',_x000D_
key2: 'value2',_x000D_
key3: 'value3',_x000D_
key4: 'value4'_x000D_
}_x000D_
var keys = Object.keys(obj);_x000D_
console.log('obj contains ' + keys.length + ' keys: '+ keys);
_x000D_
It's supported on most major browsers now.
Say you have defined your class like this:
@Data
@AllArgsConstructor(staticName = "of")
private class Pair<P,Q> {
public P first;
public Q second;
}
So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.
Pair<Integer, String> pair = Pair.of(menuItemId, category);
If you define it like this, you will get the error asked for.
Pair<Integer, String> pair = new Pair(menuItemId, category);
I've tested this using the following powershell script and using (,) between the addresses. It worked for me!
$EmailFrom = "<[email protected]>";
$EmailPassword = "<password>";
$EmailTo = "<[email protected]>,<[email protected]>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);
Try this way:
select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE()
You can use a regular expression to test for a match and capture the first two digits:
import re
for i in range(1000):
match = re.match(r'(1[56])', str(i))
if match:
print(i, 'begins with', match.group(1))
The regular expression (1[56])
matches a 1 followed by either a 5 or a 6 and stores the result in the first capturing group.
Output:
15 begins with 15
16 begins with 16
150 begins with 15
151 begins with 15
152 begins with 15
153 begins with 15
154 begins with 15
155 begins with 15
156 begins with 15
157 begins with 15
158 begins with 15
159 begins with 15
160 begins with 16
161 begins with 16
162 begins with 16
163 begins with 16
164 begins with 16
165 begins with 16
166 begins with 16
167 begins with 16
168 begins with 16
169 begins with 16
in flask using flask.ext.script, you can do it like this:
python manage.py runserver -h 127.0.0.1 -p 8000
Export this folder to a backup file and try remove this folder and all the content.
HKEY_CURRENT_USER\Software\Microsoft\Script Debugger
This also works on MAC OS:
Prev tab: Shift + Cmd + [
Next Tab: Shift + Cmd + ]
Think about what the code actually says!
>>> (1 or 2)
1
>>> (2 or 1)
2
That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:
def or(x, y):
if x: return x
if y: return y
return False
In the first example, x == 1
and y == 2
. In the second example, it's vice versa. That's why it returns different values depending on the order of them.
As suggested by @EboMike I saved the bitmap in a file named myImage in the internal storage of my application not accessible my other apps. Here's the code of that part:
public String createImageFromBitmap(Bitmap bitmap) {
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
Then in the next activity you can decode this file myImage to a bitmap using following code:
Bitmap bitmap = BitmapFactory.decodeStream(context
.openFileInput("myImage"));//here context can be anything like getActivity() for fragment, this or MainActivity.this
Note A lot of checking for null and scaling bitmap's is ommited.
I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.
If you'd like to use it as well, then:
Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.
Unzip TortoiseIDiff.exe
and TortoiseMerge.exe
to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\
in my case).
In SourceTree open Tools > Options > Diff > External Diff / Merge
. Select TortoiseMerge
in both dropdown lists.
Hit OK
and point SourceTree to your location of TortoiseIDiff.exe
and TortoiseMerge.exe
.
After that, you can select Resolve Conflicts > Launch External Merge Tool
from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.
The only problem is, that it automatically creates backup copy, even though proper option is unchecked.
It turns out that there is a float: left
property by default on all navbar-nav>li
elements, which is why they were all scrunching up to the left. Once I added the code below, it made the navbar
both centered and not scrunched up.
.navbar-nav>li {
float: none;
}
Hope this helps someone else who's looking to center a navbar
.
The original question hinted that it would be nice to be able to filter all the properties based on a prefix. I have just confirmed that this works as of Spring Boot 2.1.1.RELEASE, for Properties
or Map<String,String>
. I'm sure it's worked for while now. Interestingly, it does not work without the prefix =
qualification, i.e. I do not know how to get the entire environment loaded into a map. As I said, this might actually be what OP wanted to begin with. The prefix and the following '.' will be stripped off, which might or might not be what one wants:
@ConfigurationProperties(prefix = "abc")
@Bean
public Properties getAsProperties() {
return new Properties();
}
@Bean
public MyService createService() {
Properties properties = getAsProperties();
return new MyService(properties);
}
Postscript: It is indeed possible, and shamefully easy, to get the entire environment. I don't know how this escaped me:
@ConfigurationProperties
@Bean
public Properties getProperties() {
return new Properties();
}
Adam has already suggested database profiles.
You could check the SQLNET.ORA file. There's an EXPIRE_TIME parameter but this is for detecting lost connections, rather than terminating existing ones.
Given it happens overnight, it sounds more like an idle timeout, which could be down to a firewall between the app server and database server. Setting the EXPIRE_TIME may stop that happening (as there'll be check every 10 minutes to check the client is alive).
Or possibly the database is being shutdown and restarted and that is killing the connections.
Alternatively, you should be able to configure tomcat with a validationQuery so that it will automatically restart the connection without a tomcat restart
@Gabe Sechan, thanks for your code. It works fine except the onOutgoingCallEnded()
. It is never executed. Testing phones are Samsung S5 & Trendy. There are 2 bugs I think.
1: a pair of brackets is missing.
case TelephonyManager.CALL_STATE_IDLE:
// Went to idle- this is the end of a call. What type depends on previous state(s)
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
// Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
} else {
// this one is missing
if(isIncoming){
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
} else {
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
}
// this one is missing
break;
2: lastState
is not updated by the state
if it is at the end of the function. It should be replaced to the first line of this function by
public void onCallStateChanged(Context context, int state, String number) {
int lastStateTemp = lastState;
lastState = state;
// todo replace all the "lastState" by lastStateTemp from here.
if (lastStateTemp == state) {
//No change, debounce extras
return;
}
//....
}
Additional I've put lastState
and savedNumber
into shared preference as you suggested.
Just tested it with above changes. Bug fixed at least on my phones.
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
The most complete, concise definition of false I've come across is:
Anything that stringifies to the empty string or the string
0
is false. Everything else is true.
Therefore, the following values are false:
Keep in mind that an empty list literal evaluates to an undefined value in scalar context, so it evaluates to something false.
A note on "true zeroes"
While numbers that stringify to 0
are false, strings that numify to zero aren't necessarily. The only false strings are 0
and the empty string. Any other string, even if it numifies to zero, is true.
The following are strings that are true as a boolean and zero as a number:
"0.0"
"0E0"
"00"
"+0"
"-0"
" 0"
"0\n"
".0"
"0."
"0 but true"
"\t00"
"\n0e1"
"+0.e-9"
Scalar::Util::looks_like_number
returns false. (e.g. "abc"
)The easiest way to find the best fit in R is to code the model as:
lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)
After using step down AIC regression
lm.s <- step(lm.1)
Try this, but you can adjust frame size with bounds and edit title.
package co.form.Try;
import javax.swing.JFrame;
public class Form {
public static void main(String[] args) {
JFrame obj =new JFrame();
obj.setBounds(10,10,700,600);
obj.setTitle("Application Form");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
string DateString = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
These Links might also Help you
If you're willing to use IronPython, you can execute scripts directly in C#:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
private static void doPython()
{
ScriptEngine engine = Python.CreateEngine();
engine.ExecuteFile(@"test.py");
}
Use get_the_category()
like this:
<?php
foreach((get_the_category()) as $category) {
echo $category->cat_name . ' ';
}
?>
It returns a list because a post can have more than one category.
The documentation also explains how to do this from outside the loop.
You can force the annotation library in your test using:
androidTestCompile 'com.android.support:support-annotations:23.1.0'
Something like this:
// Force usage of support annotations in the test app, since it is internally used by the runner module.
androidTestCompile 'com.android.support:support-annotations:23.1.0'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-web:2.2.1'
Another solution is to use this in the top level file:
configurations.all {
resolutionStrategy.force 'com.android.support:support-annotations:23.1.0'
}
In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
I hope it help someone.
I guess many people are entering in this question looking for a way to avoid the new line in awk
. Thus, I am going to offer a solution to just that, since the answer to the specific context was already solved!
In awk
, print
automatically inserts a ORS
after printing. ORS
stands for "output record separator" and defaults to the new line. So whenever you say print "hi"
awk prints "hi" + new line.
This can be changed in two different ways: using an empty ORS
or using printf
.
ORS
awk -v ORS= '1' <<< "hello
man"
This returns "helloman", all together.
The problem here is that not all awks accept setting an empty ORS
, so you probably have to set another record separator.
awk -v ORS="-" '{print ...}' file
For example:
awk -v ORS="-" '1' <<< "hello
man"
Returns "hello-man-".
printf
(preferable)While print
attaches ORS
after the record, printf
does not. Thus, printf "hello"
just prints "hello", nothing else.
$ awk 'BEGIN{print "hello"; print "bye"}'
hello
bye
$ awk 'BEGIN{printf "hello"; printf "bye"}'
hellobye
Finally, note that in general this misses a final new line, so that the shell prompt will be in the same line as the last line of the output. To clean this, use END {print ""}
so a new line will be printed after all the processing.
$ seq 5 | awk '{printf "%s", $0}'
12345$
# ^ prompt here
$ seq 5 | awk '{printf "%s", $0} END {print ""}'
12345
When you start a process from a batch file, it starts as a separate process with no hint towards the batch file that started it (since this would have finished running in the meantime, things like the parent process ID won't help you).
If you know the process name, and it is unique among all running processes, you can use taskkill
, like @IVlad suggests in a comment.
If it is not unique, you might want to look into jobs. These terminate all spawned child processes when they are terminated.
You can try with Picasso, it's really nice and easy. Don't forget to add the permissions in the manifest.
Picasso.with(context)
.load("http://ImageURL")
.resize(width,height)
.into(imageView );
You can also take a look at a tutorial here : Youtube / Github
I don't think var per say is a terrible language feature, as I use it daily with code like what Jeff Yates described. Actually, almost everytime I use var is because generics can make for some extremely wordy code. I live verbose code but generics take it a step too far.
That said, I (obviously... ) think var is ripe for abuse. If code gets to 20+ lines in a method with vars littered through out, you will quickly make maintenance a nightmare. Additionally, var in a tutorial is incredibly counter intuitive and generally is a giant no-no in my books.
On the flipside, var is an "easy" feature that new programmers are going to latch onto and love. Then, within a few minutes/hours/days hit a massive roadblock when they start hitting the limits. "Why can't I return var from functions?" That kind of question. Also, adding a pseudo dynamic type to a strongly typed language is something that can easily trip up a new developer. In the long run, I think the var keyword will actually make c# harder to learn for new programmers.
That said, as an experienced programmer I do use var, mostly when dealing with generics ( and obviously anonymous types ). I do hold by my quote, I do believe var will be one of the worst abused c# features.
Java 8
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 45
System.out.println(LocalDateTime.now().getSecond()); // 32
Calendar
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
Joda Time
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 45
System.out.println(new DateTime().getSecondOfMinute()); // 32
Java 8
// 07:48:55.056
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
// 7:48:55
System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());
// 07:48:55
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
// 074855
System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));
// 07:48:55
System.out.println(new Date().toString().substring(11, 20));
It is also now possible to use OCaml for developing iOS applications. It is not part of the standard distribution and requires modifications provided by the Psellos company. See here for more information: http://psellos.com/ocaml/.
Add this permission in Manifest
,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"];
//????????????,????NSUTF8StringEncoding ????,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//??????????
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];
for (int i=0; i<[allKeys count]; i++) {
NSDictionary *arrayResult = [allKeys objectAtIndex:i];
NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]);
}
file:
[
{
"ID":1,
"idSort" : 0,
"deleted":0,
"storyboardName" : "MLMember",
"dispalyTitle" : "76.360779",
"rightLevel" : "10.010490",
"showTabBar" : 1,
"openWeb" : 0,
"webUrl":""
},
{
"ID":1,
"idSort" : 0,
"deleted":0,
"storyboardName" : "0.00",
"dispalyTitle" : "76.360779",
"rightLevel" : "10.010490",
"showTabBar" : 1,
"openWeb" : 0,
"webUrl":""
}
]
Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class RootObject
{
public string url_short { get; set; }
public string url_long { get; set; }
public int type { get; set; }
}
public class Program
{
static public void Main()
{
using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
{
string json = r.ReadToEnd();
List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
}
Console.WriteLine(ro[0].url_short);
}
}
Note : Look below link also I have answered for question similar to this.It will be help full for you How to Parse an example string in C#
If you have added test.c to your Code::Blocks project, the definition will be seen twice - once via the #include and once by the linker. You need to:
When you are using JVM in 32-bit mode, the maximum heap size that can be allocated is 1280 MB. So, if you want to go beyond that, you need to invoke JVM in 64-mode.
You can use following:
$ java -d64 -Xms512m -Xmx4g HelloWorld
where,
You can tune in -Xms and -Xmx as per you requirements (YMMV)
A very good resource on JVM performance tuning, which might want to look into: http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html
$x = $y ?? 'dev'
is short hand for x = y if y is set, otherwise x = 'dev'
There is also
$x = $y =="SOMETHING" ? 10 : 20
meaning if y equals 'SOMETHING' then x = 10, otherwise x = 20
Problem 1
You mentioned it was your private docker registry, so you probably need to check Registry API instead of Hub registry API doc, which is the link you provided.
Problem 2
docker registry API is a client/server protocol, it is up to the server's implementation on whether to remove the images in the back-end. (I guess)
DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)
Detailed explanation
Below I demo how it works now from your description as my understanding for your questions.
I run a private docker registry.
I use the default one, and listen on port 5000
.
docker run -d -p 5000:5000 registry
Then I tag the local image and push into it.
$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
Sending image list
Pushing repository localhost:5000/ubuntu (1 tags)
511136ea3c5a: Image successfully pushed
d7ac5e4f1812: Image successfully pushed
2f4b4d6a4a06: Image successfully pushed
83ff768040a0: Image successfully pushed
6c37f792ddac: Image successfully pushed
e54ca5efa2e9: Image successfully pushed
Pushing tag for rev [e54ca5efa2e9] on {http://localhost:5000/v1/repositories/ubuntu/tags/latest}
After that I can use Registry API to check it exists in your private docker registry
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags
{"latest": "e54ca5efa2e962582a223ca9810f7f1b62ea9b5c3975d14a5da79d3bf6020f37"}
Now I can delete the tag using that API !!
$ curl -X DELETE localhost:5000/v1/repositories/ubuntu/tags/latest
true
Check again, the tag doesn't exist in my private registry server
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags/latest
{"error": "Tag not found"}
Yes unfortunately it will always load the full file. If you're doing this repeatedly probably best to extract the sheets to separate CSVs and then load separately. You can automate that process with d6tstack which also adds additional features like checking if all the columns are equal across all sheets or multiple Excel files.
import d6tstack
c = d6tstack.convert_xls.XLStoCSVMultiSheet('multisheet.xlsx')
c.convert_all() # ['multisheet-Sheet1.csv','multisheet-Sheet2.csv']
In Django 1.10 (possibly earlier as well) you can do it as follows.
Model:
class Todo(models.Model):
todo_name = models.CharField(max_length=200)
todo_description = models.CharField(max_length=200, default="")
todo_created = models.DateTimeField('date created')
todo_completed = models.BooleanField(default=False)
def __str__(self):
return self.todo_name
Form:
class TodoUpdateForm(forms.ModelForm):
class Meta:
model = Todo
exclude = ('todo_created','todo_completed')
Template:
<form action="" method="post">{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.todo_name.errors }}
<label for="{{ form.name.id_for_label }}">Name:</label>
{{ form.todo_name }}
</div>
<div class="fieldWrapper">
{{ form.todo_description.errors }}
<label for="{{ form.todo_description.id_for_label }}">Description</label>
{{ form.todo_description }}
</div>
<input type="submit" value="Update" />
</form>
Using urllib, you can get this done instantly.
import urllib.request
opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
urllib.request.install_opener(opener)
urllib.request.urlretrieve(URL, "images/0.jpg")
What you should use is the errorLabelContainer
jQuery(function($) {_x000D_
var validator = $('#form').validate({_x000D_
rules: {_x000D_
first: {_x000D_
required: true_x000D_
},_x000D_
second: {_x000D_
required: true_x000D_
}_x000D_
},_x000D_
messages: {},_x000D_
errorElement : 'div',_x000D_
errorLabelContainer: '.errorTxt'_x000D_
});_x000D_
});
_x000D_
.errorTxt{_x000D_
border: 1px solid red;_x000D_
min-height: 20px;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
<input type="text" name="first" />_x000D_
<input type="text" name="second" />_x000D_
<div class="errorTxt"></div>_x000D_
<input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
If you want to retain your structure then
jQuery(function($) {_x000D_
var validator = $('#form').validate({_x000D_
rules: {_x000D_
first: {_x000D_
required: true_x000D_
},_x000D_
second: {_x000D_
required: true_x000D_
}_x000D_
},_x000D_
messages: {},_x000D_
errorPlacement: function(error, element) {_x000D_
var placement = $(element).data('error');_x000D_
if (placement) {_x000D_
$(placement).append(error)_x000D_
} else {_x000D_
error.insertAfter(element);_x000D_
}_x000D_
}_x000D_
});_x000D_
});
_x000D_
#errNm1 {_x000D_
border: 1px solid red;_x000D_
}_x000D_
#errNm2 {_x000D_
border: 1px solid green;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
<input type="text" name="first" data-error="#errNm1" />_x000D_
<input type="text" name="second" data-error="#errNm2" />_x000D_
<div class="errorTxt">_x000D_
<span id="errNm2"></span>_x000D_
<span id="errNm1"></span>_x000D_
</div>_x000D_
<input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
Try this.
public string Post(FormDataCollection form) {
string par1 = form.Get("par1");
// ...
}
It works for me with webapi 2
I would suggest you check out the various tutorials that are coming out lately. My current fav is:
Hope this helps.
I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):
class obj {
protected $fields = array('field1','field2');
protected $field1 = array();
protected $field2 = array();
protected loadfields(){}
// This will load the $field1 and $field2 with rows of data for the column they describe
protected function clearFields($num){
foreach($fields as $field) {
unset($this->$field[$num]);
// This did not work the line below worked
unset($this->{$field}[$num]); // You have to resolve $field first using {}
}
}
}
The whole purpose of $fields
was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.
Currently PIP does not have a 32bit version of tensorflow, it worked when I uninstalled python 32bit and installed x64
A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.
In a simple words range + hash key = composite primary key
CoreComponents of Dynamodb
A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.
So both have a different purpose and together help to do complex query.
In the above example hashkey1 can have multiple n-range.
Another example of range and hashkey is game, userA(hashkey)
can play Ngame(range)
The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.
A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.
https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html
I opened one Word file, 2. Now I open another word file through vb.net runtime programmatically. 3. I want to kill the second process alone through programmatically. 4. Do not kill first process
One line of code using jQuery:
$('td:nth-child(2)').hide();
// If your table has header(th), use this:
//$('td:nth-child(2),th:nth-child(2)').hide();
Source: Hide a Table Column with a Single line of jQuery code
Good question.
True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '('
and ')'
the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.
However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack.
Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation.
My answer is focused to a extended case derived from the one exposed at top.
Suppose you have group of elements from which you want to hide the child elements except first. As an example:
<html>
<div class='some-group'>
<div class='child child-0'>visible#1</div>
<div class='child child-1'>xx</div>
<div class='child child-2'>yy</div>
</div>
<div class='some-group'>
<div class='child child-0'>visible#2</div>
<div class='child child-1'>aa</div>
<div class='child child-2'>bb</div>
</div>
</html>
We want to hide all .child
elements on every group. So this will not help because will hide all .child
elements except visible#1
:
$('.child:not(:first)').hide();
The solution (in this extended case) will be:
$('.some-group').each(function(i,group){
$(group).find('.child:not(:first)').hide();
});
Anytime you're tempted to pass a collection (or pointer or reference to one) to a function, ask yourself whether you couldn't pass a couple of iterators instead. Chances are that by doing so, you'll make your function more versatile (e.g., make it trivial to work with data in another type of container when/if needed).
In this case, of course, there's not much point since the standard library already has perfectly good binary searching, but when/if you write something that's not already there, being able to use it on different types of containers is often quite handy.
I tried this code, it may work for you also:
DateFormat dateFormat2 = new SimpleDateFormat("dd");
Date date2 = new Date();
String today = dateFormat2.format(date2);
//find the calendar
WebElement dateWidget = driver.findElement(By.id("dp-calendar"));
List<WebElement> columns=dateWidget.findElements(By.tagName("td"));
//comparing the text of cell with today's date and clicking it.
for (WebElement cell : columns)
{
if (cell.getText().equals(today))
{
cell.click();
break;
}
}
An abstract function cannot have functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class.
A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.
Try this
DateTime startTime = varValue
DateTime endTime = varTime
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );
Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.
Try %*s
and %-*s
and prefix each string with the column width:
>>> print "Location: %-*s Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10 Revision: 1
>>> print "District: %-*s Date: %s" % (20,"Tower","May 16, 2012")
District: Tower Date: May 16, 2012
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'
Then parse this value with Reg Exp (it's easy) which could looks similar to this: [(.*?)]
Alternatively you can use:
PRAGMA table_info(table_name)
As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO
Another option is to specify correct default value for your column:
ALTER TABLE MY_TABLE ADD STAGE INT NOT NULL DEFAULT '0'
UPD: Please note that answer above contains GO
which is a must when you run this code on Microsoft SQL server. If you want to perform the same operation on Oracle or MySQL you need to use semicolon ;
like that:
ALTER TABLE MY_TABLE ADD STAGE INT NULL;
UPDATE MY_TABLE SET <a valid not null values for your column>;
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL;
Use substr()
with a negative number for the 2nd argument.
$newstring = substr($dynamicstring, -7);
From the php docs:
string substr ( string $string , int $start [, int $length ] )
If start is negative, the returned string will start at the start'th character from the end of string.
The void
operator evaluates the given expression and then returns undefined.
It avoids refreshing the page.
Better to return HttpResponseMessage with StreamContent inside of it.
Here is example:
public HttpResponseMessage GetFile(string id)
{
if (String.IsNullOrEmpty(id))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string fileName;
string localFilePath;
int fileSize;
localFilePath = getFileFromID(id, out fileName, out fileSize);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).
<select name="FakeName" id="Fake-ID" aria-required="true" required> <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options); foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>"; } ?> </select>
You can get the list of the fragments and look to the last one.
FragmentManager fm = getSupportFragmentManager();
List<Fragment> fragments = fm.getFragments();
Fragment lastFragment = fragments.get(fragments.size() - 1);
But sometimes (when you navigate back) list size remains same but some of the last elements are null. So in the list I iterated to the last not null fragment and used it.
FragmentManager fm = getSupportFragmentManager();
if (fm != null) {
List<Fragment> fragments = fm.getFragments();
if (fragments != null) {
for(int i = fragments.size() - 1; i >= 0; i--){
Fragment fragment = fragments.get(i);
if(fragment != null) {
// found the current fragment
// if you want to check for specific fragment class
if(fragment instanceof YourFragmentClass) {
// do something
}
break;
}
}
}
}
In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a birthday attack takes O(2^(n/2)) time, where n is the output length of the hash function in bits.
SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm.
To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take
2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years
Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.
So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords rainbow tables were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as memory-time tradeoff. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time.
Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as entropy. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.
The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.
That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5 and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.
You do not need it.
If your action has the HttpPost
attribute, then you do not need to bother with setting the JsonRequestBehavior
and use the overload without it. There is an overload for each method without the JsonRequestBehavior
enum. Here they are:
Without JsonRequestBehavior
protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);
With JsonRequestBehavior
protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType,
JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior);
You need to install “Visual Studio extension development” workload and “Class Designer” optional component from the Visual Studio 2017 Installer to get the feature.
See: Visual Studio Community 2017 component directory
But this kind of item is not available on all project types. Just try for yourself:
In a Console App (.NET Framework) is available;
In a Console App (.NET Core) is not available.
I couldn't find more info on future availability also for .NET Core projects.
Just rename the command or file name ln -s /usr/bin/nodejs /usr/bin/node
by this command
Use the following code
<span id="sptext" runat="server"></span>
Java Script
document.getElementById('<%=sptext'%>).innerHTML='change text';
C#
sptext.innerHTML
One approach (which I can't imagine is good programming practice) is to add the ...
which is traditionally used to pass arguments specified in one function to another.
> multiply <- function(a,b) a*b
> multiply(a = 2,b = 4,c = 8)
Error in multiply(a = 2, b = 4, c = 8) : unused argument(s) (c = 8)
> multiply2 <- function(a,b,...) a*b
> multiply2(a = 2,b = 4,c = 8)
[1] 8
You can read more about ...
is intended to be used here
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
None of the above answers worked for me due to their specified attachment format (application/octet-stream
). Use application/pdf
for best results with PDF files.
<?php
// just edit these
$to = "[email protected], [email protected]"; // addresses to email pdf to
$from = "[email protected]"; // address message is sent from
$subject = "Your PDF email subject"; // email subject
$body = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName = "pdf-file.pdf"; // pdf file name recipient will get
$filetype = "application/pdf"; // type
// creates headers and mime boundary
$eol = PHP_EOL;
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_$semi_rand";
$headers = "From: $from$eolMIME-Version: 1.0$eol" .
"Content-Type: multipart/mixed;$eol boundary=\"$mime_boundary\"";
// add html message body
$message = "--$mime_boundary$eol" .
"Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
"Content-Transfer-Encoding: 7bit$eol$eol$body$eol";
// fetches pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));
// attaches pdf to email
$message .= "--$mime_boundary$eol" .
"Content-Type: $filetype;$eol name=\"$pdfName\"$eol" .
"Content-Disposition: attachment;$eol filename=\"$pdfName\"$eol" .
"Content-Transfer-Encoding: base64$eol$eol$pdf$eol--$mime_boundary--";
// Sends the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
Directly from the Windows.h header file:
#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>
#include <winsock.h>
#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#include <winefs.h>
#include <winscard.h>
#endif
#ifndef NOGDI
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#include <commdlg.h>
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */
if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.
Also, from Microsoft's support page:
To speed the build process, Visual C++ and the Windows Headers provide the following new defines:
VC_EXTRALEAN
WIN32_LEAN_AND_MEANYou can use them to reduce the size of the Win32 header files.
Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.
You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.
SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
,objects.type_desc
FROM syscomments comments
,sys.objects objects
WHERE comments.id = objects.object_id
AND TEXT LIKE '%CreatedDate%'
ORDER BY 1
Updated with Swift 5 Generally we use three type of Local Notifications
Where you can send simple text notification or with action button and attachment.
Using UserNotifications package in your app, the following example Request for notification permission, prepare and send notification as per user action AppDelegate itself, and use view controller listing different type of local notification test.
AppDelegate
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
let notificationCenter = UNUserNotificationCenter.current()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Confirm Delegete and request for permission
notificationCenter.delegate = self
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
//MARK: Local Notification Methods Starts here
//Prepare New Notificaion with deatils and trigger
func scheduleNotification(notificationType: String) {
//Compose New Notificaion
let content = UNMutableNotificationContent()
let categoryIdentifire = "Delete Notification Type"
content.sound = UNNotificationSound.default
content.body = "This is example how to send " + notificationType
content.badge = 1
content.categoryIdentifier = categoryIdentifire
//Add attachment for Notification with more content
if (notificationType == "Local Notification with Content")
{
let imageName = "Apple"
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
//Add Action button the Notification
if (notificationType == "Local Notification with Action")
{
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
let category = UNNotificationCategory(identifier: categoryIdentifire,
actions: [snoozeAction, deleteAction],
intentIdentifiers: [],
options: [])
notificationCenter.setNotificationCategories([category])
}
}
//Handle Notification Center Delegate methods
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == "Local Notification" {
print("Handling notifications with the Local Notification Identifier")
}
completionHandler()
}
}
and ViewController
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var appDelegate = UIApplication.shared.delegate as? AppDelegate
let notifications = ["Simple Local Notification",
"Local Notification with Action",
"Local Notification with Content",]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notifications.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = notifications[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let notificationType = notifications[indexPath.row]
let alert = UIAlertController(title: "",
message: "After 5 seconds " + notificationType + " will appear",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "Okay, I will wait", style: .default) { (action) in
self.appDelegate?.scheduleNotification(notificationType: notificationType)
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
Why would you want to put a submit button inside an anchor? You are either trying to submit a form or go to a different page. Which one is it?
Either submit the form:
<input type="submit" class="button_active" value="1" />
Or go to another page:
<input type="button" class="button_active" onclick="location.href='1.html';" />
How about this?
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]:
one two three
0 a 1.2 4.2
1 b 70 0.03
2 x 5 0
df.dtypes
Out[17]:
one object
two object
three object
df[['two', 'three']] = df[['two', 'three']].astype(float)
df.dtypes
Out[19]:
one object
two float64
three float64
SELECT a.file_name,
substr(A.tablespace_name,1,14) tablespace_name,
trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
trunc(a.bytes/1024/1024) allocated_mb,
trunc(A.MAXSIZE/1024/1024) capacity,
a.autoextensible ae
FROM (
SELECT file_id, file_name,
tablespace_name,
autoextensible,
bytes,
decode(autoextensible,'YES',maxbytes,bytes) maxsize
FROM dba_data_files
GROUP BY file_id, file_name,
tablespace_name,
autoextensible,
bytes,
decode(autoextensible,'YES',maxbytes,bytes)
) a,
(SELECT file_id,
tablespace_name,
sum(bytes) free
FROM dba_free_space
GROUP BY file_id,
tablespace_name
) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC;
This is the only difference:
each:
irb> [1,2,3].each { |x| }
=> [1, 2, 3]
irb> x
NameError: undefined local variable or method `x' for main:Object
from (irb):2
from :0
for:
irb> for x in [1,2,3]; end
=> [1, 2, 3]
irb> x
=> 3
With the for
loop, the iterator variable still lives after the block is done. With the each
loop, it doesn't, unless it was already defined as a local variable before the loop started.
Other than that, for
is just syntax sugar for the each
method.
When @collection
is nil
both loops throw an exception:
Exception: undefined local variable or method `@collection' for main:Object
More about the question:
"When Html.RenderPartial() is called with just the name of the partial view, ASP.NET MVC will pass to the partial view the same Model and ViewData dictionary objects used by the calling view template."
“NerdDinner” from Professional ASP.NET MVC 1.0
This is how I do it:
df_ext = pd.DataFrame(index=pd.date_range(df.index[-1], periods=8, closed='right'))
df2 = pd.concat([df, df_ext], axis=0, sort=True)
df2["forecast"] = df2["some column"].shift(7)
Basically I am generating an empty dataframe with the desired index and then just concatenate them together. But I would really like to see this as a standard feature in pandas so I have proposed an enhancement to pandas.
In Swift 4.1 and Xcode 9.4.1
Add UITableViewDataSource, UITableViewDelegate delegated to your class.
Create table view variable and array.
In viewDidLoad create table view.
Call table view delegates
Call table view delegate functions based on your requirement.
import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate {
// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]
override func viewDidLoad() {
super.viewDidLoad()
// 3
yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)
self.view.addSubview(yourTableView)
// 4
yourTableView.dataSource = self
yourTableView.delegate = self
}
// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
}
if self. myArray.count > 0 {
cell?.textLabel!.text = self. myArray[indexPath.row]
}
cell?.textLabel?.numberOfLines = 0
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
If you are using storyboard, no need for Step 3.
But you need to create IBOutlet for your table view before Step 4.
You need to annotate your Customer class with @Named or @Model annotation:
package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
private String email;
private String password;
}
or create/modify beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
.document {
align-items: center;
background-color: hsl(229, 57%, 11%);
border-radius: 5px;
display: flex;
height: 40px;
width: 40px;
}
.document img {
display: block;
margin: auto;
}
_x000D_
<div class="document">
<img src="./images/icon-document.svg" alt="icon-document" />
</div>
_x000D_
API level is basically the Android version. Instead of using the Android version name (eg 2.0, 2.3, 3.0, etc) an integer number is used. This number is increased with each version. Android 1.6 is API Level 4, Android 2.0 is API Level 5, Android 2.0.1 is API Level 6, and so on.
Only solution that works was create a new conda env with the name you want (you will, unfortunately, delete the old one to keep the name). Then create a new env with a new python version and re-run your install.sh
script with the conda/pip installs (or the yaml file or whatever you use to keep your requirements):
conda remove --name original_name --all
conda create --name original_name python=3.8
sh install.sh # or whatever you usually do to install dependencies
doing conda install python=3.8
doesn't work for me. Also, why do you want 3.6? Move forward with the word ;)
If you want to update the conda version of your previous env what you can also do is the following (more complicated than it should be because you cannot rename envs in conda):
conda create --name temporary_env_name --clone original_env_name
conda deactivate
conda remove --name original_env_name --all # or its alias: `conda env remove --name original_env_name`
conda create --name original_env_name python=3.8 --clone temporary_env_name
dtTempColumn.Columns["EXCELCOLUMNS"].ColumnName = "COLUMN_NAME";
dtTempColumn.AcceptChanges();
"By the way...... How to refresh it every time so it print mi in one place just change the number."
It's really tricky topic. What zack suggested ( outputting console control codes ) is one way to achieve that.
You can use (n)curses, but that works mainly on *nixes.
On Windows (and here goes interesting part) which is rarely mentioned (I can't understand why) you can use Python bindings to WinAPI (http://sourceforge.net/projects/pywin32/ also with ActivePython by default) - it's not that hard and works well. Here's a small example:
import win32console, time
output_handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]
for i in "\\|/-\\|/-":
output_handle.WriteConsoleOutputCharacter( i, pos )
time.sleep( 1 )
Or, if you want to use print
(statement or function, no difference):
import win32console, time
output_handle = win32console.GetStdHandle( win32console.STD_OUTPUT_HANDLE )
info = output_handle.GetConsoleScreenBufferInfo()
pos = info["CursorPosition"]
for i in "\\|/-\\|/-":
print i
output_handle.SetConsoleCursorPosition( pos )
time.sleep( 1 )
win32console
module enables you to do many more interesting things with windows console... I'm not a big fan of WinAPI, but recently I realized that at least half of my antipathy towards it was caused by writing WinAPI code in C - pythonic bindings are much easier to use.
All other answers are great and pythonic, of course, but... What if I wanted to print on previous line? Or write multiline text, than clear it and write the same lines again? My solution makes that possible.
asort()
- Maintains key association: yes.
sort()
- Maintains key association: no.
Android Studio is based on IntelliJ, and it comes with support for SVN (along with git and mercurial) bundled in. Check http://www.jetbrains.com/idea/features/version_control.html for more info.
You can try lubridate package which makes life much easier
library(lubridate)
mdy_hms(mydate)
The above will change the date format to POSIXct
A sample working example:
> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt"
For case with factor use as.character
data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))
You can try using AppDomain.UnhandledException and see if that lets you catch it.
**EDIT*
Here is some more information that might be useful (it's a long read).
gi switches to insertion mode, placing the cursor at the same location it was previously.
XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.
After the successful installation navigate to your xampp folder and execute the xampp-control.exe
Press the start Button at the mysql row.
Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.
But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost
or 127.0.0.1
in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.
Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin
or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.
This worked for me
tr "\r" "\n" < sampledata.csv > sampledata2.csv
What is it about your existing query that you don't like? If you are concerned that DISTINCT
across two columns does not return just the unique permutations why not try it?
It certainly works as you might expect in Oracle.
SQL> select distinct deptno, job from emp
2 order by deptno, job
3 /
DEPTNO JOB
---------- ---------
10 CLERK
10 MANAGER
10 PRESIDENT
20 ANALYST
20 CLERK
20 MANAGER
30 CLERK
30 MANAGER
30 SALESMAN
9 rows selected.
SQL> select count(*) from (
2 select distinct deptno, job from emp
3 )
4 /
COUNT(*)
----------
9
SQL>
edit
I went down a blind alley with analytics but the answer was depressingly obvious...
SQL> select count(distinct concat(deptno,job)) from emp
2 /
COUNT(DISTINCTCONCAT(DEPTNO,JOB))
---------------------------------
9
SQL>
edit 2
Given the following data the concatenating solution provided above will miscount:
col1 col2
---- ----
A AA
AA A
So we to include a separator...
select col1 + '*' + col2 from t23
/
Obviously the chosen separator must be a character, or set of characters, which can never appear in either column.
If your git says you are commit ahead then just First,
git push origin
To make sure u have pushed all ur latest work in repo
Then,
git reset --hard origin/master
To reset and match up with the repo
Mine got smoother not by wrapping each child but wrapping whole markup with a helper div. Like this:
<div class="accordeonBigWrapper">
<div class="panel-group accordion partnersAccordeonWrapper" id="partnersAccordeon" role="tablist" aria-multiselectable="false">
accordeon markup inside...
</div>
</div>
You have your storyboard set up to expect an outlet called tableView
but the actual outlet name is myTableView
.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
Recursion has a disadvantage that the algorithm that you write using recursion has O(n) space complexity. While iterative aproach have a space complexity of O(1).This is the advantange of using iteration over recursion. Then why do we use recursion?
See below.
Sometimes it is easier to write an algorithm using recursion while it's slightly tougher to write the same algorithm using iteration.In this case if you opt to follow the iteration approach you would have to handle stack yourself.
What worked for me was adding --deep
to Other Code Signing Flags in Build Settings.
More information here: Codesign of Dropbox API fails in Xcode 4.6.3: "code object is not signed at all"
Unfortunate that this ambiguous error condition has 400 different solutions, but I digress.
This will return a list of 10 numbers selected from the range 0 to 99, without duplicates.
import random
random.sample(range(100), 10)
With reference to your specific code example, you probably want to read all the lines from the file once and then select random lines from the saved list in memory. For example:
all_lines = f1.readlines()
for i in range(50):
lines = random.sample(all_lines, 40)
This way, you only need to actually read from the file once, before your loop. It's much more efficient to do this than to seek back to the start of the file and call f1.readlines()
again for each loop iteration.
The best way to set/get the value of a textarea is the .val()
, .value
method.
.text()
internally uses the .textContent
(or .innerText
for IE) method to get the contents of a <textarea>
. The following test cases illustrate how text()
and .val()
relate to each other:
var t = '<textarea>';
console.log($(t).text('test').val()); // Prints test
console.log($(t).val('too').text('test').val()); // Prints too
console.log($(t).val('too').text()); // Prints nothing
console.log($(t).text('test').val('too').val()); // Prints too
console.log($(t).text('test').val('too').text()); // Prints test
The value
property, used by .val()
always shows the current visible value, whereas text()
's return value can be wrong.
Here is a new way to achieving same in ES6:
function SplitByString(source, splitBy) {_x000D_
var splitter = splitBy.split('');_x000D_
splitter.push([source]); //Push initial value_x000D_
_x000D_
return splitter.reduceRight(function(accumulator, curValue) {_x000D_
var k = [];_x000D_
accumulator.forEach(v => k = [...k, ...v.split(curValue)]);_x000D_
return k;_x000D_
});_x000D_
}_x000D_
_x000D_
var source = "abc,def#hijk*lmn,opq#rst*uvw,xyz";_x000D_
var splitBy = ",*#";_x000D_
console.log(SplitByString(source, splitBy));
_x000D_
Please note in this function:
source
Result of above code would be:
Merging three dicts a,b,c in a single line without any other modules or libs
If we have the three dicts
a = {"a":9}
b = {"b":7}
c = {'b': 2, 'd': 90}
Merge all with a single line and return a dict object using
c = dict(a.items() + b.items() + c.items())
Returning
{'a': 9, 'b': 2, 'd': 90}
$("input[required]").attr("oninvalid", "this.setCustomValidity('Say Somthing!')");
this work if you move to previous or next field by mouse, but by enter key, this is not work !!!
To deserialize a generic JSON-string to Java-object with Jackson you need:
To define a JSON class.
Perform an attributes mapping.
Final code, tested, and ready-to-be used:
static class MyJSON {
private Map<String, Object> content = new HashMap<>();
@JsonAnySetter
public void setContent(String key, Object value) {
content.put(key, value);
}
}
String json = "{\"City\":\"Prague\"}";
try {
MyPOJO myPOJO = objectMapper.readValue(json, MyPOJO.class);
String jsonAttVal = myPOJO.content.get("City").toString();
System.out.println(jsonAttVal);
} catch (IOException e) {
e.printStackTrace();
}
Important:
@JsonAnySetter
annotation is mandatory, it ensures a generic JSON-parsing and population.
For more complicated cases with nested arrays please see the Baeldung reference: https://www.baeldung.com/jackson-mapping-dynamic-object
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
Here's one way:
CString str;
str.Format("%d", 5);
In your case, try _T("%d")
or L"%d"
rather than "%d"
Just an addition to what Greg said:
$("#whatever").offset().left + $("#whatever").outerWidth()
This code will get the right position relative to the left side. If the intention was to get the right side position relative to the right (like when using the CSS right
property) then an addition to the code is necessary as follows:
$("#parent_container").innerWidth() - ($("#whatever").offset().left + $("#whatever").outerWidth())
This code is useful in animations where you have to set the right side as a fixed anchor when you can't initially set the right
property in CSS.
After running into the same issue - here're some of my thoughts:
As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:
for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:
if (window.chrome)
$("[type=video\\\/mp4]").each(function()
{
$(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
});
Unfortunately it's a bad Chrome hack, but hey, at least it works.
Source: user: eithedog
This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec
Also check your version of crome here: html5test
To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.
To learn more about the grid and the columns / gutter widths, please also read:
In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px.
When setting @grid-columns:3;
and setting @grid-gutter-width:15px;
in variables.less you will get:
15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px
If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.
However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.
Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:
[client]
user = <username>
password = <password>
Make sure to change the file permissions so that only you can read the file.
Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.
In response to others:
You don't need to specify case in BASH4 just use the ',,' to make a var lowercase. Also I strongly dislike putting code inside of the read block, get the result and deal with it outside of the read block IMO. Also include a 'q' for quit IMO. Lastly why type 'yes' just use -n1 and have the press y.
Example: user can press y/n and also q to just quit.
ans=''
while true; do
read -p "So is MikeQ the greatest or what (y/n/q) ?" -n1 ans
case ${ans,,} in
y|n|q) break;;
*) echo "Answer y for yes / n for no or q for quit.";;
esac
done
echo -e "\nAnswer = $ans"
if [[ "${ans,,}" == "q" ]] ; then
echo "OK Quitting, we will assume that he is"
exit 0
fi
if [[ "${ans,,}" == "y" ]] ; then
echo "MikeQ is the greatest!!"
else
echo "No? MikeQ is not the greatest?"
fi
I thought I'd add my threepence worth, just to say how the default .custom-file-label
and custom-file-input
BS4 file input and how that can be used.
The latter class is on the input group and is not visible. While the former is the visible label and has a :after pseudoelement that looks like a button.
<div class="custom-file">
<input type="file" class="custom-file-input" id="upload">
<label class="custom-file-label" for="upload">Choose file</label>
</div>
You cannot add classes to psuedoelements, but you can style them in CSS (or SASS).
.custom-file-label:after {
color: #fff;
background-color: #1e7e34;
border-color: #1c7430;
pointer: cursor;
}
do not use recyclerView inside NestedScrollView. it may cause cascading problems! I suggest using ItemViewTypes in RecyclerView for handling multiple kinds of views. just add a RecyclerView with match_parent width and height. then in your recyclerViewAdapter override getItemViewType and use position for handling what layout to be inflated. after that you can handle your view holder by using onBindViewHolder method.
I don't like to suggest it, but if you must try - first call
gmap.fitBounds(bounds);
Then create a new Thread/AsyncTask, have it sleep for 20-50ms or so and then call
gmap.setZoom( Math.max(6, gmap.getZoom()) );
from the UI thread (use a handler or the onPostExecute
method for AsyncTask).
I don't know if it works, just a suggestion. Other than that you'd have to somehow calculate the zoom level from your points yourself, check if it's too low, correct it and then just call gmap.setZoom(correctedZoom)
There is a better solution in pandas 0.24:
with pd.ExcelWriter(path, mode='a') as writer:
s.to_excel(writer, sheet_name='another sheet', index=False)
before:
after:
so upgrade your pandas now:
pip install --upgrade pandas
This function gives all 4 limits of the used range:
Function FindUsedRangeLimits()
Set Sheet = ActiveSheet
Sheet.UsedRange.Select
' Display the range's rows and columns.
row_min = Sheet.UsedRange.Row
row_max = row_min + Sheet.UsedRange.Rows.Count - 1
col_min = Sheet.UsedRange.Column
col_max = col_min + Sheet.UsedRange.Columns.Count - 1
MsgBox "Rows " & row_min & " - " & row_max & vbCrLf & _
"Columns: " & col_min & " - " & col_max
LastCellBeforeBlankInColumn = True
End Function
You can quickly serve static content in JAVA Spring-boot App via thymeleaf
(ref: source)
I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot'
and the necessary buildscript
Then go ahead and ADD thymeleaf to your build.gradle
==>
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Lets assume you have added home.html at src/main/resources
To serve this file, you will need to create a controller.
package com.ajinkya.th.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomePageController {
@RequestMapping("/")
public String homePage() {
return "home";
}
}
Thats it ! Now restart your gradle server. ./gradlew bootRun
The Python docs for hash()
state:
Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup.
Python dictionaries are implemented as hash tables. So any time you use a dictionary, hash()
is called on the keys that you pass in for assignment, or look-up.
Additionally, the docs for the dict
type state:
Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.
You could try an XPath expression like:
'//div[contains(text(), "{0}") and @class="inner"]'.format(text)
You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.
function partA() {
...
window.setTimeout(partB,1000);
}
function partB() {
...
}
I found another working solution: add the following line to your app under the onCreate event.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
My sample Cordova project looks like this:
package com.apps.demo;
import android.os.Bundle;
import android.view.WindowManager;
import org.apache.cordova.*;
public class ScanManActivity extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.loadUrl("http://stackoverflow.com");
}
}
After that, my app would not go to sleep while it was open. Thanks for the anwer goes to xSus.
For a more complete answer see: http://dbaforums.org/oracle/index.php?showtopic=16834
select
substr(a.spid,1,9) pid,
substr(b.sid,1,5) sid,
substr(b.serial#,1,5) ser#,
substr(b.machine,1,6) box,
substr(b.username,1,10) username,
-- b.server,
substr(b.osuser,1,8) os_user,
substr(b.program,1,30) program
from v$session b, v$process a
where
b.paddr = a.addr
and type='USER'
order by spid;
Installed on a Mac via Homebrew, the path
/usr/local/opt/gradle/libexec
is preferable to
/usr/local/Cellar/gradle/X.X/libexec
since the former will survive version upgrades.
If you use console.clear()
, that seems to work in chrome. Note, it will output a "Console was cleared" message.
Note, I got an error right after clearing the console, so it doesn't disable the console, only clears it. Also, I have only tried this in chrome, so I dont know how cross-browser it is.
EDIT: I tested this in Chrome, IE, Firefox, and Opera. It works in Chrome, MSIE and Opera's default consoles, but not in Firefox's, however, it does work in Firebug.
In SQL Server 2008 there are two new Dynamic Management Functions introduced to keep track of object dependencies: sys.dm_sql_referenced_entities and sys.dm_sql_referencing_entities:
1/ Returning the entities that refer to a given entity:
SELECT
referencing_schema_name, referencing_entity_name,
referencing_class_desc, is_caller_dependent
FROM sys.dm_sql_referencing_entities ('<TableName>', 'OBJECT')
2/ Returning entities that are referenced by an object:
SELECT
referenced_schema_name, referenced_entity_name, referenced_minor_name,
referenced_class_desc, is_caller_dependent, is_ambiguous
FROM sys.dm_sql_referenced_entities ('<StoredProcedureName>', 'OBJECT');
Alternatively, you can use sp_depends:
EXEC sp_depends '<TableName>'
Another option is to use a pretty useful tool called SQL Dependency Tracker from Red Gate.
This happened to because I have a rule setup in my express server to route any 404 back to /#
plus whatever the original request was. Allowing the angular router/js to handle the request. If there's no js route to handle that path, a request to /#/whatever
is made to the server, which is just a request for /
, the entire webpage.
So for example if I wanted to make a request for /correct/somejsfile.js
but I miss typed it to /wrong/somejsfile.js
the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js
. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get
Uncaught SyntaxError: Unexpected token <
So to help find the offending path/request look for 302 requests.
Hope that helps someone.
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
sudo dpkg-reconfigure -plow phpmyadmin
Select No when asked to reconfigure the database. Then when asked to choose apache2, make sure to hit space while [ ] apache2 is highlighted. An asterisk should appear between the brackets. Then hit Enter. Phpmyadmin should reconfigure and now http://localhost/phpmyadmin should work. for further detail https://www.howtoforge.com/installing-apache2-with-php5-and-mysql-support-on-ubuntu-13.04-lamp
Similar error messages will pop up when transitioning from version 5 to 6. Here is an answer for the change to rxjs-6.
Import the individual operators, then use pipe
instead of chaining.
import { map, delay, catchError } from 'rxjs/operators';
source.pipe(
map(x => x + x),
delay(4000),
catchError(err => of('error found')),
).subscribe(printResult);
public int[] posStatus;
public UsersInput()
{
//It means postStatus will contain 9 elements from index 0 to 8.
this.posStatus = new int[9];
}
int intUsersInput = 0;
if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?
{
posStatus[intUsersInput-1] += 1; //set it to 1
}
Use 51Degrees.com device detection solution to detect browser name, vendor and version.
First, follow the 4-step guide to incorporate device detector in to your project. When I say incorporate I mean download archive with PHP code and database file, extract them and include 2 files. That's all there is to do to incorporate.
Once that's done you can use the following properties to get browser information:
$_51d['BrowserName'] - Gives you the name of the browser (Safari, Molto, Motorola, MStarBrowser etc).
$_51d['BrowserVendor'] - Gives you the company who created browser.
$_51d['BrowserVersion'] - Version number of the browser
Routes monitor the $location
service and respond to changes in URL (typically through the hash). To "activate" a route, you simply change the URL. The easiest way to do that is with anchor tags.
<a href="#/home">Go Home</a>
<a href="#/about">Go to About</a>
Nothing more complicated is needed. If, however, you must do this from code, the proper way is by using the $location
service:
$scope.go = function ( path ) {
$location.path( path );
};
Which, for example, a button could trigger:
<button ng-click="go('/home')"></button>
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
Use this code to get Registration ID using GCM
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!
find
them and grep
for the string:
This will find all files of your 3 types in /starting/path and grep for the regular expression '(document\.cookie|setcookie)'
. Split over 2 lines with the backslash just for readability...
find /starting/path -type f -name "*.php" -o -name "*.html" -o -name "*.js" | \
xargs egrep -i '(document\.cookie|setcookie)'
You can grant permissions on a view and not the base table. This is one of the reasons people like using views.
Have a look here: GRANT Object Permissions (Transact-SQL)
You should use the ClearContents method if you want to clear the content but preserve the formatting.
Worksheets("Sheet1").Range("A1:G37").ClearContents
Based on Thorbjørn Ravn Andersens suggestion I wrote some code that makes this work
Add the following early in the main method and it is now possible to set the log level from the comand line. This have been tested in a project of mine but I'm new to log4j and might have made some mistake. If so please correct me.
Logger.getRootLogger().setLevel(Level.WARN);
HashMap<String,Level> logLevels=new HashMap<String,Level>();
logLevels.put("ALL",Level.ALL);
logLevels.put("TRACE",Level.TRACE);
logLevels.put("DEBUG",Level.DEBUG);
logLevels.put("INFO",Level.INFO);
logLevels.put("WARN",Level.WARN);
logLevels.put("ERROR",Level.ERROR);
logLevels.put("FATAL",Level.FATAL);
logLevels.put("OFF",Level.OFF);
for(String name:System.getProperties().stringPropertyNames()){
String logger="log4j.logger.";
if(name.startsWith(logger)){
String loggerName=name.substring(logger.length());
String loggerValue=System.getProperty(name);
if(logLevels.containsKey(loggerValue))
Logger.getLogger(loggerName).setLevel(logLevels.get(loggerValue));
else
Logger.getRootLogger().warn("unknown log4j logg level on comand line: "+loggerValue);
}
}
This gets the last value and handles empty values:
=INDEX( FILTER( H:H ; NOT(ISBLANK(H:H))) ; ROWS( FILTER( H:H ; NOT(ISBLANK(H:H)) ) ) )
for k, v in mydict.iteritems():
if v is None:
mydict[k] = ''
In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items
to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems
.
In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems'
error. Use items()
instead of iteritems()
here.
Refer to this post.
In my case (admittedly very arcane and not likely to be reproduced often), this was causing the problem (this code is related to PDF generation using iTextSharp):
PdfPTable tblDuckbilledPlatypi = new PdfPTable(3);
float[] DuckbilledPlatypiRowWidths = new float[] { 42f, 76f };
tblDuckbilledPlatypi.SetWidths(DuckbilledPlatypiRowWidths);
The declaration of a 3-celled/columned table, and then setting only two vals for the width was what caused the problem, apparently. Once I changed "PdfPTable(3)" to "PdfPTable(2)" the problem went the way of the convection oven.
Single statement that works with trailing slash. If you are using IE11 you'll have to polyfill the filter
function.
var name = window.location.pathname
.split("/")
.filter(function (c) { return c.length;})
.pop();
Just use Val()
:
currentLoad = Int(Val([f4]))
Now currentLoad
has a integer value, zero if [f4]
is not numeric.
Ah, got it myselfs.
The quirks and quarks of LINQ-2-entities.
This looks most understandable:
var query2 = (
from users in Repo.T_Benutzer
from mappings in Repo.T_Benutzer_Benutzergruppen
.Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
from groups in Repo.T_Benutzergruppen
.Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
//where users.BE_Name.Contains(keyword)
// //|| mappings.BEBG_BE.Equals(666)
//|| mappings.BEBG_BE == 666
//|| groups.Name.Contains(keyword)
select new
{
UserId = users.BE_ID
,UserName = users.BE_User
,UserGroupId = mappings.BEBG_BG
,GroupName = groups.Name
}
);
var xy = (query2).ToList();
Remove the .DefaultIfEmpty()
, and you get an inner join.
That was what I was looking for.
Only this worked for me (AndroidX support library):
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:theme="@style/AppTheme.AppBarOverlay"
android:translationZ="0.1dp"
app:elevation="0dp">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@null"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
This code removes background in all necessary views and also removes shadow from AppBarLayout (which was a problem)
Answer was found here: remove shadow below AppBarLayout widget android
This question has already been answered, but I believe it would be good to throw some useful methods not previously discussed into the mix, and compare all methods proposed thus far in terms of performance.
Here are some useful solutions to this problem, in increasing order of performance.
DataFrame.agg
This is a simple str.format
-based approach.
df['baz'] = df.agg('{0[bar]} is {0[foo]}'.format, axis=1)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
You can also use f-string formatting here:
df['baz'] = df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
char.array
-based ConcatenationConvert the columns to concatenate as chararrays
, then add them together.
a = np.char.array(df['bar'].values)
b = np.char.array(df['foo'].values)
df['baz'] = (a + b' is ' + b).astype(str)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
zip
I cannot overstate how underrated list comprehensions are in pandas.
df['baz'] = [str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])]
Alternatively, using str.join
to concat (will also scale better):
df['baz'] = [
' '.join([str(x), 'is', y]) for x, y in zip(df['bar'], df['foo'])]
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
List comprehensions excel in string manipulation, because string operations are inherently hard to vectorize, and most pandas "vectorised" functions are basically wrappers around loops. I have written extensively about this topic in For loops with pandas - When should I care?. In general, if you don't have to worry about index alignment, use a list comprehension when dealing with string and regex operations.
The list comp above by default does not handle NaNs. However, you could always write a function wrapping a try-except if you needed to handle it.
def try_concat(x, y):
try:
return str(x) + ' is ' + y
except (ValueError, TypeError):
return np.nan
df['baz'] = [try_concat(x, y) for x, y in zip(df['bar'], df['foo'])]
perfplot
Performance MeasurementsGraph generated using perfplot. Here's the complete code listing.
Functions
def brenbarn(df): return df.assign(baz=df.bar.map(str) + " is " + df.foo) def danielvelkov(df): return df.assign(baz=df.apply( lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)) def chrimuelle(df): return df.assign( baz=df['bar'].astype(str).str.cat(df['foo'].values, sep=' is ')) def vladimiryashin(df): return df.assign(baz=df.astype(str).apply(lambda x: ' is '.join(x), axis=1)) def erickfis(df): return df.assign( baz=df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)) def cs1_format(df): return df.assign(baz=df.agg('{0[bar]} is {0[foo]}'.format, axis=1)) def cs1_fstrings(df): return df.assign(baz=df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)) def cs2(df): a = np.char.array(df['bar'].values) b = np.char.array(df['foo'].values) return df.assign(baz=(a + b' is ' + b).astype(str)) def cs3(df): return df.assign( baz=[str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])])
I'll post my solution as it it subtly different from others and also took me a solid day to get right, with the assistance of the existing answers.
For a multi-module Maven project:
ROOT
|--WAR
|--LIB-1
|--LIB-2
|--TEST
Where the WAR
project is the main web app, LIB
1 and 2 are additional modules the WAR
depends on and TEST
is where the integration tests live.
TEST
spins up an embedded Tomcat instance (not via Tomcat plugin) and runs WAR
project and tests them via a set of JUnit tests.
The WAR
and LIB
projects both have their own unit tests.
The result of all this is the integration and unit test coverage being separated and able to be distinguished in SonarQube.
ROOT pom.xml
<!-- Sonar properties-->
<sonar.jacoco.itReportPath>${project.basedir}/../target/jacoco-it.exec</sonar.jacoco.itReportPath>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<!-- build/plugins (not build/pluginManagement/plugins!) -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.6.201602180812</version>
<executions>
<execution>
<id>agent-for-ut</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<append>true</append>
<destFile>${sonar.jacoco.reportPath}</destFile>
</configuration>
</execution>
<execution>
<id>agent-for-it</id>
<goals>
<goal>prepare-agent-integration</goal>
</goals>
<configuration>
<append>true</append>
<destFile>${sonar.jacoco.itReportPath}</destFile>
</configuration>
</execution>
</executions>
</plugin>
WAR
, LIB
and TEST
pom.xml
will inherit the the JaCoCo plugins execution.
TEST pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<skipTests>${skip.tests}</skipTests>
<argLine>${argLine} -Duser.timezone=UTC -Xms256m -Xmx256m</argLine>
<includes>
<includes>**/*Test*</includes>
</includes>
</configuration>
</execution>
</executions>
</plugin>
I also found Petri Kainulainens blog post 'Creating Code Coverage Reports for Unit and Integration Tests With the JaCoCo Maven Plugin' to be valuable for the JaCoCo setup side of things.
After upgrading to Angular 9 (released today), I ran into this issue as well and found that they made the breaking change mentioned in the answer. I can't find a reason for why they made this change.
I have a material.module.ts file that I import / export all the material components (not the most efficient, but useful for quick development). I went through and updated all my imports to the individual material folders, although an index.ts barrel might be better. Again, not sure why they made this change, but I'm guessing it has to do with tree-shaking efficiencies.
Including my material.module.ts below in case it helps anyone, it's inspired off other material modules I've found:
NOTE: As other blog posts have mentioned and from my personal experience, be careful when using a shared module like below. I have 5~ different feature modules (lazy loaded) in my app that I imported my material module into. Out of curiosity, I stopped using the shared module and instead only imported the individual material components each feature module needed. This reduced my bundle size quite a bit, almost a 200kb reduction. I assumed that the build optimization process would properly drop any component not used by my modules, but it doesn't seem to be the case...
// material.module.ts
import { ModuleWithProviders, NgModule} from "@angular/core";
import { MAT_LABEL_GLOBAL_OPTIONS, MatNativeDateModule, MAT_DATE_LOCALE } from '@angular/material/core';
import { MatIconRegistry } from '@angular/material/icon';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatRippleModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';
@NgModule({
imports: [
MatAutocompleteModule,
MatBadgeModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatStepperModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatFormFieldModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
MatTreeModule,
MatNativeDateModule
],
exports: [
MatAutocompleteModule,
MatBadgeModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatStepperModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatFormFieldModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
MatTreeModule,
MatNativeDateModule
],
providers: [
]
})
export class MaterialModule {
constructor(public matIconRegistry: MatIconRegistry) {
// matIconRegistry.registerFontClassAlias('fontawesome', 'fa');
}
static forRoot(): ModuleWithProviders<MaterialModule> {
return {
ngModule: MaterialModule,
providers: [MatIconRegistry]
};
}
}
Break any number of loops by just one bool
variable see below :
bool check = true;
for (unsigned int i = 0; i < 50; i++)
{
for (unsigned int j = 0; j < 50; j++)
{
for (unsigned int k = 0; k < 50; k++)
{
//Some statement
if (condition)
{
check = false;
break;
}
}
if (!check)
{
break;
}
}
if (!check)
{
break;
}
}
In this code we break;
all the loops.
You need echo -e for the newline characters to take affect
you wrote
echo "oldpassword\nnewpasswd123\nnewpasswd123" | passwd user
you should try
echo -e "oldpassword\nnewpasswd123\nnewpasswd123" | passwd user
more than likely, you will not need the oldpassword\n portion of that command, you should just need the two new passwords. Don't forget to use single quotes around exclamation points!
echo -e "new"'!'"passwd123\nnew"'!'"passwd123" | passwd user
If I start with a 3x4 array, and concatenate a 3x1 array, with axis 1, I get a 3x5 array:
In [911]: x = np.arange(12).reshape(3,4)
In [912]: np.concatenate([x,x[:,-1:]], axis=1)
Out[912]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
In [913]: x.shape,x[:,-1:].shape
Out[913]: ((3, 4), (3, 1))
Note that both inputs to concatenate have 2 dimensions.
Omit the :
, and x[:,-1]
is (3,) shape - it is 1d, and hence the error:
In [914]: np.concatenate([x,x[:,-1]], axis=1)
...
ValueError: all the input arrays must have same number of dimensions
The code for np.append
is (in this case where axis is specified)
return concatenate((arr, values), axis=axis)
So with a slight change of syntax append
works. Instead of a list it takes 2 arguments. It imitates the list append
is syntax, but should not be confused with that list method.
In [916]: np.append(x, x[:,-1:], axis=1)
Out[916]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
np.hstack
first makes sure all inputs are atleast_1d
, and then does concatenate:
return np.concatenate([np.atleast_1d(a) for a in arrs], 1)
So it requires the same x[:,-1:]
input. Essentially the same action.
np.column_stack
also does a concatenate on axis 1. But first it passes 1d inputs through
array(arr, copy=False, subok=True, ndmin=2).T
This is a general way of turning that (3,) array into a (3,1) array.
In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T
Out[922]:
array([[ 3],
[ 7],
[11]])
In [923]: np.column_stack([x,x[:,-1]])
Out[923]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
All these 'stacks' can be convenient, but in the long run, it's important to understand dimensions and the base np.concatenate
. Also know how to look up the code for functions like this. I use the ipython
??
magic a lot.
And in time tests, the np.concatenate
is noticeably faster - with a small array like this the extra layers of function calls makes a big time difference.
You can use Conditional formatting with the option "Formula Is". One possible formula is
=NOT(ISBLANK($B1))
Another possible formula is
=$B1<>""
You can do this without any code behind by using a IValueConverter
.
<Grid>
<ComboBox
x:Name="comboBox1"
ItemsSource="{Binding MyItemSource}" />
<TextBlock
Visibility="{Binding SelectedItem, ElementName=comboBox1, Converter={StaticResource NullToVisibilityConverter}}"
IsHitTestVisible="False"
Text="... Select Team ..." />
</Grid>
Here you have the converter class that you can re-use.
public class NullToVisibilityConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
And finally, you need to declare your converter in a resource section.
<Converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
Where Converters is the place you have placed the converter class. An example is:
xmlns:Converters="clr-namespace:MyProject.Resources.Converters"
The very nice thing about this approach is no repetition of code in your code behind.
Try this code refer from here
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
alert(timezone);
});
</script>
WHERE DATEDIFF(day, tstamp, @dateParam) = 0
This should get you there if you don't care about time.
This is to answer the meta question of comparing the dates of two values when you don't care about the time.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
In my case there was no DEFINER
or root@localhost
mentioned in my SQL file. Actually I was trying to import and run SQL file into SQLYog from Database
->Import
->Execute SQL Script
menu. That was giving error.
Then I copied all the script from SQL file and ran in SQLYog query editor. That worked perfectly fine.
Solution:
@Entity
@Table(name = "USER")
@Access(AccessType.FIELD)
public class User implements UserDetails, Serializable {
private static final long serialVersionUID = 2L;
@Id
@Column(name = "USER_ID", updatable=false, nullable=false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "USERNAME")
private String username;
@Column(name = "PASSWORD")
private String password;
@Column(name = "NAME")
private String name;
@Column(name = "EMAIL")
private String email;
@Column(name = "LOCKED")
private boolean locked;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = Role.class)
@JoinTable(name = "USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
private Set<Role> roles;
@Override
public GrantedAuthority[] getAuthorities() {
List<GrantedAuthorityImpl> list = new ArrayList<GrantedAuthorityImpl>(0);
for (Role role : roles) {
list.add(new GrantedAuthorityImpl(role.getRole()));
}
return (GrantedAuthority[]) list.toArray(new GrantedAuthority[list.size()]);
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return !isLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
Role.java same as above.