sudo gem install --no-user-install <gem-name>
will install your gem globally, i.e. it will be available to all user's contexts.
I had the same issue because I had 2 .git
folders in the working directory.
Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git
folders, and, if so, deleting one of them.
That allowed me to upload the project successfully.
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"
You may try this, I did it finally, it works!
If someone is still finding it hard, this simple thing worked for me:
On you main system let's say Hosting PC... Go to Control Panel > Windows Defender Firewall > Allow an app or feature through Windows Defender Firewall > Change settings > Find "Apache HTTP Server" > Check both the check-boxes (under Private & Public). See Screenshot
On any another system connected over a same network... Open browser > type: your hosting pc's IP adress followed by your project name in the url bar. Example: 192.168.72.111/example.com/
Hope it helps! Thanks.
setState()
is usually asynchronous, which means that at the time you console.log
the state, it's not updated yet. Try putting the log in the callback of the setState()
method. It is executed after the state change is complete:
this.setState({ dealersOverallTotal: total }, () => {
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
});
This is a program I wrote, which gets the number of days between 2 dates(no time here).
import java.util.Scanner;
public class HelloWorld {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter starting date separated by dots: ");
String inp1 = s.nextLine();
System.out.print("Enter ending date separated by dots: ");
String inp2 = s.nextLine();
int[] nodim = {
0,
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
};
String[] inpArr1 = split(inp1);
String[] inpArr2 = split(inp2);
int d1 = Integer.parseInt(inpArr1[0]);
int m1 = Integer.parseInt(inpArr1[1]);
int y1 = Integer.parseInt(inpArr1[2]);
int d2 = Integer.parseInt(inpArr2[0]);
int m2 = Integer.parseInt(inpArr2[1]);
int y2 = Integer.parseInt(inpArr2[2]);
if (y1 % 4 == 0) nodim[2] = 29;
int diff = m1 == m2 && y1 == y2 ? d2 - (d1 - 1) : (nodim[m1] - (d1 - 1));
int mm1 = m1 + 1, mm2 = m2 - 1, yy1 = y1, yy2 = y2;
for (; yy1 <= yy2; yy1++, mm1 = 1) {
mm2 = yy1 == yy2 ? (m2 - 1) : 12;
if (yy1 % 4 == 0) nodim[2] = 29;
else nodim[2] = 28;
if (mm2 == 0) {
mm2 = 12;
yy2 = yy2 - 1;
}
for (; mm1 <= mm2 && yy1 <= yy2; mm1++) diff = diff + nodim[mm1];
}
System.out.print("No. of days from " + inp1 + " to " + inp2 + " is " + diff);
}
public static String[] split(String s) {
String[] retval = {
"",
"",
""
};
s = s + ".";
s = s + " ";
for (int i = 0; i <= 2; i++) {
retval[i] = s.substring(0, s.indexOf("."));
s = s.substring((s.indexOf(".") + 1), s.length());
}
return retval;
}
}
Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
This would change your serif latex font. You can also specify the sans-serif Helvetica like so
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
Other options are cursive
and monospace
with their respective font names.
Your label would then be
fig.gca().set_xlabel(r'wavelength $5000 \AA$')
If the font doesn't supply an Angstrom symbol you can try using \mathring{A}
You can try a simple kernel and the filter2D function, e.g. in Python:
kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
im = cv2.filter2D(im, -1, kernel)
Wikipedia has a good overview of kernels with some more examples here - https://en.wikipedia.org/wiki/Kernel_(image_processing)
In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening, embossing, edge detection, and more. This is accomplished by doing a convolution between a kernel and an image.
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
// not using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
// jquery is prettier. :-)
You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
Don't use sprintf.
It will overflow your String-Buffer and crash your Program.
Always use snprintf
I had no success with other attempts on a SQL Server 2012. What I did was use SQL Server Management Studio to generate a script to change the value, and got this:
USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2
GO
After that, I enabled the sa
account using this:
ALTER LOGIN sa ENABLE ;
GO
ALTER LOGIN sa WITH PASSWORD = '<strongPasswordHere>' ;
GO
...then, I restarted the service, and everything worked!
You might set location
directly because it's slightly shorter. If you're trying to be terse, you can usually omit the window.
too.
URL assignments to both location.href
and location
are defined to work in JavaScript 1.0, back in Netscape 2, and have been implemented in every browser since. So take your pick and use whichever you find clearest.
Use a table inside a div.
<div>
<table style='margin-left: auto; margin-right: auto'>
<tr>
<td>
<div>Your content </div>
</td>
<td>
<div>Your content </div>
</td>
</tr>
</table>
</div>
I had the same issue but my solution was to keep the Platform target as Any CPU and UNCHECK Prefer 32-bit checkbox. After I unchecked it I was able to open a connection with the provider.
With JavaScript:
window.parent.location.href= "http://www.google.com";
It's a kludge, but assuming there's a minimum length for SEARCHSTRING
, for example 2 characters, substring
the SEARCHSTRING
parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu")
and SEARCHSTRING2 ("ll").
Concatenate
them back together when executing the query to the database.
In your code behind file, have a public variable
public partial class _Default : System.Web.UI.Page
{
public string clients;
protected void Page_Load(object sender, EventArgs e)
{
// your code that at one points sets the variable
this.clients = "abc";
}
}
now in your design code, just assign that to something, like:
<div>
<p><%= clients %></p>
</div>
or even a javascript variable
<script type="text/javascript">
var clients = '<%= clients %>';
</script>
You could use:
DELETE FROM tableName
where your_date_column < '2009-01-01';
but Keep in mind that the above is really
DELETE FROM tableName
where your_date_column < '2009-01-01 00:00:00';
Not
DELETE FROM tableName
where your_date_column < '2009-01-01 11:59';
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];_x000D_
document.writeln("<table border = '1' width = 100 >");_x000D_
document.writeln("<tr><td>No Id</td><td>Title</td></tr>"); _x000D_
for(var i=0;i<datas.length;i++){_x000D_
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");_x000D_
}_x000D_
document.writeln("</table>");
_x000D_
Even if no convention is specified about this, manual references are consistently named after the referenced collection in the Mongo documentation, for one-to-one relations. The name always follows the structure <document>_id
.
For example, in a dogs
collection, a document would have manual references to external documents named like this:
{
name: 'fido',
owner_id: '5358e4249611f4a65e3068ab',
race_id: '5358ee549611f4a65e3068ac',
colour: 'yellow'
...
}
This follows the Mongo convention of naming _id
the identifier for every document.
Based on my experience, even with python 3.3+, an empty __init__.py
is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m test.foo
, it didn't work until I created an empty __init__.py
under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.
Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty __init__.py
in your package folder.
user8657661's answer is closest to my needs (of lining things up across several lines). However, I couldn't get the example code to work as provided, but I needed to change it as follows:
<html>
<head>
<style>
.tab9 {position:absolute;left:150px; }
</style>
</head>
<body>
Dog Food: <span class="tab9"> $30</span><br/>
Milk of Magnesia:<span class="tab9"> $30</span><br/>
Pizza Kit:<span class="tab9"> $5</span><br/>
Mt Dew <span class="tab9"> $1.75</span><br/>
</body>
</html>
If you need right-aligned numbers you can change left:150px
to right:150px
, but you'll need to alter the number based on the width of the screen (as written the numbers would be 150 pixels from the right edge of the screen).
I used Brendan Bullen's answer as a starting point for a similar issue I had which was to retrive the value of a specific field in a JSON string. However, like I commented on his answer, it is not entirely accurate. If your left boundary isn't just a space like in the original question, then the discrepancy increases.
Corrected solution:
SUBSTRING(
sentence,
LOCATE(' ', sentence) + 1,
LOCATE(' ', sentence, (LOCATE(' ', sentence) + 1)) - LOCATE(' ', sentence) - 1
)
The two differences are the +1 in the SUBSTRING index parameter and the -1 in the length parameter.
For a more general solution to "find the first occurence of a string between two provided boundaries":
SUBSTRING(
haystack,
LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>'),
LOCATE(
'<rightBoundary>',
haystack,
LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>')
)
- (LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>'))
)
Quick answer:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Boolean Music;
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//restore preferences
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
Music = settings.getBoolean("key", true);
}
@Override
public void onClick() {
//save music setup to system
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("key", Music);
editor.apply();
}
}
The easiest solution is the first one of your examples:
<a href="#link" class="btn btn-info" role="button">Link Button</a>
The reason it's not working for you is most likely, as you say, a problem in the theme you're using. There is no reason to resort to bloated extra markup or inline Javascript for this.
This is how Adding new column to Table
ALTER TABLE [tableName]
ADD ColumnName Datatype
E.g
ALTER TABLE [Emp]
ADD Sr_No Int
And If you want to make it auto incremented
ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL
A little bit off topic but useful is the pythonic numpy
approach. Its robust and fast but just does compare pixels and not the objects or data the picture contains (and it requires images of same size and shape):
A very simple and fast approach to do this without openCV and any library for computer vision is to norm the picture arrays by
import numpy as np
picture1 = np.random.rand(100,100)
picture2 = np.random.rand(100,100)
picture1_norm = picture1/np.sqrt(np.sum(picture1**2))
picture2_norm = picture2/np.sqrt(np.sum(picture2**2))
After defining both normed pictures (or matrices) you can just sum over the multiplication of the pictures you like to compare:
1) If you compare similar pictures the sum will return 1:
In[1]: np.sum(picture1_norm**2)
Out[1]: 1.0
2) If they aren't similar, you'll get a value between 0 and 1 (a percentage if you multiply by 100):
In[2]: np.sum(picture2_norm*picture1_norm)
Out[2]: 0.75389941124629822
Please notice that if you have colored pictures you have to do this in all 3 dimensions or just compare a greyscaled version. I often have to compare huge amounts of pictures with arbitrary content and that's a really fast way to do so.
For what its worth, as of this writing (Nov. 29, 2018), the updated API that seems to work on my end is using this link:
https://wa.me/<phone number here>
Note:
Just replace the placeholder <phone number here>
with the intended phone number that you want to use INCLUDING the country code, this means I had to add +60
then the rest of the remaining number.
It doesn't work on my end without one (using Android and iOS at least). It doesn't work means an error message that says along the lines of "you don't have this number".
Reference:
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0)
return false;
return true;
}
OR As Per audrius
private boolean isEmpty(EditText etText) {
return etText.getText().toString().trim().length() == 0;
}
If function return false
means edittext is not empty
and return true
means edittext is empty
...
The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.
The expensive regex method and the css attribute selector with starts with ^ operator
Option Explicit
Public Sub test()
Debug.Print StartWithSubString("ab", "abc,d")
End Sub
Regex:
Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
'required reference Microsoft VBScript Regular Expressions
Dim re As VBScript_RegExp_55.RegExp
Set re = New VBScript_RegExp_55.RegExp
re.Pattern = "^" & substring
StartWithSubString = re.test(testString)
End Function
Css attribute selector with starts with operator
Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
'required reference Microsoft HTML Object Library
Dim html As MSHTML.HTMLDocument
Set html = New MSHTML.HTMLDocument
html.body.innerHTML = "<div test=""" & testString & """></div>"
StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0
End Function
It's not entirely clear from your question whether you want a logged x-axis or a logged y-axis. A logged y-axis is not a good idea when using bars because they are anchored at zero, which becomes negative infinity when logged. You can work around this problem by using a frequency polygon or density plot.
contentType
option to false
is used for multipart/form-data
forms that pass files.
When one sets the contentType
option to false
, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Use jQuery's .serialize()
method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false
.
Try using new FormData
instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log()
.
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
First go through this link https://www.python.org/downloads/ to download python 3.6.1 or 2.7.13 either of your choice.I preferred to use python 2.7 or 3.4.4 .now after installation go to the folder name python27/python34 then click on script now here open the command prompt by left click ad run as administration. After the command prompt appear write their "pip install numpy" this will install the numpy latest version and installing it will show success comment that's all. Similarly matplotlib can be install by just typing "pip install matplotlip". And now if you want to download scipy then just write "pip install scipy" and if it doesn't work then you need to download python scipy from the link https://sourceforge.net/projects/scipy/ and install it.
You can easily do this one. In each column you will get a class with the field name prefixed with mat-column, so the class will be like mat-column-yourFieldName. So for that you can set the style like following
.mat-column-yourFieldName {
flex: none;
width: 100px;
}
So we can give fixed width for column as per our requirement.
Hope this helps for someone.
Without Iframe We can do this by JQuery but it will give you only HTML page source and no dynamic links or html tags will display. Almost same as php solution but in JQuery :) Code---
var purl = "http://www.othersite.com";
$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent(purl) + '&callback=?',
function (data) {
$('#viewer').html(data.contents);
});
>>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2))
That code will normalize line breaks, which may or may not be what you really want to do.
Here's an alternative which doesn't do that, and which is (IMO) simpler to understand than the NIO code (although it still uses java.nio.charset.Charset
):
public static String readFile(String file, String csName)
throws IOException {
Charset cs = Charset.forName(csName);
return readFile(file, cs);
}
public static String readFile(String file, Charset cs)
throws IOException {
// No real need to close the BufferedReader/InputStreamReader
// as they're only wrapping the stream
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
// Potential issue here: if this throws an IOException,
// it will mask any others. Normally I'd use a utility
// method which would log exceptions and swallow them
stream.close();
}
}
axios({
method: 'post', //put
url: url,
headers: {'Authorization': 'Bearer'+token},
data: {
firstName: 'Keshav', // This is the body part
lastName: 'Gera'
}
});
Reason for adding an answer at this moment:
So far I was adding the conclusion and ‘answers’ to my initial question itself, making the question very lengthy, hence moving to separate answer.
I have also added more frequently used git commands that helps me on git, to help someone else too.
Basically to clean all local commits
$ git reset --hard
and
$ git clean -d -f
First step before you do any commits is to configure your username and email that appears along with your commit.
#Sets the name you want attached to your commit transactions
$ git config --global user.name "[name]"
#Sets the email you want atached to your commit transactions
$ git config --global user.email "[email address]"
#List the global config
$ git config --list
#List the remote URL
$ git remote show origin
#check status
git status
#List all local and remote branches
git branch -a
#create a new local branch and start working on this branch
git checkout -b "branchname"
or, it can be done as a two step process
create branch: git branch branchname
work on this branch: git checkout branchname
#commit local changes [two step process:- Add the file to the index, that means adding to the staging area. Then commit the files that are present in this staging area]
git add <path to file>
git commit -m "commit message"
#checkout some other local branch
git checkout "local branch name"
#remove all changes in local branch [Suppose you made some changes in local branch like adding new file or modifying existing file, or making a local commit, but no longer need that]
git clean -d -f
and git reset --hard
[clean all local changes made to the local branch except if local commit]
git stash -u
also removes all changes
Note:
It's clear that we can use either
(1) combination of git clean –d –f
and git reset --hard
OR
(2) git stash -u
to achieve the desired result.
Note 1: Stashing, as the word means 'Store (something) safely and secretly in a specified place.' This can always be retreived using git stash pop. So choosing between the above two options is developer's call.
Note 2: git reset --hard
will delete working directory changes. Be sure to stash any local changes you want to keep before running this command.
# Switch to the master branch and make sure you are up to date.
git checkout master
git fetch
[this may be necessary (depending on your git config) to receive updates on origin/master ]
git pull
# Merge the feature branch into the master branch.
git merge feature_branch
# Reset the master branch to origin's state.
git reset origin/master
#Accidentally deleted a file from local , how to retrieve it back?
Do a git status
to get the complete filepath of the deleted resource
git checkout branchname <file path name>
that's it!
#Merge master branch with someotherbranch
git checkout master
git merge someotherbranchname
#rename local branch
git branch -m old-branch-name new-branch-name
#delete local branch
git branch -D branch-name
#delete remote branch
git push origin --delete branchname
or
git push origin :branch-name
#revert a commit already pushed to a remote repository
git revert hgytyz4567
#branch from a previous commit using GIT
git branch branchname <sha1-of-commit>
#Change commit message of the most recent commit that's already been pushed to remote
git commit --amend -m "new commit message"
git push --force origin <branch-name>
# Discarding all local commits on this branch [Removing local commits]
In order to discard all local commits on this branch, to make the local branch identical to the "upstream" of this branch, simply run
git reset --hard @{u}
Reference: http://sethrobertson.github.io/GitFixUm/fixup.html
or do git reset --hard origin/master
[if local branch is master]
# Revert a commit already pushed to a remote repository?
$ git revert ab12cd15
#Delete a previous commit from local branch and remote branch
Use-Case: You just commited a change to your local branch and immediately pushed to the remote branch, Suddenly realized , Oh no! I dont need this change. Now do what?
git reset --hard HEAD~1
[for deleting that commit from local branch. 1 denotes the ONE commit you made]
git push origin HEAD --force
[both the commands must be executed. For deleting from remote branch]. Currently checked out branch will be referred as the branch where you are making this operation.
#Delete some of recent commits from local and remote repo and preserve to the commit that you want. ( a kind of reverting commits from local and remote)
Let's assume you have 3 commits that you've pushed to remote branch named 'develop
'
commitid-1 done at 9am
commitid-2 done at 10am
commitid-3 done at 11am. // latest commit. HEAD is current here.
To revert to old commit ( to change the state of branch)
git log --oneline --decorate --graph
// to see all your commitids
git clean -d -f
// clean any local changes
git reset --hard commitid-1
// locally reverting to this commitid
git push -u origin +develop
// push this state to remote. + to do force push
# Remove local git merge: Case: I am on master branch and merged master branch with a newly working branch phase2
$ git status
On branch master
$ git merge phase2
$ git status
On branch master
Your branch is ahead of 'origin/master' by 8 commits.
Q: How to get rid of this local git merge? Tried git reset --hard
and git clean -d -f
Both didn't work.
The only thing that worked are any of the below ones:
$ git reset --hard origin/master
or
$ git reset --hard HEAD~8
or
$ git reset --hard 9a88396f51e2a068bb7
[sha commit code - this is the one that was present before all your merge commits happened]
#create gitignore file
touch .gitignore
// create the file in mac or unix users
sample .gitignore contents:
.project
*.py
.settings
Reference link to GIT cheat sheet: https://services.github.com/on-demand/downloads/github-git-cheat-sheet.pdf
As far as I can see you have the JRE
in your PATH
, but not the JDK
.
From a command prompt try this:
set PATH=%PATH%;C:\Program Files (x86)\Java\jdk1.7.0_17\bin
Then try javac
again - if this works you'll need to permanently modify your environment variables to have PATH
include the JDK
too.
@ Merk
For ur solution insted of lambda expression you can use following code:
//var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
TranslateTransform tt = null;
TransformGroup transformGroup = (TransformGroup)grid.RenderTransform;
for (int i = 0; i < transformGroup.Children.Count; i++)
{
if (transformGroup.Children[i] is TranslateTransform)
tt = (TranslateTransform)transformGroup.Children[i];
}
this code can be use as is for .Net Frame work 3.0 or 2.0
Hope It helps you :-)
Try this
'''
This is a multiline
comment. I can type here whatever I want.
'''
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
Just use wpdb->insert(tablename, coloumn, format)
and wp will prepare that's query
<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
"name" => $name,
"email" => $email,
"phone" => $phone,
"country" => $country,
"course" => $course,
"message" => $message,
"datesent" => $now ,
));
?>
I know that this question was asked 8 years and 10 months ago but I want to present you my solution:
from multiprocessing import Pool
class Test:
def __init__(self):
self.main()
@staticmethod
def methodForMultiprocessing(x):
print(x*x)
def main(self):
if __name__ == "__main__":
p = Pool()
p.map(Test.methodForMultiprocessing, list(range(1, 11)))
p.close()
TestObject = Test()
You just need to make your class function into a static method. But it's also possible with a class method:
from multiprocessing import Pool
class Test:
def __init__(self):
self.main()
@classmethod
def methodForMultiprocessing(cls, x):
print(x*x)
def main(self):
if __name__ == "__main__":
p = Pool()
p.map(Test.methodForMultiprocessing, list(range(1, 11)))
p.close()
TestObject = Test()
Tested in Python 3.7.3
If you need to do this for a large number of articles, then instead of querying the website directly, consider downloading a Wikipedia database dump and then accessing it through an API such as JWPL.
In base R a formula interface with interactions (:
) can be used to achieve this.
df <- read.csv("~/Desktop/TestData.csv")
df <- data.frame(stack(df[,-1]), Label=df$Label) # reshape to long format
boxplot(values ~ Label:ind, data=df, col=c("red", "limegreen"), las=2)
For the record: In my own code, I favor snprintf(). With a char array on the local stack, it's not that inefficient. (Well, maybe if you exceeded the array size and looped to do it twice...)
(I've also wrapped it via vsnprintf(). But that costs me some type checking. Yelp if you want the code...)
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
You are mixing mysql and mysqli
Change these lines:
$sql = mysql_query("SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysql_num_rows($sql);
to
$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);
First, generate an Interface
Assuming you are using TypeScript & Angular CLI, you can generate one by using the following command
ng g interface car
After that set the data types of its properties
// car.interface.ts
export interface car {
id: number;
eco: boolean;
wheels: number;
name: string;
}
You can now import your interface in the class that you want.
import {car} from "app/interfaces/car.interface";
And update the collection/array of car objects by pushing items in the array.
this.car.push({
id: 12345,
eco: true,
wheels: 4,
name: 'Tesla Model S',
});
More on interfaces:
An interface is a TypeScript artifact, it is not part of ECMAScript. An interface is a way to define a contract on a function with respect to the arguments and their type. Along with functions, an interface can also be used with a Class as well to define custom types. An interface is an abstract type, it does not contain any code as a class does. It only defines the 'signature' or shape of an API. During transpilation, an interface will not generate any code, it is only used by Typescript for type checking during development. - https://angular-2-training-book.rangle.io/handout/features/interfaces.html
Since everybody covered the KeyDown
answers, how about using the IsDefault
on the button?
You can read this tip for a quick howto and what it does: http://www.codeproject.com/Tips/665886/Button-Tip-IsDefault-IsCancel-and-other-usability
Here's an example from the article linked:
<Button IsDefault = "true"
Click = "SaveClicked"
Content = "Save" ... />
'''
The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:
=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60
The use of http.createClient
is now deprecated. You can pass Headers in options collection as below.
var options = {
hostname: 'example.com',
path: '/somePath.php',
method: 'GET',
headers: {'Cookie': 'myCookie=myvalue'}
};
var results = '';
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
results = results + chunk;
//TODO
});
res.on('end', function () {
//TODO
});
});
req.on('error', function(e) {
//TODO
});
req.end();
I have tried but above not working after research found below the solution.
SELECT * FROM my_table where DATE(start_date) > '2011-01-01';
The full TypeScript code
public getClassName() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec(this["constructor"].toString());
return (results && results.length > 1) ? results[1] : "";
}
Looked around a bit, and the only thing I find is using the open
system call. It is the only function I found that allows you to create a file in a way that will fail if it already exists
#include <fcntl.h>
#include <errno.h>
int fd=open(filename, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
/* file exists or otherwise uncreatable
you might want to check errno*/
}else {
/* File is open to writing */
}
Note that you have to give permissions since you are creating a file.
This also removes any race conditions there might be
Python 3.6+ provides built-in convenience methods to find and decode the plain text body as in @Todor Minakov
's answer. You can use the EMailMessage.get_body()
and get_content()
methods:
msg = email.message_from_string(s, policy=email.policy.default)
body = msg.get_body(('plain',))
if body:
body = body.get_content()
print(body)
Note this will give None
if there is no (obvious) plain text body part.
If you are reading from e.g. an mbox file, you can give the mailbox constructor an EmailMessage
factory:
mbox = mailbox.mbox(mboxfile, factory=lambda f: email.message_from_binary_file(f, policy=email.policy.default), create=False)
for msg in mbox:
...
Note you must pass email.policy.default
as the policy, since it's not the default...
This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().
http://louisremi.github.io/jquery.transform.js/
For example
$('#div').css({ transform: 'scale(.5)' });
OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.
http://www.browsersupport.net/CSS/zoom
Or just look at this question, which this one is likely just a dupe of:
In general, you must have a file handle before opening the stream. You have a fileOutputStream handle before createNewFile() in the else block. The stream does not create the file if it doesn't exist.
Not really android specific, but that's a lot IO for this purpose. What if you do many "write" operations one after another? You will be reading the entire contents and writing the entire contents, taking time, and more importantly, battery life.
I suggest using java.io.RandomAccessFile, seek()'ing to the end, then writeChars() to append. It will be much cleaner code and likely much faster.
Thank guys for showing all those examples. I was still having trouble with my contact page on small media screens like below 480px after trying your examples. Bootstrap kept inserting height: auto
.
Element Inspector / Devtools will show the height in:
element.style {
}
In my case I was seeing: section#contact.contact-container | 303 x 743
in the browser window.
So the following full-length works to eliminate the issue:
$('section#contact.contact-container').height('');
React components (both functional as well as class) must begin with a capital letter. Like
const App=(props)=><div>Hey</div>
class App extends React.Component{
render(){
return <div>Hey</div>
}
}
React identifies user-defined components by following this semantic. React's JSX transpiles to React.createElement function which returns an object representation of the dom node. The type property of this object tells whether it is a user-defined component or a dom element like div. Therefore it is important to follow this semantics
Since useState hook can only be used inside the functional component(or a custom hook) this is the reason why you are getting the error because react is not able to identify it as a user-defined component in the first place.
useState can also be used inside the custom hooks which is used for the reusability and the abstraction of logic. So according to the rules of hooks, the name of a custom hook must begin with a "use" prefix and must be in a camelCase
I tried all the suggested remedies and none had any impact. The Android Studio emulator experience was simply unusable with my setup (Windows 10, AndroidStudio 3.5, Quadcore 3.2 Ghz, 32GB with SSD drive).
I tried Updating Studio, Installing Intel HAXM, Changing the memory settings via SDK, using an actual device, excluding the various folders from in the Windows Anti-virus among other things.
The solution that made it work like a breeze was to exclude the Android Debug Bridge (adb.exe) "as a process" from the Windows Security / Virus Protection. You can either do it yourself or read the details below to know how to do it.
I suggest verifying the severity of the speed issue yourself. The same will be used to verify the difference immediately after you apply the remedy. Running the options from within Android Studio just makes it more complex.
Steps to check the issue:
Get the path for your Android SDK Tools. You can find it from SDK Manager -> Appearance and Behavior -> System Settings -> Android SDK.
Open a command prompt or terminal window. You can do right click on Windows (Start) Icon -> Run and execute "cmd". This should give you a windows command prompt or terminal window.
In the terminal window, change your drive and path to your Android SDK folder using the CD command. Now change to the sub-folder Platform-tools.
You will find the Android Debug Bridge (adb.exe) in this folder. This plays a very crucial role in operating the emulator as well as the actual device.
In the terminal window, execute the adb.exe tool with the command adb. It should instantly return back with the help parameters for adb.
Now execute adb.exe with a command like - adb devices. This should simply stall and take several seconds to come back with the information even if you have no devices or emulator running. In my setup it took almost 30 seconds. This is the issue.
Anything you do with the emulator goes via adb and gets stuck here. Once the remedy is applied, it should execute the adb devices command as instantly as the simple adb command without any parameter.
Steps to remedy:
Go to Windows "Virus and Threat Protection" setting. There are several ways to reach it. You can use Right Click on Windows (Start) Icon and choose Settings. Choose Update & Security, then Windows Security, then Virus and Threat Protection.
You will find the option Virus and Threat Protection Settings. Select it. You will find several options, look for Exclusions. Select the option Add or remove exclusions. This will take you to the list of Files, Folders, Processes which are presently excluded by the windows anti-virus. It may be empty or may have some data.
Select "+ Add an Exclusion". You will find 4 options - File, Folder, File Type and Process. This is critical. Please choose Process.
In the "Enter Process Name" input box type in the name adb.exe. Please dont forget to type in the extension, just putting adb will not work. Accept the input with "Add" button.
You are done. Now goto the command prompt again and follow the same steps you did earlier to check the issue. Hopefully you will be pleasantly surprised and your entire Android Studio emulator experience should become seamless.
Note that the steps may slightly vary depending upon your version of Windows, Android Studio and SDK tools however it should still apply.
I've found the updated answer from this video, the accepted answer didn't work for me.
First clone the latest repo from git (if haven't) using
git clone <HTTPs link of the project>
(or using SSH) then go to the desire branch using
git checkout <branch name>
.
Use the command
git log
to check the latest commits. Copy the shal of the particular commit. Then use the command
git fetch origin <Copy paste the shal here>
After pressing enter key. Now use the command
git checkout FETCH_HEAD
Now the particular commit will be available to your local. Change anything and push the code using git push origin <branch name>
. That's all.
Check the video for reference.
In Java version prior to 1.7 you cannot cast object to primitive type
double d = (double) obj;
You can cast an Object to a Double just fine
Double d = (Double) obj;
Beware, it can throw a ClassCastException if your object isn't a Double
For Intellij IDEA Community 2019.1 you will need to follow these steps :
File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */
TypeError
# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'
# same intent with a f-string
i = 15
test = f'Here is a test that can be run {i} times'
print(test)
# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i # will cause a TypeError
# should be
t = f'test{i}'
print(t)
# output
'test15'
int
.dtype
i = '15'
# t = 15 + i # will cause a TypeError
# convert the string to int
t = 15 + int(i)
print(t)
# output
30
TypeError
shown in the question title, which is why people seem to be coming to this question.TypeError
is caused because message
type is a str
.char
, a str
type, to an int
char
to an int
secret_string
needs to be initialized with 0
instead of ""
.ValueError: chr() arg not in range(0x110000)
because 7429146
is out of range for chr()
.message = input("Enter a message you want to be revealed: ")
secret_string = 0
for char in message:
char = int(char)
value = char + 742146
secret_string += ord(chr(value))
print(f'\nRevealed: {secret_string}')
# Output
Enter a message you want to be revealed: 999
Revealed: 2226465
message
is now an int
type, so for char in message:
causes TypeError: 'int' object is not iterable
message
is converted to int
to make sure the input
is an int
.str()
value
to Unicode with chr
ord
while True:
try:
message = str(int(input("Enter a message you want to be decrypt: ")))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
value = int(char) + 10000
secret_string += chr(value)
print("Decrypted", secret_string)
# output
Enter a message you want to be decrypt: 999
Decrypted ???
Enter a message you want to be decrypt: 100
Decrypted ???
Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.
we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.
medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.
E.g Small Text
This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"
I tried to create a byte array like this
byte[] bytes = new byte[Integer.MAX_VALUE-x];
System.out.println(bytes.length);
With this run configuration:
-Xms4G -Xmx4G
And java version:
Openjdk version "1.8.0_141"
OpenJDK Runtime Environment (build 1.8.0_141-b16)
OpenJDK 64-Bit Server VM (build 25.141-b16, mixed mode)
It only works for x >= 2 which means the maximum size of an array is Integer.MAX_VALUE-2
Values above that give
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit at Main.main(Main.java:6)
Use the built in functions:
SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
GROUP BY URLx
ORDER BY Count DESC;
Who needs trig when you have complex numbers:
#include <complex.h>
#include <math.h>
#define PI 3.14159265358979323846
typedef complex double Point;
Point point_on_circle ( double radius, double angle_in_degrees, Point centre )
{
return centre + radius * cexp ( PI * I * ( angle_in_degrees / 180.0 ) );
}
This is very simple steps involved as you mentioned you have already installed JAVAEE plugin so the first step for you is go to Windows->Show View->Server
in add select the AppacheTOMcat and select the tomcat version you have downloaded and set the path and start the server after that.
It's not enough to have just compile project("xy")
dependency.
You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).
Create a settings.gradle file in the root of your project and add this:
include ':progressfragment'
to that file. Then sync Gradle and it should work.
Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.
http://getbootstrap.com/javascript/#modals shows an event for when a modal is hidden. Just tap into that:
$('#modal1').on('hidden.bs.modal', function (e) {
$(this)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
I would suggest the above as it bind the clearing to the modal itself instead of the close button, but I realize this does not address your specific question. You could use the same clearing logic bound to the dismiss buttons:
$('[data-dismiss=modal]').on('click', function (e) {
var $t = $(this),
target = $t[0].href || $t.data("target") || $t.parents('.modal') || [];
$(target)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
-- TRY THIS --
select name= case when isnumeric(empname)= 1 then 'numeric' else 'notmumeric' end from [Employees]
But conversion is quit impossible
select empname=
case
when isnumeric(empname)= 1 then empname
else 'notmumeric'
end
from [Employees]
Using ASP.Net Post call, this worked for me.
StringBuilder getNewToken = new StringBuilder();
getNewToken.Append("https://www.googleapis.com/oauth2/v4/token");
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(getNewToken.ToString());
var values = new Dictionary<string, string>
{
{ "client_id", <Your Client Id> },
{ "client_secret", <Your Client Secret> },
{ "refresh_token", <Your Saved Refresh Token> },
{ "grant_type", "refresh_token"}
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(getNewToken.ToString(), content);
import datetime
datetime.date.today() # Returns 2018-01-15
datetime.datetime.now() # Returns 2018-01-15 09:00
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
You can just expand the Date
Object with a new format
method as noted by meizz, below is the code given by the author. And
here is a jsfiddle.
Date.prototype.format = function(format) //author: meizz
{
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1 ? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
return format;
}
alert(new Date().format("yyyy-MM-dd"));
alert(new Date("january 12 2008 11:12:30").format("yyyy-MM-dd h:mm:ss"));
There are padding built into various classes.
For example:
A asp.net web forms app:
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
this code above would place the Text of "Show Deleted" too close to the checkbox to what I see at nice to look at.
However with bootstrap
<div class="checkbox-inline">
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
</div>
This created the space, if you don't want the text bold, that class=checkbox
Bootstrap is very flexible, so in this case I don't need a hack, but sometimes you need to.
You should call the bash script using source.
Here is an example:
#!/bin/bash
# Let's call this script venv.sh
source "<absolute_path_recommended_here>/.env/bin/activate"
On your shell just call it like that:
> source venv.sh
Or as @outmind suggested: (Note that this does not work with zsh)
> . venv.sh
There you go, the shell indication will be placed on your prompt.
If you choose Project
and then All Files
in the menu, all files should be displayed in the Solution Explorer that are physically in your project map, but not (yet) included in your project. If you right click on the file you want to add in the Solution Explorer, you can include it.
FWIW, htpasswd -n username
will output the result directly to stdout, and avoid touching files altogether.
"Z" doesn't stand for "Zulu"
I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):
Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.
System.setProperty("https.protocols", "TLSv1.2");
worked in my case. Have you checked that within the application?
There are a lot of great answers here - but I found my issue was quite a bit more simple.
I was trying to run the following command:
$x['name'] = $j['name'];
and I was getting this illegal string
error on $x['name']
because I hadn't defined the array first. So I put the following line of code in before trying to assign things to $x[]
:
$x = array();
and it worked.
You'd have to set up the post-build shell script as a separate Jenkins job and trigger it as a post-build step. It looks like you will need to use the Parameterized Trigger Plugin as the standard "Build other projects" option only works if your triggering build is successful.
editcolor.xml
android:textCursorDrawable="@drawable/editcolor"
In xml file set color code of edittext
background color
The answer posted by Craig White has a big performance penalty
SELECT * FROM `table` WHERE BINARY `column` = 'value'
because it doesn't use indexes. So, either you need to change the table collation like mention here https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html.
OR
Easiest fix, you should use a BINARY of value.
SELECT * FROM `table` WHERE `column` = BINARY 'value'
E.g.
mysql> EXPLAIN SELECT * FROM temp1 WHERE BINARY col1 = "ABC" AND col2 = "DEF" ;
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
| 1 | SIMPLE | temp1 | ALL | NULL | NULL | NULL | NULL | 190543 | Using where |
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
VS
mysql> EXPLAIN SELECT * FROM temp1 WHERE col1 = BINARY "ABC" AND col2 = "DEF" ;
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
| 1 | SIMPLE | temp1 | range | col1_2e9e898e | col1_2e9e898e | 93 | NULL | 2 | Using index condition; Using where |
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
enter code here
1 row in set (0.00 sec)
__all__
is very good - it helps guide import statements without automatically importing modules
http://docs.python.org/tutorial/modules.html#importing-from-a-package
using __all__
and import *
is redundant, only __all__
is needed
I think one of the most powerful reasons to use import *
in an __init__.py
to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py
files empty.
for example:
foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo
then the app grows and now it's a whole folder
foo/
__init__.py
foofactories.py
tallFoos.py
shortfoos.py
mediumfoos.py
santaslittlehelperfoo.py
superawsomefoo.py
anotherfoo.py
then the init script can say
__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo
so that a script written to do the following does not break during the change:
from foo import fooFactory, tallFoo, shortFoo
You can use a dictionary comprehension to create a new dictionary with that key removed:
>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}
You can delete by conditions. No error if key
doesn't exist.
When you put default, its called default export. You can only have one default export per file and you can import it in another file with any name you want. When you don't put default, its called named export, you have to import it in another file using the same name with curly braces inside it.
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
I know that question is a bit old but
pipenv --venv
/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
Updated your fiddle: http://jsfiddle.net/xftr5/11/ Hope, everything is clear?
$(document).ready(function() {
$('.fragment i').on('click', function(e) { $(e.target).closest('a').remove(); });
});
Added jQuery and inserted an <i>
as close trigger...
Nothing helped me so I downloaded the simulators for my deployment Target.
Download the simulators for your deployment Target
You can check Deployment target :
Hope it helps
I tried for a long time to improve vokimon's drawn marker and make it more similar to Google Maps one (and pretty much succeeded). This is the code I got:
let circle=true;
path = 'M 0,0 C -0.7,-9 -3,-14 -5.5,-18.5 '+
'A 16,16 0 0,1 -11,-29 '+
'A 11,11 0 1,1 11,-29 '+
'A 16,16 0 0,1 5.5,-18.5 '+
'C 3,-14 0.7,-9 0,0 z '+
['', 'M -2,-28 '+
'a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0'][new Number(circle)];
I also scaled it by 0.8.
I typically bind this data using the RowDatabound event with the GridView:
protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
}
}
You can also use http://projectshadowlight.org/jquery-easy-confirm-dialog/ . It's very simple and easy to use. Just include jquery common library and one more file only:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/blitzer/jquery-ui.css" type="text/css" />
<script src="jquery.easy-confirm-dialog.js"></script>
I recently needed to launch a Bootstrap 5 modal without jQuery and not with a button click (eg, on page load) using Django messages. This is how I did it:
Template/HTML
<div class="modal" id="notification">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Notification!</h5>
<button type="button" class="btn-close"
data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
{% for m in messages %}
{{ m }}
{% endfor %}
</div>
<div class="modal-footer justify-content-between">
<a class="float-none btn btn-secondary" href="{% url 'some_view' %}"
type="button">
Link/Button A
</a>
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">
Link/Button B
</button>
</div>
</div>
</div>
</div>
JS in a file or in the template
{% block javascript %}
{{ block.super }}
<script>
var test_modal = new bootstrap.Modal(
document.getElementById('notification')
)
test_modal.show()
</script>
{% endblock javascript %}
This method will work without the Django template; just use the HTML and put the JS in a file or script
elements that loads after the Bootstrap JS before the end of the body
element.
In Javascript you can do that by using the typeof function
function foo(bar){
alert(typeof(bar));
}
Use a regex to extract the "video id" after watch?v=
Store the video id in a variable, let's call this variable vid
Get the embed code from a random video, remove the video id from the embed code and replace it with the vid
you got.
I don't know how to deal with regex in php, but it shouldn't be too hard
Here's example code in python:
>>> ytlink = 'http://www.youtube.com/watch?v=7-dXUEbBz70'
>>> import re
>>> vid = re.findall( r'v\=([\-\w]+)', ytlink )[0]
>>> vid
'7-dXUEbBz70'
>>> print '''<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>''' % (vid,vid)
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
>>>
The regular expression v\=([\-\w]+)
captures a (sub)string of characters and dashes that comes after v=
To get largest size of the image
https://graph.facebook.com/{userID}?fields=picture.width(720).height(720)
or anything else you need as size. Based on experience, type=large is not the largest result you can obtain.
Try https://github.com/voidcosmos/npkill
npx npkill
it will find all node_modules and let you remove them.
@Service: It tells that particular class is a Service to the client. Service class contains mainly business Logic. If you have more Service classes in a package than provide @Qualifier otherwise it should not require @Qualifier.
Case 1:
@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
}
Case2:
@Service
public class EmployeeServiceImpl implements EmployeeService{
}
both cases are working...
try:
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]
Where the folder you want to appear in the url is in the first part of the statement - this is what it will match against and the second part 'rewrites' it to your existing folder. the [NC] flag means that it will ignore case differences eg Apple/ will still forward.
See here for a tutorial: http://www.sitepoint.com/article/guide-url-rewriting/
There is also a nice test utility for windows you can download from here: http://www.helicontech.com/download/rxtest.zip Just to note for the tester you need to leave out the domain name - so the test would be against /folder1/login.php
to redirect from /folder1 to /apple try this:
RewriteRule ^/folder1(.*)?$ /apple$1 [R]
to redirect and then rewrite just combine the above in the htaccess file:
RewriteRule ^/folder1(.*)?$ /apple$1 [R]
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]
As Python 3.0 and 3.1 are EOL'ed and no one uses them, you can and should use str.format_map(mapping)
(Python 3.2+):
Similar to
str.format(**mapping)
, except that mapping is used directly and not copied to adict
. This is useful if for example mapping is adict
subclass.
What this means is that you can use for example a defaultdict
that would set (and return) a default value for keys that are missing:
>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'
Even if the mapping provided is a dict
, not a subclass, this would probably still be slightly faster.
The difference is not big though, given
>>> d = dict(foo='x', bar='y', baz='z')
then
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)
is about 10 ns (2 %) faster than
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)
on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and
Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:
>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'
Starting from 3.6 you can use the interpolated strings too:
>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'
You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.
Here's the more concise and easy to read solution based on offset width difference:
function getScrollbarWidth(): number {
// Creating invisible container
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.overflow = 'scroll'; // forcing scrollbar to appear
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);
// Creating inner element and placing it in the container
const inner = document.createElement('div');
outer.appendChild(inner);
// Calculating difference between container's full width and the child width
const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);
// Removing temporary elements from the DOM
outer.parentNode.removeChild(outer);
return scrollbarWidth;
}
See the JSFiddle.
The ScriptIgnoreAttribute
class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.
You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.
Change the position
attribute to fixed
instead of absolute
.
numpy.append
is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append
is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:
import numpy
old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]
I think you might be able to achieve your goal by doing something like:
result = numpy.zeros((10,))
result[0:2] = [1, 2]
# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]
Update:
If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:
import numpy as np
a = np.array([0., 1.])
b = np.array([2., 3.])
temp = []
while True:
rnd = random.randint(0, 100)
if rnd > 50:
temp.append(a)
else:
temp.append(b)
if rnd == 0:
break
result = np.array(temp)
In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.
new update
The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b)
the shapes of a
and b
need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.
var express = require('express');
var fs = require('fs');
var morgan = require('morgan')
var app = express();
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(__dirname + '/access.log',{flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))
app.get('/', function (req, res) {
res.send('hello, world!')
});
Async:
fs.readFile('test.txt', 'utf8', callback);
Sync:
var content = fs.readFileSync('test.txt', 'utf8');
From a Java Game Engine:
/**
* Converts a given Image into a BufferedImage
*
* @param img The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there
With typical 3 level non-diamond non-virtual-inheritance inheritance, when you instantiate a new most-derived-object, new
is called and the size required for the object on the heap is resolved from the class type by the compiler and passed to new.
new
has a signature:
_GLIBCXX_WEAK_DEFINITION void *
operator new (std::size_t sz) _GLIBCXX_THROW (std::bad_alloc)
And makes a call to malloc
, returning the void pointer
This address is then passed to the constructor of the most derived object, which will immediately call the middle constructor and then the middle constructor will immediately call the base constructor. The base then stores a pointer to its virtual table at the start of the object and then its attributes after it. This then returns to the middle constructor which will store its virtual table pointer at the same location and then its attributes after the attributes that would have been stored by the base constructor. It then returns to the most derived constructor, which stores a pointer to its virtual table at the same location and and then stores its attributes after the attributes that would have been stored by the middle constructor.
Because the virtual table pointer is overwritten, the virtual table pointer ends up always being the one of the most derived class. Virtualness propagates towards the most derived class so if a function is virtual in the middle class, it will be virtual in the most derived class but not the base class. If you polymorphically cast an instance of the most derived class to a pointer to the base class then the compiler will not resolve this to an indirect call to the virtual table and instead will call the function directly A::function()
. If a function is virtual for the type you have cast it to then it will resolve to a call into the virtual table which will always be that of the most derived class. If it is not virtual for that type then it will just call Type::function()
and pass the object pointer to it, cast to Type.
Actually when I say pointer to its virtual table, it's actually always an offset of 16 into the virtual table.
vtable for Base:
.quad 0
.quad typeinfo for Base
.quad Base::CommonFunction()
.quad Base::VirtualFunction()
pointer is typically to the first function i.e.
mov edx, OFFSET FLAT:vtable for Base+16
virtual
is not required again in more-derived classes if it is virtual in a less-derived class because it propagates downwards in the direction of the most derived class. But it can be used to show that the function is indeed a virtual function, without having to check the classes it inherits's type definitions. When a function is declared virtual, from that point on, only the last implementation in the inheritance chain is used, but before that, it can still be used non-virtually if the object is cast to a type of a class before that in the inheritance chain that defines that method. It can be defined non-virtually in multiple classes before it in the chain before the virtualhood begins for a method of that name and signature, and they will use their own methods when referenced (and all classes after that definition in the chain will use that definition if they do not have their own definition, as opposed to virtual, which always uses the final definition). When a method is declared virtual, it must be implemented in that class or a more derived class in the inheritance chain for the full object that was constructed in order to be used.
override
is another compiler guard that says that this function is overriding something and if it isn't then throw a compiler error.
= 0
means that this is an abstract function
final
prevents a virtual function from being implemented again in a more derived class and will make sure that the virtual table of the most derived class contains the final function of that class.
= default
makes it explicit in documentation that the compiler will use the default implementation
= delete
give a compiler error if a call to this is attempted
If you call a non-virtual function, it will resolve to the correct method definition without going through the virtual table. If you call a virtual-function that has its final definition in an inherited class then it will use its virtual table and will pass the subobject to it automatically if you don't cast the object pointer to that type when calling the method. If you call a virtual function defined in the most derived class on a pointer of that type then it will use its virtual table, which will be the one at the start of the object. If you call it on a pointer of an inherited type and the function is also virtual in that class then it will use the vtable pointer of that subobject, which in the case of the first subobject will be the same pointer as the most derived class, which will not contain a thunk as the address of the object and the subobject are the same, and therefore it's just as simple as the method automatically recasting this pointer, but in the case of a 2nd sub object, its vtable will contain a non-virtual thunk to convert the pointer of the object of inherited type to the type the implementation in the most derived class expects, which is the full object, and therefore offsets the subobject pointer to point to the full object, and in the case of base subobject, will require a virtual thunk to offset the pointer to the base to the full object, such that it can be recast by the method hidden object parameter type.
Using the object with a reference operator and not through a pointer (dereference operator) breaks polymorphism and will treat virtual methods as regular methods. This is because polymorphic casting on non-pointer types can't occur due to slicing.
Consider
class Base
{
int a = 1;
int b = 2;
public:
void virtual CommonFunction(){} ; //define empty method body
void virtual VirtualFunction(){} ;
};
class DerivedClass1: virtual public Base
{
int c = 3;
public:
void virtual DerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
};
class DerivedClass2 : virtual public Base
{
int d = 4;
public:
//void virtual DerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
void virtual DerivedCommonFunction2(){} ;
};
class DerivedDerivedClass : public DerivedClass1, public DerivedClass2
{
int e = 5;
public:
void virtual DerivedDerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
};
int main () {
DerivedDerivedClass* d = new DerivedDerivedClass;
d->VirtualFunction();
d->DerivedCommonFunction();
d->DerivedCommonFunction2();
d->DerivedDerivedCommonFunction();
((DerivedClass2*)d)->DerivedCommonFunction2();
((Base*)d)->VirtualFunction();
}
Without virtually inheriting the bass class you will get an object that looks like this:
Instead of this:
I.e. there will be 2 base objects.
In the virtual diamond inheritance situation above, after new
is called, it passes the address of the allocated space for the object to the most derived constructor DerivedDerivedClass::DerivedDerivedClass()
, which calls Base::Base()
first, which writes its vtable in the base's dedicated subobject, it then DerivedDerivedClass::DerivedDerivedClass()
calls DerivedClass1::DerivedClass1()
, which writes its virtual table pointer to its subobject as well as overwriting the base subobject's pointer at the end of the object by consulting the passed VTT, and then calls DerivedClass1::DerivedClass1()
to do the same, and finally DerivedDerivedClass::DerivedDerivedClass()
overwrites all 3 pointers with its virtual table pointer for that inherited class. This is instead of (as illustrated in the 1st image above) DerivedDerivedClass::DerivedDerivedClass()
calling DerivedClass1::DerivedClass1()
and that calling Base::Base()
(which overwrites the virtual pointer), returning, offsetting the address to the next subobject, calling DerivedClass2::DerivedClass2()
and then that also calling Base::Base()
, overwriting that virtual pointer, returning and then DerivedDerivedClass
constructor overwriting both virtual pointers with its virtual table pointer (in this instance, the virtual table of the most derived constructor contains 2 subtables instead of 3).
The following is all compiled in debug mode -O0 so there will be redundant assembly
main:
.LFB8:
push rbp
mov rbp, rsp
push rbx
sub rsp, 24
mov edi, 48 //pass size to new
call operator new(unsigned long) //call new
mov rbx, rax //move the address of the allocation to rbx
mov rdi, rbx //move it to rdi i.e. pass to the call
call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor] //construct on this address
mov QWORD PTR [rbp-24], rbx //store the address of the object on the stack as the d pointer variable on -O0, will be optimised off on -Ofast if the address of the pointer itself isn't taken in the code, because this address does not need to be on the stack, it can just be passed in a register to the subsequent methods
Parenthetically, if the code were DerivedDerivedClass d = DerivedDerivedClass()
, the main
function would look like this:
main:
push rbp
mov rbp, rsp
sub rsp, 48 // make room for and zero 48 bytes on the stack for the 48 byte object, no extra padding required as the frame is 64 bytes with `rbp` and return address of the function it calls (no stack params are passed to any function it calls), hence rsp will be aligned by 16 assuming it was aligned at the start of this frame
mov QWORD PTR [rbp-48], 0
mov QWORD PTR [rbp-40], 0
mov QWORD PTR [rbp-32], 0
mov QWORD PTR [rbp-24], 0
mov QWORD PTR [rbp-16], 0
mov QWORD PTR [rbp-8], 0
lea rax, [rbp-48] // load the address of the cleared 48 bytes
mov rdi, rax // pass the address as a pointer to the 48 bytes cleared as the first parameter to the constructor
call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]
//address is not stored on the stack because the object is used directly -- there is no pointer variable -- d refers to the object on the stack as opposed to being a pointer
Moving back to the original example, the DerivedDerivedClass
constructor:
DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]:
.LFB20:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR [rbp-8], rdi
.LBB5:
mov rax, QWORD PTR [rbp-8] // object address now in rax
add rax, 32 //increment address by 32
mov rdi, rax // move object address+32 to rdi i.e. pass to call
call Base::Base() [base object constructor]
mov rax, QWORD PTR [rbp-8] //move object address to rax
mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+8 //move address of VTT+8 to edx
mov rsi, rdx //pass VTT+8 address as 2nd parameter
mov rdi, rax //object address as first (DerivedClass1 subobject)
call DerivedClass1::DerivedClass1() [base object constructor]
mov rax, QWORD PTR [rbp-8] //move object address to rax
add rax, 16 //increment object address by 16
mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+24 //store address of VTT+24 in edx
mov rsi, rdx //pass address of VTT+24 as second parameter
mov rdi, rax //address of DerivedClass2 subobject as first
call DerivedClass2::DerivedClass2() [base object constructor]
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+24 //move this to edx
mov rax, QWORD PTR [rbp-8] // object address now in rax
mov QWORD PTR [rax], rdx. //store address of vtable for DerivedDerivedClass+24 at the start of the object
mov rax, QWORD PTR [rbp-8] // object address now in rax
add rax, 32 // increment object address by 32
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+120 //move this to edx
mov QWORD PTR [rax], rdx //store vtable for DerivedDerivedClass+120 at object+32 (Base)
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+72 //store this in edx
mov rax, QWORD PTR [rbp-8] //move object address to rax
mov QWORD PTR [rax+16], rdx //store vtable for DerivedDerivedClass+72 at object+16 (DerivedClass2)
mov rax, QWORD PTR [rbp-8]
mov DWORD PTR [rax+28], 5 // stores e = 5 in the object
.LBE5:
nop
leave
ret
The DerivedDerivedClass
constructor calls Base::Base()
with a pointer to the object offset 32. Base stores a pointer to its virtual table at the address it receives and its members after it.
Base::Base() [base object constructor]:
.LFB11:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi //stores address of object on stack (-O0)
.LBB2:
mov edx, OFFSET FLAT:vtable for Base+16 //puts vtable for Base+16 in edx
mov rax, QWORD PTR [rbp-8] //copies address of object from stack to rax
mov QWORD PTR [rax], rdx //stores it address of object
mov rax, QWORD PTR [rbp-8] //copies address of object on stack to rax again
mov DWORD PTR [rax+8], 1 //stores a = 1 in the object
mov rax, QWORD PTR [rbp-8] //junk from -O0
mov DWORD PTR [rax+12], 2 //stores b = 2 in the object
.LBE2:
nop
pop rbp
ret
DerivedDerivedClass::DerivedDerivedClass()
then calls DerivedClass1::DerivedClass1()
with a pointer to the object offset 0 and also passes the address of VTT for DerivedDerivedClass+8
DerivedClass1::DerivedClass1() [base object constructor]:
.LFB14:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi //address of object
mov QWORD PTR [rbp-16], rsi //address of VTT+8
.LBB3:
mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax
mov rdx, QWORD PTR [rax] //address of DerivedClass1-in-DerivedDerivedClass+24 now in rdx
mov rax, QWORD PTR [rbp-8] //address of object now in rax
mov QWORD PTR [rax], rdx //store address of DerivedClass1-in-.. in the object
mov rax, QWORD PTR [rbp-8] // address of object now in rax
mov rax, QWORD PTR [rax] //address of DerivedClass1-in.. now implicitly in rax
sub rax, 24 //address of DerivedClass1-in-DerivedDerivedClass+0 now in rax
mov rax, QWORD PTR [rax] //value of 32 now in rax
mov rdx, rax // now in rdx
mov rax, QWORD PTR [rbp-8] //address of object now in rax
add rdx, rax //address of object+32 now in rdx
mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax
mov rax, QWORD PTR [rax+8] //derference VTT+8+8; address of DerivedClass1-in-DerivedDerivedClass+72 (Base::CommonFunction()) now in rax
mov QWORD PTR [rdx], rax //store at address object+32 (offset to Base)
mov rax, QWORD PTR [rbp-8] //store address of object in rax, return
mov DWORD PTR [rax+8], 3 //store its attribute c = 3 in the object
.LBE3:
nop
pop rbp
ret
VTT for DerivedDerivedClass:
.quad vtable for DerivedDerivedClass+24
.quad construction vtable for DerivedClass1-in-DerivedDerivedClass+24 //(DerivedClass1 uses this to write its vtable pointer)
.quad construction vtable for DerivedClass1-in-DerivedDerivedClass+72 //(DerivedClass1 uses this to overwrite the base vtable pointer)
.quad construction vtable for DerivedClass2-in-DerivedDerivedClass+24
.quad construction vtable for DerivedClass2-in-DerivedDerivedClass+72
.quad vtable for DerivedDerivedClass+120 // DerivedDerivedClass supposed to use this to overwrite Bases's vtable pointer
.quad vtable for DerivedDerivedClass+72 // DerivedDerivedClass supposed to use this to overwrite DerivedClass2's vtable pointer
//although DerivedDerivedClass uses vtable for DerivedDerivedClass+72 and DerivedDerivedClass+120 directly to overwrite them instead of going through the VTT
construction vtable for DerivedClass1-in-DerivedDerivedClass:
.quad 32
.quad 0
.quad typeinfo for DerivedClass1
.quad DerivedClass1::DerivedCommonFunction()
.quad DerivedClass1::VirtualFunction()
.quad -32
.quad 0
.quad -32
.quad typeinfo for DerivedClass1
.quad Base::CommonFunction()
.quad virtual thunk to DerivedClass1::VirtualFunction()
construction vtable for DerivedClass2-in-DerivedDerivedClass:
.quad 16
.quad 0
.quad typeinfo for DerivedClass2
.quad DerivedClass2::VirtualFunction()
.quad DerivedClass2::DerivedCommonFunction2()
.quad -16
.quad 0
.quad -16
.quad typeinfo for DerivedClass2
.quad Base::CommonFunction()
.quad virtual thunk to DerivedClass2::VirtualFunction()
vtable for DerivedDerivedClass:
.quad 32
.quad 0
.quad typeinfo for DerivedDerivedClass
.quad DerivedClass1::DerivedCommonFunction()
.quad DerivedDerivedClass::VirtualFunction()
.quad DerivedDerivedClass::DerivedDerivedCommonFunction()
.quad 16
.quad -16
.quad typeinfo for DerivedDerivedClass
.quad non-virtual thunk to DerivedDerivedClass::VirtualFunction()
.quad DerivedClass2::DerivedCommonFunction2()
.quad -32
.quad 0
.quad -32
.quad typeinfo for DerivedDerivedClass
.quad Base::CommonFunction()
.quad virtual thunk to DerivedDerivedClass::VirtualFunction()
virtual thunk to DerivedClass1::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK0
virtual thunk to DerivedClass2::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK1
virtual thunk to DerivedDerivedClass::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK2
non-virtual thunk to DerivedDerivedClass::VirtualFunction():
sub rdi, 16
jmp .LTHUNK3
.set .LTHUNK0,DerivedClass1::VirtualFunction()
.set .LTHUNK1,DerivedClass2::VirtualFunction()
.set .LTHUNK2,DerivedDerivedClass::VirtualFunction()
.set .LTHUNK3,DerivedDerivedClass::VirtualFunction()
Each inherited class has its own construction virtual table and the most derived class, DerivedDerivedClass
, has a virtual table with a subtable for each, and it uses the pointer to the subtable to overwrite construction vtable pointer that the inherited class's constructor stored for each subobject. Each virtual method that needs a thunk (virtual thunk offsets the object pointer from the base to the start of the object and a non-virtual thunk offsets the object pointer from an inherited class's object that isn't the base object to the start of the whole object of the type DerivedDerivedClass
). The DerivedDerivedClass
constructor also uses a virtual table table (VTT) as a serial list of all the virtual table pointers that it needs to use and passes it to each constructor (along with the subobject address that the constructor is for), which they use to overwrite their and the base's vtable pointer.
DerivedDerivedClass::DerivedDerivedClass()
then passes the address of the object+16 and the address of VTT for DerivedDerivedClass+24
to DerivedClass2::DerivedClass2()
whose assembly is identical to DerivedClass1::DerivedClass1()
except for the line mov DWORD PTR [rax+8], 3
which obviously has a 4 instead of 3 for d = 4
.
After this, it replaces all 3 virtual table pointers in the object with pointers to offsets in DerivedDerivedClass
's vtable to the representation for that class.
The call to d->VirtualFunction()
in main
:
mov rax, QWORD PTR [rbp-24] //store pointer to object (and hence vtable pointer) in rax
mov rax, QWORD PTR [rax] //dereference this pointer to vtable pointer and store virtual table pointer in rax
add rax, 8 // add 8 to the pointer to get the 2nd function pointer in the table
mov rdx, QWORD PTR [rax] //dereference this pointer to get the address of the method to call
mov rax, QWORD PTR [rbp-24] //restore pointer to object in rax (-O0 is inefficient, yes)
mov rdi, rax //pass object to the method
call rdx
d->DerivedCommonFunction();
:
mov rax, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rdx]
mov rdx, QWORD PTR [rdx]
mov rdi, rax //pass object to method
call rdx //call the first function in the table
d->DerivedCommonFunction2();
:
mov rax, QWORD PTR [rbp-24] //get the object pointer
lea rdx, [rax+16] //get the address of the 2nd subobject in the object
mov rax, QWORD PTR [rbp-24] //get the object pointer
mov rax, QWORD PTR [rax+16] // get the vtable pointer of the 2nd subobject
add rax, 8 //call the 2nd function in this table
mov rax, QWORD PTR [rax] //get the address of the 2nd function
mov rdi, rdx //call it and pass the 2nd subobject to it
call rax
d->DerivedDerivedCommonFunction();
:
mov rax, QWORD PTR [rbp-24] //get the object pointer
mov rax, QWORD PTR [rax] //get the vtable pointer
add rax, 16 //get the 3rd function in the first virtual table (which is where virtual functions that that first appear in the most derived class go, because they belong to the full object which uses the virtual table pointer at the start of the object)
mov rdx, QWORD PTR [rax] //get the address of the object
mov rax, QWORD PTR [rbp-24]
mov rdi, rax //call it and pass the whole object to it
call rdx
((DerivedClass2*)d)->DerivedCommonFunction2();
:
//it casts the object to its subobject and calls the corresponding method in its virtual table, which will be a non-virtual thunk
cmp QWORD PTR [rbp-24], 0
je .L14
mov rax, QWORD PTR [rbp-24]
add rax, 16
jmp .L15
.L14:
mov eax, 0
.L15:
cmp QWORD PTR [rbp-24], 0
cmp QWORD PTR [rbp-24], 0
je .L18
mov rdx, QWORD PTR [rbp-24]
add rdx, 16
jmp .L19
.L18:
mov edx, 0
.L19:
mov rdx, QWORD PTR [rdx]
add rdx, 8
mov rdx, QWORD PTR [rdx]
mov rdi, rax
call rdx
((Base*)d)->VirtualFunction();
:
//it casts the object to its subobject and calls the corresponding function in its virtual table, which will be a virtual thunk
cmp QWORD PTR [rbp-24], 0
je .L20
mov rax, QWORD PTR [rbp-24]
mov rax, QWORD PTR [rax]
sub rax, 24
mov rax, QWORD PTR [rax]
mov rdx, rax
mov rax, QWORD PTR [rbp-24]
add rax, rdx
jmp .L21
.L20:
mov eax, 0
.L21:
cmp QWORD PTR [rbp-24], 0
cmp QWORD PTR [rbp-24], 0
je .L24
mov rdx, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rdx]
sub rdx, 24
mov rdx, QWORD PTR [rdx]
mov rcx, rdx
mov rdx, QWORD PTR [rbp-24]
add rdx, rcx
jmp .L25
.L24:
mov edx, 0
.L25:
mov rdx, QWORD PTR [rdx]
add rdx, 8
mov rdx, QWORD PTR [rdx]
mov rdi, rax
call rdx
If you need to open XLS files rather than XLSX files, http://npoi.codeplex.com/ is a great choice. We've used it to good effect on our projects.
If you have 2 versions of Python (eg: 2.7.x and 3.6), you need do:
pip3 install --upgrade pip setuptools wheel
for example, in my .zshrc file:
export PATH=/usr/local/Cellar/python@2/2.7.15/bin:/usr/local/Cellar/python/3.6.5/bin:$PATH
You can exec command pip --version
and pip3 --version
check the pip from the special version. Because if don't add Python path to $PATH, and exec pip3 install --upgrade pip setuptools wheel
, your pip will be changed to pip from python3, but the pip should from python2.x
Don't try to get them inside its constructor. Try Call them in onDraw()
method.
I maybe very late but you can use "nexe" module that compile nodejs + your script in one executable: https://github.com/crcn/nexe
@RequestMapping
has a String[]
value parameter, so you should be able to specify multiple values like this:
@RequestMapping(value={"", "/", "welcome"})
Check out Flutter Dropdown Banner to easily alert users of events and prompt action without having to manage the complexity of presenting, delaying, and dismissing the component.
import 'packages:dropdown_banner/dropdown_banner.dart';
...
class MainApp extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
final navigatorKey = GlobalKey<NavigatorState>();
...
return MaterialApp(
...
home: DropdownBanner(
child: Scaffold(...),
navigatorKey: navigatorKey,
),
);
}
}
import 'packages:dropdown_banner/dropdown_banner.dart';
...
class SomeClass {
...
void doSomethingThenFail() {
DropdownBanner.showBanner(
text: 'Failed to complete network request',
color: Colors.red,
textStyle: TextStyle(color: Colors.white),
);
}
}
Click here to see an example
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).
http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html
There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.
<!--[if gte mso 9]>
<style>
#tableForOutlook {
width:800px;
}
</style>
<![endif]-->
<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
<table id="tableForOutlook"><tr><td>
<![endif]-->
<tr><td>
[Your Content Goes Here]
</td></tr>
<!--[if gte mso 9]>
</td></tr></table>
<![endif]-->
<table>
When I face this problem I just edit the file and save it... works like charm
I got this error with a mis-configured test event. I changed the source buckets ARN but forgot to edit the default S3 bucket name.
I.e. make sure that in the bucket section of the test event both the ARN and bucket name are set correctly:
"bucket": {
"arn": "arn:aws:s3:::your_bucket_name",
"name": "your_bucket_name",
"ownerIdentity": {
"principalId": "EXAMPLE"
}
Right-click the database to clone, click Tasks
, click Copy Database...
. Follow the wizard and you're done.
I had this problem in eclipse, mvn -U clean install
didn't work but right clicking the project and selecting Maven->Update Project fixed it.
You can use Joshua's solution but I think you need Elts_int <- as.matrix(tmp_int)
Or for loops:
z <- 1 ## Initialize
counter <- 1 ## Initialize
for(y in 1:48) { ## Assuming 48 columns otherwise, swap 48 and 32
for (x in 1:32) {
z[counter] <- tmp_int[x,y]
counter <- 1 + counter
}
}
z is a 1d vector.
This is an IndexError
in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.
# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64)
# check its shape
In [15]: arr.shape
Out[15]: (0,)
with this array arr
in place, if we now try to assign any value to some index, for example to the index 0
as in the case below
In [16]: arr[0] = 23
Then, we will get an IndexError
, as below:
IndexError Traceback (most recent call last) <ipython-input-16-0891244a3c59> in <module> ----> 1 arr[0] = 23 IndexError: index 0 is out of bounds for axis 0 with size 0
The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0
).
In [19]: arr.size * arr.itemsize
Out[19]: 0
So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0
and fix that.
I do not have experience with version 7 of JBoss but with 5 I often had issues when redeploying apps which went away when I cleaned the work and tmp folder. I wrote a script for that which was executed everytime the server shut down. Maybe executing it before startup is better considering abnormal shutdowns (which weren't uncommon with Jboss 5 :))
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
I would be careful with setting the display
of the element to block. Different elements have the standard display as different things. For example setting display to block for a table row in firefox causes the width of the cells to be incorrect.
Is the name of the element actually test1. I know that .NET can add extra things onto the start or end. The best way to find out if your selector is working properly is by doing this.
alert($('#text1').length);
You might just need to remove the visibility attribute
$('#text1').removeAttr('visibility');
There are actually three things here: origin master
is two separate things, and origin/master
is one thing. Three things total.
Two branches:
master
is a local branchorigin/master
is a remote branch (which is a local copy of the branch named "master" on the remote named "origin")One remote:
origin
is a remoteSince origin/master
is a branch, you can merge it. Here's a pull in two steps:
Step one, fetch master
from the remote origin
. The master
branch on origin
will be fetched and the local copy will be named origin/master
.
git fetch origin master
Then you merge origin/master
into master
.
git merge origin/master
Then you can push your new changes in master
back to origin
:
git push origin master
You can fetch multiple branches by name...
git fetch origin master stable oldstable
You can merge multiple branches...
git merge origin/master hotfix-2275 hotfix-2276 hotfix-2290
This answer is thanks to Paul LeBeau in a comment. I thought I'd write it up as a proper answer since there surprisingly wasn't one.
The only thing that worked for me (jQuery 1.12.4, Chrome 86) was:
$(".js-my-radio-button").trigger("click");
This does everything I want – changes which radio button looks selected (both visually and programmatically) and triggers events such as change
on the radio button.
Just setting the "checked" attribute as other answers suggest would not change which radio button was selected for me.
You can use either this in the onCreate() method of the activity
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
or paste this code in the Activity tags in AndroidManifest.xml
android:windowSoftInputMode="stateVisible"
Another simple example.
For this sample we can use 100x100 DIV-box:
<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
// Red box contents here...
</div>
And small jQuery trick:
<script type="text/javascript">
jQuery("#box").bind("resize", function() {
alert("Box was resized from 100x100 to 200x200");
});
jQuery("#box").width(200).height(200).trigger("resize");
</script>
Steps:
That's all. ;-)
docker container list -f "status=exited"
or
docker container ls -f "status=exited"
or
docker ps -f "status=exited"
Why do you use new Date instead of a static UTC string?
function clearListCookies(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++){
var spcook = cookies[i].split("=");
document.cookie = spcook[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";
}
}
Let me try to make it simple, suppose URL of the site is http://example.com/ and let's suppose you need to sign up by filling username and password, so we go to the login page say http://example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
What if you do this (as was suggested earlier):
new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000
//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");
//like if you click on a link (it will be saved in the session history,
//so the back button will work as expected)
window.location.href = "http://www.google.com";
I did subscript capital & bolded V. It works perfectly (although it takes some effort, if it needs to be done repetitively)
Syntax:
<sub><strong>v</strong></sub>
Output:
v
GIFImageView
public class GifImageView extends ImageView {
Movie movie;
InputStream inputStream;
private long mMovieStart;
public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public GifImageView(Context context) {
super(context);
}
public GifImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
inputStream = context.getResources()
.openRawResource(R.drawable.thunder);
byte[] array = streamToBytes(inputStream);
movie = Movie.decodeByteArray(array, 0, array.length);
}
private byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
byteArrayOutputStream.write(buffer, 0, len);
return byteArrayOutputStream.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
long now = SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (movie != null) {
int dur = movie.duration();
if (dur == 0) {
dur = 3000;
}
int relTime = (int) ((now - mMovieStart) % dur);
movie.setTime(relTime);
movie.draw(canvas, getWidth() - 200, getHeight() - 200);
invalidate();
}
}
}
In XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="abc" />
<com.example.apptracker.GifImageView
android:id="@+id/gifImageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
In Java File
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GifImageView gifImageView = (GifImageView) findViewById(R.id.gifImageView1);
if (Build.VERSION.SDK_INT >= 11) {
gifImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
}
We need to use gifImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
as when hardware accelerated enabled, GIF image not work on those device. Hardware accelerated is enabled on devices above(4.x).
If I understand your question right you are asking what is difference if you register listener callback with $watch
or if you do it with $observe
.
Callback registerd with $watch
is fired when $digest
is executed.
Callback registered with $observe
are called when value changes of attributes that contain interpolation (e.g. attr="{{notJetInterpolated}}"
).
Inside directive you can use both of them on very similar way:
attrs.$observe('attrYouWatch', function() {
// body
});
or
scope.$watch(attrs['attrYouWatch'], function() {
// body
});
You can parse the date using the Date
constructor, then spit out the individual time components:
function convert(str) {_x000D_
var date = new Date(str),_x000D_
mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
day = ("0" + date.getDate()).slice(-2);_x000D_
return [date.getFullYear(), mnth, day].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"
_x000D_
As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:
function convert(str) {_x000D_
var mnths = {_x000D_
Jan: "01",_x000D_
Feb: "02",_x000D_
Mar: "03",_x000D_
Apr: "04",_x000D_
May: "05",_x000D_
Jun: "06",_x000D_
Jul: "07",_x000D_
Aug: "08",_x000D_
Sep: "09",_x000D_
Oct: "10",_x000D_
Nov: "11",_x000D_
Dec: "12"_x000D_
},_x000D_
date = str.split(" ");_x000D_
_x000D_
return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"
_x000D_
Making changes as below and redeploying on server content type as
Response.ContentType = "application/octet-stream";
This worked for me.
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
The simplest way to do this is with a list comprehension:
[s + mystring for s in mylist]
Notice that I avoided using builtin names like list
because that shadows or hides the builtin names, which is very much not good.
Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):
(s + mystring for s in mylist)
These are very powerful, flexible, and concise. Every good python programmer should learn to wield them.
I want to make sure that the script is running in its directory. So
cd $(dirname $(which $0) )
After this, if you really want to know where the you are running then run the command below.
DIR=$(/usr/bin/pwd)
In Project level build.gradle
use only this version
ext.kotlin_version = '1.3.31'
Remove other versions
This will only work with the latest version of android studio 3.4
UPDATE: Try to use the latest version of kotlin with latest Android studio to avoid an error.
Excel shows 24:03 as 3 minutes when you format it as time, because 24:03 is the same as 12:03 AM (in military time).
Instead of trying to format as Time, use the General Format and the following formula:
=number of minutes + (number of seconds / 60)
Ex: for 24 minutes and 3 seconds:
=24+3/60
This will give you a value of 24.05.
Do this for each time period. Let's say you enter this formula in cells A1
and A2
. Then, to get the total sum of elapsed time, use this formula in cell A3
:
=INT(A1+A2)+MOD(A1+A2,1)
If you put =24+3/60
into each cell, you will have a value of 48.1 in cell A3
.
Now you need to convert this back to minutes and seconds. Use the following formula in cell A4
:
=MOD(A3,1)*60
This takes the decimal portion and multiples it by 60. Remember, we divided by 60 in the beginning, so to convert it back to seconds we need to multiply.
You could have also done this separately, i.e. in cell A3 use this formula:
=INT(A1+A2)
and this formula in cell A4
:
=MOD(A1+A2,1)*60
Here's a screenshot showing the final formulas:
$page_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
As suggested in "PostgreSQL database default location on Linux", under Linux you can find out using the following command:
ps aux | grep postgres | grep -- -D
When a subscriber unsubscribes you are changing contents of the collection of Subscribers during enumeration.
There are several ways to fix this, one being changing the for loop to use an explicit .ToList()
:
public void NotifySubscribers(DataRecord sr)
{
foreach(Subscriber s in subscribers.Values.ToList())
{
^^^^^^^^^
...
There is no way to configure an exclusion to the proxy settings, but a colleague of mine had an create solution for that particular problem. He installed a local proxy server called cntlm. That server supports ntlm authentication and exclusions to the general proxy settings. A perfect match.
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
Best answer:
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($arr as $a) {
// This is the line that does the checking
if (!each($arr)) echo "End!\n";
echo $a."\n";
}
You can also use the index for the sheet:
xls = pd.ExcelFile('path_to_file.xls')
sheet1 = xls.parse(0)
will give the first worksheet. for the second worksheet:
sheet2 = xls.parse(1)
Use execute_script
, here's a python example:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python")
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")
Using table
:
library(magrittr)
myvec %>% unique %>% '['(1) %>% table %>% as.data.frame %>%
setNames(c("name","number_of_distinct_orders"))
# name number_of_distinct_orders
# 1 Amy 2
# 2 Dave 1
# 3 Jack 3
# 4 Larry 1
# 5 Tom 2
The easiest would probably be tag stripping combined with replacement of some tags with text layout elements like dashes for list elements (li) and line breaks for br's and p's. It shouldn't be too hard to extend this to tables.
I did not want to install visual studio and development environment, so I have installed AspNetMVC4Setup.exe in Windows server 2016 machine and it solved the problem. The installer was downloaded from Microsoft website.
ul.menu li a:before, ul.menu li .item:before, ul.menu li .separator:before {
content: "\2022";
font-family: FontAwesome;
margin-right: 10px;
display: inline;
vertical-align: middle;
font-size: 1.6em;
font-weight: normal;
}
Is present in your site's CSS, looks like it's coming from a compiled CSS file from within your application. Perhaps from a plugin. Changing the name of the "menu" class you are using should resolve the issue.
Visual for you - http://i.imgur.com/d533SQD.png
ASP.NET Core 2.0 with Angular
Make sure to use type of authentication filter
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
When and where to use \\\"
instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.
If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\"
is the one you're looking for.
However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\"
. This is because you're building your text string within an HTML <script>
block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \"
from the standard answer and the JSON parser will parse this as just the double quotes.
<script>
var text="{";
text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
text += "}";
var obj=JSON.parse(text);
</script>
+1: since it's a JavaScript text string, a double backslash double quote \\"
would work too; because the double quote does not need escaped within a single quoted string eg '\"'
and '"'
result in the same JS string.
Just set the display:none on the elements that you want to hide:
<table>
<tr><th>Test Table</th><tr>
<tr style="display:none"><td>1. 123456789</td><tr>
<tr><td>2. 123456789</td><tr>
<tr><td>3. 123456789</td><tr>
</table>
Javascript
This method is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
html code in my case
<ul class="navs">
<li id="tab1"><a href="index-2.html">home</a></li>
<li id="tab2"><a href="about.html">about</a></li>
<li id="tab3"><a href="project-02.html">Products</a></li>
<li id="tab4"><a href="contact.html">contact</a></li>
</ul>
and js code is
$('.navs li a').click(function (e) {
var $parent = $(this).parent();
document.cookie = eraseCookie("tab");
document.cookie = createCookie("tab", $parent.attr('id'),0);
});
$().ready(function () {
var $activeTab = readCookie("tab");
if (!$activeTab =="") {
$('#tab1').removeClass('ActiveTab');
}
// alert($activeTab.toString());
$('#'+$activeTab).addClass('active');
});
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
This is an example that could work for you if what you need is not exactly the path, but a reference to the file working offline.
http://www.ab-d.fr/date/2008-07-12/
It is in french, but the code is javascript :)
This are the references the article points to: http://developer.mozilla.org/en/nsIDOMFile http://developer.mozilla.org/en/nsIDOMFileList
Mine was fixed by just using this command :-
>git config --global http.proxy XXX.XXX.XXX.XXX:ZZ
where XXX.XXX.XXX.XXX is the proxy server address and ZZ is the port number of the proxy server.
There was no need to specify any username or password in my case.
You can achieve this with the background-size
property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%
. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!
. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion
to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &
, &&
, or ||
are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET
or SET /?
from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
The settings which has been advised to change in @Diego's accepted answer might be good if you want to set this option permanently for all future query sessions that you open within SQL Server Management Studio(SSMS). This is usually not the case. Also, changing this setting requires restarting SQL Server Management Studio (SSMS) application. This is again a 'not-so-nice' experience if you've many unsaved open query session windows and you are in the middle of some debugging.
SQL Server gives a much slick option of changing it on per session basis which is very quick, handy and convenient. I'm detailing the steps below using query options window:
Query Options...
at the bottom of the context menu as shown below:Results
> Grid
in the left navigation pane. Check the Include column headers when copying or saving the results
check box in right pane as shown below:That's it. Your current session will honour your settings with immediate effect without restarting SSMS. Also, this setting won't be propagated to any future session. Effectively changing this setting on a per session basis is much less noisy.
var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();
Easy and simple
#right {
background-color: red;
height: 300px;
width: 300px;
z-index: 9999;
margin-top: 0px;
position: absolute;
top:0;
right:0;
}
position: absolute; top:0; right:0; do the work here! :) Also remove the floating!
class.method
should work.
class SomeClass:
@classmethod
def some_class_method(cls):
pass
@staticmethod
def some_static_method():
pass
SomeClass.some_class_method()
SomeClass.some_static_method()
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:
http://howtonode.org/control-flow
Also see the Sequential Actions section of the second part of that posting:
Another way to resolve this problem:
$('input').oninvalid(function (event, errorMessage) {
event.target.focus();
});
A kotlin version
fun openAppInPlayStore() {
val uri = Uri.parse("market://details?id=" + context.packageName)
val goToMarketIntent = Intent(Intent.ACTION_VIEW, uri)
var flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
flags = if (Build.VERSION.SDK_INT >= 21) {
flags or Intent.FLAG_ACTIVITY_NEW_DOCUMENT
} else {
flags or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
goToMarketIntent.addFlags(flags)
try {
startActivity(context, goToMarketIntent, null)
} catch (e: ActivityNotFoundException) {
val intent = Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName))
startActivity(context, intent, null)
}
}
When I tried cloning from the remote, got the same issue repeatedly:
remote: Counting objects: 182, done.
remote: Compressing objects: 100% (149/149), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
Finally this worked for me:
git clone https://[email protected]/repositoryName.git --depth 1
Nicely explained above!
For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the %
with a !
So:
SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!
Have a read at this post: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/
It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:
if(myvar) { }
It also mentions what's considered 'falsey' that you might not realise.
OAuth(Open Authorization) is an open standard for access granting/deligation protocol. It used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. It does not deal with authentication.
Or
OAuth 2.0 is a protocol that allows a user to grant limited access to their resources on one site, to another site, without having to expose their credentials.
Analogy 1: Many luxury cars today come with a valet key. It is a special key you give the parking attendant and unlike your regular key, will not allow the car to drive more than a mile or two. Some valet keys will not open the trunk, while others will block access to your onboard cell phone address book. Regardless of what restrictions the valet key imposes, the idea is very clever. You give someone limited access to your car with a special key, while using your regular key to unlock everything. src from auth0
Analogy 2: Assume, we want to fill an application form for a bank account. Here Oauth works as, instead of filling the form by applicant, bank can fill the form using Adhaar or passport.
Here the following three entities are involved:
You can add a row to a table in the most easiest way like this :-
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body
is the id of the table body tag .
u can check onCancelled() once then :
protected Object doInBackground(Object... x) {
while (/* condition */) {
if (isCancelled()) break;
}
return null;
}
Without explicitly defining the height
I determined I need to apply the flex
value to the parent and grandparent div
elements...
<div style="display: flex;">
<div style="display: flex;">
<img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>
If you're using a single element (e.g. dead-centered text in a single flex
element) use the following:
align-items: center;
display: flex;
justify-content: center;
but classes are so 2018
ScrollToTop.js
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return (null);
}
export default withRouter(ScrollToTop);
Usage:
<Router>
<Fragment>
<ScrollToTop />
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</Fragment>
</Router>
ScrollToTop can also be implemented as a wrapper component:
ScrollToTop.js
import React, { useEffect, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history, children }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return <Fragment>{children}</Fragment>;
}
export default withRouter(ScrollToTop);
Usage:
<Router>
<ScrollToTop>
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</ScrollToTop>
</Router>
You do it exactly as you showed with this line:
get.setHeader("Content-Type", "application/x-zip");
So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.
Take a look at calc() specification. Here is an example of usage:
border-right:1px solid;
border-left:1px solid;
width:calc(100% - 2px);
select sequence_owner, sequence_name from dba_sequences;
DBA_SEQUENCES -- all sequences that exist
ALL_SEQUENCES -- all sequences that you have permission to see
USER_SEQUENCES -- all sequences that you own
Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES
, there is no SEQUENCE_OWNER
column in USER_SEQUENCES
.
Kotlin:
var ver: String = packageManager.getPackageInfo(packageName, 0).versionName
The problem with source
is that it requires the file to have a proper bash syntax, and some special characters will ruin it: =
, "
, '
, <
, >
, and others. So in some cases you can't just
source development.env
This version, however, withstands every special character in values:
set -a
source <(cat development.env | \
sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
set +a
Explanation:
-a
means that every bash variable would become an environment variable/^#/d
removes comments (strings that start with #
)/^\s*$/d
removes empty strings, including whitespace"s/'/'\\\''/g"
replaces every single quote with '\''
, which is a trick sequence in bash to produce a quote :)"s/=\(.*\)/='\1'/g"
converts every a=b
into a='b'
As a result, you are able to use special characters :)
To debug this code, replace source
with cat
and you'll see what this command produces.
In python3:
pip install python-dateutil
from dateutil.parser import tz
mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None)
I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then a float too, and that gives you the warning.