As @stevebot said, do this:
https://<bucket-name>.s3.amazonaws.com/<key>
The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.
Actually it is really easy. The problem is understanding that once passing classic arguments, you are scoped into another, read-only zone.
The solution is to pass the arguments using JavaScript's object-oriented design. It is the same as putting the arguments in a global/scoped variable, but better...
function action(){
/* Process this.arg, modification allowed */
}
action.arg = [["empty-array"], "some string", 0x100, "last argument"];
action();
You can also promise stuff up to enjoy the well-known chain: Here is the whole thing, with promise-like structure
function action(){
/* Process this.arg, modification allowed */
this.arg = ["a", "b"];
}
action.setArg = function(){this.arg = arguments; return this;}
action.setArg(["empty-array"], "some string", 0x100, "last argument")()
Or better yet...
action.setArg(["empty-array"],"some string",0x100,"last argument").call()
As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.
new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1
Simply add static
in the declaration of these two methods and the compile time error will disappear!
By default in C# methods are instance methods, and they receive the implicit "self" argument. By making them static, no such argument is needed (nor available), and the method must then of course refrain from accessing any instance (non-static) objects or methods of the class.
More info on static methods
Provided the class and the method's access modifiers (public vs. private) are ok, a static method can then be called from anywhere without having to previously instantiate a instance of the class. In other words static methods are used with the following syntax:
className.classMethod(arguments)
rather than
someInstanceVariable.classMethod(arguments)
A classical example of static methods are found in the System.Math class, whereby we can call a bunch of these methods like
Math.Sqrt(2)
Math.Cos(Math.PI)
without ever instantiating a "Math" class (in fact I don't even know if such an instance is possible)
You can do this with map()
var arrOfObj = [{_x000D_
name: 'eve'_x000D_
}, {_x000D_
name: 'john'_x000D_
}, {_x000D_
name: 'jane'_x000D_
}];_x000D_
_x000D_
var result = arrOfObj.map(function(o) {_x000D_
o.isActive = true;_x000D_
return o;_x000D_
})_x000D_
_x000D_
console.log(result)
_x000D_
If you want to keep original array you can clone objects with Object.assign()
var arrOfObj = [{_x000D_
name: 'eve'_x000D_
}, {_x000D_
name: 'john'_x000D_
}, {_x000D_
name: 'jane'_x000D_
}];_x000D_
_x000D_
var result = arrOfObj.map(function(el) {_x000D_
var o = Object.assign({}, el);_x000D_
o.isActive = true;_x000D_
return o;_x000D_
})_x000D_
_x000D_
console.log(arrOfObj);_x000D_
console.log(result);
_x000D_
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
<link rel="shortcut icon" type="image/ico" href="/favicon.ico"/>
<link rel="shortcut icon" type="image/ico" href="http://example.com/favicon.ico"/>
<link rel="shortcut icon" type="image/png" href="/favicon.png"/>
<link rel="shortcut icon" type="image/png" href="http://example.com/favicon.png"/>
A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There are three different ways where Pointer acts as dangling pointer.
- De-allocation of memory
- Function Call
- Variable goes out of scope
—— from https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/
I've found Waldo!
How I've done it
First, I'm filtering out all colours that aren't red
waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];
Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.
corr = ImageCorrelate[red,
Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]],
NormalizedSquaredEuclideanDistance];
I use Binarize
to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation
pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];
I had to play around a little with the level. If the level is too high, too many false positives are picked out.
Finally I'm combining this result with the original image to get the result above
found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]
I had the same problem, tnsnames.ora
worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.
It turns out that the database was caching backup copies of tnsnames.ora
like tnsnames.ora.bk2
, tnsnames09042811AM4501.bak
, tnsnames.ora.bk
etc. These files were not readable by the average user.
I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.
The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.
Compatibility Supports Says that
Under compatibility level 110, the default style for CAST and CONVERT
operations on time
and datetime2
data types is always 121. If your query relies on the old behavior, use a compatibility level less than 110, or explicitly specify the 0 style in the affected query.
That means by default datetime2
is CAST as varchar
to 121 format
. For ex; col1
and col2
formats (below) are same (other than the 0s at the end)
SELECT CONVERT(varchar, GETDATE(), 121) col1,
CAST(convert(datetime2,GETDATE()) as varchar) col2,
CAST(GETDATE() as varchar) col3
--Results
COL1 | COL2 | COL3
2013-02-08 09:53:56.223 | 2013-02-08 09:53:56.2230000 | Feb 8 2013 9:53AM
FYI, if you use CONVERT
instead of CAST
you can use a third parameter to specify certain formats as listed here on MSDN
Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.
Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");
Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;
Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);
Your Java application now has a drop-down date selection dialog.
Inside relative path tag do as follows
<relative>{project_name}/pom.xml</relative>
and then RunAs-> Maven build
It worked for me.
I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.
May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and all these files are on your hard drive?
In that case I see no contra to store such a content in STATIC.
And all becomes really simple:
static
To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you're using RequestContext or not.
{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />
copied from Official django 1.4 documentation / Built-in template tags and filters
The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the .length
of the collection returned by the selector or check whether the first array element is 'undefined'.
You can use any the following examples inside an IF statement and they all produce the same result. True, if the selector found a matching element, false otherwise.
$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
The cherry-pick command can read the list of commits from the standard input.
The following command cherry-picks commits authored by the user John that exist in the "develop" branch but not in the "release" branch, and does so in the chronological order.
git log develop --not release --format=%H --reverse --author John | git cherry-pick --stdin
A copy of System.Management.Automation.dll is installed when you install the windows SDK (a suitable, recent version of it, anyway). It should be in C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\
Heres a nice circle example:
drawable/circle.xml
:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#ff87cefa"/>
<size
android:width="60dp"
android:height="60dp"/>
</shape>
And then the button in your xml file:
<Button
android:id="@+id/btn_send"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@drawable/circle"
android:text="OK"/>
It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).
The solution is to write a generic operator<<
function which will work for any scoped enum. The solution employs SFINAE via std::enable_if
and is as follows.
#include <iostream>
#include <type_traits>
// Scoped enum
enum class Color
{
Red,
Green,
Blue
};
// Unscoped enum
enum Orientation
{
Horizontal,
Vertical
};
// Another scoped enum
enum class ExecStatus
{
Idle,
Started,
Running
};
template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
return stream << static_cast<typename std::underlying_type<T>::type>(e);
}
int main()
{
std::cout << Color::Blue << "\n";
std::cout << Vertical << "\n";
std::cout << ExecStatus::Running << "\n";
return 0;
}
No, a view consists of a single SELECT
statement. You cannot create or drop tables in a view.
Maybe a common table expression (CTE) can solve your problem. CTEs are temporary result sets that are defined within the execution scope of a single statement and they can be used in views.
Example (taken from here) - you can think of the SalesBySalesPerson
CTE as a temporary table:
CREATE VIEW vSalesStaffQuickStats
AS
WITH SalesBySalesPerson (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS
(
SELECT SalesPersonID, COUNT(*), MAX(OrderDate)
FROM Sales.SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT E.EmployeeID,
EmployeeOrders = OS.NumberOfOrders,
EmployeeLastOrderDate = OS.MostRecentOrderDate,
E.ManagerID,
ManagerOrders = OM.NumberOfOrders,
ManagerLastOrderDate = OM.MostRecentOrderDate
FROM HumanResources.Employee AS E
INNER JOIN SalesBySalesPerson AS OS ON E.EmployeeID = OS.SalesPersonID
LEFT JOIN SalesBySalesPerson AS OM ON E.ManagerID = OM.SalesPersonID
GO
ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`)
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
First of all, you really should be including the position on absolutely positioned elements or you will come across odd and confusing behavior; you probably want to add top: 0; left: 0
to the CSS for both of your absolutely positioned elements. You'll also want to have position: relative
on .container_row
if you want the absolutely positioned elements to be positioned with respect to their parent rather than the document's body:
If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed' ...
Your problem is that position: absolute
removes elements from the normal flow:
It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants. However, the contents of an absolutely positioned element do not flow around any other boxes.
This means that absolutely positioned elements have no effect whatsoever on their parent element's size and your first <div class="container_row">
will have a height of zero.
So you can't do what you're trying to do with absolutely positioned elements unless you know how tall they're going to be (or, equivalently, you can specify their height). If you can specify the heights then you can put the same heights on the .container_row
and everything will line up; you could also put a margin-top
on the second .container_row
to leave room for the absolutely positioned elements. For example:
This YouTube video by Fabio Scopel explains how to debug a Windows service quite nicely... the actual method of doing it starts at 4:45 in the video...
Here is the code explained in the video... in your Program.cs file, add the stuff for the Debug section...
namespace YourNamespace
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
}
In your Service1.cs file, add the OnDebug() method...
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
// your code to do something
}
protected override void OnStop()
{
}
How it works
Basically you have to create a public void OnDebug()
that calls the OnStart(string[] args)
as it's protected and not accessible outside. The void Main()
program is added with #if
preprocessor with #DEBUG
.
Visual Studio defines DEBUG
if project is compiled in Debug mode.This will allow the debug section(below) to execute when the condition is true
Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
And it will run just like a console application, once things go OK you can change the mode Release
and the regular else
section will trigger the logic
When a float
is passed to printf
, it is automatically converted to a double
. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...
), largely for historical reasons. Therefore, the “natural” specifier for a float
, %f
, must work with a double
argument. So the %f
and %lf
specifiers for printf
are the same; they both take a double
value.
When scanf
is called, pointers are passed, not direct values. A pointer to float
is not converted to a pointer to double
(this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf
, the argument for %f
must be a pointer to float
, and the argument for %lf
must be a pointer to double
.
Another option I have working, in a linux server with Postfix:
First, configure CI email to use your server's email system: eg, in email.php
, for example
# alias to postfix in a typical Postfix server
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
Then configure your postfix to relay the mail to google (perhaps depending on the sender address). You'll probably need to put you user-password settings in /etc/postfix/sasl_passwd
(docs)
This is much simpler (and less fragmente) if you have a linux box, already configured to send some/all of its outgoing emails to Google.
TL;DR:
The ActionListener
s (there can be multiple) execute in the order they were registered BEFORE the action
Long Answer:
A business action
typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view
if that is not what you are doing an actionListener
is more appropriate i.e. for when the user interacts with the components, such as h:commandButton
or h:link
they can be handled by passing the name of the managed bean method in actionListener
attribute of a UI Component or to implement an ActionListener
interface and pass the implementation class name to actionListener
attribute of a UI Component.
You may have made some new commits in the detached HEAD
state. I believe if you do as other answers advise:
git checkout master
# or
git checkout -
then you may lose your commits!! Instead, you may want to do this:
# you are currently in detached HEAD state
git checkout -b commits-from-detached-head
and then merge commits-from-detached-head
into whatever branch you want, so you don't lose the commits.
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"
In a single statement it would be.
echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
In Bluetooth, all objects are identified by UUIDs. These include services, characteristics and many other things. Bluetooth maintains a database of assigned numbers for standard objects, and assigns sub-ranges for vendors (that have paid enough for a reservation). You can view this list here:
https://www.bluetooth.com/specifications/assigned-numbers/
If you are implementing a standard service (e.g. a serial port, keyboard, headset, etc.) then you should use that service's standard UUID - that will allow you to be interoperable with devices that you didn't develop.
If you are implementing a custom service, then you should generate unique UUIDs, in order to make sure incompatible third-party devices don't try to use your service thinking it is something else. The easiest way is to generate random ones and then hard-code the result in your application (and use the same UUIDs in the devices that will connect to your service, of course).
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
Try using itertools.count([n])
We can set font as per our requirement like,
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.font = UIFont.boldSystemFontOfSize(15)
label.font = UIFont.italicSystemFontOfSize(15)
label.font = UIFont.systemFontOfSize(17)
note that the span & group are indexed for multi capture groups in a regex
regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
for idx in range(0, 4):
print(match.span(idx), match.group(idx))
Its also possible with a simple for
loop:
const result = {};
for(const {make, model, year} of cars) {
if(!result[make]) result[make] = [];
result[make].push({ model, year });
}
The -std=c++14
flag is not supported on GCC 4.8. If you want to use C++14 features you need to compile with -std=c++1y
. Using godbolt.org it appears that the earilest version to support -std=c++14
is GCC 4.9.0 or Clang 3.5.0
You can get the name value from an input field using name element in jQuery by:
var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD_x000D_
var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ _x000D_
console.log(firstname);_x000D_
console.log(lastname);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name="form1" id="form1">_x000D_
<input type="text" name="firstname" value="ABCD"/>_x000D_
<input type="text" name="lastname" value="XYZ"/>_x000D_
</form>
_x000D_
Additional tip for the programmatic approach:
String filePath = Environment.getExternalStorageDirectory() + "/logcat.txt";
Runtime.getRuntime().exec(new String[]{"logcat", "-f", filepath, "MyAppTAG:V", "*:S"});
This opens a continuous output stream between logcat and the file provided. This can result in a deadlock if you then waitFor the Process returned by exec, or an exception if the provided file is prematurely disposed.
I found that including the "-d" flag simply dumps logcat and closes the connection, which prevents the above behavior.
Select the platform to be iPhone Simulator then click Build and Go. If it builds correctly then it will launch the simulator and run. If it does not build ok then it will indicate errors at the bottom of the window on the right hand side.
If you only have the app file then you would need to manually install that into the simulator. The simulator was not designed to be used this way, but I'm sure it would be possible, even if it was incredibly difficult.
If you have the source code (.proj .m .h etc) files then it should be a simple case of build and go.
In the following scenario, we can't use new since it calls constructor.
class B {
private:
B *ptr;
int x;
public:
B(int n) {
cout<<"B: ctr"<<endl;
//ptr = new B; //keep calling ctr, result is segmentation fault
ptr = (B *)malloc(sizeof(B));
x = n;
ptr->x = n + 10;
}
~B() {
//delete ptr;
free(ptr);
cout<<"B: dtr"<<endl;
}
};
I faced similar issues:
I faced this issue in a directive, i fixed it adding a as its parent element and making pointer-events:none for that
The above fix did not work for select tag, then i added cursor:text (which was what i wanted) and it worked for me
If a normal cursor is needed you could add cursor:default
you should be searching about how to add favicon.ico
. You can try adding favicon.ico
directly in your html pages like this
<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />
Or you can update that in your webserver
. It is advised to add in your webserver
as you don't need to add this in each of your html
pages (assuming no includes
).
To add in your apache
place the favicon.ico
in your root website director and add this in httpd.conf
AddType image/x-icon .ico
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
This topic is well covered but I still would like to propose another approach in a slightly different philosophy.
It is a bit more complex to set-up but it allow (in my opinion) a bit more flexibility. For example, one can play with the respective ratios of each subplots / colorbar:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
# Define number of rows and columns you want in your figure
nrow = 2
ncol = 3
# Make a new figure
fig = plt.figure(constrained_layout=True)
# Design your figure properties
widths = [3,4,5,1]
gs = GridSpec(nrow, ncol + 1, figure=fig, width_ratios=widths)
# Fill your figure with desired plots
axes = []
for i in range(nrow):
for j in range(ncol):
axes.append(fig.add_subplot(gs[i, j]))
im = axes[-1].pcolormesh(np.random.random((10,10)))
# Shared colorbar
axes.append(fig.add_subplot(gs[:, ncol]))
fig.colorbar(im, cax=axes[-1])
plt.show()
In Java, the optimizations are usually done at the JVM level. At runtime, the JVM perform some "complicated" analysis to determine which methods to inline. It can be aggressive in inlining, and the Hotspot JVM actually can inline non-final methods.
The java compilers almost never inline any method call (the JVM does all of that at runtime). They do inline compile time constants (e.g. final static primitive values). But not methods.
For more resources:
Article: The Java HotSpot Performance Engine: Method Inlining Example
Wiki: Inlining in OpenJDK, not fully populated but contains links to useful discussions.
I suggest using Hits's answer, but adding a Locale format, this is how Android Developers recommends:
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
return dateFormat.format(new Date()); // Find todays date
} catch (Exception e) {
e.printStackTrace();
return null;
}
Maybe you're not using the latest version of a JSON for Java Library.
json-simple
has not been updated for a long time, while JSON-Java
was updated 2 month ago.
JSON-Java
can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java
After switching the library, you can refer to my sample code down below:
public static void main(String[] args) {
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
Object level = getSth.get("2");
System.out.println(level);
}
And as JSON-Java
open-sourced, you can read the code and its document, they will guide you through.
Hope that it helps.
I had a similar question, so I worked up a complete runnable answer below. What I needed to do is pass a class (C) to an object (O) of an unrelated class and have that object (O) emit new objects of class (C) back to me when I asked for them.
The example below shows how this is done. There is a MagicGun class that you load with any subtype of the Projectile class (Pebble, Bullet or NuclearMissle). The interesting is you load it with subtypes of Projectile, but not actual objects of that type. The MagicGun creates the actual object when it's time to shoot.
You've annoyed the target!
You've holed the target!
You've obliterated the target!
click
click
import java.util.ArrayList;
import java.util.List;
public class PassAClass {
public static void main(String[] args) {
MagicGun gun = new MagicGun();
gun.loadWith(Pebble.class);
gun.loadWith(Bullet.class);
gun.loadWith(NuclearMissle.class);
//gun.loadWith(Object.class); // Won't compile -- Object is not a Projectile
for(int i=0; i<5; i++){
try {
String effect = gun.shoot().effectOnTarget();
System.out.printf("You've %s the target!\n", effect);
} catch (GunIsEmptyException e) {
System.err.printf("click\n");
}
}
}
}
class MagicGun {
/**
* projectiles holds a list of classes that extend Projectile. Because of erasure, it
* can't hold be a List<? extends Projectile> so we need the SuppressWarning. However
* the only way to add to it is the "loadWith" method which makes it typesafe.
*/
private @SuppressWarnings("rawtypes") List<Class> projectiles = new ArrayList<Class>();
/**
* Load the MagicGun with a new Projectile class.
* @param projectileClass The class of the Projectile to create when it's time to shoot.
*/
public void loadWith(Class<? extends Projectile> projectileClass){
projectiles.add(projectileClass);
}
/**
* Shoot the MagicGun with the next Projectile. Projectiles are shot First In First Out.
* @return A newly created Projectile object.
* @throws GunIsEmptyException
*/
public Projectile shoot() throws GunIsEmptyException{
if (projectiles.isEmpty())
throw new GunIsEmptyException();
Projectile projectile = null;
// We know it must be a Projectile, so the SuppressWarnings is OK
@SuppressWarnings("unchecked") Class<? extends Projectile> projectileClass = projectiles.get(0);
projectiles.remove(0);
try{
// http://www.java2s.com/Code/Java/Language-Basics/ObjectReflectioncreatenewinstance.htm
projectile = projectileClass.newInstance();
} catch (InstantiationException e) {
System.err.println(e);
} catch (IllegalAccessException e) {
System.err.println(e);
}
return projectile;
}
}
abstract class Projectile {
public abstract String effectOnTarget();
}
class Pebble extends Projectile {
@Override public String effectOnTarget() {
return "annoyed";
}
}
class Bullet extends Projectile {
@Override public String effectOnTarget() {
return "holed";
}
}
class NuclearMissle extends Projectile {
@Override public String effectOnTarget() {
return "obliterated";
}
}
class GunIsEmptyException extends Exception {
private static final long serialVersionUID = 4574971294051632635L;
}
You don't need to change port number for your application, just configure your www server (nginx or apache) to proxy queries to flask port. Pay attantion on uWSGI
.
Short answer:
Going by the answer given here. You can have two applications listening on the same IP address, and port number, so long one of the port is a UDP port, while other is a TCP port.
Explanation:
The concept of port is relevant on the transport layer of the TCP/IP stack, thus as long as you are using different transport layer protocols of the stack, you can have multiple processes listening on the same <ip-address>:<port>
combination.
One doubt that people have is if two applications are running on the same <ip-address>:<port>
combination, how will a client running on a remote machine distinguish between the two? If you look at the IP layer packet header (https://en.wikipedia.org/wiki/IPv4#Header), you will see that bits 72 to 79 are used for defining protocol, this is how the distinction can be made.
If however you want to have two applications on same TCP <ip-address>:<port>
combination, then the answer is no (An interesting exercise will be launch two VMs, give them same IP address, but different MAC addresses, and see what happens - you will notice that some times VM1 will get packets, and other times VM2 will get packets - depending on ARP cache refresh).
I feel that by making two applications run on the same <op-address>:<port>
you want to achieve some kind of load balancing. For this you can run the applications on different ports, and write IP table rules to bifurcate the traffic between them.
Also see @user6169806's answer.
You can use run-as
shell command to access private application data.
If you only want to copy database you can use this snippet, provided in https://stackoverflow.com/a/31504263/998157
adb -d shell "run-as com.example.test cat /data/data/com.example.test/databases/data.db" > data.db
new Thing();
is explicit that you want a constructor called whereas new Thing;
is taken to imply you don't mind if the constructor isn't called.
If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };
) then new Thing;
is like malloc(sizeof(Thing));
whereas new Thing();
is like calloc(sizeof(Thing));
- it gets zero initialized.
The gotcha lies in-between:
struct Thingy {
~Thingy(); // No-longer a trivial class
virtual WaxOn();
int i;
};
The behavior of new Thingy;
vs new Thingy();
in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.
Have you considered List.BinarySearch(item)
?
You said that your large collection is already sorted so this seems like the perfect opportunity? A hash would definitely be the fastest, but this brings about its own problems and requires a lot more overhead for storage.
You can do almost everything from a utility provided as part of WAMPServer.
Create a folder inside to contain your project.site. This can be under the C:\wamp\www\
directory or in a completely seperate folder like C:\websites
.
Create a folder inside the location you have chosen EG C:\websites\project1\www
or under the c:\wamp\www\project1\www
Now open localhost wampmanager->localhost
and click on the link Add a Virtual Host
under the TOOLS section on the homepage.
You will see a page like this:
Fill in the fields as specified by the instructions above each field
The Virtual Host config will have been created for you.
Now you must restart the DNS Cache. You can do this from the wampmanager menus like this right click wampmanager->Tools->Restart DNS
. The DNS Cache will be restarted and then Apache will also be stopped and restarted. When the wampmanager icon goes green again all is completed.
Now you must create a simple index.php
file or install your site into the folder you created above.
Assuming your VH was called project.dev
You should see that name under the Your Virtual Hosts Section of the WAMPServer homepage.
You can launch the site from this menu, or just use the new Domain Name in the address bar EG project1.dev
and the site shoudl launch.
There has been a change of concept in WampServer 2.5 and above and there is a good reason for this change!
In WampServer it is now STRONGLY encouraged to create a Virtual Host for each of your projects, even if you hold them in a \wamp\www\subfolder
structure.
The WampServer home page ( \wamp\www\index.php
) now expects you to have created a Virtual Host for all your projects and will therefore work properly only if you do so.
History
In order to make life easier for beginners using WampServer to learn PHP Apache and MySQL it was suggested that you create subfolders under the \wamp\www\
folder.
wamp
|-- www
|-- Chapter1
|-- Chapter2
|-- etc
These subfolders would then show as links in the WampServer Homepage under a menu called 'Your Projects' and these links would contain a link to localhost/subfoldername
.
Acceptable only for simple tutorials
This made life easy for the complete beginner, and was perfectly acceptable for example for those following tutorials to learn PHP coding. However it was never intended for use when developing a real web site that you would later want to copy to your live hosted server. In fact if you did use this mechanism it often caused problems as the live sites configuration would not match your development configuration.
The Problem for real website development.
The reason for this is of course that the default DocumentRoot setting for wamp is
DocumentRoot "c:/wamp/www/"
regardless of what your subfolder was called. This ment that often used PHP code that queried the structure or your site received different information when running on your development WampServer to what it would receive when running on a live hosted server, where the DocumentRoot configuration points to the folder at the top of the website file hierarchy. This kind of code exists in many frameworks and CMS's for example WordPress and Joomla etc.
For Example
Lets say we have a project called project1 held in wamp\www\project1
and run incorrectly as localhost/project1/index.php
This is what would be reported by some of the PHP command in question:
$_SERVER['HTTP_HOST'] = localhost
$_SERVER['SERVER_NAME'] = localhost
$_SERVER['DOCUMENT_ROOT'] = c:/wamp/www
Now if we had correctly defined that site using a Virtual Host definition and ran it as http://project1
the results on the WAMPServer devlopment site will match those received when on a live hosted environment.
$_SERVER['HTTP_HOST'] = project1
$_SERVER['SERVER_NAME'] = project1
$_SERVER['DOCUMENT_ROOT'] = c:/wamp/www/project1
Now this difference may seem trivial at first but if you were to use a framework like WordPress or one of the CMS's like Joomla for example, this can and does cause problems when you move your site to a live server.
Actually this should work basically the same for any wndows Apache server, with differences only in where you may find the Apache config files.
There are 3 steps to create your first Virtual Host in Apache, and only 2 if you already have one defined.
Step 1, Create the Virtual Host definition(s)
Edit the file called httpd-hosts.conf
which for WampServer lives in
\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf
(Apache version numbers may differ, engage brain before continuing)
If this is the first time you edit this file, remove the default example code, it is of no use.
I am assuming we want to create a definition for a site called project1 that lives in
\wamp\www\project1
Very important, first we must make sure that localhost still works so that is the first VHOST definition we will put in this file.
<VirtualHost *:80>
DocumentRoot "c:/wamp/www"
ServerName localhost
ServerAlias localhost
<Directory "c:/wamp/www">
Options Indexes FollowSymLinks
AllowOverride All
Require local
</Directory>
</VirtualHost>
Now we define our project: and this of course you do for each of your projects as you start a new one.
<VirtualHost *:80>
DocumentRoot "c:/wamp/www/project1"
ServerName project1
<Directory "c:/wamp/www/project1">
Options Indexes FollowSymLinks
AllowOverride All
Require local
</Directory>
</VirtualHost>
NOTE: That each Virtual Host as its own DocumentRoot
defined. There are also many other parameters you can add to a Virtual Hosts definition, check the Apache documentation.
Small aside
The way virtual hosts work in Apache: The first definition in this file will also be the default site, so should the domain name used in the browser not match any actually defined virtually hosted domain, making localhost the first domain in the file will therefore make it the site that is loaded if a hack attempt just uses your IP Address. So if we ensure that the Apache security for this domain is ALWAYS SET TO
Require local
any casual hack from an external address will receive an error and not get into your PC, but should you misspell a domain you will be shown the WampServer homepage, because you are on the same PC as WampServer and therfore local
.
Step 2:
Add your new domain name to the HOSTS file. Now we need to add the domain name that we have used in the Virtual Host definition to the HOSTS file so that windows knows where to find it. This is similiar to creating a DNS A record, but it is only visible in this case on this specific PC.
Edit C:\windows\system32\drivers\etc\hosts
The file has no extension and should remain that way. Watch out for notepad, as it may try and add a .txt
extension if you have no better editor.
I suggest you download Notepad++, its free and a very good editor.
Also this is a protected file so you must edit it with administrator privileges, so launch you editor using the Run as Administrator menu option.
The hosts file should look like this when you have completed these edits
127.0.0.1 localhost
127.0.0.1 project1
::1 localhost
::1 project1
Note that you should have definitions in here for the IPV4 loopback address 127.0.0.1
and also the IPV6 loopback address ::1
as Apache is now IPV6 aware and the browser will use either IPV4 or IPV6 or both. I have no idea how it decides which to use, but it can use either if you have the IPV6 stack turned on, and most window OS's do as of XP SP3.
Now we must tell windows to refresh its domain name cache, so launch a command window again using the Run as Administrator menu option again, and do the following.
net stop dnscache
net start dnscache
This forces windows to clear its domain name cache and reload it, in reloading it will re-read the HOSTS file so now it knows about the domain project1
.
Step 3: Uncomment the line in httpd.conf that includes the Virtual Hosts definition file.
Edit your httpd.conf, use the wampmanager.exe menus to make sure you edit the correct file.
Find this line in httpd.conf
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
And just remove the #
to uncomment that line.
To activate this change in you running Apache we must now stop and restart the Apache service.
wampmanager.exe -> Apache -> Service -> Restart Service
Now if the WAMP icon in the system tray does not go GREEN again, it means you have probably done something wrong in the \wamp\bin\apache\apache2.4.9\conf\extra\httpd-hosts.conf
file.
If so here is a useful mechanism to find out what is wrong. It uses a feature of the Apache exe (httpd.exe) to check its config files and report errors by filename and line numbers.
Launch a command window.
cd \wamp\bin\apache\apache2.4.9\bin
httpd -t
So fix the errors and retest again until you get the output
Syntax OK
Now there is one more thing.
There are actually 2 new menu items on the wampmanager menu system. One called 'My Projects' which is turned on by default. And a second one, called 'My Virtual Hosts', which is not activated by default.
'My Projects' will list any sub directory of the \wamp\www directory and provide a link to launch the site in that sub directory. As I said earlier, it launches 'project1` and not 'localhost/project1' so to make the link work we must create a Virtual Host definition to make this link actually launch that site in your browser, without the Virtual Host definition it's likely to launch a web search for the site name as a keyword or just return a site not found condition.
The 'My Virtual Hosts' menu item is a little different. It searches the file that is used to define Virtual Hosts ( we will get to that in a minute ) and creates menu links for each ServerName parameter it finds and creates a menu item for each one. This may seem a little confusing as once we create a Virtual Host definition for the sub directories of the \wamp\www folder some items will appear on both of the 'My Projects' menu and the 'My Virtual Hosts' menu's.
How do I turn this other 'My Virtual Hosts' menu on?
;WAMPPROJECTSUBMENU
, its in the '[Menu.Left]' section.;WAMPVHOSTSUBMENU
either before or after the ;WAMPPROJECTSUBMENU
parameter.Big Note The new menu will only appear if you already have some Virtual Hosts defined! Otherwise you will see no difference until you define a VHOST.
Now if you take this to its logical extension
You can now move your web site code completely outside the \wamp\
folder structure simply by changing the DocumentRoot parameter in the VHOST definition. So for example you could do this:
Create a folder on the wamp disk or any other disk ( beware of network drive, they are a bit more complicated)
D:
MD websites
CD websites
MD example.com
CD example.com
MD www
You now copy your site code to, or start creating it in the \websites\example.com\www
folder and define your VHOST like this:
<VirtualHost *:80>
DocumentRoot "d:/websites/example.com/www"
ServerName example.dev
ServerAlias www.example.dev
<Directory "d:/websites/example.com/www">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
php_flag display_errors Off
php_flag log_errors On
php_value max_upload_size 40M
php_value max_execution_time 60
php_value error_log "d:/wamp/logs/example_com_phperror.log"
</VirtualHost>
Then add this new development domain to the HOSTS file:
127.0.0.1 localhost
::1 localhost
127.0.0.1 project1
::1 project1
127.0.0.1 example.dev
::1 example.dev
NOTE: It is not a good idea to use a ServerName or ServerAlias that is the same as your live domain name, as if we had used example.com as the ServerName it would mean we could no longer get to the real live site from this PC as it would direct example.com to 127.0.0.1 i.e. this PC and not out onto the internet.
ALSO: See that I have allowed this site to be accessed from the internet from within the VHOST definitions, this change will apply to only this site and no other. Very useful for allowing a client to view your changes for an hour or so without having to copy them to the live server. This does mean that we have to edit this file manually to turn this access on and off rather than use the Put Online/Offline menu item on wampmanager.
Also I have added some modifications to the PHP config, again that will only apply to this one site. Very useful when maintaining a site with specific requirement unlike all the other sites you maintain. I guess we can assume from the parameters used that it has a long running page in it somewhere and it is very badly written and will not run with errors being displayed on the browser without making a horrible mess of the page. Believe me sites like this exist and people still want them maintained badly. But this mean we only have to change these parameters for this specific site and not globally to all Virtual sites running on WampServer.
It does not cause problems but it's a trick to do the same as PreventDefault
when you're way down in the page and an anchor as:
<a href="#" onclick="fn()">click here</a>
you will jump to the top and the URL will have the anchor #
as well, to avoid this we simply return false;
or use javascript:void(0);
regarding your examples
<a onclick="fn()">Does not appear as a link, because there's no href</a>
just do a {text-decoration:underline;}
and you will have "link a-like"
<a href="javascript:void(0)" onclick="fn()">fn is called</a>
<a href="javascript:" onclick="fn()">fn is called too!</a>
it's ok, but in your function
at the end, just return false;
to prevent the default behavior, you don't need to do anything more.
Until I get a better option, this is the most "bootstrappy" answer I can work out:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/
I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less
file:
in _layout.cshtml master page
body-content
containernavbar-fixed-bottom
on the footer<hr/>
before the footer (as now redundant)Relevant page HTML:
<div class="container-fluid body-content">
@RenderBody()
</div>
<footer class="navbar-fixed-bottom">
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
In Site.less
HTML
and BODY
heights to 100%BODY
overflow
to hidden
body-content
div position
to absolute
body-content
div top
to @navbar-height
instead of hard-wiring valuebody-content
div bottom
to 30px
.body-content
div left
and right
to 0body-content
div overflow-y
to auto
Site.less
html {
height: 100%;
body {
height: 100%;
overflow: hidden;
.container-fluid.body-content {
position: absolute;
top: @navbar-height;
bottom: 30px;
right: 0;
left: 0;
overflow-y: auto;
}
}
}
The remaining problem is there seems to be no defining variable for the footer height
in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.
If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head>
tag
<%= stylesheet_link_tag controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>
Also, to specify the same class CSS on a different controller
Add this line in the body
of application.html.erb
<body class="<%= controller.controller_name %>-<%= controller.action_name %>">
So, now for example I would like to change the p
tag in 'home' controller and 'index' action.
Inside index.scss
file adds.
.nameOfController-nameOfAction <tag> { }
.home-index p {
color:red !important;
}
const date = moment(YOUR_DATE)
return (moment().diff(date, 'days') >= 2) ? date.fromNow() : date.calendar().split(' ')[0]
First off, this is one of those things that slaps me in the face with surprise: renaming of a column requires creating an entirely new table and copying the data from the old table to the new table...
The GUI I've landed on to do SQLite operations is Base. It's got a nifty Log window that shows all the commands that have been executed. Doing a rename of a column via Base populates the log window with the necessary commands:
These can then be easily copied and pasted where you might need them. For me, that's into an ActiveAndroid migration file. A nice touch, as well, is that the copied data only includes the SQLite commands, not the timestamps, etc.
Hopefully, that saves some people time.
Front :
<Image Name="camImage"/>
Back:
public async void Base64ToImage(string base64String)
{
// read stream
var bytes = Convert.FromBase64String(base64String);
var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
camImage.Source = output;
}
in build.gradle add Guava
compile group: 'com.google.guava', name: 'guava', version: '27.0-jre'
and then
public static List<String> splitByComma(String str) {
Iterable<String> split = Splitter.on(",")
.omitEmptyStrings()
.trimResults()
.split(str);
return Lists.newArrayList(split);
}
public static String joinWithComma(Set<String> words) {
return Joiner.on(", ").skipNulls().join(words);
}
enjoy :)
Just little elaboration of regex for search a directory and file
Find a directroy with name like book
find . -name "*book*" -type d
Find a file with name like book word
find . -name "*book*" -type f
Do you mean something like this? JSFiddle
Attribute used:
margin-left: 50px;
I've found what I think is an easier way. If you put an Iframe in the page, you can redirect the exit of the action there and make it show up. You can do nothing, of course. In that case, you can set the iframe display to none.
<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
<input type="submit" value="Skicka Tips">
<input type="hidden" name="ad_id" value="2">
</form>
A tree can be called as a binary tree if and only if the maximum number of children of any of the nodes is two.
A tree can be called as a binary search tree if and only if the maximum number of children of any of the nodes is two and the left child is always smaller than the right child.
This is actually redundant except in cases where you want to override the defaults. All of these settings are implied defaults.
You can verify that by checking your effective POM using this command
mvn help:effective-pom
<finalName>name</finalName>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
For example, if i want to point to a different test resource path or resource path you should use this otherwise you don't.
<resources>
<resource>
<directory>/home/josh/desktop/app_resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>/home/josh/desktop/test_resources</directory>
</testResource>
</testResources>
Import your csv or sql to sqlite with phpLiteAdmin, it is excellent.
Try it like,
<?php
$name='your name';
echo '<table>
<tr><th>Name</th></tr>
<tr><td>'.$name.'</td></tr>
</table>';
?>
Updated
<?php
echo '<table>
<tr><th>Rst</th><th>Marks</th></tr>
<tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
</table>';
?>
For anyone using Windows container like me, know that you CANNOT bind or mount single files using windows container.
The following examples will fail when using Windows-based containers, as the destination of a volume or bind mount inside the container must be one of: a non-existing or empty directory; or a drive other than C:. Further, the source of a bind mount must be a local directory, not a file.
net use z: \\remotemachine\share
docker run -v z:\foo:c:\dest ...
docker run -v \\uncpath\to\directory:c:\dest ...
docker run -v c:\foo\somefile.txt:c:\dest ...
docker run -v c:\foo:c: ...
docker run -v c:\foo:c:\existing-directory-with-contents ...
It's hard to spot but it's there
Link to the Github issue regarding mapping files into Windows container
There are two differences between static inner and non static inner classes.
In case of declaring member fields and methods, non static inner class cannot have static fields and methods. But, in case of static inner class, can have static and non static fields and method.
The instance of non static inner class is created with the reference of object of outer class, in which it has defined, this means it has enclosing instance. But the instance of static inner class is created without the reference of Outer class, which means it does not have enclosing instance.
See this example
class A
{
class B
{
// static int x; not allowed here
}
static class C
{
static int x; // allowed here
}
}
class Test
{
public static void main(String… str)
{
A a = new A();
// Non-Static Inner Class
// Requires enclosing instance
A.B obj1 = a.new B();
// Static Inner Class
// No need for reference of object to the outer class
A.C obj2 = new A.C();
}
}
For Oracle versions which does not support the WM_CONCAT, the following can be used
select "User", RTRIM(
XMLAGG (XMLELEMENT(e, department||',') ORDER BY department).EXTRACT('//text()') , ','
) AS departments
from yourtable
group by "User"
This one is much more powerful and flexible - you can specify both delimiters and sort order within each group as in listagg.
For the case when key is unused for collection:
Public Function Contains(col As Collection, thisItem As Variant) As Boolean
Dim item As Variant
Contains = False
For Each item In col
If item = thisItem Then
Contains = True
Exit Function
End If
Next
End Function
As the other answers have indicated, you need to use an anonymous type.
As far as syntax is concerned, I personally far prefer method chaining. The method chaining equivalent would be:-
var employee = _db.EMPLOYEEs
.Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
.Select(x => new { x.EMAIL, x.ID });
AFAIK, the declarative LINQ syntax is converted to a method call chain similar to this when it is compiled.
UPDATE
If you want the entire object, then you just have to omit the call to Select()
, i.e.
var employee = _db.EMPLOYEEs
.Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo);
asp:TextBox ID="txtName" placeholder="any text here"
Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.
In .NET 4.0, you can use the Task Parallel Library.
In earlier versions, you can create a list of Thread
objects in a loop, calling Start
on each one, and then make another loop and call Join
on each one.
You could just write to the file as you would write any normal file.
with open('csvfile.csv','wb') as file:
for l in text:
file.write(l)
file.write('\n')
If just in case, it is a list of lists, you could directly use built-in csv
module
import csv
with open("csvfile.csv", "wb") as file:
writer = csv.writer(file)
writer.writerows(text)
From Docker 17.06 onwards, a special Mac-only DNS name is available in docker containers that resolves to the IP address of the host. It is:
docker.for.mac.localhost
The documentation is here: https://docs.docker.com/docker-for-mac/networking/#httphttps-proxy-support
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.START | Gravity.TOP;
params.x = left;
params.y = top;
windowManager.addView(view, params);
} else {
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.START | Gravity.TOP;
params.x = left;
params.y = top;
windowManager.addView(view, params);
}
If I understand the question correctly, it has to do with output buffering and the affect this might have on closing/ending tags. I am not sure that is an entirely valid question. The problem is that the output buffer does not mean all content is held in memory before sending it out to the client. It means some of the content is.
The programmer can purposely flush the buffer, or the output buffer so does the output buffer option in PHP really change how the closing tag affects coding? I would argue that it does not.
And maybe that is why most of the answers went back to personal style and syntax.
I think you can't achieve what you want in a more efficient manner than you proposed.
The underlying problem is that the timestamps (as you seem aware) are made up of two parts. The data that represents the UTC time, and the timezone, tz_info. The timezone information is used only for display purposes when printing the timezone to the screen. At display time, the data is offset appropriately and +01:00 (or similar) is added to the string. Stripping off the tz_info value (using tz_convert(tz=None)) doesn't doesn't actually change the data that represents the naive part of the timestamp.
So, the only way to do what you want is to modify the underlying data (pandas doesn't allow this... DatetimeIndex are immutable -- see the help on DatetimeIndex), or to create a new set of timestamp objects and wrap them in a new DatetimeIndex. Your solution does the latter:
pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])
For reference, here is the replace
method of Timestamp
(see tslib.pyx):
def replace(self, **kwds):
return Timestamp(datetime.replace(self, **kwds),
offset=self.offset)
You can refer to the docs on datetime.datetime
to see that datetime.datetime.replace
also creates a new object.
If you can, your best bet for efficiency is to modify the source of the data so that it (incorrectly) reports the timestamps without their timezone. You mentioned:
I want to work with timezone naive timeseries (to avoid the extra hassle with timezones, and I do not need them for the case I am working on)
I'd be curious what extra hassle you are referring to. I recommend as a general rule for all software development, keep your timestamp 'naive values' in UTC. There is little worse than looking at two different int64 values wondering which timezone they belong to. If you always, always, always use UTC for the internal storage, then you will avoid countless headaches. My mantra is Timezones are for human I/O only.
$("#co").click(function(){
$(this).css({"backgroundColor" : "blue"});
});
Collection is the Super interface of List so every Java list is as well an instance of collection. Collections are only iterable sequentially (and in no particular order) whereas a List allows access to an element at a certain position via the get(int index)
method.
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementById
because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
You would need to use append
or appendTo
or after
etc.. to put it in the dom first..
Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..
Rotating image is one thing, proper image boundaries in another. Here is a code which can help anyone. I created this based on some search on internet long ago.
/// <summary>
/// Rotates image in radian angle
/// </summary>
/// <param name="bmpSrc"></param>
/// <param name="theta">in radian</param>
/// <param name="extendedBitmapBackground">Because of rotation returned bitmap can have different boundaries from original bitmap. This color is used for filling extra space in bitmap</param>
/// <returns></returns>
public static Bitmap RotateImage(Bitmap bmpSrc, double theta, Color? extendedBitmapBackground = null)
{
theta = Convert.ToSingle(theta * 180 / Math.PI);
Matrix mRotate = new Matrix();
mRotate.Translate(bmpSrc.Width / -2, bmpSrc.Height / -2, MatrixOrder.Append);
mRotate.RotateAt((float)theta, new Point(0, 0), MatrixOrder.Append);
using (GraphicsPath gp = new GraphicsPath())
{ // transform image points by rotation matrix
gp.AddPolygon(new Point[] { new Point(0, 0), new Point(bmpSrc.Width, 0), new Point(0, bmpSrc.Height) });
gp.Transform(mRotate);
PointF[] pts = gp.PathPoints;
// create destination bitmap sized to contain rotated source image
Rectangle bbox = BoundingBox(bmpSrc, mRotate);
Bitmap bmpDest = new Bitmap(bbox.Width, bbox.Height);
using (Graphics gDest = Graphics.FromImage(bmpDest))
{
if (extendedBitmapBackground != null)
{
gDest.Clear(extendedBitmapBackground.Value);
}
// draw source into dest
Matrix mDest = new Matrix();
mDest.Translate(bmpDest.Width / 2, bmpDest.Height / 2, MatrixOrder.Append);
gDest.Transform = mDest;
gDest.DrawImage(bmpSrc, pts);
return bmpDest;
}
}
}
private static Rectangle BoundingBox(Image img, Matrix matrix)
{
GraphicsUnit gu = new GraphicsUnit();
Rectangle rImg = Rectangle.Round(img.GetBounds(ref gu));
// Transform the four points of the image, to get the resized bounding box.
Point topLeft = new Point(rImg.Left, rImg.Top);
Point topRight = new Point(rImg.Right, rImg.Top);
Point bottomRight = new Point(rImg.Right, rImg.Bottom);
Point bottomLeft = new Point(rImg.Left, rImg.Bottom);
Point[] points = new Point[] { topLeft, topRight, bottomRight, bottomLeft };
GraphicsPath gp = new GraphicsPath(points, new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Line, (byte)PathPointType.Line, (byte)PathPointType.Line });
gp.Transform(matrix);
return Rectangle.Round(gp.GetBounds());
}
Simplest working solution:
Download the MySQL Connector C 6.0.2 from below link and Install.
http://dev.mysql.com/downloads/connector/c/6.0.html#downloads
After installing the MySQL Connector C 6.0.2, copy the folder "MySQL Connector C 6.0.2" from "C:\Program Files\MySQL" to "C:\Program Files (x86)\MySQL".
Then type
pip install MySQL-python
It will definitely work.
I have found a fairly simple way to do this.
Initially, through your Anaconda Prompt, you can follow the steps in this official Tensorflow site - here. You have to follow the steps as is, no deviation.
Later, you open the Anaconda Navigator. In Anaconda Navigator, go to Applications On --- section. Select the drop down list, after following above steps you must see an entry - tensorflow into it. Select tensorflow and let the environment load.
Then, select Jupyter Notebook in this new context, and install it, let the installation get over.
After that you can run the Jupyter notebook like the regular notebook in tensorflow environment.
I think it would make more sense to use "Find" function in Excel instead of For Each loop. It works much much faster and it's designed for such actions. Try this:
Sub FindSomeCells(strSearchQuery As String)
Set SearchRange = Worksheets("Sheet1").Range("A1:A100")
FindWhat = strSearchQuery
Set FoundCells = FindAll(SearchRange:=SearchRange, _
FindWhat:=FindWhat, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByColumns, _
MatchCase:=False, _
BeginsWith:=vbNullString, _
EndsWith:=vbNullString, _
BeginEndCompare:=vbTextCompare)
If FoundCells Is Nothing Then
Debug.Print "Value Not Found"
Else
For Each FoundCell In FoundCells
FoundCell.Interior.Color = XlRgbColor.rgbLightGreen
Next FoundCell
End If
End Sub
That subroutine searches for some string and returns a collections of cells fullfilling your search criteria. Then you can do whatever you want with the cells in that collection. Forgot to add the FindAll
function definition:
Function FindAll(SearchRange As Range, _
FindWhat As Variant, _
Optional LookIn As XlFindLookIn = xlValues, _
Optional LookAt As XlLookAt = xlWhole, _
Optional SearchOrder As XlSearchOrder = xlByRows, _
Optional MatchCase As Boolean = False, _
Optional BeginsWith As String = vbNullString, _
Optional EndsWith As String = vbNullString, _
Optional BeginEndCompare As VbCompareMethod = vbTextCompare) As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FindAll
' This searches the range specified by SearchRange and returns a Range object
' that contains all the cells in which FindWhat was found. The search parameters to
' this function have the same meaning and effect as they do with the
' Range.Find method. If the value was not found, the function return Nothing. If
' BeginsWith is not an empty string, only those cells that begin with BeginWith
' are included in the result. If EndsWith is not an empty string, only those cells
' that end with EndsWith are included in the result. Note that if a cell contains
' a single word that matches either BeginsWith or EndsWith, it is included in the
' result. If BeginsWith or EndsWith is not an empty string, the LookAt parameter
' is automatically changed to xlPart. The tests for BeginsWith and EndsWith may be
' case-sensitive by setting BeginEndCompare to vbBinaryCompare. For case-insensitive
' comparisons, set BeginEndCompare to vbTextCompare. If this parameter is omitted,
' it defaults to vbTextCompare. The comparisons for BeginsWith and EndsWith are
' in an OR relationship. That is, if both BeginsWith and EndsWith are provided,
' a match if found if the text begins with BeginsWith OR the text ends with EndsWith.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim FoundCell As Range
Dim FirstFound As Range
Dim LastCell As Range
Dim ResultRange As Range
Dim XLookAt As XlLookAt
Dim Include As Boolean
Dim CompMode As VbCompareMethod
Dim Area As Range
Dim MaxRow As Long
Dim MaxCol As Long
Dim BeginB As Boolean
Dim EndB As Boolean
CompMode = BeginEndCompare
If BeginsWith <> vbNullString Or EndsWith <> vbNullString Then
XLookAt = xlPart
Else
XLookAt = LookAt
End If
' this loop in Areas is to find the last cell
' of all the areas. That is, the cell whose row
' and column are greater than or equal to any cell
' in any Area.
For Each Area In SearchRange.Areas
With Area
If .Cells(.Cells.Count).Row > MaxRow Then
MaxRow = .Cells(.Cells.Count).Row
End If
If .Cells(.Cells.Count).Column > MaxCol Then
MaxCol = .Cells(.Cells.Count).Column
End If
End With
Next Area
Set LastCell = SearchRange.Worksheet.Cells(MaxRow, MaxCol)
On Error GoTo 0
Set FoundCell = SearchRange.Find(what:=FindWhat, _
after:=LastCell, _
LookIn:=LookIn, _
LookAt:=XLookAt, _
SearchOrder:=SearchOrder, _
MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
Set FirstFound = FoundCell
Do Until False ' Loop forever. We'll "Exit Do" when necessary.
Include = False
If BeginsWith = vbNullString And EndsWith = vbNullString Then
Include = True
Else
If BeginsWith <> vbNullString Then
If StrComp(Left(FoundCell.Text, Len(BeginsWith)), BeginsWith, BeginEndCompare) = 0 Then
Include = True
End If
End If
If EndsWith <> vbNullString Then
If StrComp(Right(FoundCell.Text, Len(EndsWith)), EndsWith, BeginEndCompare) = 0 Then
Include = True
End If
End If
End If
If Include = True Then
If ResultRange Is Nothing Then
Set ResultRange = FoundCell
Else
Set ResultRange = Application.Union(ResultRange, FoundCell)
End If
End If
Set FoundCell = SearchRange.FindNext(after:=FoundCell)
If (FoundCell Is Nothing) Then
Exit Do
End If
If (FoundCell.Address = FirstFound.Address) Then
Exit Do
End If
Loop
End If
Set FindAll = ResultRange
End Function
while (itr.hasNext()) {
Vehicle vc=(Vehicle) itr.next();
if(vc.getVehicleType().equalsIgnoreCase(s)) {
count++;
}
}
Don't try to do this yourself if you're serious about getting edge cases right. So while they many naive/simple methods are theoretically exact, they can have nasty numerical behavior for nearly singular matrices. In particular you can get cancelation/round-off errors that cause you to get arbitrarily bad results.
A "correct" way is Gaussian elimination with row and column pivoting so that you're always dividing by the largest remaining numerical value. (This is also stable for NxN matrices.). Note that row pivoting alone doesn't catch all the bad cases.
However IMO implementing this right and fast is not worth your time - use a well tested library and there are a heap of header only ones.
INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
Please go to File| Settings | Tools | Python Integrated Tools and change the default test runner to py.test. Then you'll get the py.test option to create tests instead of the unittest one.
In regular programming calculations, we don’t use float. If we ensure that the result range is within the range of float data type then we can choose a float data type for saving memory. Generally, we use double because of two reasons:-
Both float and double data types were designed especially for scientific calculations, where approximation errors are acceptable. If accuracy is the most prior concern then, it is recommended to use BigDecimal class instead of float or double data types. Source:- Float and double datatypes in Java
No, but the 32-bit version runs just fine on 64-bit Windows.
This is what worked for me for extracting TTFs from .dfont and .ttc files from Mac OS X: http://transfonter.org/ttc-unpack
The resulting TTFs work fine in Windows 7.
Thanks for great and quick replies. I will gives some up votes inmediately to acknowledge your help. I have coded the best solution in my opinion based on your answers.
LinkedList<Patch> patches1 = diff.patch_make(text2, text1);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(patches1);
String serialized_patches1 = bos.toString();
os.close();
ByteArrayInputStream bis = new ByteArrayInputStream(serialized_patches1.getBytes());
ObjectInputStream oInputStream = new ObjectInputStream(bis);
LinkedList<Patch> restored_patches1 = (LinkedList<Patch>) oInputStream.readObject();
// patches1 equals restored_patches1
oInputStream.close();
} catch(Exception ex) {
ex.printStackTrace();
}
Note i did not considered using JSON because is less efficient.
Note: I will considered your advice about not storing serialized object as strings in the database but byte[] instead.
fetch
/merge
vs. pull
People often advise you to separate "fetching" from "merging". They say instead of this:
git pull remoteR branchB
do this:
git fetch remoteR
git merge remoteR branchB
What they don't mention is that such a fetch command will actually fetch all branches from the remote repo, which is not what that pull command does. If you have thousands of branches in the remote repo, but you do not want to see all of them, you can run this obscure command:
git fetch remoteR refs/heads/branchB:refs/remotes/remoteR/branchB
git branch -a # to verify
git branch -t branchB remoteR/branchB
Of course, that's ridiculously hard to remember, so if you really want to avoid fetching all branches, it is better to alter your .git/config
as described in ProGit.
The best explanation of all this is in Chapter 9-5 of ProGit, Git Internals - The Refspec (or via github). That is amazingly hard to find via Google.
First, we need to clear up some terminology. For remote-branch-tracking, there are typically 3 different branches to be aware of:
refs/heads/branchB
inside the other reporefs/remotes/remoteR/branchB
in your reporefs/heads/branchB
inside your repoRemote-tracking branches (in refs/remotes
) are read-only. You do not modify those directly. You modify your own branch, and then you push to the corresponding branch at the remote repo. The result is not reflected in your refs/remotes
until after an appropriate pull or fetch. That distinction was difficult for me to understand from the git man-pages, mainly because the local branch (refs/heads/branchB
) is said to "track" the remote-tracking branch when .git/config
defines branch.branchB.remote = remoteR
.
Think of 'refs' as C++ pointers. Physically, they are files containing SHA-digests, but basically they are just pointers into the commit tree. git fetch
will add many nodes to your commit-tree, but how git decides what pointers to move is a bit complicated.
As mentioned in another answer, neither
git pull remoteR branchB
nor
git fetch remoteR branchB
would move refs/remotes/branches/branchB
, and the latter certainly cannot move refs/heads/branchB
. However, both move FETCH_HEAD
. (You can cat
any of these files inside .git/
to see when they change.) And git merge
will refer to FETCH_HEAD
, while setting MERGE_ORIG
, etc.
Another interesting thing I found is that the ReSharper error can be 'satisfied' by doing something like below which is dumb to me. However, as mentioned by many earlier, it still is not a good idea to call virtual properties/methods in constructor.
public class ConfigManager
{
public virtual int MyPropOne { get; private set; }
public virtual string MyPropTwo { get; private set; }
public ConfigManager()
{
Setup();
}
private void Setup()
{
MyPropOne = 1;
MyPropTwo = "test";
}
}
pandas DataFrame/Series
or numpy array
:The top answers are optimized methods for single point calculation, but when you want to apply these methods to a pandas series or numpy array, it requires apply
, which is basically for loop in the background and will iterate over every row and apply the method. This is quite inefficient.
To speed up our code, we can make use of vectorization and numpy broadcasting:
x = np.arange(-5,5)
np.divide(1, 1+np.exp(-x))
0 0.006693
1 0.017986
2 0.047426
3 0.119203
4 0.268941
5 0.500000
6 0.731059
7 0.880797
8 0.952574
9 0.982014
dtype: float64
Or with a pandas Series
:
x = pd.Series(np.arange(-5,5))
np.divide(1, 1+np.exp(-x))
Update : for the new apache 2.4 jump directly to the end.
The Order keyword and its relation with Deny
and Allow
Directives is a real nightmare. It would be quite interesting to understand how we ended up with such solution, a non-intuitive one to say the least.
Order
keyword will have a big impact on how Allow
and Deny
directives are used.Deny
and Allow
directives are not applied in the order they are written, they must be seen as two distinct blocks (one the for Deny
directives, one for Allow
).You have two main modes:
Order Deny,Allow
Deny
rules.Deny
rules reject some requests.Allow
.I would rephrase it as:
Rule Deny
list of Deny rules
Except
list of Allow rules
Policy Allow (when no rule fired)
Order Allow,Deny
Allow
rules.Allow
rule.Allow
, you can still reject them with a Deny
.In the simplified form:
Rule Allow
list of Allow rules
Except
list of Deny rules
Policy Deny (when no rule fired)
You need to allow a list of networks which are the country networks. And in this country you want to exclude some proxies' IP addresses.
You have taken the allow-anyone-except-this-list-or-maybe-not mode, so by default anyone can access your server, except proxies' IPs listed in the Deny
list, but if they get rejected you still allow the country networks. That's too broad. Not good.
By inverting to order allow,deny
you will be in the reject-everyone-except-this-list-or-maybe-not mode.
So you will reject access to everyone but allow the country networks and then you will reject the proxies. And of course you must remove the Deny from all
as stated by @Gerben and @Michael Slade (this answer only explains what they wrote).
The Deny from all
is usually seen with order deny,allow
to remove the allow by default access and make a simple, readable configuration. For example, specify a list of allowed IPs after that. You don't need that rule and your question is a perfect case of a 3-way access mode (default policy, exceptions, exceptions to exceptions).
But the guys who designed these settings are certainly insane.
The whole authorization scheme has been refactored in Apache 2.4 with RequireAll, RequireAny and RequireNone directives. See for example this complex logic example.
So the old strange Order
logic becomes a relic, and to quote the new documentation:
Controling how and in what order authorization will be applied has been a bit of a mystery in the past
If you want to style the output of a data frame in a jupyter notebook cell, you can set the display style on a per-dataframe basis:
df = pd.DataFrame({'A': np.random.randn(4)*1e7})
df.style.format("{:.1f}")
See the documentation here.
Two options:
Code for #2:
render(){
return(
<View style={{ flex: 1 }}>
<Image style={{ width: screenWidth, height: screenHeight, position: 'absolute', top: 0, left: 0 }}/>
<Text>Hey look, image background</Text>
</View>
)
}
Edit:
For option #2 you can experiment with resizeMode="stretch|cover"
Edit 2: Keep in mind that option #2 renders the image and then everything after that in this order, which means that some pixels are rendered twice, this might have a very small performance impact (usually unnoticeable) but just for your information
Following the answer from DruidKuma and jumping_monkey
You can also include optional and make your code a bit nicer and cleaner:
public static MyService getService(String type) {
return Optional.ofNullable(myServiceCache.get(type))
.orElseThrow(() -> new RuntimeException("Unknown service type: " + type));
}
According to oracle online documentation
ORA-12541: TNS:no listener
Cause: The connection request could not be completed because the listener is not running.
Action: Ensure that the supplied destination address matches one of the addresses used by
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on
the remote machine.
I will use collection.save(the_changed_dict)
this way. I've just tested this, and it still works for me. The following is quoted directly from pymongo doc.
:
save(to_save[, manipulate=True[, safe=False[, **kwargs]]])
Save a document in this collection.
If to_save already has an "_id" then an update() (upsert) operation is performed and any existing document with that "_id" is overwritten. Otherwise an insert() operation is performed. In this case if manipulate is True an "_id" will be added to to_save and this method returns the "_id" of the saved document. If manipulate is False the "_id" will be added by the server but this method will return None.
As I know you cannot do this in easy way (see fork exec etc (don't work under windows)), may be you can reverse the approach, use the background of the browser posting the form in ajax, so if the post still work you've no wait time.
This can help even if you have to do some long elaboration.
About sending mail it's always suggest to use a spooler, may be a local & quick smtp server that accept your requests and the spool them to the real MTA or put all in a DB, than use a cron that spool the queue.
The cron may be on another machine calling the spooler as external url:
* * * * * wget -O /dev/null http://www.example.com/spooler.php
Nouns.h
doesn't include <string>
, but it needs to. You need to add
#include <string>
at the top of that file, otherwise the compiler doesn't know what std::string
is when it is encountered for the first time.
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
</div>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
///////////////// OR ////////////
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
</div>
menuController have access for menu div. And widgetController have access to both.
Another potential treatment is using PATCH after all. A PATCH is defined as something that changes the internal state and is not restricted to appending.
PATCH would solve the problem by allowing you to update already existing items. See: RFC 5789: PATCH
Hmm, you could also just make a 1 pixel wide line with a length of 1 pixel and make it's direction move along a single axis.
ctx.beginPath();
ctx.lineWidth = 1; // one pixel wide
ctx.strokeStyle = rgba(...);
ctx.moveTo(50,25); // positioned at 50,25
ctx.lineTo(51,25); // one pixel long
ctx.stroke();
make iframe with align="middle" and put it in paragraph with style="text-aling:center":
<p style="text-align:center;">
<iframe width="420" height="315" align="middle" src="https://www.youtube.com/embed/YOURVIDEO">
</iframe>
</p>
Use:
/*/ITEM[starts-with(REVENUE_YEAR,'2552')]/REGION
Note: Unless your host language can't handle element instance as result, do not use text nodes specially in mixed content data model. Do not start expressions with //
operator when the schema is well known.
Unless I'm mistaken, I'd say it's to write your own function.
function findIndexOfGreatest(array) {
var greatest;
var indexOfGreatest;
for (var i = 0; i < array.length; i++) {
if (!greatest || array[i] > greatest) {
greatest = array[i];
indexOfGreatest = i;
}
}
return indexOfGreatest;
}
Assuming type TreeMap<String,Integer> :
for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " => " + value);
}
(key and Value types can be any class of course)
first get the profiler Exe from: http://expressprofiler.codeplex.com
then you can add it simply to the Management studio:
Tools -> External tools... ->
a- locate the exe file on your disk (If installed, it's typically C:\Program Files (x86)\ExpressProfiler\ExpressProfiler.exe)
b- give it a name e.g. Express Profiler
that's it :) you have your Profiler with your sql express edition
I think of it this way
+----------------+
| super |
+----------------+ <-----------------+
| +------------+ | |
| | this | | <-+ |
| +------------+ | | |
| | @method1() | | | |
| | @method2() | | | |
| +------------+ | | |
| method4() | | |
| method5() | | |
+----------------+ | |
We instantiate that class, not that one!
Let me move that subclass a little to the left to reveal what's beneath... (Man, I do love ASCII graphics)
We are here
|
/ +----------------+
| | super |
v +----------------+
+------------+ |
| this | |
+------------+ |
| @method1() | method1() |
| @method2() | method2() |
+------------+ method3() |
| method4() |
| method5() |
+----------------+
Then we call the method
over here...
| +----------------+
_____/ | super |
/ +----------------+
| +------------+ | bar() |
| | this | | foo() |
| +------------+ | method0() |
+-> | @method1() |--->| method1() | <------------------------------+
| @method2() | ^ | method2() | |
+------------+ | | method3() | |
| | method4() | |
| | method5() | |
| +----------------+ |
\______________________________________ |
\ |
| |
...which calls super, thus calling the super's method1() here, so that that
method (the overidden one) is executed instead[of the overriding one].
Keep in mind that, in the inheritance hierarchy, since the instantiated
class is the sub one, for methods called via super.something() everything
is the same except for one thing (two, actually): "this" means "the only
this we have" (a pointer to the class we have instantiated, the
subclass), even when java syntax allows us to omit "this" (most of the
time); "super", though, is polymorphism-aware and always refers to the
superclass of the class (instantiated or not) that we're actually
executing code from ("this" is about objects [and can't be used in a
static context], super is about classes).
In other words, quoting from the Java Language Specification:
The form
super.Identifier
refers to the field namedIdentifier
of the current object, but with the current object viewed as an instance of the superclass of the current class.The form
T.super.Identifier
refers to the field namedIdentifier
of the lexically enclosing instance corresponding toT
, but with that instance viewed as an instance of the superclass ofT
.
In layman's terms, this
is basically an object (*the** object; the very same object you can move around in variables), the instance of the instantiated class, a plain variable in the data domain; super
is like a pointer to a borrowed block of code that you want to be executed, more like a mere function call, and it's relative to the class where it is called.
Therefore if you use super
from the superclass you get code from the superduper class [the grandparent] executed), while if you use this
(or if it's used implicitly) from a superclass it keeps pointing to the subclass (because nobody has changed it - and nobody could).
Try making your changes in:
- (void) viewWillLayoutSubviews {}
The code will run at every orientation change as the subviews get laid out again.
You can use the blade template engine:
@include('view.name')
'view.name' would live in your main views folder:
// for laravel 4.X
app/views/view/name.blade.php
// for laravel 5.X
resources/views/view/name.blade.php
Another example
@include('hello.world');
would display the following view
// for laravel 4.X
app/views/hello/world.blade.php
// for laravel 5.X
resources/views/hello/world.blade.php
Another example
@include('some.directory.structure.foo');
would display the following view
// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php
// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php
So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views
folder for laravel 4.x or your resources/views
folder in laravel 5.x
ADDITIONAL
If you want to pass parameters: @include('view.name', array('paramName' => 'value'))
You can then use the value in your views like so <p>{{$paramName}}</p>
You can use the union() function in python.
joinedlist = union(listone, listtwo)
print(joinedlist)
Essentially what this is doing is its removing one of every duplicate in the two lists. Since your lists don't have any duplicates it, it just returns the concatenated version of the two lists.
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
WORKING Method (unless there is no other problem)
By default, Apache is not restricting access from IPv4 (common external IP address)
What are restricted are the commands given in 'httpd.conf
'.
Replace all
<Directory />
AllowOverride none
Require all denied
</Directory>
with
<Directory />
AllowOverride none
# Require all denied
</Directory>
hence removing out all restriction given to Apache.
Replace Require local
with Require all granted
for the C:/wamp/www/ directory.
<Directory "c:/wamp/www/">
Options Indexes FollowSymLinks
AllowOverride all
Require all granted
# Require local
</Directory>
@Component({
selector: 'my-app',
template: `
<div>
<input name="file" type="file" (change)="onChange($event)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
file: File;
onChange(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.file = files[0];
console.log(this.file);
}
doAnythingWithFile() {
}
}
innerText is the current correct answer for this. The other answers are outdated and incorrect.
document.getElementById('ShowButton').innerText = 'Show filter';
innerHTML also works, and can be used to insert HTML.
If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.
In this case ë
could be encoded with 0xC3 0xAB that represents the Unicode character ë
(U+00EB) in UTF-8.
To show the full element (if it's possible with the current window size):
var element = $("#some_element");
var elementHeight = element.height();
var windowHeight = $(window).height();
var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);
The root cause is: your environment variable LC_ALL
is missing or invalid somehow
Short answer-
just run the following command:
$ export LC_ALL=C
If you keep getting the error in new terminal windows, add it at the bottom of your .bashrc
file.
Long answer-
Here is my locale
settings:
$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C
Python2.7
$ uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
$ python --version
Python 2.7.9
$ pip --version
pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
$ unset LC_ALL
$ pip install virtualenv
Traceback (most recent call last):
File "/usr/local/bin/pip", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
locale.setlocale(locale.LC_ALL, '')
File "/usr/lib/python2.7/locale.py", line 579, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
$ export LC_ALL=C
$ pip install virtualenv
Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages
New, improved answer to an old, frequently asked question...
Double quote ("
) may appear without escaping:
In XML textual content:
<NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
In XML attributes delimited by single quotes ('
):
<NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
Note: switching to single quotes ('
) also requires no escaping:
<NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
Double quote ("
) must be escaped:
In XML attributes delimited by double quotes:
<EscapeNeeded name="Pete "Maverick" Mitchell"/>
Double quote ("
) must be escaped as "
in XML only in very limited contexts.
The question is for linux but I had the same issue with git bash on my Windows machine.
My pqsql is installed here:
C:\Program Files\PostgreSQL\10\bin\psql.exe
You can add the location of psql.exe
to your Path environment variable as shown in this screenshot:
After changing the above, please close all cmd
and/or bash
windows, and re-open them (as mentioned in the comments @Ayush Shankar)
You might need to change default logging user using below command.
psql -U postgres
Here postgres
is the username. Without -U
, it will pick the windows loggedin user.
Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.
Serialize/Unserialize array for storage in a DB
Visit http://php.net/manual/en/function.serialize.php
From the PHP Manual:
Look under "Return" on the page
Returns a string containing a byte-stream representation of value that can be stored anywhere.
Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.
Note: If you want to store html into a blob, be sure to base64 encode it or it could break the serialize function.
Example encoding:
$YourSerializedData = base64_encode(serialize($theHTML));
$YourSerializedData
is now ready to be stored in blob.
After getting data from blob you need to base64_decode then unserialize Example decoding:
$theHTML = unserialize(base64_decode($YourSerializedData));
For version 19.1 and above goto specified directory and delete these mentioned files:
C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\20.1<smart-git-version>
C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\20.1\.backup
For the previous version goto specified directory and delete mentioned file:
C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\17<smart-git-version>
None of the above solved the issue for me. In my case it was not also setting the correct application scene manifest.
I had to change LoginScreen used to be Main
First, I don't understand why you are adding all the keys and values count times, Index is never used.
I tried this example :
var source = new BindingSource();
List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"), new MyStruct("c","d") };
source.DataSource = list;
grid.DataSource = source;
and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.
class MyStruct
{
public string Name { get; set; }
public string Adres { get; set; }
public MyStruct(string name, string adress)
{
Name = name;
Adres = adress;
}
}
Try to build a type that takes one key and value, and add it one by one. Hope this helps.
Use shared variable to communicate. For example like this:
import multiprocessing
def worker(procnum, return_dict):
"""worker function"""
print(str(procnum) + " represent!")
return_dict[procnum] = procnum
if __name__ == "__main__":
manager = multiprocessing.Manager()
return_dict = manager.dict()
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i, return_dict))
jobs.append(p)
p.start()
for proc in jobs:
proc.join()
print(return_dict.values())
you can see the result here In these simple block of code you can change the size of your image ,and make it bigger when the mouse enter over the image , and it will return to its original size when mouve leave.
html:
<div>
<img onmouseover="fifo()" onmouseleave="fifo()" src="your_image"
width="10%" id="f" >
</div>
js file:
var b=0;
function fifo() {
if(b==0){
document.getElementById("f").width = "300";
b=1;
}
else
{
document.getElementById("f").width = "100";
b=0;
}
}
Don't forget to write the permissions without extra spaces in the manifest. In my case i had:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE " />
But look, at the end, there's an extra space. Just write it the right way
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And it's working now
In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
image = pygame.image.load(imgfile, 'img_01.png')
finally:
imgfile.close()
Scenario:
Your domain: mydomain.com
Domain you wish to send to: theirdomain.com
1. Determine the mail server you're sending to. Open a CMD prompt Type
NSLOOKUP
set q=mx
theirdomain.com
Response:
Non-authoritative answer:
theirdomain.com MX preference = 50, mail exchanger = mail.theirdomain.com
Nslookup_big
EDIT Be sure to type exit to terminate NSLOOKUP.
2. Connect to their mail server
SMTP communicates over port 25. We will now try to use TELNET to connect to their mail server "mail.theirdomain.com"
Open a CMD prompt
TELNET MAIL.THEIRDOMAIN.COM 25
You should see something like this as a response:
220 mx.google.com ESMTP 6si6253627yxg.6
Be aware that different servers will come up with different greetings but you should get SOMETHING. If nothing comes up at this point there are 2 possible problems. Port 25 is being blocked at your firewall, or their server is not responding. Try a different domain, if that works then it's not you.
3. Send an Email
Now, use simple SMTP commands to send a test email. This is very important, you CANNOT use the backspace key, it will work onscreen but not be interpreted correctly. You have to type these commands perfectly.
ehlo mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
This is a test, please do not respond
.
quit
So, what does that all mean? EHLO - introduce yourself to the mail server HELO can also be used but EHLO tells the server to use the extended command set (not that we're using that).
MAIL FROM - who's sending the email. Make sure to place this is the greater than/less than brackets as many email servers will require this (Postini).
RCPT TO - who you're sending it to. Again you need to use the brackets. See Step #4 on how to test relaying mail!
DATA - tells the SMTP server that what follows is the body of your email. Make sure to hit "Enter" at the end.
. - the period alone on the line tells the SMTP server you're all done with the data portion and it's clear to send the email.
quit - exits the TELNET session.
4. Test SMTP relay Testing SMTP relay is very easy, and simply requires a small change to the above commands. See below:
ehlo mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
This is a test, please do not respond
.
quit
See the difference? On the RCPT TO line, we're sending to a domain that is not controlled by the SMTP server we're sending to. You will get an immediate error is SMTP relay is turned off. If you're able to continue and send an email, then relay is allowed by that server.
And yet another variation
a = ['12','34','35','231']
a.to_s.gsub(/\"/, '\'').gsub(/[\[\]]/, '')
If you need to return the table's total row count, you can use an alternative way to the SELECT COUNT(*)
statement.
Because SELECT COUNT(*)
makes a full table scan to return the row count, it can take very long time for a large table. You can use the sysindexes
system table instead in this case. There is a ROWS
column that contains the total row count for each table in your database. You can use the following select statement:
SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2
This will drastically reduce the time your query takes.
Another great solution to debug the Network calls before redirecting to other pages is to select the beforeunload
event break point
This way you assure to break the flow right before it redirecting it to another page, this way all network calls, network data and console logs are still there.
This solution is best when you want to check what is the response of the calls
P.S: You can also use XHR break points if you want to stop right before a specific call or any call (see image example)
There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:
with open(filename, 'r') as f:
next(f)
for line in f:
and:
with open(filename,'r') as f:
lines = f.readlines()[1:]
No.
if ([[UIScreen mainScreen] bounds].size.height > 960)
on iPhone 5 is wrong
if ([[UIScreen mainScreen] bounds].size.height == 568)
I have found the only reliable, portable method to be
bytes(bytearray([n]))
Just bytes([n]) does not work in python 2. Taking the scenic route through bytearray seems like the only reasonable solution.
If you just want go get
to work real fast, and move along with your work...
Just export GIT_TERMINAL_PROMPT=1
$ export GIT_TERMINAL_PROMPT=1
$ go get [whatever]
It will now prompt you for a user/pass for the rest of your shell session. Put this in your .profile
or setup git
as above for a more permanent solution.
The syntax error is just due to a missing alias for the subquery:
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) mySubQuery /* Alias */
The SSL only helps with sniffing attacks. If an attacker has access to your machine I will assume they can copy your secure cookie too.
At the very least, make sure old cookies lose their value after a while. Even a successful hijaking attack will be thwarted when the cookie stops working. If the user has a cookie from a session that logged in more than a month ago, make them reenter their password. Make sure that whenever a user clicks on your site's "log out" link, that the old session UUID can never be used again.
I'm not sure if this idea will work but here goes: Add a serial number into your session cookie, maybe a string like this:
SessionUUID, Serial Num, Current Date/Time
Encrypt this string and use it as your session cookie. Regularly change the serial num - maybe when the cookie is 5 minutes old and then reissue the cookie. You could even reissue it on every page view if you wanted to. On the server side, keep a record of the last serial num you've issued for that session. If someone ever sends a cookie with the wrong serial number it means that an attacker may be using a cookie they intercepted earlier so invalidate the session UUID and ask the user to reenter their password and then reissue a new cookie.
Remember that your user may have more than one computer so they may have more than one active session. Don't do something that forces them to log in again every time they switch between computers.
Use your code
public class FragmentOne extends Fragment implements OnClickListener{
View view;
Fragment fragmentTwo;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi);
buttonSayHi.setOnClickListener(this);
return view;
}
But I think is better handle the buttons in this way:
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonSayHi:
/** Do things you need to..
fragmentTwo = new FragmentTwo();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
*/
break;
}
}
You can continue chaining them like you've done.
results = results.Where (o => o.OrderStatus == OrderStatus.Open);
results = results.Where (o => o.InvoicePaid);
This represents an AND.
The max_allowed_packet variable can be set globally by running a query.
However, if you do not change it in the my.ini
file (as dragon112 suggested), the value will reset when the server restarts, even if you set it globally.
To change the max allowed packet for everyone to 1GB until the server restarts:
SET GLOBAL max_allowed_packet=1073741824;
Please run below script in your terminal
curl -X POST \
-H "Authorization: key= write here api_key" \
-H "Content-Type: application/json" \
-d '{
"registration_ids": [
"write here reg_id generated by gcm"
],
"data": {
"message": "Manual push notification from Rajkumar"
},
"priority": "high"
}' \
https://android.googleapis.com/gcm/send
it will give the message if it is succeeded or failed
You can get rid of the first line. You don't need import java.lang.*;
Just change your 5th line to:
public static void main(String [] args) throws Exception
Below is a working example code.
Please note you need to add a reference to Newtonsoft.Json.Linq
string url = "https://yourAPIurl";
WebRequest myReq = WebRequest.Create(url);
string credentials = "xxxxxxxxxxxxxxxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
CredentialCache mycache = new CredentialCache();
myReq.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
var json = "[" + content + "]"; // change this to array
var objects = JArray.Parse(json); // parse as array
foreach (JObject o in objects.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = p.Value.ToString();
Console.Write(name + ": " + value);
}
}
Console.ReadLine();
Reference: TheDeveloperBlog.com
When you select a column with type ZEROFILL
it pads the displayed value of the field with zeros up to the display width specified in the column definition. Values longer than the display width are not truncated. Note that usage of ZEROFILL
also implies UNSIGNED
.
Using ZEROFILL
and a display width has no effect on how the data is stored. It affects only how it is displayed.
Here is some example SQL that demonstrates the use of ZEROFILL
:
CREATE TABLE yourtable (x INT(8) ZEROFILL NOT NULL, y INT(8) NOT NULL);
INSERT INTO yourtable (x,y) VALUES
(1, 1),
(12, 12),
(123, 123),
(123456789, 123456789);
SELECT x, y FROM yourtable;
Result:
x y
00000001 1
00000012 12
00000123 123
123456789 123456789
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
super.finishAndRemoveTask();
}
else {
super.finish();
}
Use it after initialization code to get current date (in datepicker format):
$(".ui-datepicker-today").trigger("click");
I solved it with library PHP_PDO , because my hosting provider didn't accept my requirement for installation of PDO driver to apache server.
Or you can split your string to string array, splitting by space and then add every item of string array to empty string.
May be this is not the best and fastest method, but you can try, if other answer aren't what you whant.
The > null does not work in the quotes. It sees the > null as the batch filename.
The robocopy no output worked!!!
Here is the new batch file:
robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\EnvBackup c:\offsite_backup\EnvBackup
robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\shares c:\offsite_backup\shares
robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\Quickbooks_Backup c:\offsite_backup\Quickbooks_Backup
The date values from the text fields can be fetched by jquery's .val() Method like
var datestr1 = $('#datefield1-id').val();
var datestr2 = $('#datefield2-id').val();
I'd strongly recommend to parse the date strings before comparing them. Javascript's Date object has a parse()-Method, but it only supports US date formats (YYYY/MM/DD). It returns the milliseconds since the beginning of the unix epoch, so you can simply compare your values with > or <.
If you want different formats (e.g. ISO 8661), you need to resort to regular expressions or the free date.js library.
If you want to be super user-fiendly, you can use jquery ui datepickers instead of textfields. There is a datepicker variant that allows to enter date ranges:
http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/
Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:
Excerpt:
To include and then reference an outer-system assembly 1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item. 2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control). 3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.
The null character is '\0'
, not '/0'
.
while (*(forward++) != '\0')
so simple ...!
use this method:
<?php echo json_encode($your_array); ?>;
in laravel blade {{ }} use this method:
{{ str_replace('"', '', json_encode($your_array)) }}
working for associated and unassociated array.
mystycs, you are using the variable i
to control your loop, however you are editing the value of i
within the loop:
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
Try this instead:
int sum = 0;
for (int i=0; i < positiveInteger; i++)
{
sum = sum + i;
cout << sum << " " << i;
}
OperationContext.Current.RequestContext.RequestMessage
this context is accesible server side during processing of request. This doesn`t works for one-way operations
You need rawQuery method.
Example:
private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});
Use ? bindings instead of putting values into raw sql query.
Here's an alternative solution:
>>> import pyexcel as pe
>>> text="""1,2,3
... a,b,c
... d,e,f"""
>>> s = pe.load_from_memory('csv', text)
>>> s
Sheet Name: csv
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| a | b | c |
+---+---+---+
| d | e | f |
+---+---+---+
>>> s.to_array()
[[u'1', u'2', u'3'], [u'a', u'b', u'c'], [u'd', u'e', u'f']]
Here's the documentation
If you are using latest versions of Angular (2/5/6) :
In your component.ts
//x.component.ts
prefs = false;
hidePrefs(){
this.prefs = true;
}
<script type="text/javascript">
var app = angular.module('sampleapp', [])
app.controller('samplecontrol', function ($scope) {
var today = new Date();
console.log($scope.cdate);
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var current_date = date+'/'+month+'/'+year;
console.log(current_date);
});
</script>
Basic Structure Here is an example of a JUnit output file, showing a skip and failed result, as well as a single passed result.
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
<testsuite name="JUnitXmlReporter" errors="0" tests="0" failures="0" time="0" timestamp="2013-05-24T10:23:58" />
<testsuite name="JUnitXmlReporter.constructor" errors="0" skipped="1" tests="3" failures="1" time="0.006" timestamp="2013-05-24T10:23:58">
<properties>
<property name="java.vendor" value="Sun Microsystems Inc." />
<property name="compiler.debug" value="on" />
<property name="project.jdk.classpath" value="jdk.classpath.1.6" />
</properties>
<testcase classname="JUnitXmlReporter.constructor" name="should default path to an empty string" time="0.006">
<failure message="test failure">Assertion failed</failure>
</testcase>
<testcase classname="JUnitXmlReporter.constructor" name="should default consolidate to true" time="0">
<skipped />
</testcase>
<testcase classname="JUnitXmlReporter.constructor" name="should default useDotNotation to true" time="0" />
</testsuite>
</testsuites>
Below is the documented structure of a typical JUnit XML report. Notice that a report can contain 1 or more test suite. Each test suite has a set of properties (recording environment information). Each test suite also contains 1 or more test case and each test case will either contain a skipped, failure or error node if the test did not pass. If the test case has passed, then it will not contain any nodes. For more details of which attributes are valid for each node please consult the following section "Schema".
<testsuites> => the aggregated result of all junit testfiles
<testsuite> => the output from a single TestSuite
<properties> => the defined properties at test execution
<property> => name/value pair for a single property
...
</properties>
<error></error> => optional information, in place of a test case - normally if the tests in the suite could not be found etc.
<testcase> => the results from executing a test method
<system-out> => data written to System.out during the test run
<system-err> => data written to System.err during the test run
<skipped/> => test was skipped
<failure> => test failed
<error> => test encountered an error
</testcase>
...
</testsuite>
...
</testsuites>
In res/color
place a file "text_selector.xml":
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/blue" android:state_focused="true" />
<item android:color="@color/blue" android:state_selected="true" />
<item android:color="@color/green" />
</selector>
Then in TextView
use it:
<TextView
android:id="@+id/value_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text"
android:textColor="@color/text_selector"
android:textSize="15sp"
/>
And in code you'll need to set a click listener.
private var isPressed = false
private fun TextView.setListener() {
this.setOnClickListener { v ->
run {
if (isPressed) {
v.isSelected = false
v.clearFocus()
} else {
v.isSelected = true
v.requestFocus()
}
isPressed = !isPressed
}
}
}
override fun onResume() {
super.onResume()
textView.setListener()
}
override fun onPause() {
textView.setOnClickListener(null)
super.onPause()
}
Sorry if there are errors, I changed a code before publishing and didn't check.
If you have given same text name for both of your Id and Name properties you can give like document.getElementByName('frmMain')[index]
other wise object required error will come.And if you have only one table in your page you can use document.getElementBytag('table')[index]
.
EDIT:
You can replace the index according to your form, if its first form place 0 for index.
eval isn't always evil. There are times where it's perfectly appropriate.
However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way.
To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato':
eval('document.' + potato + '.style.color = "red"');
If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval:
document[potato].style.color = 'red';
...which is much easier to read as well as less potentially buggy.
(But then, someone who /really/ knew what they were doing would say:
document.getElementById(potato).style.color = 'red';
which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)
Here's one way:
Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = theDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
Modified from here:MSDN OpenFileDialog.OpenFile
EDIT Here's another way more suited to your needs:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
string filename = theDialog.FileName;
string[] filelines = File.ReadAllLines(filename);
List<Employee> employeeList = new List<Employee>();
int linesPerEmployee = 4;
int currEmployeeLine = 0;
//parse line by line into instance of employee class
Employee employee = new Employee();
for (int a = 0; a < filelines.Length; a++)
{
//check if to move to next employee
if (a != 0 && a % linesPerEmployee == 0)
{
employeeList.Add(employee);
employee = new Employee();
currEmployeeLine = 1;
}
else
{
currEmployeeLine++;
}
switch (currEmployeeLine)
{
case 1:
employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
break;
case 2:
employee.Name = filelines[a].Trim();
break;
case 3:
employee.Address = filelines[a].Trim();
break;
case 4:
string[] splitLines = filelines[a].Split(' ');
employee.Wage = Convert.ToDouble(splitLines[0].Trim());
employee.Hours = Convert.ToDouble(splitLines[1].Trim());
break;
}
}
//Test to see if it works
foreach (Employee emp in employeeList)
{
MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
emp.Name + Environment.NewLine +
emp.Address + Environment.NewLine +
emp.Wage + Environment.NewLine +
emp.Hours + Environment.NewLine);
}
}
}
This is how Adding new column to Table
ALTER TABLE [tableName]
ADD ColumnName Datatype
E.g
ALTER TABLE [Emp]
ADD Sr_No Int
And If you want to make it auto incremented
ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL
The following output illustrates results of using copy constructor and Collections.copy():
Copy [1, 2, 3] to [1, 2, 3] using copy constructor.
Copy [1, 2, 3] to (smaller) [4, 5]
java.lang.IndexOutOfBoundsException: Source does not fit in dest
at java.util.Collections.copy(Collections.java:556)
at com.farenda.java.CollectionsCopy.copySourceToSmallerDest(CollectionsCopy.java:36)
at com.farenda.java.CollectionsCopy.main(CollectionsCopy.java:14)
Copy [1, 2] to (same size) [3, 4]
source: [1, 2]
destination: [1, 2]
Copy [1, 2] to (bigger) [3, 4, 5]
source: [1, 2]
destination: [1, 2, 5]
Copy [1, 2] to (unmodifiable) [4, 5]
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList.set(Collections.java:1311)
at java.util.Collections.copy(Collections.java:561)
at com.farenda.java.CollectionsCopy.copyToUnmodifiableDest(CollectionsCopy.java:68)
at com.farenda.java.CollectionsCopy.main(CollectionsCopy.java:20)
The source of full program is here: Java List copy. But the output is enough to see how java.util.Collections.copy() behaves.
Swift 3.0
Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.
lazy var tableView: UITableView = {
let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
view.delegate = self
view.dataSource = self
view.separatorStyle = .none
return view
}()
you can also use the below code.
function activateController(){
console.log('HELLO WORLD');
}
$scope.$on('$viewContentLoaded', function ($evt, data) {
activateController();
});
This question has been asked long ago but none of the answers above helped me out, though Milad Moosavi`s answer was very close. To open a new activity from a certain position on the recycler view, the following code may help:
@Override
public void onBindViewHolder(@NonNull TripViewHolder holder, int position) {
Trip currentTrip = trips.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), EditTrip.class);
v.getContext().startActivity(intent);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(v.getContext(), ReadTripActivity.class);
v.getContext().startActivity(intent);
return false;
}
});
}
Try SQLDeveloper - there is a migration workbench there
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
If the element has no class, give it one. Otherwise, append a space followed by the new className:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
Messages have content. Content can be text, html, a DataHandler or a Multipart, and there can only be one content. Multiparts only have BodyParts but can have more than one. BodyParts, like Messages, can have content which has already been described.
A message with HTML, text and an a attachment can be viewed hierarchically like this:
message
mainMultipart (content for message, subType="mixed")
->htmlAndTextBodyPart (bodyPart1 for mainMultipart)
->htmlAndTextMultipart (content for htmlAndTextBodyPart, subType="alternative")
->textBodyPart (bodyPart2 for the htmlAndTextMultipart)
->text (content for textBodyPart)
->htmlBodyPart (bodyPart1 for htmlAndTextMultipart)
->html (content for htmlBodyPart)
->fileBodyPart1 (bodyPart2 for the mainMultipart)
->FileDataHandler (content for fileBodyPart1 )
And the code to build such a message:
// the parent or main part if you will
Multipart mainMultipart = new MimeMultipart("mixed");
// this will hold text and html and tells the client there are 2 versions of the message (html and text). presumably text
// being the alternative to html
Multipart htmlAndTextMultipart = new MimeMultipart("alternative");
// set text
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(text);
htmlAndTextMultipart.addBodyPart(textBodyPart);
// set html (set this last per rfc1341 which states last = best)
MimeBodyPart htmlBodyPart = new MimeBodyPart();
htmlBodyPart.setContent(html, "text/html; charset=utf-8");
htmlAndTextMultipart.addBodyPart(htmlBodyPart);
// stuff the multipart into a bodypart and add the bodyPart to the mainMultipart
MimeBodyPart htmlAndTextBodyPart = new MimeBodyPart();
htmlAndTextBodyPart.setContent(htmlAndTextMultipart);
mainMultipart.addBodyPart(htmlAndTextBodyPart);
// attach file body parts directly to the mainMultipart
MimeBodyPart filePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("/path/to/some/file.txt");
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());
mainMultipart.addBodyPart(filePart);
// set message content
message.setContent(mainMultipart);
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
Combining and organizing all the current answers into one answer, then adding my own research:
Brief summary of Microsoft gadget development:
What are they written in? Windows Vista/Seven gadgets are developed in a mix of XML, HTML, CSS, and some IE scripting language. It is also possible to use C# with the latest release of Script#.
How are they packaged/deployed? The actual gadgets are stored in *.gadget files, which are simply the text source files listed above compressed into a single zip file.
Useful references for gadget development:
where do I start? Good introductory references to Windows Vista/Seven gadget development:
If you are willing to use offline resources, this book appears to be an excellent resource:
What do I need to know? Some other useful references; not necessarily instructional
Update: Well, this has proven to be a popular answer~ Sharing my own recent experience with Windows 7 gadget development:
Perhaps the easiest way to get started with Windows 7 gadget development is to modify a gadget that has already been developed. I recently did this myself because I wanted a larger clock gadget. Unable to find any, I tinkered with a copy of the standard Windows clock gadget until it was twice as large. I recommend starting with the clock gadget because it is fairly small and well-written. Here is the process I used:
C:\Program Files\Windows Sidebar\Gadgets\Clock.Gadget\
<name>Clock</name>
This is the name that will be displayed in the "Gadgets Gallery" window.%LOCALAPPDATA%\Microsoft\Windows Sidebar\
)I use this simple script to get a log from the pods of a deployment:
#!/usr/bin/env bash
DEPLOYMENT=$1
for p in $(kubectl get pods | grep ^${DEPLOYMENT}- | cut -f 1 -d ' '); do
echo ---------------------------
echo $p
echo ---------------------------
kubectl logs $p
done
Usage: log_deployment.sh "deployment-name".
Script will then show log of all pods that start with that "deployment-name".
Here is how I do it. You will need to get the namespace URL and the element name from your generated code.
new JAXBElement(new QName("http://www.novell.com/role/service","userDN"),
new String("").getClass(),testDN);
Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)
git mergetool
Then add your changes and go on
git rebase --continue
Good luck
It depends what you wanted to do with that column e.g. here's an example of appending a new column to a recordset which can be updated on the client side:
Sub MSDataShape_AddNewCol()
Dim rs As ADODB.Recordset
Set rs = CreateObject("ADODB.Recordset")
With rs
.ActiveConnection = _
"Provider=MSDataShape;" & _
"Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Tempo\New_Jet_DB.mdb"
.Source = _
"SHAPE {" & _
" SELECT ExistingField" & _
" FROM ExistingTable" & _
" ORDER BY ExistingField" & _
"} APPEND NEW adNumeric(5, 4) AS NewField"
.LockType = adLockBatchOptimistic
.Open
Dim i As Long
For i = 0 To .RecordCount - 1
.Fields("NewField").Value = Round(.Fields("ExistingField").Value, 4)
.MoveNext
Next
rs.Save "C:\rs.xml", adPersistXML
End With
End Sub
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
You can't install and run in one go - but you can certainly use adb to start your already installed application. Use adb shell am start to fire an intent - you will need to use the correct intent for your application though. A couple of examples:
adb shell am start -a android.intent.action.MAIN -n com.android.settings/.Settings
will launch Settings, and
adb shell am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
will launch the Browser. If you want to point the Browser at a particular page, do this
adb shell am start -a android.intent.action.VIEW -n com.android.browser/.BrowserActivity http://www.google.co.uk
If you don't know the name of the activities in the APK, then do this
aapt d xmltree <path to apk> AndroidManifest.xml
the output content will includes a section like this:
E: activity (line=32)
A: android:theme(0x01010000)=@0x7f080000
A: android:label(0x01010001)=@0x7f070000
A: android:name(0x01010003)="com.anonymous.MainWindow"
A: android:launchMode(0x0101001d)=(type 0x10)0x3
A: android:screenOrientation(0x0101001e)=(type 0x10)0x1
A: android:configChanges(0x0101001f)=(type 0x11)0x80
E: intent-filter (line=33)
E: action (line=34)
A: android:name(0x01010003)="android.intent.action.MAIN"
XE: (line=34)
That tells you the name of the main activity (MainWindow), and you can now run
adb shell am start -a android.intent.action.MAIN -n com.anonymous/.MainWindow
Just use it like it was an object you defined. i.e.
$trends = $json_output->trends;
Try This
.content {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 250px;_x000D_
width: 200px;_x000D_
border: solid;_x000D_
word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.content h1 , .content h2 {_x000D_
margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
.content p {_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="content">_x000D_
<h1>heading 1</h1>_x000D_
<h2>heading 2</h2>_x000D_
<p>Some more or less text</p>_x000D_
<a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
You need to specify the column in both expressions.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
There are a few ways of doing that... the simplest is to have the async method also do the follow-on operation. Another popular approach is to pass in a callback, i.e.
void RunFooAsync(..., Action<bool> callback) {
// do some stuff
bool result = ...
if(callback != null) callback(result);
}
Another approach would be to raise an event (with the result in the event-args data) when the async operation is complete.
Also, if you are using the TPL, you can use ContinueWith
:
Task<bool> outerTask = ...;
outerTask.ContinueWith(task =>
{
bool result = task.Result;
// do something with that
});
jQuery.fn
is defined shorthand for jQuery.prototype
. From the source code:
jQuery.fn = jQuery.prototype = {
// ...
}
That means jQuery.fn.jquery
is an alias for jQuery.prototype.jquery
, which returns the current jQuery version. Again from the source code:
// The current version of jQuery being used
jquery: "@VERSION",
<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>
if you want to capture the result in a variable
Have a look at the rack-cors middleware. It will handle CORS headers in a configurable manner.
I was using the following:
from module import Foo
foo_instance = Foo()
but to get rid of circular reference
I did the following and it worked:
import module.foo
foo_instance = foo.Foo()