Unbelievably, in 3 years nobody has answered your excellent question with examples of both ways to map the relationship.
As mentioned by others, the "owner" side contains the pointer (foreign key) in the database. You can designate either side as the owner, however, if you designate the One side as the owner, the relationship will not be bidirectional (the inverse aka "many" side will have no knowledge of its "owner"). This can be desirable for encapsulation/loose coupling:
// "One" Customer owns the associated orders by storing them in a customer_orders join table
public class Customer {
@OneToMany(cascade = CascadeType.ALL)
private List<Order> orders;
}
// if the Customer owns the orders using the customer_orders table,
// Order has no knowledge of its Customer
public class Order {
// @ManyToOne annotation has no "mappedBy" attribute to link bidirectionally
}
The only bidirectional mapping solution is to have the "many" side own its pointer to the "one", and use the @OneToMany "mappedBy" attribute. Without the "mappedBy" attribute Hibernate will expect a double mapping (the database would have both the join column and the join table, which is redundant (usually undesirable)).
// "One" Customer as the inverse side of the relationship
public class Customer {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
private List<Order> orders;
}
// "many" orders each own their pointer to a Customer
public class Order {
@ManyToOne
private Customer customer;
}
You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
ECMAScript 6 introduced template strings:
Template strings are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
For example:
alert(`Please Select file
to delete`);
will alert:
Please Select file
to delete
Inside your git repository directory, run git config user.name
.
Why is running this command within your git repo directory important?
If you are outside of a git repository, git config user.name
gives you the value of user.name
at global level. When you make a commit, the associated user name is read at local level.
Although unlikely, let's say user.name
is defined as foo
at global level, but bar
at local level. Then, when you run git config user.name
outside of the git repo directory, it gives bar
. However, when you really commits something, the associated value is foo
.
Git config variables can be stored in 3 different levels. Each level overrides values in the previous level.
1. System level (applied to every user on the system and all their repositories)
git config --list --system
(may need sudo
)git config --system color.ui true
git config --edit --system
2. Global level (values specific personally to you, the user. )
git config --list --global
git config --global user.name xyz
git config --edit --global
3. Repository level (specific to that single repository)
git config --list --local
git config --local core.ignorecase true
(--local
optional)git config --edit --local
(--local
optional)How to view all settings?
git config --list
, showing system, global, and (if inside a repository) local configsgit config --list --show-origin
, also shows the origin file of each config itemHow to read one particular config?
git config user.name
to get user.name
, for example.--system
, --global
, --local
to read that value at a particular level.Reference: 1.6 Getting Started - First-Time Git Setup
Here is a complete program how to recursively list folder's contents:
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#define NORMAL_COLOR "\x1B[0m"
#define GREEN "\x1B[32m"
#define BLUE "\x1B[34m"
/* let us make a recursive function to print the content of a given folder */
void show_dir_content(char * path)
{
DIR * d = opendir(path); // open the path
if(d==NULL) return; // if was not able return
struct dirent * dir; // for the directory entries
while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
{
if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
printf("%s%s\n",BLUE, dir->d_name);
else
if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
{
printf("%s%s\n",GREEN, dir->d_name); // print its name in green
char d_path[255]; // here I am using sprintf which is safer than strcat
sprintf(d_path, "%s/%s", path, dir->d_name);
show_dir_content(d_path); // recall with the new path
}
}
closedir(d); // finally close the directory
}
int main(int argc, char **argv)
{
printf("%s\n", NORMAL_COLOR);
show_dir_content(argv[1]);
printf("%s\n", NORMAL_COLOR);
return(0);
}
I realize this is an older post, but thought this might be helpful to anyone wondering the same question:
While the previous answers are no doubt valid, there is a more simple reason for the distinction between textarea and input.
As mentioned previously, HTML is used to describe and give as much semantic structure to web content as possible, including input forms. A textarea may be used for input, however a textarea can also be marked as read only via the readonly attribute. The existence of such an attribute would not make any sense for an input type, and thus the distinction.
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {res.EMAIL, res.USERNAME} );
OR you can use
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {email=res.EMAIL, username=res.USERNAME} );
Explanation :
Select employee from the db as res.
Filter the employee details as per the where condition.
Select required fields from the employee object by creating an Anonymous object using new { }
Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.
Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")
Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing
End Sub
I found a solution in case you have installed Eclipse(Luna) with the SVN Client JavaHL(JNI) 1.8.13 and Tortoise:
Open Eclipse: First try to add the project / maven module to Version Control (Project -> Context Menu -> Team -> Add to Version Control)
You will see the following Eclipse error message:
org.apache.subversion.javahl.ClientException: Entry already exists svn: 'PathToYouProject' is already under version control
After that you have to open your workspace directory in your explorer, select your project and resolve it via Tortoise (Project -> Context Menu -> TortoiseSVN -> Resolve)
You will see the following message dialog: "File list is empty"
Press cancel and refresh the project in Eclipse. Your project should be under version control again.
Unfortunately it is not possible to resolve more the one project at the same time ... you don't have to delete anything but depending on the size of your project it could be a little bit laborious.
The <scope>
element can take 6 values: compile, provided, runtime, test, system and import.
This scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.
compile
This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
provided
This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.
runtime
This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
test
This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.
system
This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.
import (only available in Maven 2.0.9 or later)
This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.
To answer the second part of your question:
How can we use it for running test?
Note that the test
scope allows to use dependencies only for the test phase.
Read the documentation for full details.
I've created the following script and it worked for me just fine.
#! /bin/sh
cd $(dirname $0)
DB=$1
DBUSER=$2
DBPASSWD=$3
FILE=$DB-$(date +%F).sql
mysqldump --routines "--user=${DBUSER}" --password=$DBPASSWD $DB > $PWD/$FILE
gzip $FILE
echo Created $PWD/$FILE*
and you call the script using command line arguments.
backupdb.sh my_db dev_user dev_password
Pure javascript would be like this
var children = document.getElementById('test').children;
If you are using jQuery it would be like this
$("#test").children()
To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.
DataTable dt;
int desiredSize = 10;
while (dt.Columns.Count > desiredSize)
{
dt.Columns.RemoveAt(desiredSize);
}
Modify your HTML like this:
<table border="0" cellpadding="0" cellspacing="0">
<thead>
<tr><td>1</td><td>2</td><td>3</td></tr>
</thead>
<tbody>
<tr><td>a</td><td>b></td><td>c</td></tr>
<tr class='odd'><td>x</td><td>y</td><td>z</td></tr>
</tbody>
</table>
(I added border="0" cellpadding="0" cellspacing="0"
)
In CSS, you could do the following:
table {
border-collapse: collapse;
}
$filelist | % {
$file = $_
mkdir -force (Split-Path $dest) | Out-Null
cp $file $dest
}
COLUMN()
and ROW()
won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.
For instance, if you want to use this conditional formating on a range begining on cell A1
, you can try:
`COLUMN(A1)` and `ROW(A1)`
Excel will automatically adapt the conditional formating to the current cell.
This does not allow space in the beginning. But allowes spaces in between words. Also allows for special characters between words. A good regex for FirstName and LastName fields.
\w+.*$
C is a macro assembler! And it's the best one!
It can do nearly everything assembly can, it can be portable and in most of the rare cases where it can't do something you can still use embedded assembly code. This leaves only a small fraction of programs that you absolutely need to write in assembly and nothing but assembly.
And the higher level abstractions and the portability make it more worthwhile for most people to write system software in C. And although you might not need portability now if you invest a lot of time and money in writing some program you might not want to limit yourself in what you'll be able to use it for in the future.
-Right click on either axis
-Click "Select Data..."
-Then Press the "Edit" button
-Copy the "Series X values" to the "Series Y values" and vise versa finally hit ok
I found this answer on this youtube video https://www.youtube.com/watch?v=xLKIWWIWltE
You should check ExcelJS
Works with CSV and XLSX formats.
Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:
app.get('/some/route', function(req, res) {
res.writeHead(200, {
'Content-Disposition': 'attachment; filename="file.xlsx"',
'Transfer-Encoding': 'chunked',
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
var workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: res })
var worksheet = workbook.addWorksheet('some-worksheet')
worksheet.addRow(['foo', 'bar']).commit()
worksheet.commit()
workbook.commit()
}
Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)
See also this SO answer.
First we should know that regular expression can separately be used. Here is an example:
import scala.util.matching.Regex
val pattern = "Scala".r // <=> val pattern = new Regex("Scala")
val str = "Scala is very cool"
val result = pattern findFirstIn str
result match {
case Some(v) => println(v)
case _ =>
} // output: Scala
Second we should notice that combining regular expression with pattern matching would be very powerful. Here is a simple example.
val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
"2014-11-20" match {
case date(year, month, day) => "hello"
} // output: hello
In fact, regular expression itself is already very powerful; the only thing we need to do is to make it more powerful by Scala. Here are more examples in Scala Document: http://www.scala-lang.org/files/archive/api/current/index.html#scala.util.matching.Regex
URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.
There are several ways to soften the pain:
JSF EL offers a shorthand to ${pageContext.request}
in flavor of #{request}
:
<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>
You can if necessary use <c:set>
tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:
<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>
JSF 2.x offers the <h:link>
which can take a view ID relative to the context root in outcome
and it will append the context path and FacesServlet
mapping automatically:
<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>
HTML offers the <base>
tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>
.
<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>
(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring()
, see also this answer)
This should end up in the generated HTML something like as
<base href="http://example.com/webname/" />
Note that the <base>
tag has a caveat: it makes all jump anchors in the page like <a href="#top">
relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a>
or <h:link value="top" fragment="top" />
.
The git submodule update
command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. If you want to update your submodules to the latest commit available from their remote, you will need to do this directly in the submodules.
So in summary:
# Get the submodule initially
git submodule add ssh://bla submodule_dir
git submodule init
# Time passes, submodule upstream is updated
# and you now want to update
# Change to the submodule directory
cd submodule_dir
# Checkout desired branch
git checkout master
# Update
git pull
# Get back to your project root
cd ..
# Now the submodules are in the state you want, so
git commit -am "Pulled down update to submodule_dir"
Or, if you're a busy person:
git submodule foreach git pull origin master
The focus only works if the window is focused.
Use ((JavascriptExecutor)webDriver).executeScript("window.focus();");
to be sure.
Apart from what others have mentioned, I would like to add that, Linting will run through your source code to find
- formatting discrepancy
- non-adherence to coding standards and conventions
- pinpointing possible logical errors in your program
Running a Lint program over your source code, helps to ensure that source code is legible, readable, less polluted and easier to maintain.
If this isn't a good solution for any reason, please let me know. It worked fine for me.
What I did is to hide the Sidebar and then make appear the navbar with breakpoints
@media screen and (max-width: 771px) {
#fixed-sidebar {
display: none;
}
#navbar-superior {
display: block !important;
}
}
You can use:
<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>
Or this:
textbox.Style["text-align"] = "center"; //right, left
In this line:
const char* cstr2 = ss.str().c_str();
ss.str()
will make a copy of the contents of the stringstream. When you call c_str()
on the same line, you'll be referencing legitimate data, but after that line the string will be destroyed, leaving your char*
to point to unowned memory.
If You're using php5.6 and Ubuntu 18.04 Then run these two commands in your terminal your errors will be solved definitely.
sudo apt-get install php5.6-gd
then restart your apache server by this command.
sudo service apache2 restart
If you use Vundle, :PluginList
.
No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).
This is indeed rather odd.
If aSourceDictionary
were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.
This leads to two hypotheses:
The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)
aSourceDictionary
is in fact not a dictionary, but is some other structure (for example, a list).
new_data <- data %>% filter_all(any_vars(is.na(.)))
This should create a new data frame (new_data
) with only the missing values in it.
Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).
Please see this link for more information on setting the text size in code. Basically it says:
public void setTextSize (int unit, float size)
Since: API Level 1 Set the default text size to a given unit and value. See TypedValue for the possible dimension units. Related XML Attributes
android:textSize Parameters
unit The desired dimension unit.
size The desired size in the given units.
Check out this code :-
/* Create Date Object */
Date date = new Date();
XMLGregorianCalendar xmlDate = null;
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
try{
xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("XMLGregorianCalendar :- " + xmlDate);
You can see complete example here
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
No, VB.NET does not yet have such a feature. It will be available in the next iteration of VB (visual basic 10) however (link)
:: savevars.bat
:: Use $ to prefix any important variable to save it for future runs.
@ECHO OFF
SETLOCAL
REM Load variables
IF EXIST config.txt FOR /F "delims=" %%A IN (config.txt) DO SET "%%A"
REM Change variables
IF NOT DEFINED $RunCount (
SET $RunCount=1
) ELSE SET /A $RunCount+=1
REM Display variables
SET $
REM Save variables
SET $>config.txt
ENDLOCAL
PAUSE
EXIT /B
Output:
$RunCount=1
$RunCount=2
$RunCount=3
The technique outlined above can also be used to share variables among multiple batch files.
I face the same problem. After reading numerous posts, I would like to introduce the following solution I finally chose over many other methods (e.g. use urllib
, httpimport
, clone from GitHub, package the modules for installation, etc). The solution utilizes Google Drive API (official doc) for proper authorization.
id=
" - the file id assigned by Google Drive!pip install pydrive # Package to use Google Drive API - not installed in Colab VM by default
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth # Other necessary packages
from oauth2client.client import GoogleCredentials
auth.authenticate_user() # Follow prompt in the authorization process
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
your_module = drive.CreateFile({"id": "your_module_file_id"}) # "your_module_file_id" is the part after "id=" in the shareable link
your_module.GetContentFile("your_module_file_name.py") # Save the .py module file to Colab VM
import your_module_file_name # Ready to import. Don't include".py" part, of course :)
Last but not least, I should credit the original contributor of this approach. That post might have some typo in the code as it triggered an error when I tried it. After more reading and troubleshooting my code snippets above worked (as of today on Colab VM OS: Linux 4.14.79).
What about using Replace all? Just replace All on bracket to space. And comma to space. And I think you can achieve it.
You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."
Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.
Update:
The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg
Unlike subversion, git does not have a per-file history. If you look at the commit data structure, it only points to the previous commits and the new tree object for this commit. No explicit information is stored in the commit object which files are changed by the commit; nor the nature of these changes.
The tools to inspect changes can detect renames based on heuristics. E.g. "git diff" has the option -M that turns on rename detection. So in case of a rename, "git diff" might show you that one file has been deleted and another one created, while "git diff -M" will actually detect the move and display the change accordingly (see "man git diff" for details).
So in git this is not a matter of how you commit your changes but how you look at the committed changes later.
One of the reason I found was why it doesn't find a jar from repository might be because the .pom file for that particular jar might be missing or corrupt. Just correct it and try to load from local repository.
Try docker rmi node
. That should work.
Seeing all created containers is as simple as docker ps -a
.
To remove all existing containers (not images!) run docker rm $(docker ps -aq)
There are two options, really:
E.g.,
int[] ints = {11367, 11358, 11421, 11530, 11491, 11218, 11789};
Arrays.sort(ints);
System.out.println(Arrays.asList(ints));
That of course assumes that you already have your integers as an array. If you need to parse those first, look for String.split and Integer.parseInt.
FLAnimatedImage is a performant open source animated GIF engine for iOS:
It's a well-tested component that I wrote to power all GIFs in Flipboard.
There is a much simpler solution for detecting caps-lock:
function isCapsLockOn(event) {
var s = String.fromCharCode(event.which);
if (s.toUpperCase() === s && s.toLowerCase() !== s && !event.shiftKey) {
return true;
}
}
Open a terminal and type:
mongo
The below command should show the listed databases:
show dbs
/* the <dbname> is the database you'd like to drop */
use <dbname>
/* the below command will delete the database */
db.dropDatabase()
The below should be the output in the terminal:
{
"dropped": "<dbname>",
"ok": 1
}
There will be a new option when Python 3.8 releases (scheduled for 20 October, 2019), thanks to PEP 572: Assignment Expressions. The new assignment expression operator :=
allows you to assign the result of the copy
and still use it to call update
, leaving the combined code a single expression, rather than two statements, changing:
newdict = dict1.copy()
newdict.update(dict2)
to:
(newdict := dict1.copy()).update(dict2)
while behaving identically in every way. If you must also return the resulting dict
(you asked for an expression returning the dict
; the above creates and assigns to newdict
, but doesn't return it, so you couldn't use it to pass an argument to a function as is, a la myfunc((newdict := dict1.copy()).update(dict2))
), then just add or newdict
to the end (since update
returns None
, which is falsy, it will then evaluate and return newdict
as the result of the expression):
(newdict := dict1.copy()).update(dict2) or newdict
Important caveat: In general, I'd discourage this approach in favor of:
newdict = {**dict1, **dict2}
The unpacking approach is clearer (to anyone who knows about generalized unpacking in the first place, which you should), doesn't require a name for the result at all (so it's much more concise when constructing a temporary that is immediately passed to a function or included in a list
/tuple
literal or the like), and is almost certainly faster as well, being (on CPython) roughly equivalent to:
newdict = {}
newdict.update(dict1)
newdict.update(dict2)
but done at the C layer, using the concrete dict
API, so no dynamic method lookup/binding or function call dispatch overhead is involved (where (newdict := dict1.copy()).update(dict2)
is unavoidably identical to the original two-liner in behavior, performing the work in discrete steps, with dynamic lookup/binding/invocation of methods.
It's also more extensible, as merging three dict
s is obvious:
newdict = {**dict1, **dict2, **dict3}
where using assignment expressions won't scale like that; the closest you could get would be:
(newdict := dict1.copy()).update(dict2), newdict.update(dict3)
or without the temporary tuple of None
s, but with truthiness testing of each None
result:
(newdict := dict1.copy()).update(dict2) or newdict.update(dict3)
either of which is obviously much uglier, and includes further inefficiencies (either a wasted temporary tuple
of None
s for comma separation, or pointless truthiness testing of each update
's None
return for or
separation).
The only real advantage to the assignment expression approach occurs if:
set
s and dict
s (both of them support copy
and update
, so the code works roughly as you'd expect it to)dict
itself, and must preserve the type and semantics of the left hand side (rather than ending up with a plain dict
). While myspecialdict({**speciala, **specialb})
might work, it would involve an extra temporary dict
, and if myspecialdict
has features plain dict
can't preserve (e.g. regular dict
s now preserve order based on the first appearance of a key, and value based on the last appearance of a key; you might want one that preserves order based on the last appearance of a key so updating a value also moves it to the end), then the semantics would be wrong. Since the assignment expression version uses the named methods (which are presumably overloaded to behave appropriately), it never creates a dict
at all (unless dict1
was already a dict
), preserving the original type (and original type's semantics), all while avoiding any temporaries.Another simple way I found for using in LAN is
ssh [username@ip] uname -n
If you need to login command line will be
sshpass -p "[password]" ssh [username@ip] uname -n
This problem was a plague to me!!! The 100% solution is to forget using the mysql module: import mysql.connector, instead use pymysql via import pymysql. I installed it via the instructions: python3 -m pip install PyMySQL
made a change to the: 1. Import statement 2. The connector 3. The cursor
After that everything worked like a charm. Hope this helps!
Let's break >> /dev/null 2>&1
statement into parts:
Part 1: >>
output redirection
This is used to redirect the program output and append the output at the end of the file. More...
Part 2: /dev/null
special file
This is a Pseudo-devices special file.
Command ls -l /dev/null
will give you details of this file:
crw-rw-rw-. 1 root root 1, 3 Mar 20 18:37 /dev/null
Did you observe crw
? Which means it is a pseudo-device file which is of character-special-file type that provides serial access.
/dev/null
accepts and discards all input; produces no output (always returns an end-of-file indication on a read). Reference: Wikipedia
Part 3: 2>&1
file descriptor
Whenever you execute a program, the operating system always opens three files, standard input, standard output, and standard error as we know whenever a file is opened, the operating system (from kernel) returns a non-negative integer called a file descriptor. The file descriptor for these files are 0, 1, and 2, respectively.
So 2>&1
simply says redirect standard error to standard output.
&
means whatever follows is a file descriptor, not a filename.
In short, by using this command you are telling your program not to shout while executing.
What is the importance of using 2>&1
?
If you don't want to produce any output, even in case of some error produced in the terminal. To explain more clearly, let's consider the following example:
$ ls -l > /dev/null
For the above command, no output was printed in the terminal, but what if this command produces an error:
$ ls -l file_doesnot_exists > /dev/null
ls: cannot access file_doesnot_exists: No such file or directory
Despite I'm redirecting output to /dev/null
, it is printed in the terminal. It is because we are not redirecting error output to /dev/null
, so in order to redirect error output as well, it is required to add 2>&1
:
$ ls -l file_doesnot_exists > /dev/null 2>&1
I simple used Eval(string)
and it evaluated as Double.
If you want a more transparent solution, you can subclass dict
to get this behavior:
class NoneDict(dict):
def __getitem__(self, key):
return dict.get(self, key)
>>> foo = NoneDict([(1,"asdf"), (2,"qwerty")])
>>> foo[1]
'asdf'
>>> foo[2]
'qwerty'
>>> foo[3] is None
True
As an example, I am using a login modal window, where the modal window is the parent, the login form is the child and the login button calls back to the modal parent's close function.
The parent modal contains the function to close the modal. This parent passes the close function to the login child component.
import { Component} from '@angular/core';
import { LoginFormComponent } from './login-form.component'
@Component({
selector: 'my-modal',
template: `<modal #modal>
<login-form (onClose)="onClose($event)" ></login-form>
</modal>`
})
export class ParentModalComponent {
modal: {...};
onClose() {
this.modal.close();
}
}
After the child login component submits the login form, it closes the parent modal using the parent's callback function
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'login-form',
template: `<form (ngSubmit)="onSubmit()" #loginForm="ngForm">
<button type="submit">Submit</button>
</form>`
})
export class ChildLoginComponent {
@Output() onClose = new EventEmitter();
submitted = false;
onSubmit() {
this.onClose.emit();
this.submitted = true;
}
}
Use this method and pass your array in parameter
Collections.shuffle(arrayList);
This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.
You can now use arraylist which is shuffled.
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
Swift 3.0
Through a small abstraction https://github.com/daltoniam/swiftHTTP
Example
do {
let opt = try HTTP.GET("https://google.com")
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
print("opt finished: \(response.description)")
//print("data is: \(response.data)") access the response of the data with response.data
}
} catch let error {
print("got an error creating the request: \(error)")
}
Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:
insert into blob_fun values(1, hextoraw('453d7a34'));
453d7a34
is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.
Try doing this :
recipients="[email protected],[email protected],[email protected]"
And another approach, using shell here-doc :
/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from
Example Message
EOF
Be sure to separate the headers from the body with a blank line as per RFC 822.
Cleaner Solution (CSS Only)
.table-fixed tbody {
display:block;
height:85vh;
overflow:auto;
}
.table-fixed thead, .table-fixed tbody tr {
display:table;
width:100%;
}
<table class="table table-striped table-fixed">
<thead>
<tr align="center">
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
<td>Content 1</td>
<td>Content 1</td>
<td>Content 1</td>
</tr>
<tr>
<td>Longer Content 1</td>
<td>Longer Content 1</td>
<td>Longer Content 1</td>
<td>Longer Content 1</td>
</tr>
</tbody
</table
To get uppercase letters in addition to lower case letters, you could also do the following:
String alphabetWithUpper = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz".toUpperCase();
char[] letters = alphabetWithUpper.toCharArray();
Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.
I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.
EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/
In my case, there was an error, but it was not properly parsed out by VS and shown in the "Error List" window. To find it, you much view the ol "Output" from build window and parse through the messages starting from top down and resolve the actual error. M$, please fix! This is a huge waste of time of the worlds collective developers.
Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:
class MathsOperations:
@staticmethod
def testAddition (x, y):
return x + y
@staticmethod
def testMultiplication (a, b):
return a * b
Try this:
diff -rq /path/to/folder1 /path/to/folder2
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
Not sure if this fits here, but I had similar question and found following simple solution/example for me:
private EntityManager entityManager;
...
final String sql = " SELECT * FROM STORE "; // select from the table STORE
final Query sqlQuery = entityManager.createNativeQuery(sql, Store.class);
@SuppressWarnings("unchecked")
List<Store> results = (List<Store>) sqlQuery.getResultList();
In my case I had to use SQL parts defined in Strings somewhere else, so I could not just use NamedNativeQuery.
for bootstrap 3 use like
$('#myModal').on('hidden.bs.modal', function () {
// do something…
})
If gnupg2 and gpg-agent 2.x are used, be sure to set the environment variable GPG_TTY
.
export GPG_TTY=$(tty)
It's the ternary form of the if-else operator. The above statement basically reads like this:
if ($add_review) then {
return FALSE; //$add_review evaluated as True
} else {
return $arg //$add_review evaluated as False
}
See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/
Just because the bean injected into the controller is prototype-scoped doesn't mean the controller is!
As my understanding, the 'Apartment' is used to protect the COM objects from multi-threading issues.
If a COM object is not thread-safe, it should declare it as a STA object. Then only the thread who creates it can access it. The creation thread should declare itself as a STA thread. Under the hood, the thread stores the STA information in its TLS(Thread Local Storage). We call this behavior as that the thread enters a STA apartment. When other threads want to access this COM object, it should marshal the access to the creation thread. Basically, the creation thread uses messages mechanism to process the in-bound calls.
If a COM object is thread-safe, it should declare it as a MTA object. The MTA object can be accessed by multi-threads.
Use this
public static boolean isNum(String strNum) {
boolean ret = true;
try {
Double.parseDouble(strNum);
}catch (NumberFormatException e) {
ret = false;
}
return ret;
}
You don't need --header "Content-Length: $LENGTH".
curl --request POST --data-binary "@template_entry.xml" $URL
Note that GET request does not support content body widely.
Also remember that POST request have 2 different coding schema. This is first form:
$ nc -l -p 6666 & $ curl --request POST --data-binary "@README" http://localhost:6666 POST / HTTP/1.1 User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6 Host: localhost:6666 Accept: */* Content-Length: 9309 Content-Type: application/x-www-form-urlencoded Expect: 100-continue .. -*- mode: rst; coding: cp1251; fill-column: 80 -*- .. rst2html.py README README.html .. contents::
You probably request this:
-F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
other way(unicode string even):
$res = array();
$str = 'test 1234 555 2.7 string ..... 2.2 3.3';
$str = preg_replace("/[^0-9\.]/", " ", $str);
$str = trim(preg_replace('/\s+/u', ' ', $str));
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++) {
if (is_numeric($arr[$i])) {
$res[] = $arr[$i];
}
}
print_r($res); //Array ( [0] => 1234 [1] => 555 [2] => 2.7 [3] => 2.2 [4] => 3.3 )
They represent [
and ]
. The encoding is called "URL encoding".
Starting file:
line 1
line 2
line 3
line 4
Code:
with open("filename.txt", "r") as f:
lines = f.readlines()
for line in lines:
stripped = line.strip()
print(stripped)
Output:
line 1
line 2
line 3
line 4
I want to offer an alternate solution for perhaps a slightly different case, since many of my searches for answers kept leading me to this thread.
My case - I'm creating/adding pages dynamically and sliding them into a ViewPager, but when rotated (onConfigurationChange) I end up with a new page because of course OnCreate is called again. But I want to keep reference to all the pages that were created prior to the rotation.
Problem - I don't have unique identifiers for each fragment I create, so the only way to reference was to somehow store references in an Array to be restored after the rotation/configuration change.
Workaround - The key concept was to have the Activity (which displays the Fragments) also manage the array of references to existing Fragments, since this activity can utilize Bundles in onSaveInstanceState
public class MainActivity extends FragmentActivity
So within this Activity, I declare a private member to track the open pages
private List<Fragment> retainedPages = new ArrayList<Fragment>();
This is updated everytime onSaveInstanceState is called and restored in onCreate
@Override
protected void onSaveInstanceState(Bundle outState) {
retainedPages = _adapter.exportList();
outState.putSerializable("retainedPages", (Serializable) retainedPages);
super.onSaveInstanceState(outState);
}
...so once it's stored, it can be retrieved...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
retainedPages = (List<Fragment>) savedInstanceState.getSerializable("retainedPages");
}
_mViewPager = (CustomViewPager) findViewById(R.id.viewPager);
_adapter = new ViewPagerAdapter(getApplicationContext(), getSupportFragmentManager());
if (retainedPages.size() > 0) {
_adapter.importList(retainedPages);
}
_mViewPager.setAdapter(_adapter);
_mViewPager.setCurrentItem(_adapter.getCount()-1);
}
These were the necessary changes to the main activity, and so I needed the members and methods within my FragmentPagerAdapter for this to work, so within
public class ViewPagerAdapter extends FragmentPagerAdapter
an identical construct (as shown above in MainActivity )
private List<Fragment> _pages = new ArrayList<Fragment>();
and this syncing (as used above in onSaveInstanceState) is supported specifically by the methods
public List<Fragment> exportList() {
return _pages;
}
public void importList(List<Fragment> savedPages) {
_pages = savedPages;
}
And then finally, in the fragment class
public class CustomFragment extends Fragment
in order for all this to work, there were two changes, first
public class CustomFragment extends Fragment implements Serializable
and then adding this to onCreate so Fragments aren't destroyed
setRetainInstance(true);
I'm still in the process of wrapping my head around Fragments and Android life cycle, so caveat here is there may be redundancies/inefficiencies in this method. But it works for me and I hope might be helpful for others with cases similar to mine.
Update the following commands in command prompt in windows:
i) android update sdk --no-ui --all // It update your SDK packages and it takes 3 minutes. ii) android update sdk --no-ui --filter platform-tools,tools //It updates the platform tools and its packages. iii) android update sdk --no-ui --all --filter extra-android-m2repository // Those who are working with maven project update this to support with latest support design library which will include extra maven android maven Repository.
1)In the command prompt it asks you for Y/N .click on the Y then it proceeds with the installation. 2) It updates all Kernel-qemu files and qt5.dll commands. so that the Emulator works fine without any issues.
I tend to use yield-return when I calculate the next item in the list (or even the next group of items).
Using your Version 2, you must have the complete list before returning. By using yield-return, you really only need to have the next item before returning.
Among other things, this helps spread the computational cost of complex calculations over a larger time-frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.
Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.
In your particular example, you have the full list of products, so I'd use Version 2.
Yes there is a difference in the performance of both:
jQuery('#id').show()
is slower than jQuery('#id').css("display","block")
as in former case extra work is to be done for retrieving the initial state from the jquery cache as display is not a binary attribute it can be inline
,block
,none
,table
, etc.
similar is the case with hide()
method.
You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.
With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.
http://www.dba-oracle.com/t_with_clause.htm
It requires some effort though. Don't be afraid to post a concrete example.
Using simple pseudo table DUAL helps too.
Hibernate 5.2.5
Jar Files Required in the class path. This is within a required folder of Hibernate 5.2.5 Final release. It can be downloaded from http://hibernate.org/orm/downloads/
Create an xml file "persistence.xml" in
YourProject/src/META-INF/persistence.xml
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="sample">
<class>org.pramod.data.object.UserDetail</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/hibernate_project"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="root"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.archive.autodetection" value="true"/>
</properties>
</persistence-unit>
EntityManagerFactor = Persistance.createEntityManagerFactory("sample");. "sample" can be changed as per your naming convention.
Now create a Entity class. with name as per my example UserDetail, in the package org.pramod.data.object
UserDetail.java
package org.pramod.data.object;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_detail")
public class UserDetail {
@Id
@Column(name="user_id")
private int id;
@Column(name="user_name")
private String userName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "UserDetail [id=" + id + ", userName=" + userName + "]";
}
}
Now create a class with main method.
HibernateTest.java
package org.pramod.hibernate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.pramod.data.object.UserDetail;
public class HibernateTest {
private static EntityManagerFactory entityManagerFactory;
public static void main(String[] args) {
UserDetail user = new UserDetail();
user.setId(1);
user.setUserName("Pramod Sharma");
try {
entityManagerFactory = Persistence.createEntityManagerFactory("sample");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist( user );
entityManager.getTransaction().commit();
System.out.println("successfull");
entityManager.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output will be
UserDetail [id=1, userName=Pramod Sharma]
Hibernate: drop table if exists user_details
Hibernate: create table user_details (user_id integer not null, user_name varchar(255), primary key (user_id))
Hibernate: insert into user_details (user_name, user_id) values (?, ?)
successfull
I'm not sure for JPA 1.0 but you can pass a Collection
in JPA 2.0:
String qlString = "select item from Item item where item.name IN :names";
Query q = em.createQuery(qlString, Item.class);
List<String> names = Arrays.asList("foo", "bar");
q.setParameter("names", names);
List<Item> actual = q.getResultList();
assertNotNull(actual);
assertEquals(2, actual.size());
Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:
String qlString = "select item from Item item where item.name IN (:names)";
But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.
Here is what works for me on Swift 3
let _ = (dict[key].map { $0 as? String } ?? "")
Check out the grid from Infragistics jQuery controls
Here is a ASP.NET MVC sample with code:
the core functions are getBytes(String charset)
and new String(byte[] data)
. you can use these functions to do UTF-8 decoding.
UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String()
is the byte array, which calling is equal to new String(bytes, "UTF-8")
Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.
The decoding sentence should be
String decoded = new String(encoded.getBytes("ISO-8859-1"));
git fetch <gitserver> <remotetag>:<localtag>
===================================
I just did this. First I made sure I knew the tag name spelling.
git ls-remote --tags gitserver; : or origin, whatever your remote is called
This gave me a list of tags on my git server to choose from. The original poster already knew his tag's name so this step is not necessary for everyone. The output looked like this, though the real list was longer.
8acb6864d10caa9baf25cc1e4857371efb01f7cd refs/tags/v5.2.2.2
f4ba9d79e3d760f1990c2117187b5010e92e1ea2 refs/tags/v5.2.3.1
8dd05466201b51fcaf4ca85897347d82fcb29518 refs/tags/Fix_109
9b5087090d9077c10ba22d99d5ce90d8a45c50a3 refs/tags/Fix_110
I picked the tag I wanted and fetched that and nothing more as follows.
git fetch gitserver Fix_110
I then tagged this on my local machine, giving my tag the same name.
git tag Fix_110 FETCH_HEAD
I didn't want to clone the remote repository as other people have suggested doing, as the project I am working on is large and I want to develop in a nice clean environment. I feel this is closer to the original questions "I'm trying to figure out how do download A PARTICULAR TAG" than the solution which suggests cloning the whole repository. I don't see why anyone should have to have a copy of Windows NT and Windows 8.1 source code if they want to look at DOS 0.1 source code (for example).
I also didn't want to use CHECKOUT as others have suggested. I had a branch checked out and didn't want to affect that. My intention was to fetch the software I wanted so that I could cherry-pick something and add that to my development.
There is probably a way to fetch the tag itself rather than just a copy of the commit that was tagged. I had to tag the fetched commit myself. EDIT: Ah yes, I have found it now.
git fetch gitserver Fix_110:Fix_110
Where you see the colon, that is remote-name:local-name and here they are the tag names. This runs without upsetting the working tree etc. It just seems to copy stuff from the remote to the local machine so you have your own copy.
git fetch gitserver --dry-run Fix_110:Fix_110
with the --dry-run option added will let you have a look at what the command would do, if you want to verify its what you want. So I guess a simple
git fetch gitserver remotetag:localtag
is the real answer.
=
A separate note about tags ... When I start something new I usually tag the empty repository after git init, since
git rebase -i XXXXX
requires a commit, and the question arises "how do you rebase changes that include your first software change?" So when I start working I do
git init
touch .gitignore
[then add it and commit it, and finally]
git tag EMPTY
i.e. create a commit before my first real change and then later use
git rebase -i EMPTY
if I want to rebase all my work, including the first change.
Update! You can access the Android filesystem via Android Device Monitor. In Android Studio go to Tools >> Android >> Android Device Monitor.
Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.
Recently I had to do something similar and I resolved it with the code below. Hope it helps!
Sub ColorCode()
Dim i As Integer
Dim j As Integer
i = 2
j = 1
Do While ActiveSheet.Cells(i, 1) <> ""
If Cells(i, 5).Value = "RED" Then
ActiveSheet.ChartObjects("YourChartName").Chart.FullSeriesCollection(1).Points(j).MarkerForegroundColor = RGB(255, 0, 0)
Else
If Cells(i, 5).Value = "GREEN" Then
ActiveSheet.ChartObjects("YourChartName").Chart.FullSeriesCollection(1).Points(j).MarkerForegroundColor = RGB(0, 255, 0)
Else
If Cells(i, 5).Value = "GREY" Then
ActiveSheet.ChartObjects("YourChartName").Chart.FullSeriesCollection(1).Points(j).MarkerForegroundColor = RGB(192, 192, 192)
Else
If Cells(i, 5).Value = "YELLOW" Then
ActiveSheet.ChartObjects("YourChartName").Chart.FullSeriesCollection(1).Points(j).MarkerForegroundColor = RGB(255, 255, 0)
End If
End If
End If
End If
i = i + 1
j = j + 1
Loop
End Sub
Integer division occurs, then the result, which is an integer, is assigned as a float. If the result is less than 1 then it ends up as 0.
You'll want to cast the expressions to floats first before dividing, e.g.
float m = (float)(a.y - b.y) / (float)(a.x - b.x);
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
This will work
@Cacheable(value="bookCache", key="#checkwarehouse.toString().append(#isbn.toString())")
A more idiomatic approach would be to use Array.prototype.reduce
:
var arr = [_x000D_
[ 'cardType', 'iDEBIT' ],_x000D_
[ 'txnAmount', '17.64' ],_x000D_
[ 'txnId', '20181' ],_x000D_
[ 'txnType', 'Purchase' ],_x000D_
[ 'txnDate', '2015/08/13 21:50:04' ],_x000D_
[ 'respCode', '0' ],_x000D_
[ 'isoCode', '0' ],_x000D_
[ 'authCode', '' ],_x000D_
[ 'acquirerInvoice', '0' ],_x000D_
[ 'message', '' ],_x000D_
[ 'isComplete', 'true' ],_x000D_
[ 'isTimeout', 'false' ]_x000D_
];_x000D_
_x000D_
var obj = arr.reduce(function (o, currentArray) {_x000D_
var key = currentArray[0], value = currentArray[1]_x000D_
o[key] = value_x000D_
return o_x000D_
}, {})_x000D_
_x000D_
console.log(obj)_x000D_
document.write(JSON.stringify(obj).split(',').join(',<br>'))
_x000D_
This is more visually appealing, when done with ES6 (rest parameters) syntax:
let obj = arr.reduce((o, [ key, value ]) => {
o[key] = value
return o
}, {})
<form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="image" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-xs-12">Add</button>
</div>
</form>
My Action Is
[HttpPost]
public IActionResult AddNews(IFormFile image)
{
Tbl_News tbl_News = new Tbl_News();
if (image!=null)
{
//Set Key Name
string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//Get url To Save
string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);
using(var stream=new FileStream(SavePath, FileMode.Create))
{
image.CopyTo(stream);
}
}
return View();
}
A very simple solution, just pass in input: mkdir dirname
void execute_command_mkdir(char *input)
{
char rec_dir[500];
int s;
if(strcmp(input,"mkdir") == 0)
printf("mkdir: operand required");
else
{
char *split = strtok(input," \t");
while(split)
{
if(strcmp(split,"create_dir") != 0)
strcpy(rec_dir,split);
split = strtok(NULL, " \t");
}
char *split2 = strtok(rec_dir,"/");
char dir[500];
strcpy(dir, "");
while(split2)
{
strcat(dir,split2);
strcat(dir,"/");
printf("%s %s\n",split2,dir);
s = mkdir(dir,0700);
split2 = strtok(NULL,"/");
}
strcpy(output,"ok");
}
if(s < 0)
printf(output,"Error!! Cannot Create Directory!!");
}
The problem is because of post back happens on submit button click. So while posting data on submit click again write before returning View()
ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");
Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.
https://tools.percona.com/wizard
Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/
Everyone points to key_buffer_size
first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).
I strongly recommend that you not define your own scheme. This goes against the web standards for URI schemes, which attempts to rigidly control those names for good reason -- to avoid name conflicts between different entities. Once you put a link to your scheme on a web site, you have put that little name into entire the entire Internet's namespace, and should be following those standards.
If you just want to be able to have a link to your own app, I recommend you follow the approach I described here:
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
I'am trying to install SQL SERVER developer 2008 R2 alongside SQL SERVER 2005 EXPRESS,
i went to program features, clicked on unistall SQL SERVER 2005 EXPRESS, and only checked, WORKSTATION COMPONENTS, it unistalled: support files, sql mngmt studio
After that installation of sql 2008 r2 developer went ok....
Hopes this helps somebody
To get the output of ls
, use stdout=subprocess.PIPE
.
>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo
The command cdrecord --help
outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True
argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.
>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
-version print version information and exit
dev=target SCSI target to use as CD/DVD-Recorder
gracetime=# set the grace time before starting to write to #.
...
If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.
subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
As mentioned by Chris Morgan, you should be using proc.communicate()
instead of proc.read()
.
>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout:
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
-version print version information and exit
dev=target SCSI target to use as CD/DVD-Recorder
gracetime=# set the grace time before starting to write to #.
...
Use the following method.
self.imageView_VedioContainer
is the container view of your AVPlayer
.
- (void)playMedia:(UITapGestureRecognizer *)tapGesture
{
playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = [AVPlayer playerWithURL:[[NSBundle mainBundle]
URLForResource:@"VID"
withExtension:@"3gp"]];
[playerViewController.player play];
playerViewController.showsPlaybackControls =YES;
playerViewController.view.frame=self.imageView_VedioContainer.bounds;
[playerViewController.view setAutoresizingMask:UIViewAutoresizingNone];// you can comment this line
[self.imageView_VedioContainer addSubview: playerViewController.view];
}
you compiled your code using maven compile and then used maven test to run it worked fine. Now if you changed something in your code and then without compiling you are running it, you will get this error.
Solution: Again compile it and then run test. For me it worked this way.
I had the same issue and I used command line in order to import the SQL file. This method has 3 advantages:
If you want to do this just follow this 3 steps:
Navigate to this path (i use wamp):
C:\wamp\bin\mysql\mysql5.6.17\bin>
Copy your sql file inside this path (ex file.sql)
Run this command:
mysql -u username -p database_name < file.sql
Note: if you already have your msql enviroment variable path set, you don't need to move your file.sql in the bin directory and you should only navigate to the path of the file.
Setting session timeout through the deployment descriptor should work - it sets the default session timeout for the web app. Calling session.setMaxInactiveInterval() sets the timeout for the particular session it is called on, and overrides the default. Be aware of the unit difference, too - the deployment descriptor version uses minutes, and session.setMaxInactiveInterval() uses seconds.
So
<session-config>
<session-timeout>60</session-timeout>
</session-config>
sets the default session timeout to 60 minutes.
And
session.setMaxInactiveInterval(600);
sets the session timeout to 600 seconds - 10 minutes - for the specific session it's called on.
This should work in Tomcat or Glassfish or any other Java web server - it's part of the spec.
Used this approach for array of bytes:
Initially:
byte[] bytes = new byte[0];
Whenever required (Need to provide original length for extending):
Array.Resize<byte>(ref bytes, bytes.Length + requiredSize);
Reset:
Array.Resize<byte>(ref bytes, 0);
Typed List Method
Initially:
List<byte> bytes = new List<byte>();
Whenever required:
bytes.AddRange(new byte[length]);
Release/Clear:
bytes.Clear()
The [0]
needs to be inside the )
.
If you want to pass the variable to your proxy backend, you have to set it with the proxy module.
location / {
proxy_pass http://example.com;
proxy_set_header Host example.com;
proxy_set_header HTTP_Country-Code $geoip_country_code;
proxy_pass_request_headers on;
}
And now it's passed to the proxy backend.
print("single",end=" ")
print("line")
this will give output
single line
for the question asked use
i = 0
while i <10:
i += 1
print (i,end="")
Thanks to everyone above, but this is now fixed. For the benefit of others the most significant error was in aligning the three namespaces as suggested by Ian.
For completeness, here is the corrected XML and XSD
Here is the XML, with the typos corrected (sorry for any confusion caused by tardiness)
<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="urn:Test.Namespace"
xsi:schemaLocation="urn:Test.Namespace Test1.xsd">
<element1 id="001">
<element2 id="001.1">
<element3 id="001.1" />
</element2>
</element1>
</Root>
and, here is the Schema
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:Test.Namespace"
xmlns="urn:Test.Namespace"
elementFormDefault="qualified">
<xsd:element name="Root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="element1" maxOccurs="unbounded" type="element1Type"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="element1Type">
<xsd:sequence>
<xsd:element name="element2" maxOccurs="unbounded" type="element2Type"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="element2Type">
<xsd:sequence>
<xsd:element name="element3" type="element3Type"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="element3Type">
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>
Thanks again to everyone, I hope this is of use to somebody else in the future.
it could be multiple reason, in my case under Application pool->advance setting->Enable 32 bit application (should be true).It was set to false before.
LocalDate.parse(
"01-23-2017" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)
I have a java.util.Date in the format yyyy-mm-dd
As other mentioned, the Date
class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.
The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.
If you have a java.util.Date
, convert to a Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.
Define the time zone by which you want context for your Instant
.
ZoneId z = ZoneId.of( "America/Montreal" );
Apply the ZoneId
to get a ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( z );
LocalDate
If you only care about the date without a time-of-day, extract a LocalDate
.
LocalDate localDate = zdt.toLocalDate();
To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString
. The java.time classes use the standard formats by default when generating/parsing strings.
String output = localDate.toString();
2017-01-23
If you want a MM-DD-YYYY format, define a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );
Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm
(minute of hour) rather than MM
(month of year).
Use the same DateTimeFormatter
object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.
LocalDate localDate = LocalDate.parse( "01-23-2017" , f );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
DANGER - most of these answers will wipe your database and is not recommended for production use.
It's clear there are a lot of "solutions" for this problem, but all these solutions I read through are very destructive solutions and none of them work for a production database. Based on the number of solutions, it also seems that there could be several causes to this error.
My error was being caused by a missing entry in my migrations table. I'm not sure exactly how it happened but by adding it back in I no longer received the error.
As an alternative, I would suggest looking at your conda config file.
Reason
Sometimes for creating a virtual env at a specified location other than the pre-defined path at ~/anaconda3/envs
we append the conda config file using: conda config --append envs_dirs /path/to/envs
where envs_dirs
is a specified function in config file for allocating different paths where conda can find your virtual envs. Removing a recently added path in this config file may solve the problem.
Solution
$:> conda config --show envs_dirs
envs_dirs:
- /home/some_recent_path # remove this
- /home/.../anaconda3/envs
Note the value specifing a different directory other than the predefined location, and remove it using
$:> conda config --remove envs_dirs /home/some_recent_path
Now the config file envs_dirs
is set to default location of envs. Try creating a new env now.
You can try with jQuery also
$('textarea').css("resize", "none");
You are missing a closing h2 tag. It should be:
<h2><!-- Content --></h2>
If you really need to transform a date to a LocalDateTime object, you could use the LocalDate.atStartOfDay(). This will give you a LocalDateTime object at the specified date, having the hour, minute and second fields set to 0:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();
The selector would be label[for=email]
, so in CSS:
label[for=email]
{
/* ...definitions here... */
}
...or in JavaScript using the DOM:
var element = document.querySelector("label[for=email]");
...or in JavaScript using jQuery:
var element = $("label[for=email]");
It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.
(I'm assuming that the template {t _your_email}
will fill in a field with id="email"
. If not, use a class instead.)
Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:
label[for="field[]"]
{
/* ...definitions here... */
}
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
The join feature supported by Mongodb 3.2 and later versions. You can use joins by using aggregate query.
You can do it using below example :
db.users.aggregate([
// Join with user_info table
{
$lookup:{
from: "userinfo", // other table name
localField: "userId", // name of users table field
foreignField: "userId", // name of userinfo table field
as: "user_info" // alias for userinfo table
}
},
{ $unwind:"$user_info" }, // $unwind used for getting data in object or for one record only
// Join with user_role table
{
$lookup:{
from: "userrole",
localField: "userId",
foreignField: "userId",
as: "user_role"
}
},
{ $unwind:"$user_role" },
// define some conditions here
{
$match:{
$and:[{"userName" : "admin"}]
}
},
// define which fields are you want to fetch
{
$project:{
_id : 1,
email : 1,
userName : 1,
userPhone : "$user_info.phone",
role : "$user_role.role",
}
}
]);
This will give result like this:
{
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "[email protected]",
"userName" : "admin",
"userPhone" : "0000000000",
"role" : "admin"
}
Hope this will help you or someone else.
Thanks
Please see my answer here. As dreamwerx.myopenid.com points out, it is possible to do this with SimpleXML, but the DOM extension would be the better and more flexible way. Additionally there is a third way: using XMLWriter. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.
$w=new XMLWriter();
$w->openMemory();
$w->startDocument('1.0','UTF-8');
$w->startElement("root");
$w->writeAttribute("ah", "OK");
$w->text('Wow, it works!');
$w->endElement();
echo htmlentities($w->outputMemory(true));
By the way: DOM stands for Document Object Model; this is the standardized API into XML documents.
Change
CREATE DEFINER = `root`@`localhost` FUNCTION `fnc_calcWalkedDistance` (
By
FUNCTION `fnc_calcWalkedDistance` (
Use -execdir
which automatically holds the current file in {}
, for example:
find . -type f -execdir echo '{}' ';'
You can also use $PWD
instead of .
(on some systems it won't produce an extra dot in the front).
If you still got an extra dot, alternatively you can run:
find . -type f -execdir basename '{}' ';'
-execdir utility [argument ...] ;
The
-execdir
primary is identical to the-exec
primary with the exception that utility will be executed from the directory that holds the current file.
When used +
instead of ;
, then {}
is replaced with as many pathnames as possible for each invocation of utility. In other words, it'll print all filenames in one line.
A jar file is simply a file containing a collection of java files. To make a jar file executable, you need to specify where the main
Class is in the jar file. Example code would be as follows.
public class JarExample {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// your logic here
}
});
}
}
Compile your classes. To make a jar, you also need to create a Manifest File (MANIFEST.MF
). For example,
Manifest-Version: 1.0
Main-Class: JarExample
Place the compiled output class files (JarExample.class,JarExample$1.class) and the manifest file in the same folder. In the command prompt, go to the folder where your files placed, and create the jar using jar command. For example (if you name your manifest file as jexample.mf)
jar cfm jarexample.jar jexample.mf *.class
It will create executable jarexample.jar.
Another approach if you are using Directory.EnumerateFiles
and want to read files in latest modified by first.
foreach (string file in Directory.EnumerateFiles(fileDirectory, fileType).OrderByDescending(f => new FileInfo(f).LastWriteTime))
}
using System.IO;
this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))
both should be quite easy to understand and use.
string pathToFile = "";//to save the location of the selected object
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(theDialog.FileName.ToString());
pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object
}
if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
{
//method1
string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();
//method2
string text = "";
using(StreamReader sr =new StreamReader(pathToFile))
{
text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
}
}
}
To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.
to add the data to your class you can use the constructor to add the data like:
public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
{
EmployeeNum = EMPLOYEENUM;
Name = NAME;
Address = ADRESS;
Wage = WAGE;
Hours = HOURS;
}
or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).
Yes, there is a difference. continue
forces the loop to start at the next iteration while pass
means "there is no code to execute here" and will continue through the remainder or the loop body.
Run these and see the difference:
for element in some_list:
if not element:
pass
print 1 # will print after pass
for element in some_list:
if not element:
continue
print 1 # will not print after continue
They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my .phtml
files (Zend Framework) I will write something like this:
<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>
It doesn't because the href value is not sign_up
.It is #sign_up
. Try like below,
You need to add "#" to indicate the id of the href value.
$('a[href="#sign_up"]').click(function(){
alert('Sign new href executed.');
});
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
I answered a similar question here.
In the Project’s Settings, add /FORCE:MULTIPLE
to the Linker’s Command Line options.
From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."
That's what programmers call a "quick and dirty" solution, but sometimes you just want the build to be completed and get to the bottom of the problem later, so that's kind of a ad-hoc solution. To actually avoid this error, provided that you want
int WIDTH = 1024;
int HEIGHT = 800;
to be shared among several source files, just declare them only in a single .c / .cpp file, and refer to them in a header file:
extern int WIDTH;
extern int HEIGHT;
Then include the header in any other source file you wish these global variables to be available.
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.
Programming Hub randomly provided a code snippet which in fact does reduce the length of an array
for (i = position_to_remove; i < length_of_array; ++i) {
inputarray[i] = inputarray[i + 1];
}
Not sure if it's behaviour that was added only later. It does the trick though.
In ViewPager2
and ViewPager
from version androidx.fragment:fragment:1.1.0
you can just use onPause
and onResume
callbacks to determine which fragment is currently visible for the user. onResume
callback is called when fragment became visible and onPause
when it stops to be visible.
In case of ViewPager2 it is default behavior but the same behavior can be enabled for old good ViewPager
easily.
To enable this behavior in the first ViewPager you have to pass FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
parameter as second argument of FragmentPagerAdapter
constructor.
FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
Note: setUserVisibleHint()
method and FragmentPagerAdapter
constructor with one parameter are now deprecated in the new version of Fragment from android jetpack.
It's not compiling that's hurting me here, it's the typing. I could disable all the smart features and be back to notepad++ like TomTsagk suggested in a comment. For today I need more cores and RAM.
Playing devil's advocate I'd argue that typing shouldn't require a 16Gb PC octacore PC. Liked Sajan Rana's advice but things are so slow here it felt mostly a placebo.
To be fair I am using 1.4RC1, which is just short of being in the stable branch. Turning the internet off helped a little. The new feature of simultaneous Design (Preview) and Text views working with XML layouts is very helpful.
No, it is ridiculous. Never leave the stable channel.
Maybe it is just my Java and C background showing, but I prefer CamelCase (CapCase) over punctuation in the name. My workgroup uses such names, probably to match the names of the app or service the repository contains.
I know this seems to be already answered, but I ran into a specific case, and I feel most answers miss the point.
The overflow:hidden
answers cover 90% of the cases. That's more or less the "sticky nav" scenario.
But the sticky behavior is best used within the height of a container. Think of a newsletter form in the right column of your website that scrolls down with the page. If your sticky element is the only child of the container, the container is the exact same size, and there's no room to scroll.
Your container needs to be the height you expect your element to scroll within. Which in my "right column" scenario is the height of the left column.
The best way to achieve this is to use display:table-cell
on the columns. If you can't, and are stuck with float:right
and such like I was, you'll have to either guess the left column height of compute it with Javascript.
Since the add-ons don't work anymore, the most helpful set of tools I've found is using Visual Studio/IE because you can set breakpoints in your JS and inspect your data that way. Of course Chrome and Firefox have much better dev tools in general. Also, good ol' console.log() has been super helpful!
Try like this.
You must give a function as value to onClick()
You button:
<button type="button" onClick={ refreshPage }> <span>Reload</span> </button>
refreshPage function:
function refreshPage(){
window.location.reload();
}
You can try DBVisualizer some features are not free, but you can get an evaluate license...
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
Whitequark responded nicely. But with the current versions of Node.js and Express.js it requires one more line. Make sure to add the 'require http' (second line). I've posted a fuller example here that shows how this call can work. Once running, type http://localhost:8080/?name=abel&fruit=apple
in your browser, and you will get a cool response based on the code.
var express = require('express');
var http = require('http');
var app = express();
app.configure(function(){
app.set('port', 8080);
});
app.get('/', function(req, res){
res.writeHead(200, {'content-type': 'text/plain'});
res.write('name: ' + req.query.name + '\n');
res.write('fruit: ' + req.query.fruit + '\n');
res.write('query: ' + req.query + '\n');
queryStuff = JSON.stringify(req.query);
res.end('That\'s all folks' + '\n' + queryStuff);
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
})
This code uses cv2.putText to overlay text on an image. You need NumPy and OpenCV installed.
import numpy as np
import cv2
# Create a black image
img = np.zeros((512,512,3), np.uint8)
# Write some Text
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10,500)
fontScale = 1
fontColor = (255,255,255)
lineType = 2
cv2.putText(img,'Hello World!',
bottomLeftCornerOfText,
font,
fontScale,
fontColor,
lineType)
#Display the image
cv2.imshow("img",img)
#Save image
cv2.imwrite("out.jpg", img)
cv2.waitKey(0)
This code is working fine for me.
Encode data with btoa
let data_str = btoa(JSON.stringify(jsonData));
$("#target_id").attr('data-json', data_str);
And then decode it with atob
let tourData = $(this).data("json");
tourData = atob(tourData);
You can use the stringr
library:
library('stringr')
a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A_C
# 6 0.55313288 f A_C
# 7 0.31264280 g A_C
# 8 0.33759921 h A_C
# 9 0.72322599 i A_C
# 10 0.25223075 j A_C
data$c <- str_replace_all(data$c, '_', '-')
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A-C
# 6 0.55313288 f A-C
# 7 0.31264280 g A-C
# 8 0.33759921 h A-C
# 9 0.72322599 i A-C
# 10 0.25223075 j A-C
Note that this does change factored variables into character.
Use the target
attribute on your anchor
tag with the _blank
value.
Example:
<a href="http://google.com" target="_blank">Click Me!</a>
numpy.char.mod
may also be useful, depending on the details of your application e.g.:numpy.char.mod('Value=%4.2f', numpy.arange(5, 10, 0.1))
will return a string array with elements "Value=5.00", "Value=5.10" etc. (as a somewhat contrived example).
I know I am very late.. (almost nine years), but if someone wants small explanation then you can go for this:
In simple words, you use Interface when you know what an Object can do or what function we are going to implement on an object.. Example Insert,Update, and Delete.
interface ICRUD{
void InsertData(); // will insert data
void UpdateData(); // will update data
void DeleteData(); // will delete data
}
Important Note: Interfaces are ALWAYS public.
Hope this helps.
Since String
IS-A CharSequence
, you can pass a String
wherever you need a CharSequence
, or assign a String
to a CharSequence
:
CharSequence cs = "string";
String s = cs.toString();
foo(s); // prints "string"
public void foo(CharSequence cs) {
System.out.println(cs);
}
If you want to convert a CharSequence
to a String
, just use the toString
method that must be implemented by every concrete implementation of CharSequence
.
Hope it helps.
I will add that if your need is just to override a property used by your bean, the id approach works too like skaffman explained :
In your first called XML configuration file :
<bean id="myBeanId" class="com.blabla">
<property name="myList" ref="myList"/>
</bean>
<util:list id="myList">
<value>3</value>
<value>4</value>
</util:list>
In your second called XML configuration file :
<util:list id="myList">
<value>6</value>
</util:list>
Then your bean "myBeanId" will be instantiated with a "myList" property of one element which is 6.
I am also phase these error and i am little bit change in modelClass which are implemented Serializable interface like:
At that Model class also implement Parcelable interface with writeToParcel() override method
Then just got error to "create creator" so CREATOR is write and also create with modelclass contructor with arguments & without arguments..
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(name);
}
protected ArtistTrackClass(Parcel in) {
id = in.readString();
name = in.readString();
}
public ArtistTrackClass() {
}
public static final Creator<ArtistTrackClass> CREATOR = new Creator<ArtistTrackClass>() {
@Override
public ArtistTrackClass createFromParcel(Parcel in) {
return new ArtistTrackClass(in);
}
@Override
public ArtistTrackClass[] newArray(int size) {
return new ArtistTrackClass[size];
}
};
Here,
ArtistTrackClass -> ModelClass
Constructor with Parcel arguments "read our attributes" and writeToParcel() is "write our attributes"
Even if you are using IIS or apache, in my guess you are using static html page as a landing page, and by default the web server doesn't allow POST or GET verb on .html page, facebook calls your page via POST/GET verb
the solution would be to rename the page into .php or .aspx and you should be good to go :)
For Me adding few below line in WebApi.config works as after updating the new nuget package did not works out
var setting = config.Formatters.JsonFormatter.SerializerSettings;
setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
setting.Formatting = Formatting.Indented;
Don't forget to add namespace:
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
Use parentheses:
data(2)
But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector
(immutable) or ArrayBuffer
(mutable) or possibly Array
(which is just a Java array, except again you index into it with (i)
instead of [i]
).
You have checked that R is actually able to find the file, e.g. file.exists("C:/AB_DNA_Tag_Numbers.xlsx") ? – Ben Bolker Aug 14 '11 at 23:05
Above comment should've solved your problem:
require("xlsx")
read.xlsx("filepath/filename.xlsx",1)
should work fine after that.
I was able to resolve this very easily my simply enqueuing jQuery
wp_enqueue_script("jquery");
This is not the code, but the algorithm for very fast searching.
If your list and the value you are looking for are all numbers, this is pretty straightforward. If strings: look at the bottom:
If you also need the original position of your number, look for it in the second, index column.
If your list is not made of numbers, the method still works and will be fastest, but you may need to define a function which can compare/order strings.
Of course, this needs the investment of the sorted() method, but if you keep reusing the same list for checking, it may be worth it.
This can be done very straightforwardly.
Define your struct explicitly with [StructLayout(LayoutKind.Explicit)]
int size = list.GetLength(0);
IntPtr addr = Marshal.AllocHGlobal(size * sizeof(DataStruct));
DataStruct *ptrBuffer = (DataStruct*)addr;
foreach (DataStruct ds in list)
{
*ptrBuffer = ds;
ptrBuffer += 1;
}
This code can only be written in an unsafe context. You have to free addr
when you're done with it.
Marshal.FreeHGlobal(addr);
I prefer to limit the number of retries, so that if there's a problem with that specific item you will eventually continue onto the next one, thus:
for i in range(100):
for attempt in range(10):
try:
# do thing
except:
# perhaps reconnect, etc.
else:
break
else:
# we failed all the attempts - deal with the consequences.
without linq,
use Sort()
and then Reverse()
it.
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
I don't think zip
returns a list. zip
returns a generator. You have got to do list(zip(a, b))
to get a list of tuples.
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)
**For Oreo & PIE ** I found below way through this
private WifiManager.LocalOnlyHotspotReservation mReservation;
private boolean isHotspotEnabled = false;
private final int REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS = 101;
private boolean isLocationPermissionEnable() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
return false;
}
return true;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOnHotspot() {
if (!isLocationPermissionEnable()) {
return;
}
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (manager != null) {
// Don't start when it started (existed)
manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
//Log.d(TAG, "Wifi Hotspot is on now");
mReservation = reservation;
isHotspotEnabled = true;
}
@Override
public void onStopped() {
super.onStopped();
//Log.d(TAG, "onStopped: ");
isHotspotEnabled = false;
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
//Log.d(TAG, "onFailed: ");
isHotspotEnabled = false;
}
}, new Handler());
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOffHotspot() {
if (!isLocationPermissionEnable()) {
return;
}
if (mReservation != null) {
mReservation.close();
isHotspotEnabled = false;
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void toggleHotspot() {
if (!isHotspotEnabled) {
turnOnHotspot();
} else {
turnOffHotspot();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void enableLocationSettings() {
LocationRequest mLocationRequest = new LocationRequest();
/*mLocationRequest.setInterval(10);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest)
.setAlwaysShow(false); // Show dialog
Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(task1 -> {
try {
LocationSettingsResponse response = task1.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
toggleHotspot();
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(HotspotActivity.this, REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
toggleHotspot();
Toast.makeText(HotspotActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(HotspotActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
UseAge
btnHotspot.setOnClickListenr(view -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Step 1: Enable the location settings use Google Location Service
// Step 2: https://stackoverflow.com/questions/29801368/how-to-show-enable-location-dialog-like-google-maps/50796199#50796199
// Step 3: If OK then check the location permission and enable hotspot
// Step 4: https://stackoverflow.com/questions/46843271/how-to-turn-off-wifi-hotspot-programmatically-in-android-8-0-oreo-setwifiapen
enableLocationSettings();
return;
}
}
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
implementation 'com.google.android.gms:play-services-location:15.0.1'
You can also install gems in your local environment (without sudo
) with
gem install --user-install <gemname>
I recommend that so you don't mess with your system-level configuration even if it's a single-user computer.
You can check where the gems go by looking at gempaths with gem environment
. In my case it's "~/.gem/ruby/1.8".
If you need some binaries from local installs added to your path, you can add something to your bashrc like:
if which ruby >/dev/null && which gem >/dev/null; then
PATH="$(ruby -r rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi
Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?
var ele = /*Your Form Element*/;
if(ele.addEventListener){
ele.addEventListener("submit", callback, false); //Modern browsers
}else if(ele.attachEvent){
ele.attachEvent('onsubmit', callback); //Old IE
}
callback
is a function that you want to call when the form is being submitted.
About EventTarget.addEventListener
, check out this documentation on MDN.
To cancel the native submit
event (prevent the form from being submitted), use .preventDefault()
in your callback function,
document.querySelector("#myForm").addEventListener("submit", function(e){
if(!isValid){
e.preventDefault(); //stop form from submitting
}
});
submit
event with librariesIf for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:
jQuery
$(ele).submit(callback);
Where ele
is the form element reference, and callback
being the callback function reference. Reference
<iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
_x000D_
AngularJS (1.x)
<form ng-submit="callback()">
$scope.callback = function(){ /*...*/ };
Very straightforward, where $scope
is the scope provided by the framework inside your controller. Reference
React
<form onSubmit={this.handleSubmit}>
class YourComponent extends Component {
// stuff
handleSubmit(event) {
// do whatever you need here
// if you need to stop the submit event and
// perform/dispatch your own actions
event.preventDefault();
}
// more stuff
}
Simply pass in a handler to the onSubmit
prop. Reference
Other frameworks/libraries
Refer to the documentation of your framework.
You can always do your validation in JavaScript, but with HTML5 we also have native validation.
<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">
You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.
If you want to use isolated scopes you can pass a control object using bi-directional binding =
of a variable from the controller scope. You can also control also several instances of the same directive on a page with the same control object.
angular.module('directiveControlDemo', [])_x000D_
_x000D_
.controller('MainCtrl', function($scope) {_x000D_
$scope.focusinControl = {};_x000D_
})_x000D_
_x000D_
.directive('focusin', function factory() {_x000D_
return {_x000D_
restrict: 'E',_x000D_
replace: true,_x000D_
template: '<div>A:{{internalControl}}</div>',_x000D_
scope: {_x000D_
control: '='_x000D_
},_x000D_
link: function(scope, element, attrs) {_x000D_
scope.internalControl = scope.control || {};_x000D_
scope.internalControl.takenTablets = 0;_x000D_
scope.internalControl.takeTablet = function() {_x000D_
scope.internalControl.takenTablets += 1;_x000D_
}_x000D_
}_x000D_
};_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="directiveControlDemo">_x000D_
<div ng-controller="MainCtrl">_x000D_
<button ng-click="focusinControl.takeTablet()">Call directive function</button>_x000D_
<p>_x000D_
<b>In controller scope:</b>_x000D_
{{focusinControl}}_x000D_
</p>_x000D_
<p>_x000D_
<b>In directive scope:</b>_x000D_
<focusin control="focusinControl"></focusin>_x000D_
</p>_x000D_
<p>_x000D_
<b>Without control object:</b>_x000D_
<focusin></focusin>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
This works
$(document).ready(function() {
for (var row = 0; row < 3; row++) {
for (var col = 0; col < 3; col++) {
$("#tbl").children().children()[row].children[col].innerHTML = "H!";
}
}
});
Use This..... You will love it
<TextView
android:layout_width="fill_parent"
android:layout_height="1px"
android:text=" "
android:background="#anycolor"
android:id="@+id/textView"/>
The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName
from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)
class Foo:
def __init__(self):
self.__privateField = 4;
print self.__privateField # yields 4 no problem
foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'
It will be accessible through _Foo__privateField
instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.
IF OBJECT_ID('tempdb..#TAB') IS NOT NULL
BEGIN
DROP TABLE #TAB
END
CREATE TABLE #TAB(CH1 INT,CH2 INT,CH3 INT)
DECLARE @CH2 INT = NULL , @CH3 INT=NULL,@SPID INT=NULL,@SQL NVARCHAR(4000)='', @ParmDefinition NVARCHAR(50)= '',
@RET_MESSAGE AS VARCHAR(8000)='',@RET_ERROR INT=0
SET @ParmDefinition='@SPID INT,@CH2 INT OUTPUT,@CH3 INT OUTPUT'
SET @SQL='UPDATE T
SET CH1=@SPID,@CH2= T.CH2,@CH3= T.CH3
FROM #TAB T WITH(ROWLOCK)
INNER JOIN (
SELECT TOP(1) CH1,CH2,CH3
FROM
#TAB WITH(NOLOCK)
WHERE CH1 IS NULL
ORDER BY CH2 DESC) V ON T.CH2= V.CH2 AND T.CH3= V.CH3'
INSERT INTO #TAB
(CH2 ,CH3 )
SELECT 1,2 UNION ALL
SELECT 2,3 UNION ALL
SELECT 3,4
BEGIN TRY
WHILE EXISTS(SELECT TOP 1 1 FROM #TAB WHERE CH1 IS NULL)
BEGIN
EXECUTE @RET_ERROR = sp_executesql @SQL, @ParmDefinition,@SPID =@@SPID, @CH2=@CH2 OUTPUT,@CH3=@CH3 OUTPUT;
SELECT * FROM #TAB
SELECT @CH2,@CH3
END
END TRY
BEGIN CATCH
SET @RET_ERROR=ERROR_NUMBER()
SET @RET_MESSAGE = '@ERROR_NUMBER : ' + CAST(ERROR_NUMBER() AS VARCHAR(255)) + '@ERROR_SEVERITY :' + CAST( ERROR_SEVERITY() AS VARCHAR(255))
+ '@ERROR_STATE :' + CAST(ERROR_STATE() AS VARCHAR(255)) + '@ERROR_LINE :' + CAST( ERROR_LINE() AS VARCHAR(255))
+ '@ERROR_MESSAGE :' + ERROR_MESSAGE() ;
SELECT @RET_ERROR,@RET_MESSAGE;
END CATCH
Use this query this will give your output:
select
t.name
,( select
count (*) as num_value
from Table
where num =t.num) cnt
from Table t;
You can try installing one of the following localhost softwares:
There are many more such softwares but the best among them are the ones mentioned above. they also allow domain names (for example: example.com
)
I had same issue for which I came here. With some trials, I figured out for copying multiple pages of chrome data as in the question I zoomed out till I got all the data in one page, that is, without scroll, with very small font size. Now copy and paste that in excel which copies all the records and in normal font. This is good for few pages of data I think.
The Interface of Postman is changing acccording to the updates.
So You can get full information about postman can get Here.
string filePath = System.IO.Path.GetFullPath("settings.app.config");
var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
try
{
// Open App.Config of executable
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
// Add an Application Setting if not exist
config.AppSettings.Settings.Add("key1", "value1");
config.AppSettings.Settings.Add("key2", "value2");
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException ex)
{
if (ex.BareMessage == "Root element is missing.")
{
File.Delete(filePath);
return;
}
MessageBox.Show(ex.Message);
}
uniq
should do fine if you're file is/can be sorted, if you can't sort the file for some reason you can use awk
:
awk '{a[$0]++}END{for(i in a)if(a[i]<2)print i}'
By default, the datetime
object is naive
in Python, so you need to make both of them either naive or aware datetime
objects. This can be done using:
import datetime
import pytz
utc=pytz.UTC
challenge.datetime_start = utc.localize(challenge.datetime_start)
challenge.datetime_end = utc.localize(challenge.datetime_end)
# now both the datetime objects are aware, and you can compare them
Note: This would raise a ValueError
if tzinfo
is already set. If you are not sure about that, just use
start_time = challenge.datetime_start.replace(tzinfo=utc)
end_time = challenge.datetime_end.replace(tzinfo=utc)
BTW, you could format a UNIX timestamp in datetime.datetime object with timezone info as following
d = datetime.datetime.utcfromtimestamp(int(unix_timestamp))
d_with_tz = datetime.datetime(
year=d.year,
month=d.month,
day=d.day,
hour=d.hour,
minute=d.minute,
second=d.second,
tzinfo=pytz.UTC)
here's a native javascript inline code to change image onmouseover & onmouseout:
<a href="#" id="name">
<img title="Hello" src="/ico/view.png" onmouseover="this.src='/ico/view.hover.png'" onmouseout="this.src='/ico/view.png'" />
</a>
I tried most of these, but they give false positives, all for the same reason.. It is not enough to test the directory for an available permission, you have to check that the logged in user is a member of a group that has that permission. To do this you get the users identity, and check if it is a member of a group that contains the FileSystemAccessRule IdentityReference. I have tested this, works flawlessly..
/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full path to directory </param>
/// <param name="AccessRight">File System right tested</param>
/// <returns>State [bool]</returns>
public static bool DirectoryHasPermission(string DirectoryPath, FileSystemRights AccessRight)
{
if (string.IsNullOrEmpty(DirectoryPath)) return false;
try
{
AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
foreach (FileSystemAccessRule rule in rules)
{
if (identity.Groups.Contains(rule.IdentityReference))
{
if ((AccessRight & rule.FileSystemRights) == AccessRight)
{
if (rule.AccessControlType == AccessControlType.Allow)
return true;
}
}
}
}
catch { }
return false;
}
You need
/^[a-zA-Z]+$/
Currently, you are matching a single character at the start of the input. If your goal is to match letter characters (one or more) from start to finish, then you need to repeat the a-z character match (using +
) and specify that you want to match all the way to the end (via $
)
To replace all spaces
:
UPDATE `table` SET `col_name` = REPLACE(`col_name`, ' ', '')
To remove all tabs
characters :
UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\t', '' )
To remove all new line
characters :
UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\n', '')
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
To remove first and last space(s)
of column :
UPDATE `table` SET `col_name` = TRIM(`col_name`)
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim
I used the concept from the answer posted by @marcg and it works great with JPA 2.1. His code wasn't quite right, so I'm posted my working implementation. This will convert Boolean
entity fields to a Y/N character column in the database.
From my entity class:
@Convert(converter=BooleanToYNStringConverter.class)
@Column(name="LOADED", length=1)
private Boolean isLoadedSuccessfully;
My converter class:
/**
* Converts a Boolean entity attribute to a single-character
* Y/N string that will be stored in the database, and vice-versa
*
* @author jtough
*/
public class BooleanToYNStringConverter
implements AttributeConverter<Boolean, String> {
/**
* This implementation will return "Y" if the parameter is Boolean.TRUE,
* otherwise it will return "N" when the parameter is Boolean.FALSE.
* A null input value will yield a null return value.
* @param b Boolean
*/
@Override
public String convertToDatabaseColumn(Boolean b) {
if (b == null) {
return null;
}
if (b.booleanValue()) {
return "Y";
}
return "N";
}
/**
* This implementation will return Boolean.TRUE if the string
* is "Y" or "y", otherwise it will ignore the value and return
* Boolean.FALSE (it does not actually look for "N") for any
* other non-null string. A null input value will yield a null
* return value.
* @param s String
*/
@Override
public Boolean convertToEntityAttribute(String s) {
if (s == null) {
return null;
}
if (s.equals("Y") || s.equals("y")) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}
This variant is also fun if you love emoticons and are just sick and tired of Y/N or T/F in your database. In this case, your database column must be two characters instead of one. Probably not a big deal.
/**
* Converts a Boolean entity attribute to a happy face or sad face
* that will be stored in the database, and vice-versa
*
* @author jtough
*/
public class BooleanToHappySadConverter
implements AttributeConverter<Boolean, String> {
public static final String HAPPY = ":)";
public static final String SAD = ":(";
/**
* This implementation will return ":)" if the parameter is Boolean.TRUE,
* otherwise it will return ":(" when the parameter is Boolean.FALSE.
* A null input value will yield a null return value.
* @param b Boolean
* @return String or null
*/
@Override
public String convertToDatabaseColumn(Boolean b) {
if (b == null) {
return null;
}
if (b) {
return HAPPY;
}
return SAD;
}
/**
* This implementation will return Boolean.TRUE if the string
* is ":)", otherwise it will ignore the value and return
* Boolean.FALSE (it does not actually look for ":(") for any
* other non-null string. A null input value will yield a null
* return value.
* @param s String
* @return Boolean or null
*/
@Override
public Boolean convertToEntityAttribute(String s) {
if (s == null) {
return null;
}
if (HAPPY.equals(s)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}
If anyone is interested in getting the localized string from the property with DisplayAttribute and ResourceType like this:
[Display(Name = "Year", ResourceType = typeof(ArrivalsResource))]
public int Year { get; set; }
Use the following after displayAttribute != null
(as shown above by @alex' answer):
ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);
var entry = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
.OfType<DictionaryEntry>()
.FirstOrDefault(p => p.Key.ToString() == displayAttribute.Name);
return entry.Value.ToString();
Since your "async property" is in a viewmodel, you could use AsyncMVVM:
class MyViewModel : AsyncBindableBase
{
public string Title
{
get
{
return Property.Get(GetTitleAsync);
}
}
private async Task<string> GetTitleAsync()
{
//...
}
}
It will take care of the synchronization context and property change notification for you.
From here what I understand DataFrames are:
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
And Series are:
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).
Series have a name
attribute which can be accessed like so:
In [27]: s = pd.Series(np.random.randn(5), name='something')
In [28]: s
Out[28]:
0 0.541
1 -1.175
2 0.129
3 0.043
4 -0.429
Name: something, dtype: float64
In [29]: s.name
Out[29]: 'something'
EDIT: Based on OP's comments, I think OP was looking for something like:
>>> df = pd.DataFrame(...)
>>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
>>> print(df.name)
'df'
Please note, that this only applies for Ubuntu 14.04 LTS and newer releases.
In my Ubuntu 14.04 LTS, the document root was set to /var/www/html
. It was configured in the following file:
/etc/apache2/sites-available/000-default.conf
So just do a
sudo nano /etc/apache2/sites-available/000-default.conf
and change the following line to what you want:
DocumentRoot /var/www/html
Also do a
sudo nano /etc/apache2/apache2.conf
and find this
<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
and change /var/www/html
to your preferred directory
and save it.
After you saved your changes, just restart the apache2 webserver and you'll be done :)
sudo service apache2 restart
sudo nano
by a gksu gedit
.
You can append a queryString to your src and change it only when you will release an updated version:
<script src="test.js?v=1"></script>
In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)
Best source of information for all of your DOM woes
http://www.w3.org/TR/dom/#nodes
"Objects implementing the Document, DocumentFragment, DocumentType, Element, Text, ProcessingInstruction, or Comment interface (simply called nodes) participate in a tree."
http://www.w3.org/TR/dom/#element
"Element nodes are simply known as elements."
git checkout {branch-name} -- {file-name}
This will use the file from the branch of choice.
I like this because posh-git
autocomplete works great with this. It also removes any ambiguity as to which branch is remote and which is local.
And --theirs
didn't work for me anyways.
If you have php installed on your local machine try:
$ php -a
Interactive shell
php > phpinfo();
A good place to start learning how to manipulate pages s the Mozilla Developer Network, they've got a great tutorial about the DOM.
One way you could do it is with document.write
, which writes html at the end of the currently loaded part of the document - in this case, after the script tag.
<script>
var name = prompt("What's your name?");
document.write("<p>" + name.length + "</p>");
</script>
But it's not a very clean way of doing it. Keep document.write
for testing purpose because in most cases you can't predict where it will append the content.
EDIT: Here, the "clever" way would be to do something like this:
<script type="text/javascript">
window.addEventListener("load", function(e) {
var name = prompt("What's your name?") || "";
var text = document.createTextNode(name.length);
document.getElementById("nameLength").appendChild(text);
});
</script>
<p id="nameLength"></p>
But people are generally lazy and you'll often see .innerHTML = "something"
instead of a text node.
The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.
On other servers, where the same services are consumed, the certificates were configured as follows:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"
As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"
Once that change was made, all was well. Thanks to everyone who offered assistance.
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
nib is fine. If in doubt, refer to the Python style guide.
From PEP 8:
Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.
When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).