While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt
and python-pip
.
Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
php5-mcrypt \
python-pip
However, according to this answer you should think about installing the python3-pip
package instead of the python-pip
package when using Python 3.x.
Furthermore, to make the php5-mcrypt
package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository
command missing in the Ubuntu Docker image so I installed the package software-properties-common
at first to make the command available.
Splitting up the statements and putting apt-get update
and apt-get install
into one RUN
command is also recommended here.
Oh and by the way, you actually don't need the -y
flag at apt-get update
because there is nothing that has to be confirmed automatically.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
apache2 \
curl \
git \
libapache2-mod-php5 \
php5 \
php5-mcrypt \
php5-mysql \
python3.4 \
python3-pip
Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.
In my situation (Azure Time Series Insights wss://)
Using the ReconnectingWebsocket wrapper and was able to achieve adding headers with a simple solution:
socket.onopen = function(e) {
socket.send(payload);
};
Where payload in this case is:
{
"headers": {
"Authorization": "Bearer TOKEN",
"x-ms-client-request-id": "CLIENT_ID"
},
"content": {
"searchSpan": {
"from": "UTCDATETIME",
"to": "UTCDATETIME"
},
"top": {
"sort": [
{
"input": {"builtInProperty": "$ts"},
"order": "Asc"
}],
"count": 1000
}}}
just past this on head of your php page. before any code on this should be the top code.
<?php
header("Content-Type: application/vnd.ms-word");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=Hawala.doc");
?>
this will convert all html to MSWORD, now you can customize it according to your client requirement.
If you have access to the Java 8 Comparable API, Comparable.comparingToInt()
may be of use. (See Java 8 Comparable Documentation).
For example, a Comparator<Dog>
to sort Dog
instances descending by age could be created with the following:
Comparable.comparingToInt(Dog::getDogAge).reversed();
The function take a lambda mapping T
to Integer
, and creates an ascending comparator. The chained function .reversed()
turns the ascending comparator into a descending comparator.
Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.
Answer for Angular 2+
Remove component from imports and declaration array
of app.modules.ts.
Second check its reference is added in other module, if yes then remove it and
finally delete that component Manually
from app and you are done.
Or you can do it in reverse order also.
In windows 8 I found its path as below:
C:\Program Files (x86)\Git\bin\git.exe
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
To provide another much simpler solution:-
"Add as link"
Thats it.
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
cond? statementA: statementB
Equals to:
if (cond)
statementA
else
statementB
For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.
You can use $(function(){ // code });
which is executed when the document is ready to execute the code inside that block.
$(function(){
$('#clicker').click(function(){
alert('hey');
$('.hide_div').hide();
});
});
In version 0.18.1
is added dt.weekday_name
:
print df
my_dates myvals
0 2015-01-01 1
1 2015-01-02 2
2 2015-01-03 3
print df.dtypes
my_dates datetime64[ns]
myvals int64
dtype: object
df['day_of_week'] = df['my_dates'].dt.weekday_name
print df
my_dates myvals day_of_week
0 2015-01-01 1 Thursday
1 2015-01-02 2 Friday
2 2015-01-03 3 Saturday
Another solution with assign
:
print df.assign(day_of_week = df['my_dates'].dt.weekday_name)
my_dates myvals day_of_week
0 2015-01-01 1 Thursday
1 2015-01-02 2 Friday
2 2015-01-03 3 Saturday
I have created a small demo to show how resize properties work. I hope it will help you and others as well.
.resizeable {_x000D_
resize: both;_x000D_
}_x000D_
_x000D_
.noResizeable {_x000D_
resize: none;_x000D_
}_x000D_
_x000D_
.resizeable_V {_x000D_
resize: vertical;_x000D_
}_x000D_
_x000D_
.resizeable_H {_x000D_
resize: horizontal;_x000D_
}
_x000D_
<textarea class="resizeable" rows="5" cols="20" name="resizeable" title="This is Resizable.">_x000D_
This is Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="noResizeable" rows="5" title="This will not Resizable. " cols="20" name="resizeable">_x000D_
This will not Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="resizeable_V" title="This is Vertically Resizable." rows="5" cols="20" name="resizeable">_x000D_
This is Vertically Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="resizeable_H" title="This is Horizontally Resizable." rows="5" cols="20" name="resizeable">_x000D_
This is Horizontally Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>
_x000D_
Might help some else - I came here because I missed putting two // after http:. This is what I had:
http:/abc.my.domain.com:55555/update
AFAIK, I don't think this is possible with a direct method naming query. You can however use the built in sorting mechanism, using the Sort
class. The repository has a findAll(Sort)
method that you can pass an instance of Sort
to. For example:
import org.springframework.data.domain.Sort;
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(sortByIdAsc());
}
private Sort sortByIdAsc() {
return new Sort(Sort.Direction.ASC, "id");
}
}
ROWID is a hidden column on Oracle tables, so, for SQL Server, build your own. Add a column called ROWID with a default value of NEWID()
.
How to do that: Add column, with default value, to existing table in SQL Server
Django querysets are lazy. That means a query will hit the database only when you specifically ask for the result.
So until you print or actually use the result of a query you can filter further with no database access.
As you can see below your code only executes one sql query to fetch only the last 10 items.
In [19]: import logging
In [20]: l = logging.getLogger('django.db.backends')
In [21]: l.setLevel(logging.DEBUG)
In [22]: l.addHandler(logging.StreamHandler())
In [23]: User.objects.all().order_by('-id')[:10]
(0.000) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" ORDER BY "auth_user"."id" DESC LIMIT 10; args=()
Out[23]: [<User: hamdi>]
2018 now. You don't need any extensions for auto-imports in Javascript (as long as you have checkjs: true
in your jsconfig.json
file) and TypeScript.
There are two types of auto imports: the add missing import quick fix which shows up as a lightbulb on errors:
And the auto import suggestions. These show up a suggestion items as you type. Accepting an auto import suggestion automatically adds the import at the top of the file
Both should work out of the box with JavaScript and TypeScript. If auto imports still do not work for you, please open an issue
public void captureScreenShot(String obj) throws IOException {
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("Screenshots\\" + obj + "" + GetTimeStampValue() + ".png"));
}
public String GetTimeStampValue()throws IOException{
Calendar cal = Calendar.getInstance();
Date time = cal.getTime();
String timestamp = time.toString();
System.out.println(timestamp);
String systime = timestamp.replace(":", "-");
System.out.println(systime);
return systime;
}
Using these two methods you can take a screen shot with the date and time as well.
JavaScript does not have a built-in map/hashmap. It should be called an associative array.
hash["X"]
is equal to hash.X
, but it allows "X" as a string variable.
In other words, hash[x]
is functionally equal to eval("hash."+x.toString())
.
It is more similar to object.properties rather than key-value mapping. If you are looking for a better key/value mapping in JavaScript, please use the Map object.
If you want to search recursively, you can use this beautiful piece of code:
public static FileInfo GetNewestFile(DirectoryInfo directory) {
return directory.GetFiles()
.Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
.OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
.FirstOrDefault();
}
Just call it the following way:
FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"C:\directory\"));
and that's it. Returns a FileInfo
instance or null
if the directory is empty.
To solve a similar problem, I'm using groupby
:
print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")
Whether that's appropriate will depend on what you want to do with the result, though (in my case, I just wanted the equivalent of COUNT DISTINCT
as shown).
if you want your check box to keep its height and width but only be invisible:
.hiddenCheckBox{
visibility: hidden;
}
if you want your check box to be invisible without any with and height:
.hiddenCheckBox{
display: none;
}
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
You are confusing a Mock
with a Spy
.
In a mock all methods are stubbed and return "smart return types". This means that calling any method on a mocked class will do nothing unless you specify behaviour.
In a spy the original functionality of the class is still there but you can validate method invocations in a spy and also override method behaviour.
What you want is
MyProcessingAgent mockMyAgent = Mockito.spy(MyProcessingAgent.class);
A quick example:
static class TestClass {
public String getThing() {
return "Thing";
}
public String getOtherThing() {
return getThing();
}
}
public static void main(String[] args) {
final TestClass testClass = Mockito.spy(new TestClass());
Mockito.when(testClass.getThing()).thenReturn("Some Other thing");
System.out.println(testClass.getOtherThing());
}
Output is:
Some Other thing
NB: You should really try to mock the dependencies for the class being tested not the class itself.
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.
If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.
Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.
First I declared all my variables as Public
Then I defined/set each variable
Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges
Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range
With Sheet8
c = pvt.DataBodyRange.Columns.Count + 1
d = 3
r = .Cells(.Rows.Count, 1).End(xlUp).Row
Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
FormulaRange3.NumberFormat = "0"
Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
FormulaRange4.NumberFormat = "0"
Set SelectRanges = Union(FormulaRange3, FormulaRange4)
I had nearly the same Problem but the return Value of my Controller was blocked with other Values.
Found a simple Solution but it seems a bit rough.
Try to type Viewbag.
in your Controller and now you give it a name like Viewbag.Checkbool
Now switch to the View and try this @Viewbag.Checkbool
with this you will get the value out of the Controller.
My Controller Parameters look like this:
public ActionResult Anzeigen(int productid = 90, bool islive = true)
and my Checkbox will update like this:
<input id="isLive" type="checkbox" checked="@ViewBag.Value" ONCLICK="window.location.href = '/MixCategory/Anzeigen?isLive=' + isLive.checked.toString()" />
Is
is not the same as =
-- Is
compares the references, whilst =
will compare the values.
If you're using v2 of the .Net Framework (or later), there is the IsNot
operator which will do the right thing, and read more naturally.
The answer with screenshots (put the checkbox as in the second pic, then press OK):
The traditional approach is full of boilerplate code and clumsy resource handling. That's why I made the Spyglass framework. To demonstrate how it works, here's an example showing how to make a custom view that displays a String title.
Step 1: Create a custom view class.
public class CustomView extends FrameLayout {
private TextView titleView;
public CustomView(Context context) {
super(context);
init(null, 0, 0);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr, 0);
}
@RequiresApi(21)
public CustomView(
Context context,
AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs, defStyleAttr, defStyleRes);
}
public void setTitle(String title) {
titleView.setText(title);
}
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
}
}
Step 2: Define a string attribute in the values/attrs.xml
resource file:
<resources>
<declare-styleable name="CustomView">
<attr name="title" format="string"/>
</declare-styleable>
</resources>
Step 3: Apply the @StringHandler
annotation to the setTitle
method to tell the Spyglass framework to route the attribute value to this method when the view is inflated.
@HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
titleView.setText(title);
}
Now that your class has a Spyglass annotation, the Spyglass framework will detect it at compile-time and automatically generate the CustomView_SpyglassCompanion
class.
Step 4: Use the generated class in the custom view's init
method:
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
CustomView_SpyglassCompanion
.builder()
.withTarget(this)
.withContext(getContext())
.withAttributeSet(attrs)
.withDefaultStyleAttribute(defStyleAttr)
.withDefaultStyleResource(defStyleRes)
.build()
.callTargetMethodsNow();
}
That's it. Now when you instantiate the class from XML, the Spyglass companion interprets the attributes and makes the required method call. For example, if we inflate the following layout then setTitle
will be called with "Hello, World!"
as the argument.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:width="match_parent"
android:height="match_parent">
<com.example.CustomView
android:width="match_parent"
android:height="match_parent"
app:title="Hello, World!"/>
</FrameLayout>
The framework isn't limited to string resources has lots of different annotations for handling other resource types. It also has annotations for defining default values and for passing in placeholder values if your methods have multiple parameters.
Have a look at the Github repo for more information and examples.
If all above point not work. Then try this one. I tried it. It's working for me.
UPDATE 2017
For new versions of apache the file is called apache2.conf
So to access the file, type sudo nano /etc/apache2/apache2.conf and change the correspondent line inside block <Directory /var/www >
You mention already having a background image on body
.
You could set that background image on html
, and the new one on body
. This will of course depend upon your layout, but you wouldn't need to use your footer for it.
Use the $expr
operator which allows the use of aggregation expressions within the query language. This will give you the power to use the Date Aggregation Operators in your query as follows:
month = 11
db.mydatabase.mycollection.find({
"$expr": {
"$eq": [ { "$month": "$date" }, month ]
}
})
or
day = 17
db.mydatabase.mycollection.find({
"$expr": {
"$eq": [ { "$dayOfMonth": "$date" }, day ]
}
})
You could also run an aggregate operation with the aggregate()
function that takes in a $redact
pipeline:
month = 11
db.mydatabase.mycollection.aggregate([
{
"$redact": {
"$cond": [
{ "$eq": [ { "$month": "$date" }, month ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
For the other request
day = 17
db.mydatabase.mycollection.aggregate([
{
"$redact": {
"$cond": [
{ "$eq": [ { "$dayOfMonth": "$date" }, day ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
month = 11
day = 17
db.mydatabase.mycollection.aggregate([
{
"$redact": {
"$cond": [
{
"$or": [
{ "$eq": [ { "$month": "$date" }, month ] },
{ "$eq": [ { "$dayOfMonth": "$date" }, day ] }
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
])
var month = 11,
day = 17;
db.collection.aggregate([
{
"$redact": {
"$cond": [
{
"$and": [
{ "$eq": [ { "$month": "$createdAt" }, month ] },
{ "$eq": [ { "$dayOfMonth": "$createdAt" }, day ] }
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
])
The $redact
operator incorporates the functionality of $project
and $match
pipeline and will return all documents match the condition using $$KEEP
and discard from the pipeline those that don't match using the $$PRUNE
variable.
Assuming you want to list grants on all objects a particular user has received:
select * from all_tab_privs_recd where grantee = 'your user'
This will not return objects owned by the user. If you need those, use all_tab_privs
view instead.
Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.
movdir = r"C:\Scans"
basedir = r"C:\Links"
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(movdir):
for filename in files:
# I use absolute path, case you want to move several dirs.
old_name = os.path.join( os.path.abspath(root), filename )
# Separate base from extension
base, extension = os.path.splitext(filename)
# Initial new name
new_name = os.path.join(basedir, base, filename)
# If folder basedir/base does not exist... You don't want to create it?
if not os.path.exists(os.path.join(basedir, base)):
print os.path.join(basedir,base), "not found"
continue # Next filename
elif not os.path.exists(new_name): # folder exists, file does not
shutil.copy(old_name, new_name)
else: # folder exists, file exists as well
ii = 1
while True:
new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
if not os.path.exists(new_name):
shutil.copy(old_name, new_name)
print "Copied", old_name, "as", new_name
break
ii += 1
I was confused by this for hours.
Right click on project -> Build Path -> Configure Build Path -> Add Folder
du -d1
is perhaps the shortest option. (As long as you don't need to pipe the input to another command.)
This was a problem with the user having deny privileges as well; in my haste to grant permissions I basically gave the user everything. And deny was killing it. So as soon as I removed those permissions it worked.
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})
My sources are : StackOverflow
, tutorialspoint.com
, programmers.stackexchange.com
and CodeProject.com
.
Factory Method
(also called Factory
) is for decouple client of a Interface
implementation. For sample we have a Shape
interface with two Circle
and Square
implementations. We have define a factory class with a factory method with a determiner parameter such as Type
and new related implementation of Shape
interface.
Abstract Factory
contains several factory method or a factory interface by several factory implementations.
For next above sample we have a Color
interface with two Red
and Yellow
implementations.
We have define a ShapeColorFactory
interface with two RedCircleFactory
and YellowSquareFactory
. Following code for explain this concept:
interface ShapeColorFactory
{
public Shape getShape();
public Color getColor();
}
class RedCircleFactory implements ShapeColorFactory
{
@Override
public Shape getShape() {
return new Circle();
}
@Override
public Color getColor() {
return new Red();
}
}
class YellowSquareFactory implements ShapeColorFactory
{
@Override
public Shape getShape() {
return new Square();
}
@Override
public Color getColor() {
return new Yellow();
}
}
Here difference between FactoryMethod
and AbstractFactory
. Factory Method
as simply return a concrete class of a interface but Abstract Factory
return factory of factory
. In other words Abstract Factory
return different combine of a series of interface.
I hope my explanation useful.
Your activity must have
public void insertIntoDb(View v) {
...
}
not Fragment .
If you don't want the above in activity. initialize button in fragment and set listener to the same.
<Button
android:id="@+id/btn_conferma" // + missing
Then
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rssitem_detail,
container, false);
Button button = (Button) view.findViewById(R.id.btn_conferma);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// do something
}
});
return view;
}
Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:
^([A-Z]{3})$
The {3}
indicates that the [A-Z]
must appear exactly 3 times.
Unfortunately, there is no formula way to result in a truly blank cell, ""
is the best formulas can offer.
I dislike ISBLANK because it will not see cells that only have ""
as blanks. Instead I prefer COUNTBLANK, which will count ""
as blank, so basically =COUNTBLANK(C1)>0
means that C1 is blank or has ""
.
If you need to remove blank cells in a column, I would recommend filtering on the column for blanks, then selecting the resulting cells and pressing Del. After which you can remove the filter.
In Swift 4, you don't have to use characters
to use map()
. Just do map()
on String.
let letters = "ABC".map { String($0) }
print(letters) // ["A", "B", "C"]
print(type(of: letters)) // Array<String>
Or if you'd prefer shorter: "ABC".map(String.init)
(2-bytes )
In Swift 2 and Swift 3, You can use map()
function to characters
property.
let letters = "ABC".characters.map { String($0) }
print(letters) // ["A", "B", "C"]
Accepted answer doesn't seem to be the best, because sequence-converted String
is not a String
sequence, but Character
:
$ swift
Welcome to Swift! Type :help for assistance.
1> Array("ABC")
$R0: [Character] = 3 values {
[0] = "A"
[1] = "B"
[2] = "C"
}
This below works for me:
let str = "ABC"
let arr = map(str) { s -> String in String(s) }
Reference for a global function map()
is here: http://swifter.natecook.com/func/map/
Its simple You can you curl to do so, make sure curl installed on server :
for triggering every minute : * * * * * curl --request POST 'https://glassdoor.com/admin/sendBdayNotification'
minute hour day month week
Let say you want to send this notification 2:15 PM everyday You may change POST/GET based on your API:
15 14 * * * curl --request POST 'url of ur API'
A very simple way to do so with IPython that worked for me in Visual Studio Code is to add the following:
{
"key": "ctrl+space",
"command": "jupyter.runallcells"
}
to the keybindings.json that you can access by typing F1 and 'open keyboard shortcuts'.
This is how I did it with Kotlin to show progress with percentage.
My fragment layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:layout_marginLeft="32dp"
android:layout_marginRight="32dp"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/progressBar"/>
</FrameLayout>
My kotlin fragment in onViewCreated
progressBar.max = 100;
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
progressBar.progress = newProgress;
}
}
webView!!.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
progressBar.visibility = View.VISIBLE
progressBar.progress = 0;
super.onPageStarted(view, url, favicon)
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url)
return true
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view?.loadUrl(request?.url.toString())
}
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
progressBar.visibility = View.GONE
}
}
webView.loadUrl(url)
How about:
git branch -D email
git checkout staging
git checkout -b email
git push origin email --force-with-lease
When you have several words like this which you want to concatenate in a string, I recommend using format
or f-strings
which increase readability dramatically (in my opinion).
To give an example:
s = "a word that needs quotation marks"
s2 = "another word"
Now you can do
print('"{}" and "{}"'.format(s, s2))
which will print
"a word that needs quotation marks" and "another word"
As of Python 3.6 you can use:
print(f'"{s}" and "{s2}"')
yielding the same output.
You might want to use the timeit module instead.
Definition:
public static string GetLast(string source, int last)
{
return last >= source.Length ? source : source.Substring(source.Length - last);
}
Usage:
GetLast("string of", 2);
Result:
of
Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:
import requests
url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)
print(response.text)
More about Request object: https://requests.readthedocs.io/en/master/api/
Drop in the image in /res/drawable folder. Then in Eclipse Menu, do ->Project -> Clean. This will do a clean build if set to build automatically.
Implementation with Guzzle library:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$httpClient = new Client();
$response = $httpClient->post(
'https://postman-echo.com/post',
[
RequestOptions::BODY => 'POST raw request content',
RequestOptions::HEADERS => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]
);
echo(
$response->getBody()->getContents()
);
PHP CURL extension:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify request content
*/
CURLOPT_POSTFIELDS => 'POST raw request content',
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
Curl does that by default without any parameters or flags, I would use it for your purposes:
curl $url > /dev/null 2>&1
Curl is more about streams and wget is more about copying sites based on this comparison.
Clearly HttpContext.Current
is not null
only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".
It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.
Overall, don't use Application["Setting"]
to store global stuffs, as they are not global as you discovered.
If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext
or Application["Settings"]
, as that violates the principles of isolation and decoupling.
Update:
Due to the introduction of async/await
it is more often that such issues happen, so you might consider the following tip,
In general, you should only call HttpContext.Current
in only a few scenarios (within an HTTP module for example). In all other cases, you should use
Page.Context
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.context?view=netframework-4.7.2 Controller.HttpContext
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.httpcontext?view=aspnet-mvc-5.2instead of HttpContext.Current
.
You can use:
JsonConvert.PopulateObject(json, obj);
here: json
is the json string,obj
is the target object. See: example
Note: PopulateObject()
will not erase obj's list data, after Populate()
, obj's
list member will contains its original data and data from json string
I hope the below example will provide more clarity.
package main
type EmployeeManager struct{
category string
city string
calculateSalary func() int64
}
func NewEmployeeManager() (*EmployeeManager,error){
return &EmployeeManager{
category : "MANAGEMENT",
city : "NY",
calculateSalary: func() int64 {
var calculatedSalary int64
// some formula
return calculatedSalary
},
},nil
}
func (self *EmployeeManager) emWithSalaryCalculation(){
self.calculateSalary = func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}
}
func updateEmployeeInfo(em EmployeeManager){
// Some code
}
func processEmployee(){
updateEmployeeInfo(struct {
category string
city string
calculateSalary func() int64
}{category: "", city: "", calculateSalary: func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}})
}
You can consider using numpy.putmask:
np.putmask(arr, arr>=T, 255.0)
Here is a performance comparison with the Numpy's builtin indexing:
In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit np.putmask(A, A>0.5, 5)
1000 loops, best of 3: 1.34 ms per loop
In [4]: timeit A[A > 0.5] = 5
1000 loops, best of 3: 1.82 ms per loop
It is up to the http server to decide if there is a limit. The product I work on allows the admin to configure the limit.
You can follow this official documentation by Google: https://developer.android.com/studio/build/application-id.html
Application ID should be changed in Build.gradle, while package name can be changed in AndroidManifest.xml.
However one should be careful changing package name.
Also while re uploading the app, one should be careful since it matches the application ID of previously uploaded app with new upload.
Here are a few options:
In Perl, you can choose alternate delimiters. You're not confined to m//
. You could choose another, such as m{}
. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{}
is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters, //
and {}
seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples are m(...)
, m[...]
, and m!...!
.
In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/
for example (using an alternate delimiter that could become m{/[^/]+$}
, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.
Its undefined
because, console.log(response)
runs before doCall(urlToCall);
is finished. You have to pass in a callback function aswell, that runs when your request is done.
First, your function. Pass it a callback:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return callback(finalData);
});
}
Now:
var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
// Here you have access to your variable
console.log(response);
})
@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.
You might have to put one or both of:
html { height:100%; }
or
body { height:100%; }
EDIT: Whoops, didn't notice they were floated. You just need to float the container.
In Tensorflow 2.0+ (or in Eager mode environment) you can call .numpy()
method:
import tensorflow as tf
matrix1 = tf.constant([[3., 3.0]])
matrix2 = tf.constant([[2.0],[2.0]])
product = tf.matmul(matrix1, matrix2)
print(product.numpy())
If you are using jsvc to run tomcat as tomcat (run /etc/init.d/tomcat
as root), edit /etc/init.d/tomcat
and add $CATALINA_HOME/bin/tomcat-juli.jar
to CLASSPATH
.
what worked for me is converting the props.data to an array using
data = Array.from(props.data);
then I could use the data.map()
function
Perl string match can also be used for a simple yes/no.
my @foo=("hello", "world", "foo", "bar");
if ("@foo" =~ /\bhello\b/){
print "found";
}
else{
print "not found";
}
If you pad and offset it like this:
textarea
{
border:1px solid #999999;
width:100%;
padding: 7px 0 7px 7px;
position:relative; left:-8px; /* 1px border, too */
}
the right side of the textarea perfectly aligns with the right side of the container, and the text inside the textarea aligns perfectly with the body text in the container... and the left side of the textarea 'sticks out' a bit. it's sometimes prettier.
<?php
// in woocommerce.php
$cat = get_queried_object();
$cat->term_id;
$cat->name;
?>
<?php
// get product cat image
if ( is_product_category() ){
$cat = get_queried_object();
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<img src="' . $image . '" alt="" />';
}
}
?>
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
A List<T>
is an IEnumerable<T>
, so actually, there's no need to 'convert' a List<T>
to an IEnumerable<T>
.
Since a List<T>
is an IEnumerable<T>
, you can simply assign a List<T>
to a variable of type IEnumerable<T>
.
The other way around, not every IEnumerable<T>
is a List<T>
offcourse, so then you'll have to call the ToList()
member method of the IEnumerable<T>
.
Try using BindingExpression.UpdateTarget()
Actually, there is no need to restore the database in native SQL Server terms, since you "want to fiddle with some data" and "browse through the data of that .bak file"
You can use ApexSQL Restore – a SQL Server tool that attaches both native and natively compressed SQL database backups and transaction log backups as live databases, accessible via SQL Server Management Studio, Visual Studio or any other third-party tool. It allows attaching single or multiple full, differential and transaction log backups
Moreover, I think that you can do the job while the tool is in fully functional trial mode (14 days)
Disclaimer: I work as a Product Support Engineer at ApexSQL
Use this command for Angular 6 to build
ng build --prod --configuration=dev
I always find myself on this same page everytime I try to do this. Sure, the other answers get the job done, but aren't easy to remember for next time! ex: import ticker and use lambda, custom def, etc.
Here's a simple solution if you have an axes named ax
:
ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
The std::string::append()
method expects its argument to be a NULL terminated string (char*
).
There are several approaches for producing a string
containg an int
:
#include <sstream>
std::ostringstream s;
s << "select logged from login where id = " << ClientID;
std::string query(s.str());
std::to_string
(C++11)
std::string query("select logged from login where id = " +
std::to_string(ClientID));
#include <boost/lexical_cast.hpp>
std::string query("select logged from login where id = " +
boost::lexical_cast<std::string>(ClientID));
do a dir /s /b > out.txt
and then add a guide at position 260
In powershell cmd /c dir /s /b |? {$_.length -gt 260}
Steps to fix are:
Tools
Import and Export Settings
Reset all settings
Back up your config
Select your environment settings and finish
Consider see this answer, specially if you want use generics in List
Spring RestTemplate and generic types ParameterizedTypeReference collections like List<T>
You can follow this answer to see many different ways to process CSV in C++.
In your case, the last call to getline
is actually putting the last field of the first line and then all of the remaining lines into the variable genero
. This is because there is no space delimiter found up until the end of file. Try changing the space character into a newline instead:
getline(file, genero, file.widen('\n'));
or more succinctly:
getline(file, genero);
In addition, your check for file.good()
is premature. The last newline in the file is still in the input stream until it gets discarded by the next getline()
call for ID
. It is at this point that the end of file is detected, so the check should be based on that. You can fix this by changing your while
test to be based on the getline()
call for ID
itself (assuming each line is well formed).
while (getline(file, ID, ',')) {
cout << "ID: " << ID << " " ;
getline(file, nome, ',') ;
cout << "User: " << nome << " " ;
getline(file, idade, ',') ;
cout << "Idade: " << idade << " " ;
getline(file, genero);
cout << "Sexo: " << genero<< " " ;
}
For better error checking, you should check the result of each call to getline()
.
Yes, it's possible. In python, Comprehension can be used in List, Set, Dictionary, etc. You can write it this way
mydict = {k:v for (k,v) in blah}
Another detailed example of Dictionary Comprehension with the Conditional Statement and Loop:
parents = [father, mother]
parents = {parent:1 - P["mutation"] if parent in two_genes else 0.5 if parent in one_gene else P["mutation"] for parent in parents}
def get_true_text(tag):
children = tag.find_elements_by_xpath('*')
original_text = tag.text
for child in children:
original_text = original_text.replace(child.text, '', 1)
return original_text
I had the same problem and fixed it by clicking File>Invalidate caches/ restart
Try this
boxValue = boxValue.replace(/[^0-9\.]/g,"");
This Regular Expression will allow only digits and dots in the value of text box.
Found the answer on a blog and it's as simple as:
strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400
And you'll get the days between the 2 dates.
sort()
was deprecated for DataFrames in favor of either:
sort_values()
to sort by column(s)sort_index()
to sort by the index sort()
was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values()
and sort_index()
. It was removed from Pandas with release 0.20 (2017-05-05).
You can use
LEFT(column, length)
or
SUBSTRING(column, start index, length)
All good answers. To put it in simple language [BCNF] No partial key can depend on a key.
i.e No partial subset ( i.e any non trivial subset except the full set ) of a candidate key can be functionally dependent on some candidate key.
Here is a Swift 5 solution for downloading and saving an image or in general a file to the documents directory by using Alamofire
:
func dowloadAndSaveFile(from url: URL) {
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
documentsURL.appendPathComponent(url.lastPathComponent)
return (documentsURL, [.removePreviousFile])
}
let request = SessionManager.default.download(url, method: .get, to: destination)
request.validate().responseData { response in
switch response.result {
case .success:
if let destinationURL = response.destinationURL {
print(destinationURL)
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
This problem can be fixed by installing the C++ compiler (python27 or python26). Download it from Microsoft https://www.microsoft.com/en-us/download/details.aspx?id=44266 and re-run the command : pip install pycrypto
to run the gui web access when you kill the process of easy_install.exe
.
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
You have four options
Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.
Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.
Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy
syntax then Theano might be a good choice.
Here is an example using SymPy
In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2·x
In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2. 2. 2. 2. 2.]
<script type="text/javascript">
jQuery(function () {
var container = jQuery("\#content");
jQuery(container)
.kendoGrid({
selectable: "single row",
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
dataType: "json",
},
},
batch: true,
}),
editable: "popup",
columns: [
{ field: "Id", title: "Id", width: 250, hidden: true },
{ field: "Data", title: "Message Body", width: 100 },
{ field: "mobile", title: "Mobile Number", width: 100 },
]
});
});
After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:
General -> Editors -> Text Editors -> Annotations
Look for Occurences
from the Annotation types list.
Then, be sure that Text as highlighted
is selected, then choose the desired color.
And, a picture is worth a thousand words...
(source: coobird.net)
(source: coobird.net)
Use YQL and you don't need to worry. It's a query language by Yahoo and you can get all the stock data including the name of the company for the ticker. It's a REST API and it returns the results via XML or JSON. I have a full tutorial and source code on my site take a look: http://www.jarloo.com/yahoo-stock-symbol-lookup/
In PHP 5.5 there is also a new concept: generators
, where you can yield multiple values from a function:
function hasMultipleValues() {
yield "value1";
yield "value2";
}
$values = hasMultipleValues();
foreach ($values as $val) {
// $val will first be "value1" then "value2"
}
What you really want here is:
<col align="right"/>
but it looks like Gecko doesn't support this yet: it's been an open bug for over a decade.
(Geez, why can't Firefox have decent standards support like IE6?)
Older SQLite command-line shells (sqlite3.exe
) do not appear to offer the .open
command or any readily identifiable alternative.
Although I found no definitive reference it seems that the .open
command was introduced around version 3.15. The SQLite Release History first mentions the .open
command with 2016-10-14 (3.15.0).
After spend hours to fix that; and for some who installed it uncorrectly, you need to uninstall current version and reinstall it again as Administrator
Just to build upon solving the namespace issues, in my case I've been running into documents with multiple namespaces and needed to handle namespaces properly. I wrote the function below to get a namespace manager to deal with any namespace in the document:
private XmlNamespaceManager GetNameSpaceManager(XmlDocument xDoc)
{
XmlNamespaceManager nsm = new XmlNamespaceManager(xDoc.NameTable);
XPathNavigator RootNode = xDoc.CreateNavigator();
RootNode.MoveToFollowing(XPathNodeType.Element);
IDictionary<string, string> NameSpaces = RootNode.GetNamespacesInScope(XmlNamespaceScope.All);
foreach (KeyValuePair<string, string> kvp in NameSpaces)
{
nsm.AddNamespace(kvp.Key, kvp.Value);
}
return nsm;
}
The given answer assumes that the project in question use project inheritance in addition to module aggregation. In fact those are distinct concepts:
Some projects may be an aggregation of modules, yet not have a parent-child relationship between aggregator POM and the aggregated modules. (There may be no parent-child relationship at all, or the child modules may use a separate POM altogether as the "parent".) In these situations the given answer will not work.
After much reading and experimentation, it turns out there is a way to use the Versions Maven Plugin to update not only the aggregator POM but also all aggregated modules as well; it is the processAllModules
option. The following command must be done in the directory of the aggregator project:
mvn versions:set -DnewVersion=2.50.1-SNAPSHOT -DprocessAllModules
The Versions Maven Plugin will not only update the versions of all contained modules, it will also update inter-module dependencies!!!! This is a huge win and will save a lot of time and prevent all sorts of problems.
Of course don't forget to commit the changes in all modules, which you can also do with the same switch:
mvn versions:commit -DprocessAllModules
You may decide to dispense with the backup POMS altogether and do everything in one command:
mvn versions:set -DnewVersion=2.50.1-SNAPSHOT -DprocessAllModules -DgenerateBackupPoms=false
I know that this already has plenty of answers and is a rather old question. But I just came up with this neat one-liner:
JSON.parse(JSON.stringify(raw, ['key', 'value', 'item1', 'item3']))
That returns another object with just the whitelisted attributes. Note that the key
and value
is included in the list.
I tried this with python3 and it worked, source
def output_reader(proc):
for line in iter(proc.stdout.readline, b''):
print('got line: {0}'.format(line.decode('utf-8')), end='')
def main():
proc = subprocess.Popen(['python', 'fake_utility.py'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
t = threading.Thread(target=output_reader, args=(proc,))
t.start()
try:
time.sleep(0.2)
import time
i = 0
while True:
print (hex(i)*512)
i += 1
time.sleep(0.5)
finally:
proc.terminate()
try:
proc.wait(timeout=0.2)
print('== subprocess exited with rc =', proc.returncode)
except subprocess.TimeoutExpired:
print('subprocess did not terminate in time')
t.join()
The way I always do it (assuming the data is never to be deleted, only inserted) is to
insert
, if this fails with a unique constraint violation then you know the row is there,update
Unfortunately many frameworks such as Hibernate treat all database errors (e.g. unique constraint violation) as unrecoverable conditions, so it isn't always easy. (In Hibernate the solution is to open a new session/transaction just to execute this one insert
command.)
You can't just do a select count(*) .. where ..
as even if that returns zero, and therefore you choose to do an insert
, between the time you do the select
and the insert
someone else might have insert
ed the row and therefore your insert
will fail.
You can try using ModelAndView
:
@RequestMapping("/")
public ModelAndView index () {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
You can use
SELECT SYS_EXTRACT_UTC(TIMESTAMP '2000-03-28 11:30:00.00 -02:00') FROM DUAL;
You may also need to change your timezone
ALTER SESSION SET TIME_ZONE = 'Europe/Berlin';
Or read it
SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM dual;
Try browser.execute_script
instead of selenium.GetEval
.
See this answer for example.
If you are using Gradle, you can add it as a compile
dependency.
Instructions
Make sure you have the Android Support Repository
SDK package installed. Android Studio automatically recognizes this repository during the build process (not sure about plain IntelliJ).
Add the dependency to {project}/build.gradle
dependencies {
compile 'com.android.support:appcompat-v7:+'
}
Click the Sync Project with Gradle Files
button.
EDIT: Looks like these same instructions are on the documentation under Adding libraries with resources -> Using Android Studio
.
You can connect using
\c dbname
If you would like to see all possible commands for POSTGRESQL or SQL follow this steps :
rails dbconsole (You will redericted to your current ENV database)
\? (For POSTGRESQL commands)
or
\h (For SQL commands)
Press Q to Exit
When you do git status
, Git tells you how to unstage:
Changes to be committed: (use "git reset HEAD <file>..." to unstage).
So git reset HEAD <file>
worked for me and the changes were un-touched.
Easier and more succinct with || ...:
$(document).ready(function(){
var str = ((document.getElementById("cal_preview")||{}).value)||"";
var str1 = ((document.getElementById("year")||{}).value)||"";
var str2 = ((document.getElementById("holiday")||{}).value)||"";
var str3 = ((document.getElementById("cal_option")||{}).value)||"";
if (str=="" && str1=="" && str2=="" && str3=="" )
{
document.getElementById("calendar_preview").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("calendar_preview").innerHTML=xmlhttp.responseText;
}
}
var url = calendar_preview_vars.plugin_url + "?id=" + str +"&"+"y="+str1+"&"+"h="+str2+"&"+"opt="+str3;
xmlhttp.open("GET",url,true);
xmlhttp.send();
});
struct Bool {
int true;
int false;
}
int main() {
/* bool is a variable of data type – bool*/
struct Bool bool;
/*below I’m accessing struct members through variable –bool*/
bool = {1,0};
print("Student Name is: %s", bool.true);
return 0;
}
ES6: In HTML, include the main JavaScript file using attribute type="module"
(browser support):
<script type="module" src="script.js"></script>
And in the script.js
file, include another file like this:
import { hello } from './module.js';
...
// alert(hello());
Inside the included file (module.js
), you must export the function/class that you will import:
export function hello() {
return "Hello World";
}
A working example is here. More information is here.
If you don't need in a complete reference to the most part of algorithms and data structures that are in use and just want to get acquainted with common techniques I would recommend something more lightweight than Cormen, Sedgewick or Knuth. I think, Algorithms and Data Structures by N. Wirth is not as bad choice even in spite of it was printed far ago.
When you expand or collapse accordion it just adds/removes a class "in" and sets the height:auto
or 0
to the accordion div.
So in your accordion when you define it just remove "in" class from the div as below. Whenever you expand an accorion it just adds the "in" class to make it visible.
If you render the page with "in" bootstrap looks for the class and it will make the div's height:auto, if it not present it will be at zero height.
<div id="collapseOne" class="accordion-body collapse">
Sometimes a dependency added with ng add
will add more than one package, typing npm uninstall lib1 lib2
could be error prone and slow, so just remove the not needed libraries from package.json
and run npm i
In Google Maps API v3 you can try changing marker icon. For example for green icon use:
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
Or as part of marker init:
marker = new google.maps.Marker({
icon: 'http://...'
});
Other colors:
Etc.
The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes and it should go fine
Old question but this answer might help someone.
If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden
, otherwise anything outside of it will be cut off.
How about a workaround?
In my case I took the value of the textarea in a jQuery variable, and changed all "<p> "
to <p class="clear">
and clear class to have certain height and margin, as the following example:
jQuery
tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p> /g, '<p class="clear">');
the val is then saved to the database with the new val.
CSS
p.clear{height: 2px; margin-bottom: 3px;}
You can adjust the height & margin as you wish. And since 'p' is a display: block element. it should give you the expected output.
Hope that helps!
WRONG #1: Forgetting Decorator:
//Uncaught Error: Can't resolve all parameters for MyFooService: (?).
export class MyFooService { ... }
WRONG #2: Omitting "@" Symbol:
//Uncaught Error: Can't resolve all parameters for MyFooService: (?).
Injectable()
export class MyFooService { ... }
WRONG #3: Omitting "()" Symbols:
//Uncaught Error: Can't resolve all parameters for TypeDecorator: (?).
@Injectable
export class MyFooService { ... }
WRONG #4: Lowercase "i":
//Uncaught ReferenceError: injectable is not defined
@injectable
export class MyFooService { ... }
WRONG #5: You forgot: import { Injectable } from '@angular/core';
//Uncaught ReferenceError: Injectable is not defined
@Injectable
export class MyFooService { ... }
CORRECT:
@Injectable()
export class MyFooService { ... }
you can also use append function
b = [ ]
for x in range(0, 5):
b.append(["O"] * 5)
def print_b(b):
for row in b:
print " ".join(row)
https://github.com/wongatech/angular-confirm-field is a good project for this.
Example here http://wongatech.github.io/angular-confirm-field/
The code below shows 2 input fields with the implemented functionality
<input ng-confirm-field ng-model="emailconfirm" confirm-against="email" name="my-email-confirm"/>
<input ng-model="email" name="my-email" />
I have installed the new WAMP 2.5, i have windows 8 x64 bit. I have tried All the above solutions but it didn't work with me and the WAMP icon stays Orange. the thing that works with me is:
I hope that i will help somebody searching for this answer
personaly, i'm using exceptions to handle validation. it requires following steps:
the trick here, is to bind only to objects which derive from DependencyObject. simple implementation of INotifyPropertyChanged wouldn't work - there is a bug in the framework, which prevents you from accessing error collection.
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
Assembling one INSERT
statement with multiple rows is much faster in MySQL than one INSERT
statement per row.
That said, it sounds like you might be running into string-handling problems in PHP, which is really an algorithm problem, not a language one. Basically, when working with large strings, you want to minimize unnecessary copying. Primarily, this means you want to avoid concatenation. The fastest and most memory efficient way to build a large string, such as for inserting hundreds of rows at one, is to take advantage of the implode()
function and array assignment.
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
The advantage of this approach is that you don't copy and re-copy the SQL statement you've so far assembled with each concatenation; instead, PHP does this once in the implode()
statement. This is a big win.
If you have lots of columns to put together, and one or more are very long, you could also build an inner loop to do the same thing and use implode()
to assign the values clause to the outer array.
Another way this could be accomplished is by using the Start-Transcript
and Stop-Transcript
commands, respectively before and after command execution. This would capture the entire session including commands.
For this particular case Out-File
is probably your best bet though.
You can do it programmatically:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main() {
int fd = creat("/tmp/foo.txt", 0644);
ftruncate(fd, SIZE_IN_BYTES);
close(fd);
return 0;
}
This approach is especially useful to subsequently mmap the file into memory.
use the following command to check that the file has the correct size:
# du -B1 --apparent-size /tmp/foo.txt
Be careful:
# du /tmp/foo.txt
will probably print 0 because it is allocated as Sparse file if supported by your filesystem.
see also: man 2 open and man 2 truncate
Did you try using -removeObjectForKey
?
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"defunctPreference"];
I'm going to go against the general wisdom here that std::copy
will have a slight, almost imperceptible performance loss. I just did a test and found that to be untrue: I did notice a performance difference. However, the winner was std::copy
.
I wrote a C++ SHA-2 implementation. In my test, I hash 5 strings using all four SHA-2 versions (224, 256, 384, 512), and I loop 300 times. I measure times using Boost.timer. That 300 loop counter is enough to completely stabilize my results. I ran the test 5 times each, alternating between the memcpy
version and the std::copy
version. My code takes advantage of grabbing data in as large of chunks as possible (many other implementations operate with char
/ char *
, whereas I operate with T
/ T *
(where T
is the largest type in the user's implementation that has correct overflow behavior), so fast memory access on the largest types I can is central to the performance of my algorithm. These are my results:
Time (in seconds) to complete run of SHA-2 tests
std::copy memcpy % increase
6.11 6.29 2.86%
6.09 6.28 3.03%
6.10 6.29 3.02%
6.08 6.27 3.03%
6.08 6.27 3.03%
Total average increase in speed of std::copy over memcpy: 2.99%
My compiler is gcc 4.6.3 on Fedora 16 x86_64. My optimization flags are -Ofast -march=native -funsafe-loop-optimizations
.
Code for my SHA-2 implementations.
I decided to run a test on my MD5 implementation as well. The results were much less stable, so I decided to do 10 runs. However, after my first few attempts, I got results that varied wildly from one run to the next, so I'm guessing there was some sort of OS activity going on. I decided to start over.
Same compiler settings and flags. There is only one version of MD5, and it's faster than SHA-2, so I did 3000 loops on a similar set of 5 test strings.
These are my final 10 results:
Time (in seconds) to complete run of MD5 tests
std::copy memcpy % difference
5.52 5.56 +0.72%
5.56 5.55 -0.18%
5.57 5.53 -0.72%
5.57 5.52 -0.91%
5.56 5.57 +0.18%
5.56 5.57 +0.18%
5.56 5.53 -0.54%
5.53 5.57 +0.72%
5.59 5.57 -0.36%
5.57 5.56 -0.18%
Total average decrease in speed of std::copy over memcpy: 0.11%
Code for my MD5 implementation
These results suggest that there is some optimization that std::copy used in my SHA-2 tests that std::copy
could not use in my MD5 tests. In the SHA-2 tests, both arrays were created in the same function that called std::copy
/ memcpy
. In my MD5 tests, one of the arrays was passed in to the function as a function parameter.
I did a little bit more testing to see what I could do to make std::copy
faster again. The answer turned out to be simple: turn on link time optimization. These are my results with LTO turned on (option -flto in gcc):
Time (in seconds) to complete run of MD5 tests with -flto
std::copy memcpy % difference
5.54 5.57 +0.54%
5.50 5.53 +0.54%
5.54 5.58 +0.72%
5.50 5.57 +1.26%
5.54 5.58 +0.72%
5.54 5.57 +0.54%
5.54 5.56 +0.36%
5.54 5.58 +0.72%
5.51 5.58 +1.25%
5.54 5.57 +0.54%
Total average increase in speed of std::copy over memcpy: 0.72%
In summary, there does not appear to be a performance penalty for using std::copy
. In fact, there appears to be a performance gain.
Explanation of results
So why might std::copy
give a performance boost?
First, I would not expect it to be slower for any implementation, as long as the optimization of inlining is turned on. All compilers inline aggressively; it is possibly the most important optimization because it enables so many other optimizations. std::copy
can (and I suspect all real world implementations do) detect that the arguments are trivially copyable and that memory is laid out sequentially. This means that in the worst case, when memcpy
is legal, std::copy
should perform no worse. The trivial implementation of std::copy
that defers to memcpy
should meet your compiler's criteria of "always inline this when optimizing for speed or size".
However, std::copy
also keeps more of its information. When you call std::copy
, the function keeps the types intact. memcpy
operates on void *
, which discards almost all useful information. For instance, if I pass in an array of std::uint64_t
, the compiler or library implementer may be able to take advantage of 64-bit alignment with std::copy
, but it may be more difficult to do so with memcpy
. Many implementations of algorithms like this work by first working on the unaligned portion at the start of the range, then the aligned portion, then the unaligned portion at the end. If it is all guaranteed to be aligned, then the code becomes simpler and faster, and easier for the branch predictor in your processor to get correct.
Premature optimization?
std::copy
is in an interesting position. I expect it to never be slower than memcpy
and sometimes faster with any modern optimizing compiler. Moreover, anything that you can memcpy
, you can std::copy
. memcpy
does not allow any overlap in the buffers, whereas std::copy
supports overlap in one direction (with std::copy_backward
for the other direction of overlap). memcpy
only works on pointers, std::copy
works on any iterators (std::map
, std::vector
, std::deque
, or my own custom type). In other words, you should just use std::copy
when you need to copy chunks of data around.
In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button
From all I have read you cannot do exactly what you want without javascript. If you float left before text
<div style="float:left;">widget</div> here is some CONTENT, etc.
Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content
here is some CONTENT, etc. <div style="float:left;">widget</div>
Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:
here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>
In your question you are using bootstrap which just adds row-fluid::after { content: ""}
which resolves the border/background issue.
Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/
<div class="container-fluid">
<div class="row-fluid">
<div class="offset1 span8 pull-right">
... Widget 1...
</div>
.... a lot of content ....
<div class="span8" style="margin-left: 0;">
... Widget 2...
</div>
</div>
</div><!--/.fluid-container-->
if you are using tensorflow 2.x use:
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))
I would suggest the following simple approach for conversion:
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:
date += timedelta(days=10)
date -= timedelta(days=5)
And convert back using:
s = date.strftime("%Y%m%d")
To convert the integer to a string safely, use:
s = "{0:-08d}".format(i)
This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).
Further reference: datetime objects, timedelta objects
The same issue came up for me inside of $elms.each()
.
Because:
.each(Function)
exposes (at least) two arguments; the first being the index and the second being the element in the current element in the list, andyou may be tempted to do this:
$elms.each((item) => $(item).addClass('wrong'));
When this is what you need:
$elms.each((index, item) => $(item).addClass('wrong'));
Facade discusses encapsulating a complex subsystem within a single interface object. This reduces the learning curve necessary to successfully leverage the subsystem. It also promotes decoupling the subsystem from its potentially many clients. On the other hand, if the Facade is the only access point for the subsystem, it will limit the features and flexibility that "power users" may need.
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.You have to use the for-in loop
But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.
Therefore, when using for-in loops, always make use of the hasOwnProperty
method to determine if the current property in iteration is really a property of the object you're checking on:
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
window.opener
refers to the window that called window.open( ... )
to open the window from which it's calledwindow.parent
refers to the parent of a window in a <frame>
or <iframe>
window.top
refers to the top-most window from a window nested in one or more layers of <iframe>
sub-windowsThose will be null
(or maybe undefined
) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)
Hmmm... would it be much different if you just had non-static classes filled with static methods..?
Using guava
Doubles.asList(1.2, 5.6, 10.1);
or immutable list
ImmutableList.of(1.2, 5.6, 10.1);
For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..
function AbsoluteCoordinates($element) {
var sTop = $(window).scrollTop();
var sLeft = $(window).scrollLeft();
var w = $element.width();
var h = $element.height();
var offset = $element.offset();
var $p = $element;
while(typeof $p == 'object') {
var pOffset = $p.parent().offset();
if(typeof pOffset == 'undefined') break;
offset.left = offset.left + (pOffset.left);
offset.top = offset.top + (pOffset.top);
$p = $p.parent();
}
var pos = {
left: offset.left + sLeft,
right: offset.left + w + sLeft,
top: offset.top + sTop,
bottom: offset.top + h + sTop,
}
pos.tl = { x: pos.left, y: pos.top };
pos.tr = { x: pos.right, y: pos.top };
pos.bl = { x: pos.left, y: pos.bottom };
pos.br = { x: pos.right, y: pos.bottom };
//console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom );
return pos;
}
I use something like this (you should add code to deal with the various fails):
var response = RunTaskWithTimeout<ReturnType>(
(Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);
/// <summary>
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
/// </summary>
/// <typeparam name="T">Return type of function</typeparam>
/// <param name="TaskAction">Function delegate for task to perform</param>
/// <param name="TimeoutSeconds">Time to allow before task times out</param>
/// <returns></returns>
private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
{
Task<T> backgroundTask;
try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
}
if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
}
// task succeeded
return backgroundTask.Result;
}
Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.
it will create the file in the root directory of your project/solution.
You can specify a location of choice in the web.config of your app as follows:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:/ServiceLogs/Olympus.Core.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value=".yyyyMMdd.log" />
<maximumFileSize value="5MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
<maxSizeRollBackups value="-1" />
<countDirection value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
</layout>
</appender>
the file tag specifies the location.
Many of these projects mentioned above are dead or dying, lacking activity and interest from author side. Interesting to follow how this area develops.
For the record, in era of plugin based implementations, KDE camp had an attempt to solve this with plugin and non-language specific way and created the Kross https://en.wikipedia.org/wiki/Kross_(software) - in my understanding it never took off even inside the community itself.
During this chicken and egg -problem time, javascript-based implementions are definately way to go. Maybe in the future we seee pure and clean, full Python support natively in browsers.
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
Tk is available for Ruby. Some nice examples (in Ruby, Perl and Tcl) can be found at http://www.tkdocs.com/
from ..gen_py.lib import MyService
or
from main.gen_py.lib import MyService
Make sure you have a (at least empty) __init__.py
file on each directory.
From the documentation I found this
JObject o = new JObject(
new JProperty("Name", "John Smith"),
new JProperty("BirthDate", new DateTime(1983, 3, 20))
);
JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
Console.WriteLine(p.Name);
The class definition for Person
should be compatible to the following:
class Person {
public string Name { get; internal set; }
public DateTime BirthDate { get; internal set; }
}
Edit
If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.
I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:
unordered_map
separately, instead of using the equality comparison operator (operator==
). This might be helpful, for example, if you want to use the latter for comparing all members of two Node
objects to each other, but only some specific members as key of an unordered_map
.All in all, for your Node
class, the code could be written as follows:
using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);
Notes:
Viewgroup inherits properties of views and does more with other views and viewgroup.
See the Android API: http://developer.android.com/reference/android/view/ViewGroup.html
I think you want to return a REFCURSOR:
create function test_cursor
return sys_refcursor
is
c_result sys_refcursor;
begin
open c_result for
select * from dual;
return c_result;
end;
Update: If you need to call this from SQL, use a table function like @Tony Andrews suggested.
I am using org.springframework.core.ResolvableType for a ListResultEntity :
ResolvableType resolvableType = ResolvableType.forClassWithGenerics(ListResultEntity.class, itemClass);
ParameterizedTypeReference<ListResultEntity<T>> typeRef = ParameterizedTypeReference.forType(resolvableType.getType());
So in your case:
public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
ResponseEntity<ResponseWrapper<T>> response = template.exchange(
uri,
HttpMethod.POST,
null,
ParameterizedTypeReference.forType(ResolvableType.forClassWithGenerics(ResponseWrapper.class, clazz)));
return response;
}
This only makes use of spring and of course requires some knowledge about the returned types (but should even work for things like Wrapper>> as long as you provide the classes as varargs )
Using Powershell V2 and below, get-content reads the entire file, so it was of no use to me. The following code works for what I needed, though there are likely some issues with character encodings. This is effectively tail -f, but it could be easily modified to get the last x bytes, or last x lines if you want to search backwards for line breaks.
$filename = "\wherever\your\file\is.txt"
$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($filename, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length
while ($true)
{
Start-Sleep -m 100
#if the file size has not changed, idle
if ($reader.BaseStream.Length -eq $lastMaxOffset) {
continue;
}
#seek to the last max offset
$reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null
#read out of the file until the EOF
$line = ""
while (($line = $reader.ReadLine()) -ne $null) {
write-output $line
}
#update the last max offset
$lastMaxOffset = $reader.BaseStream.Position
}
I found most of the code to do this here.
You can even avoid the function at the parent updating the state directly
In Parent Component:
render(){
return(<Child sendData={ v => this.setState({item: v}) } />);
}
In the Child Component:
demoMethod(){
this.props.sendData(value);
}
The best solution I have found is to override onCreateDialog()
instead of onCreateView()
. setContentView() will set the correct window dimensions before inflating. It removes the need to store/set a dimension, background color, style, etc in resource files and setting them manually.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.fragment_dialog);
Button button = (Button) dialog.findViewById(R.id.dialog_button);
// ...
return dialog;
}
If your source folder is structured /go/src/blog (assuming the name of your source folder is blog).
That should run all of your files at the same time, instead of you having to list the files manually or "bashing" a method on the command line.
A more pythonic way, without using set is as follows:
lst = [1, 2, 3, 4]
lst.append(3) if 3 not in lst else lst
I have had this problem and I consider we are missing a well explained way of doing this programmatically without losing the already set filters.
Setting the length in XML:
As the accepted answer states correctly, if you want to define a fixed length to an EditText which you won't change further in the future just define in your EditText XML:
android:maxLength="10"
Setting the length programmatically
To set the length programmatically you'll need to set it through an InputFilter
. But if you create a new InputFilter and set it to the EditText
you will lose all the other already defined filters (e.g. maxLines, inputType, etc) which you might have added either through XML or programatically.
So this is WRONG:
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
To avoid losing previously added filters you need to get those filters, add the new one (maxLength in this case), and set the filters back to the EditText
as follow:
Java
InputFilter[] editFilters = editText.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = new InputFilter.LengthFilter(maxLength);
editText.setFilters(newFilters);
Kotlin however made it easier for everyone, you also need to add the filter to the already existing ones but you can achieve that with a simple:
editText.filters += InputFilter.LengthFilter(maxLength)
$('#loading-image').html('<img src="/images/ajax-loader.gif"> Sending...');
$.ajax({
url: uri,
cache: false,
success: function(){
$('#loading-image').html('');
},
error: function(jqXHR, textStatus, errorThrown) {
var text = "Error has occured when submitting the job: "+jqXHR.status+ " Contact IT dept";
$('#loading-image').html('<span style="color:red">'+text +' </span>');
}
});
try this:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
return true;
}
}
if (verifyPwd()==true){
addNewUser();
}
else {
// passwords do not match
}
You can make a template of templates too, and reach private variable.
var a= {e:10, gy:'sfdsad'}; //global object
console.log(`e is ${a.e} and gy is ${a.gy}`);
//e is 10 and gy is sfdsad
var b = "e is ${a.e} and gy is ${a.gy}" // template string
console.log( `${b}` );
//e is ${a.e} and gy is ${a.gy}
console.log( eval(`\`${b}\``) ); // convert template string to template
//e is 10 and gy is sfdsad
backtick( b ); // use fonction's variable
//e is 20 and gy is fghj
function backtick( temp ) {
var a= {e:20, gy:'fghj'}; // local object
console.log( eval(`\`${temp}\``) );
}
isEmpty()
Returns true if this list contains no elements.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/List.html
You can try this:
const union = (a, b) => Array.from(new Set([...a, ...b]));_x000D_
_x000D_
console.log(union(["neymar","messi"], ["ronaldo","neymar"]));
_x000D_
Try this instead:
(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));
@AHegde - To get the tab delimited output use separator sep='\t'.
For df.to_csv:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')
For np.savetxt:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')
With Swift 5 and iOS 12, try the following implementation of textField(_:shouldChangeCharactersIn:replacementString:)
method that is part of the UITextFieldDelegate
protocol:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10
}
range
(NSRange
) to rangeOfTextToReplace
(Range<String.Index>
). See this video tutorial to understand why this conversion is important.textField
's smartInsertDeleteType
value to UITextSmartInsertDeleteType.no
. This will prevent the possible insertion of an (unwanted) extra space when performing a paste operation.The complete sample code below shows how to implement textField(_:shouldChangeCharactersIn:replacementString:)
in a UIViewController
:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField! // Link this to a UITextField in Storyboard
override func viewDidLoad() {
super.viewDidLoad()
textField.smartInsertDeleteType = UITextSmartInsertDeleteType.no
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10
}
}
I know this is old but...
I found this:
http://javaforge.com/project/schemasel
From the description, after you install the plugin it appears that if you follow the logical connection name with a schema in square brackets, it should connect to the schema by default.
It does but the object browser does not.
Oh well.
Your solution is nearly correct. You could add DISTINCT:
SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN orders ON (orders.pe_id = people.pe_id)
INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
people.pe_id;
Will result always be the floor of the division? What is the defined behavior?
Not quite. It rounds toward 0, rather than flooring.
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
and the corresponding footnote:
- This is often called ‘‘truncation toward zero’’.
Of course two points to note are:
3 The usual arithmetic conversions are performed on the operands.
and:
5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
[Note: Emphasis mine]
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
Try Skyscreamer's JSONAssert.
Its non-strict mode has two major advantages that make it less brittle:
In strict mode it behaves more like json-lib's test class.
A test looks something like this:
@Test
public void testGetFriends() {
JSONObject data = getRESTData("/friends/367.json");
String expected = "{friends:[{id:123,name:\"Corby Page\"}"
+ ",{id:456,name:\"Solomon Duskis\"}]}";
JSONAssert.assertEquals(expected, data, false);
}
The parameters in the JSONAssert.assertEquals() call are expectedJSONString, actualDataString, and isStrict.
The result messages are pretty clear, which is important when comparing really big JSON objects.
Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).
So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.
I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException
can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.
Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.
using System.Collections.Generic;
using System.Linq;
namespace YourProject.Extensions
{
public static class ListExtensions
{
public static bool SetwiseEquivalentTo<T>(this List<T> list, List<T> other)
where T: IEquatable<T>
{
if (list.Except(other).Any())
return false;
if (other.Except(list).Any())
return false;
return true;
}
}
}
Sometimes you only need to know if two lists are different, and not what those differences are. In that case, consider adding this extension method to your project. Note that your listed objects should implement IEquatable!
Usage:
public sealed class Car : IEquatable<Car>
{
public Price Price { get; }
public List<Component> Components { get; }
...
public override bool Equals(object obj)
=> obj is Car other && Equals(other);
public bool Equals(Car other)
=> Price == other.Price
&& Components.SetwiseEquivalentTo(other.Components);
public override int GetHashCode()
=> Components.Aggregate(
Price.GetHashCode(),
(code, next) => code ^ next.GetHashCode()); // Bitwise XOR
}
Whatever the Component
class is, the methods shown here for Car
should be implemented almost identically.
It's very important to note how we've written GetHashCode. In order to properly implement IEquatable
, Equals
and GetHashCode
must operate on the instance's properties in a logically compatible way.
Two lists with the same contents are still different objects, and will produce different hash codes. Since we want these two lists to be treated as equal, we must let GetHashCode
produce the same value for each of them. We can accomplish this by delegating the hashcode to every element in the list, and using the standard bitwise XOR to combine them all. XOR is order-agnostic, so it doesn't matter if the lists are sorted differently. It only matters that they contain nothing but equivalent members.
Note: the strange name is to imply the fact that the method does not consider the order of the elements in the list. If you do care about the order of the elements in the list, this method is not for you!
The same happened for me with eslint
module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression
for await in second if statement.
if (condition_one) {
let result = await myFunction()
}
if (condition_two) {
let result = await myFunction() // eslint parsing error
}
As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.
if (condition_one) {
let result = await myFunction();
}
if (condition_two) {
let result = await myFunction();
}
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
It dipends on which distribution you are in general but... You have to install the php-curl module and then enable it on php.ini like you did in windows. Once you are done remember to restart apache demon!
Or... in shell...
service mysql restart
Yeah, I know, I'm lazy, but it can be handy too.
There is a Rails inbuilt method called 'underscore' that you can use for this purpose
"CamelCaseString".underscore #=> "camel_case_string"
The 'underscore' method can typically be considered as inverse of 'camelize'
To call ruby file use : ruby your_program.rb
To execute your ruby file as script:
start your program with #!/usr/bin/env ruby
run that script using ./your_program.rb param
Use text-center
instead of center-block
.
Or use center-block
on the span element (I did the column wider so you can see the alignment better):
<div class="row">
<div class="col-xs-10" style="background-color:#123;">
<span class="center-block" style="width:100px; background-color:#ccc;">abc</span>
</div>
</div>
Consider if instead it was:
class RectangularRoom(object):
def __init__(self, width, height):
pass
def cleanTileAtPosition(self, pos):
pass
def isTileCleaned(self, m, n):
pass
and you subclass and forget to tell it how to isTileCleaned()
or, perhaps more likely, typo it as isTileCLeaned()
. Then in your code, you'll get a None
when you call it.
None
valid output? Who knows. raise NotImplmentedError
forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.
Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).
To solve the OP problem without breaking the MVVM, I would use custom value converter and a wrapper for the value (the password) that has to be retrieved from the password box.
public interface IWrappedParameter<T>
{
T Value { get; }
}
public class PasswordBoxWrapper : IWrappedParameter<string>
{
private readonly PasswordBox _source;
public string Value
{
get { return _source != null ? _source.Password : string.Empty; }
}
public PasswordBoxWrapper(PasswordBox source)
{
_source = source;
}
}
public class PasswordBoxConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Implement type and value check here...
return new PasswordBoxWrapper((PasswordBox)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("No conversion.");
}
}
In the view model:
public string Username { get; set; }
public ICommand LoginCommand
{
get
{
return new RelayCommand<IWrappedParameter<string>>(password => { Login(Username, password); });
}
}
private void Login(string username, string password)
{
// Perform login here...
}
Because the view model uses IWrappedParameter<T>
, it does not need to have any knowledge about PasswordBoxWrapper
nor PasswordBoxConverter
. This way you can isolate the PasswordBox
object from the view model and not break the MVVM pattern.
In the view:
<Window.Resources>
<h:PasswordBoxConverter x:Key="PwdConverter" />
</Window.Resources>
...
<PasswordBox Name="PwdBox" />
<Button Content="Login" Command="{Binding LoginCommand}"
CommandParameter="{Binding ElementName=PwdBox, Converter={StaticResource PwdConverter}}" />
I was having a similar error, it seems that the compiler misunderstand the call to the constructor without arguments. I made it work by removing the parenthesis from the variable declaration, in your code something like this:
class Foo
{
public:
Foo() {};
Foo(int a) {};
void bar() {};
};
int main()
{
// this works...
Foo foo1(1);
foo1.bar();
// this does not...
Foo foo2; // Without "()"
foo2.bar();
return 0;
}
For Rails 4.x the log level is configured a bit different than in Rails 3.x
Add this to config/environment/test.rb
# Enable stdout logger
config.logger = Logger.new(STDOUT)
# Set log level
config.log_level = :ERROR
The logger level is set on the logger instance from config.log_level
at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70
Environment variable
As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:
# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")
And then running tests from shell:
# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test
# Log level :ERROR
$ rake test
in api 26 with build.gradle 3.0.0 and higher you can create a font directory in res and use this line in your style
<item name="android:fontFamily">@font/your_font</item>
for change build.gradle use this in your build.gradle dependecies
classpath 'com.android.tools.build:gradle:3.0.0'
If you are behind a proxy, you can set the proxies in java program as below:
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("https.proxyHost", "https proxy of your org");
systemSettings.put("https.proxyPort", "8080");
If you are not behind a proxy, don't include the lines above in your code. Full working code to download a file when you are behind a proxy.
public static void main(String[] args) throws IOException {
String url="https://raw.githubusercontent.com/bpjoshi/fxservice/master/src/test/java/com/bpjoshi/fxservice/api/TradeControllerTest.java";
OutputStream outStream=null;
URLConnection connection=null;
InputStream is=null;
File targetFile=null;
URL server=null;
//Setting up proxies
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("https.proxyHost", "https proxy of my organisation");
systemSettings.put("https.proxyPort", "8080");
//The same way we could also set proxy for http
System.setProperty("java.net.useSystemProxies", "true");
//code to fetch file
try {
server=new URL(url);
connection = server.openConnection();
is = connection.getInputStream();
byte[] buffer = new byte[is.available()];
is.read(buffer);
targetFile = new File("src/main/resources/targetFile.java");
outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
} catch (MalformedURLException e) {
System.out.println("THE URL IS NOT CORRECT ");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Io exception");
e.printStackTrace();
}
finally{
if(outStream!=null) outStream.close();
}
}
If you have no changes, you can always be really thorough and/or lazy and do...
rm -rf *
svn update
But, no really, do not do that unless you are really sure that the nuke-from-space option is what you want!! This has the advantage of also nuking all build cruft, temporary files, and things that SVN ignores.
The more correct solution is to use the revert command:
svn revert -R .
The -R causes subversion to recurse and revert everything in and below the current working directory.
Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.
The configuration and the access to the Connection string looks all right to me. I would always add a providername
<connectionStrings>
<add name="Dbconnection"
connectionString="Server=localhost; Database=OnlineShopping;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
You could try to force the browser to open a "Save As..." dialog by doing something like:
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";
Which should work across most major browsers.
The solutions here are old and now deprecated: https://github.com/uuidjs/uuid#deep-requires-now-deprecated
Use this:
npm install uuid
//add these lines to your code
const { v4: uuidv4 } = require('uuid');
var your_uuid = uuidv4();
console.log(your_uuid);