I had this when build my application with "All cpu" target while it referenced a 3rd party x64-only (managed) dll.
Use CDATA in the below way for formatting your text
<resources>
<string name="app_name">DemoShareActionButton</string>
<string name="intro_message">
<b>
<![CDATA[ This sample shows you how a provide a context-sensitive ShareActionProvider.
]]>
</b>
</string>
Just add any tag you want before the <![CDATA[
and you will get your proper output.
Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".
Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.
For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.
Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.
Using Stack
, here are the steps to follow: Push the first vertex on the stack then,
Here's the Java program following the above steps:
public void searchDepthFirst() {
// begin at vertex 0
vertexList[0].wasVisited = true;
displayVertex(0);
stack.push(0);
while (!stack.isEmpty()) {
int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
// if no such vertex
if (adjacentVertex == -1) {
stack.pop();
} else {
vertexList[adjacentVertex].wasVisited = true;
// Do something
stack.push(adjacentVertex);
}
}
// stack is empty, so we're done, reset flags
for (int j = 0; j < nVerts; j++)
vertexList[j].wasVisited = false;
}
Create a UITextView inside of a tableViewController. I used function: textViewDidChange and then checked for return-key-input. then if it detected return-key-input, delete the input of return key and dismiss keyboard.
func textViewDidChange(_ textView: UITextView) {
tableView.beginUpdates()
if textView.text.contains("\n"){
textView.text.remove(at: textView.text.index(before: textView.text.endIndex))
textView.resignFirstResponder()
}
tableView.endUpdates()
}
1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.
2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:
The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me Codd).
Say you have a table containing courses that are taken in a certain semester, and you have the following data:
|-----Primary Key----| uh oh |
V
CourseID | SemesterID | #Places | Course Name |
------------------------------------------------|
IT101 | 2009-1 | 100 | Programming |
IT101 | 2009-2 | 100 | Programming |
IT102 | 2009-1 | 200 | Databases |
IT102 | 2010-1 | 150 | Databases |
IT103 | 2009-2 | 120 | Web Design |
This is not in 2NF, because the fourth column does not rely upon the entire key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.
Primary Key |
CourseID | Course Name |
---------------------------|
IT101 | Programming |
IT102 | Databases |
IT103 | Web Design |
No redundancy!
Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:
|-----Primary Key----| uh oh |
V
Course | Semester | #Places | TeacherID | TeacherName |
---------------------------------------------------------------|
IT101 | 2009-1 | 100 | 332 | Mr Jones |
IT101 | 2009-2 | 100 | 332 | Mr Jones |
IT102 | 2009-1 | 200 | 495 | Mr Bentley |
IT102 | 2010-1 | 150 | 332 | Mr Jones |
IT103 | 2009-2 | 120 | 242 | Mrs Smith |
Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is not in 3NF. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.
Primary Key |
TeacherID | TeacherName |
---------------------------|
332 | Mr Jones |
495 | Mr Bentley |
242 | Mrs Smith |
No redundancy!!
One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires everything that the lower normal forms had, plus some extra conditions, which must all be fulfilled.
something like below
var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
friends.ForEach(a=>a.msgSentBy='1234');
db.SaveChanges();
}
you can update multiple fields as below
friends.ForEach(a =>
{
a.property1 = value1;
a.property2 = value2;
});
The best solution I could find at present time to open a window maximized is (Internet Explorer 11, Chrome 49, Firefox 45):
var popup = window.open("your_url", "popup", "fullscreen");
if (popup.outerWidth < screen.availWidth || popup.outerHeight < screen.availHeight)
{
popup.moveTo(0,0);
popup.resizeTo(screen.availWidth, screen.availHeight);
}
see https://jsfiddle.net/8xwocrp6/7/
Note 1: It does not work on Edge (13.1058686). Not sure whether it's a bug or if it's as designed (I've filled a bug report, we'll see what they have to say about it). Here is a workaround:
if (navigator.userAgent.match(/Edge\/\d+/g))
{
return window.open("your_url", "popup", "width=" + screen.width + ",height=" + screen.height);
}
Note 2: moveTo
or resizeTo
will not work (Access denied) if the window you are opening is on another domain.
Here is code you can directly copy paste :
String imageName = "picture1.jpg";
String [] imageNameArray = imageName.split("\\.");
for(int i =0; i< imageNameArray.length ; i++)
{
system.out.println(imageNameArray[i]);
}
And what if mistakenly there are spaces left before or after "." in such cases? It's always best practice to consider those spaces also.
String imageName = "picture1 . jpg";
String [] imageNameArray = imageName.split("\\s*.\\s*");
for(int i =0; i< imageNameArray.length ; i++)
{
system.out.println(imageNameArray[i]);
}
Here, \\s* is there to consider the spaces and give you only required splitted strings.
Using tail:
#dmesg
...
...
...
[132059.017752] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
[132116.566238] cfg80211: Calling CRDA to update world regulatory domain
[132116.568939] cfg80211: World regulatory domain updated:
[132116.568942] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132116.568944] cfg80211: (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568945] cfg80211: (2457000 KHz - 2482000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568947] cfg80211: (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
[132116.568948] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568949] cfg80211: (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132120.288218] cfg80211: Calling CRDA for country: GB
[132120.291143] cfg80211: Regulatory domain changed to country: GB
[132120.291146] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211: (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211: (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211: (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | head 2
head: cannot open ‘2’ for reading: No such file or directory
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -2
[132120.291153] cfg80211: (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -5
[132120.291148] cfg80211: (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211: (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211: (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -6
[132120.291146] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211: (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211: (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211: (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$
If you are using the updated Microsoft.Web.RedisSessionStateProvider
(starting from 3.0.2
) you can add this to your web.config
to allow concurrent sessions.
<appSettings>
<add key="aspnet:AllowConcurrentRequestsPerSession" value="true"/>
</appSettings>
In my case, I deleted out the caniuse-lite
, browserslist
folders from node_modules
.
Then I type the following command to install the packages.
npm i -g browserslist caniuse-lite --save
worked fine.
Use boost::filesystem:
#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}
I tried the above solutions. None worked.
In the end I opened Makefile file and manually changed prefix path to desired installation path like below.
PREFIX ?= "installation path"
When I tried --prefix, "make" complained that there is not such command input. However, perhaps some packages accepts --prefix which is of course a cleaner solution.
You can change the background or ripple color of each Tab like this:
//set ripple color for each tab
for(int n = 0; n < mTabLayout.getTabCount(); n++){
View tab = ((ViewGroup)mTabLayout.getChildAt(0)).getChildAt(n);
if(tab != null && tab.getBackground() instanceof RippleDrawable){
RippleDrawable rippleDrawable = (RippleDrawable)tab.getBackground();
if (rippleDrawable != null) {
rippleDrawable.setColor(ColorStateList.valueOf(rippleColor));
}
}
}
The windows handle limit for your application is 10,000 handles. You're getting the error because your program is creating too many handles. You'll need to find the memory leak. As other users have suggested, use a Memory Profiler. I use the .Net Memory Profiler as well. Also, make sure you're calling the dispose method on controls if you're removing them from a form before the form closes (otherwise the controls won't dispose). You'll also have to make sure that there are no events registered with the control. I myself have the same issue, and despite what I already know, I still have some memory leaks that continue to elude me..
How to hard reset Visual Studio instance
When developing extensions sometimes you just mess up, others someone else does. If you start getting errors loading even the most mundane extensions, these are the instructions to hard reset your instance.
Close Visual Studio (if you haven’t already).
Open the registry editor (regedit.exe)
Delete the HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{version}
Delete the HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{version}_Config
Delete the %LOCALAPPDATA%\Microsoft\VisualStudio\{version} directory.
Enjoy your brand new Visual Studio instance.
If on the other side you want to reset the experimental hive you can do the same to with the ‘{version}Exp’ ones.
Happy coding!
Source: http://www.corvalius.com/site/hacks/how-to-hard-reset-visual-studio-instance/
Another solution would be to use Empty
.
Returns an empty IEnumerable that has the specified type argument.
IEnumerable<object> a = Enumerable.Empty<object>();
There is a thread on SO about it: Is it better to use Enumerable.Empty() as opposed to new List to initialize an IEnumerable?
If you use an empty array or empty list, those are objects and they are stored in memory. The Garbage Collector has to take care of them. If you are dealing with a high throughput application, it could be a noticeable impact.
Enumerable.Empty
does not create an object per call thus putting less load on the GC.
While at it, do not forget that all collections are finite, while Iterable has no promises whatsoever. If something is Iterable you can get an Iterator and that is it.
for (piece : sthIterable){
..........
}
will be expanded to:
Iterator it = sthIterable.iterator();
while (it.hasNext()){
piece = it.next();
..........
}
it.hasNext() is not required to ever return false. Thus in the general case you cannot expect to be able to convert every Iterable to a Collection. For example you can iterate over all positive natural numbers, iterate over something with cycles in it that produces the same results over and over again, etc.
Otherwise: Atrey's answer is quite fine.
One way of doing this would be by using ngClass directive and the $location service. In your template you could do:
ng-class="{active:isActive('/dashboard')}"
where isActive
would be a function in a scope defined like this:
myApp.controller('MyCtrl', function($scope, $location) {
$scope.isActive = function(route) {
return route === $location.path();
}
});
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/KzAfG/
Repeating ng-class="{active:isActive('/dashboard')}"
on each navigation tab might be tedious (if you've got many tabs) so this logic might be a candidate for a very simple directive.
After some serious searching it seems i've found the answer to my question:
from: http://www.brunildo.org/test/Overflowxy2.html
In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.
also the W3C spec says:
The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.
Short Version:
If you are using visible
for either overflow-x
or overflow-y
and something other than visible
for the other, the visible
value is interpreted as auto
.
this works. thanks. I am injecting custom html and compile it using angular in the controller.
var tableContent= '<div>Search: <input ng-model="searchText"></div>'
+'<div class="table-heading">'
+ '<div class="table-col">Customer ID</div>'
+ ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';
$timeout(function () {
var linkingFunction = $compile(tableContent);
var elem = linkingFunction($scope);
// You can then use the DOM element like normal.
jQuery(tablePanel).append(elem);
console.log("timeout");
},100);
My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.
To provide a simple sample:
@Model namespace.model
<!Doctype html>
<html>
<head>
<title>Test Razor</title>
</head>
<body>
<ul class="mainList">
@foreach(var x in ViewData.model)
{
<li>@x.PropertyName</li>
}
</ul>
</body>
And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.
As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.
Thanks Nathj07
Just Add android:background="#10000000" in your AppBarLayout tag It works
Create a C# class that maps to your Json and use Newsoft JsonConvert
to Deserialise it.
For example:
public Class MyResponse
{
public Meta Meta { get; set; }
public Response Response { get; set; }
}
I agree that Amazon appears to be intentionally obfuscating even how to find the API documentation, as well as use it. I'm just speculating though.
Renaming the services from "ECS" to "Product Advertising API" was probably also not the best move, it essentially invalidated all that Google mojo they had built up over time.
It took me quite a while to 'discover' this updated link for the Product Advertising API. I don't remember being able to easily discover it through the typical 'Developer' link on the Amazon webpage. This documentation appears to valid and what I've worked from recently.
The change to authentication procedures also seems to add further complexity, but I'm sure they have a reason for it.
I use SOAP via C# to communicate with Amazon Product API.
With the REST API you have to encrypt the whole URL in a fairly specific way. The params have to be sorted, etc. There is just more to do. With the SOAP API, you just encrypt the operation+timestamp, and thats it.
Adam O'Neil's post here, How to get album, dvd, and blueray cover art from Amazon, walks through the SOAP with C# method. Its not the original sample I pulled down, and contrary to his comment, it was not an official Amazon sample I stumbled on, though the code looks identical. However, Adam does a good job at presenting all the necessary steps. I wish I could credit the original author.
As of Java 1.8, you can use Files.list to get a stream:
Path findFile(Path targetDir, String fileName) throws IOException {
return Files.list(targetDir).filter( (p) -> {
if (Files.isRegularFile(p)) {
return p.getFileName().toString().equals(fileName);
} else {
return false;
}
}).findFirst().orElse(null);
}
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
it should end up like this in the $_POST[] array (PHP format for easy visualization)
$_POST[] = array(
'firstname'=>'value',
'lastname'=>'value',
'email'=>'value',
'address'=>'value',
'tree' => array(
'tree1'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree2'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree3'=>array(
'fruit'=>'value',
'height'=>'value'
)
)
)
ScreenCapture sc = new ScreenCapture();
// capture entire screen, and save it to a file
Image img = sc.CaptureScreen();
// display image in a Picture control named imageDisplay
this.imageDisplay.Image = img;
// capture this window, and save it
sc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif);
http://www.developerfusion.com/code/4630/capture-a-screen-shot/
I had a sub folder named web.config renaming this folder resolved the issue
The easiest way is to use Math library.
Use Math.pow(a, b)
and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!
<span class="menu">Menu</span>
.menu {
position: relative;
text-decoration: none;
font-weight: 400;
color: blue;
transition: all .35s ease;
&::before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: yellow;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all 0.3s ease-in-out 0s;
transition: all 0.3s ease-in-out 0s;
}
&:hover {
color: yellow;
&::before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
}
}
It's possible to do with just one image file using the ColorFilter method. However, ColorFilter expects to work with ImageViews and not Buttons, so you have to transform your buttons into ImageViews. This isn't a problem if you're using images as your buttons anyway, but it's more annoying if you had text... Anyway, assuming you find a way around the problem with text, here's the code to use:
ImageView button = (ImageView) findViewById(R.id.button);
button.setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
That applies a red overlay to the button (the color code is the hex code for fully opaque red - first two digits are transparency, then it's RR GG BB.).
Hi we can use ToLower Method sometimes it is not filter.
EmployeeId = Session["EmployeeID"].ToString();
var rows = dtCrewList.AsEnumerable().Where
(row => row.Field<string>("EmployeeId").ToLower()== EmployeeId.ToLower());
if (rows.Any())
{
tblFiltered = rows.CopyToDataTable<DataRow>();
}
If it helps anybody, for me that happened because I was trying to run a Django implementation in python 3.4 with my python 2.7 command
Without using connect by or regexp:
with mytable as (
select 108 name, 'test' project, 'Err1,Err2,Err3' error from dual
union all
select 109, 'test2', 'Err1' from dual
)
,x as (
select name
,project
,','||error||',' error
from mytable
)
,iter as (SELECT rownum AS pos
FROM all_objects
)
select x.name,x.project
,SUBSTR(x.error
,INSTR(x.error, ',', 1, iter.pos) + 1
,INSTR(x.error, ',', 1, iter.pos + 1)-INSTR(x.error, ',', 1, iter.pos)-1
) error
from x, iter
where iter.pos < = (LENGTH(x.error) - LENGTH(REPLACE(x.error, ','))) - 1;
1 Close Android Studio (AS)
2 Delete the folder in C:\Users.gradle\wrapper\dists\gradle-2.1-all
3 Run AS as admin
4 Sync your project files
I've a way and work like this:
<'a href="FOLDER_PATH" target="_explorer.exe">Link Text<'/a>
There's a bug in IE6
Content with "Content-Encoding: gzip" is always cached even if you use "Cache-Control: no-cache".
http://support.microsoft.com/kb/321722
You can disable gzip compression for IE6 users (check the user agent for "MSIE 6")
Another use that I've been putting to good purpose is fetching data from multiple sources. In the example below, I'm fetching multiple, independent JSON schema objects used in an existing application for validation between a client and a REST server. In this case, I don't want the browser-side application to start loading data before it has all the schemas loaded. $.when.apply().then() is perfect for this. Thank to Raynos for pointers on using then(fn1, fn2) to monitor for error conditions.
fetch_sources = function (schema_urls) {
var fetch_one = function (url) {
return $.ajax({
url: url,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
return $.map(schema_urls, fetch_one);
}
var promises = fetch_sources(data['schemas']);
$.when.apply(null, promises).then(
function () {
var schemas = $.map(arguments, function (a) {
return a[0]
});
start_application(schemas);
}, function () {
console.log("FAIL", this, arguments);
});
The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2)
, it should work
SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table
OR
SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table
Using Ref forwarding you can pass the ref from parent to further down to a child.
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Note The second ref argument only exists when you define a component with React.forwardRef call. Regular functional or class components don’t receive the ref argument, and ref is not available in props either.
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
Reference: React Documentation.
This will handle negative numbers, fractions, string, everything:
ORDER BY ISNUMERIC(col) DESC, Try_Parse(col AS decimal(10,2)), col;
Try the following:
LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/python
Replace /usr/local/lib
with the folder where you have installed libpython2.7.so.1.0
if it is not in /usr/local/lib
.
If this works and you want to make the changes permanent, you have two options:
Add export LD_LIBRARY_PATH=/usr/local/lib
to your .profile
in your home directory (this works only if you are using a shell which loads this file when a new shell instance is started). This setting will affect your user only.
Add /usr/local/lib
to /etc/ld.so.conf
and run ldconfig
. This is a system-wide setting of course.
You can take a screenshot and save the rendered page in a location and you can check the screenshot if the page loaded completely without broken images
In my case @component
was not working because I initialized that class instance by using new <classname>()
.
If we initialize instance by conventional Java way anywhere in code, then spring won't add that component in IOC container.
You can also do it from the storyboard. Click the table view cell and in the attributes inspector under Table View Cell, change the drop down next to Selection to None.
It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.
If you dataframe is df
you can simply use:
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(15, 10))
sns.heatmap(df.corr(), annot=True)
I believe you need to map the result before you subscribe to it. You configure it like this:
updateProfileInformation(user: User) {
var headers = new Headers();
headers.append('Content-Type', this.constants.jsonContentType);
var t = localStorage.getItem("accessToken");
headers.append("Authorization", "Bearer " + t;
var body = JSON.stringify(user);
return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
.map((response: Response) => {
var result = response.json();
return result;
})
.catch(this.handleError)
.subscribe(
status => this.statusMessage = status,
error => this.errorMessage = error,
() => this.completeUpdateUser()
);
}
Go to httpd.conf
on /Applications/MAMP/conf/apache
and see if the LoadModule rewrite_module modules/mod_rewrite.so
line is un-commented (without the # at the beginning)
and change these from ...
<VirtualHost *:80>
ServerName ...
DocumentRoot /....
</VirtualHost>
To this:
<VirtualHost *:80>
ServerAdmin ...
ServerName ...
DocumentRoot ...
<Directory ...>
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory ...>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
Can also use:
find . -mindepth 1 -mtime +3 -delete
To not delete target directory
What version of .NET and Visual Studio are you using?
When you created the new project, you should have a file in your solution called app.config. That is the default configuration file.
var line = "<label onclick="alert(1)">aaa</label>";
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
using (html):
<span ng-bind-html="line | unsafe"></span>
==>click `aaa` show alert box
include angular-sanitize.js
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
add ngSanitize
in root angular app
var app = angular.module("app", ["ngSanitize"]);
using (html):
<span ng-bind-html="line"></span>
==>click `aaa` nothing happen
Find server.xml at $CATALINA_BASE/conf/server.xml
Find appBase
attribute in <Host>
element
by default it will be something like :
<Host name="localhost" appBase="webapps ...>
Change appBase to your required path. There are different way people put it, but I use
/c:/myfolder/newwebapps
Remember, no slash at the end, but at start. Also note it's direction as well.
Meanwhile I have found the (for me) perfect solution: nexe, which creates a single executable from a Node.js application including all of its modules.
It's the next best thing to an ideal solution.
What is the portable way to annotate a byte[] property?
It depends on what you want. JPA can persist a non annotated byte[]
. From the JPA 2.0 spec:
11.1.6 Basic Annotation
The
Basic
annotation is the simplest type of mapping to a database column. TheBasic
annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive, types, wrappers of the primitive types,java.lang.String
,java.math.BigInteger
,java.math.BigDecimal
,java.util.Date
,java.util.Calendar
,java.sql.Date
,java.sql.Time
,java.sql.Timestamp
,byte[]
,Byte[]
,char[]
,Character[]
, enums, and any other type that implementsSerializable
. As described in Section 2.8, the use of theBasic
annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.
And Hibernate will map a it "by default" to a SQL VARBINARY
(or a SQL LONGVARBINARY
depending on the Column
size?) that PostgreSQL handles with a bytea
.
But if you want the byte[]
to be stored in a Large Object, you should use a @Lob
. From the spec:
11.1.24 Lob Annotation
A
Lob
annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use theLob
annotation when mapping to a databaseLob
type. TheLob
annotation may be used in conjunction with the Basic annotation or with theElementCollection
annotation when the element collection value is of basic type. ALob
may be either a binary or character type. TheLob
type is inferred from the type of the persistent field or property and, except for string and character types, defaults to Blob.
And Hibernate will map it to a SQL BLOB
that PostgreSQL handles with a oid
.
Is this fixed in some recent version of hibernate?
Well, the problem is that I don't know what the problem is exactly. But I can at least say that nothing has changed since 3.5.0-Beta-2 (which is where a changed has been introduced)in the 3.5.x branch.
But my understanding of issues like HHH-4876, HHH-4617 and of PostgreSQL and BLOBs (mentioned in the javadoc of the PostgreSQLDialect
) is that you are supposed to set the following property
hibernate.jdbc.use_streams_for_binary=false
if you want to use oid
i.e. byte[]
with @Lob
(which is my understanding since VARBINARY
is not what you want with Oracle). Did you try this?
As an alternative, HHH-4876 suggests using the deprecated PrimitiveByteArrayBlobType
to get the old behavior (pre Hibernate 3.5).
Try this.
public function insert_data_function($your_data)
{
$this->db->insert("your_table",$your_data);
$last_id = $this->db->insert_id();
return $last_id;
}
I would recommend setting AutoEllipsis
property of label to true
and AutoSize
to false
. If text length exceeds label bounds, it'll add three dots (...)
at the end and automatically set the complete text as a tooltip. So users can see the complete text by hovering over the label.
You can derive a normal array from the ArrayBuffer
by using Array.prototype.slice
.
Use a function like Array.prototype.map
to convert bytes in to characters and join
them together to forma string.
function arrayBufferToBase64(ab){
var dView = new Uint8Array(ab); //Get a byte view
var arr = Array.prototype.slice.call(dView); //Create a normal array
var arr1 = arr.map(function(item){
return String.fromCharCode(item); //Convert
});
return window.btoa(arr1.join('')); //Form a string
}
This method is faster since there are no string concatenations running in it.
This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "
This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.
Maybe using the TOR network may help you do your job.
On POSIX, ultimately you want to be invoking the TIOCGWINSZ
(Get WINdow SiZe) ioctl()
call. Most languages ought to have some sort of wrapper for that. E.g in Perl you can use Term::Size:
use Term::Size qw( chars );
my ( $columns, $rows ) = chars \*STDOUT;
Try:
gem install pg -- --with-pg-config=`which pg_config`
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
As others answered you, if you are creating a new project, you can separate frontend and backend and use any django rest plugin to create rest api for your frontend application. This is in the ideal world.
If you have a project with the django templating already in place, then you must load your react dom render in the page you want to load the application. In my case I had already django-pipeline and I just added the browserify extension. (https://github.com/j0hnsmith/django-pipeline-browserify)
As in the example, I loaded the app using django-pipeline:
PIPELINE = {
# ...
'javascript':{
'browserify': {
'source_filenames' : (
'js/entry-point.browserify.js',
),
'output_filename': 'js/entry-point.js',
},
}
}
Your "entry-point.browserify.js" can be an ES6 file that loads your react app in the template:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app.js';
import "babel-polyfill";
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promise from 'redux-promise';
import reducers from './reducers/index.js';
const createStoreWithMiddleware = applyMiddleware(
promise
)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App/>
</Provider>
, document.getElementById('my-react-app')
);
In your django template, you can now load your app easily:
{% load pipeline %}
{% comment %}
`browserify` is a PIPELINE key setup in the settings for django
pipeline. See the example above
{% endcomment %}
{% javascript 'browserify' %}
{% comment %}
the app will be loaded here thanks to the entry point you created
in PIPELINE settings. The key is the `entry-point.browserify.js`
responsable to inject with ReactDOM.render() you react app in the div
below
{% endcomment %}
<div id="my-react-app"></div>
The advantage of using django-pipeline is that statics get processed during the collectstatic
.
In Typescript use the For Each like below.
selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
{
for (var childObj in obj )
{
value.checked = parentChecked;
}
}
}
It seems clear that $(TESTS)
is empty so your 1.4.0 makefile is effectively
all:
clean:
rm -f gtest.a gtest_main.a *.o
Indeed, all has nothing to do. and clean does exactly what it says rm -f gtest.a ...
A refinement to JustinStolle's edit (Eran Yogev's use of BlockCopy).
The proposed solution is indeed faster than using Encoding. Problem is that it doesn't work for encoding byte arrays of uneven length. As given, it raises an out-of-bound exception. Increasing the length by 1 leaves a trailing byte when decoding from string.
For me, the need came when I wanted to encode from DataTable
to JSON
.
I was looking for a way to encode binary fields into strings and decode from string back to byte[]
.
I therefore created two classes - one that wraps the above solution (when encoding from strings it's fine, because the lengths are always even), and another that handles byte[]
encoding.
I solved the uneven length problem by adding a single character that tells me if the original length of the binary array was odd ('1') or even ('0')
As follows:
public static class StringEncoder
{
static byte[] EncodeToBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string DecodeToString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
}
public static class BytesEncoder
{
public static string EncodeToString(byte[] bytes)
{
bool even = (bytes.Length % 2 == 0);
char[] chars = new char[1 + bytes.Length / sizeof(char) + (even ? 0 : 1)];
chars[0] = (even ? '0' : '1');
System.Buffer.BlockCopy(bytes, 0, chars, 2, bytes.Length);
return new string(chars);
}
public static byte[] DecodeToBytes(string str)
{
bool even = str[0] == '0';
byte[] bytes = new byte[(str.Length - 1) * sizeof(char) + (even ? 0 : -1)];
char[] chars = str.ToCharArray();
System.Buffer.BlockCopy(chars, 2, bytes, 0, bytes.Length);
return bytes;
}
}
Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.
Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.
The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.
You need the path of the plugins directory of your local GATE install. So if Gate is installed in "/home/user/GATE_Developer_8.1", the code looks like this:
System.setProperty("gate.home", "/home/user/GATE_Developer_8.1/plugins");
You don't have to set gate.home from the command line. You can set it in your application, as long as you set it BEFORE you call Gate.init().
For Windows users something like this should work:
PS C:\angular> npm install --python=C:\Python27\python.exe
Use this following code:
let intVal=56
let floatval:Double=56.897898
let doubleValue=89.0
let explicitDaouble:Double=89.56
let stringValue:"Hello"
let stringValue="String:\(stringValue) Integer:\(intVal) Float:\(floatval) Double:\(doubleValue) ExplicitDouble:\(explicitDaouble) "
MonoDevelop from: http://monodevelop.com/
There is no equivalent to Visual Studio. However, for writing C# on Mac or Linux, you can't get better than MonoDevelop.
The Mac build is pre beta. From the MonoDevelop site on Mac:
The Mac OS X port of MonoDevelop is under active development and has not seen a stable release yet. Recent work described by Michael Hutchinson has focussed on improving the usability and stability of Monodevelop on the Mac. This work will be released in MonoDevelop 2.2. Right now it's not finished, and is very much an alpha.
I know there is an accepted answer by @Ovidiu Latcu but after some while, error still persist.
@Override
protected void onSaveInstanceState(Bundle outState) {
//No call for super(). Bug on API Level > 11.
}
Crashlytics still sending me this weird error message.
However error now occurring only on version 7+ (Nougat) My fix was to use commitAllowingStateLoss() instead of commit() at the fragmentTransaction.
This post is helpful for commitAllowingStateLoss() and never had a fragment issue ever again.
To sum it up, the accepted answer here might work on pre Nougat android versions.
This might save someone a few hours of searching. happy codings. <3 cheers
You'll need to check menuItem.getItemId()
against android.R.id.home
in the onOptionsItemSelected
method
Duplicate of Android Sherlock ActionBar Up button
On []: !=, =, == ... are string comparison operators and -eq, -gt ... are arithmetic binary ones.
I would use:
if [ "$#" != "1" ]; then
Or:
if [ $# -eq 1 ]; then
ping localhost -n (your time) >nul
example
@echo off
title Test
echo hi
ping localhost -n 3 >nul && :: will wait 3 seconds before going next command (it will not display)
echo bye! && :: still wont be any spaces (just below the hi command)
ping localhost -n 2 >nul && :: will wait 2 seconds before going to next command (it will not display)
@exit
You can use the cd
builtin, or the pushd
and popd
builtins for this purpose. For example:
# do something with /etc as the working directory
cd /etc
:
# do something with /tmp as the working directory
cd /tmp
:
You use the builtins just like any other command, and can change directory context as many times as you like in a script.
Microsoft finally heard you!
Now with C# 7 you can:
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
I found Maven Integration for Eclipse here.
http://download.eclipse.org/technology/m2e/releases
After installing restart eclipse. Worked for me running Eclipse Juno.
Select Text and selected value on dropdown/select change event in jQuery
$("#yourdropdownid").change(function() {
console.log($("option:selected", this).text()); //text
console.log($(this).val()); //value
})
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
If you don't mind the binary size, you can use iproute2 as library.
Pros:
Cons:
You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.
body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
I have my menu in the site master page. I used the Page_Load() function to make the "Admin" menu item only visible to users with an Admin role.
using System;
using System.Linq;
using Telerik.Web.UI;
using System.Web.Security;
<telerik:RadMenu ID="menu" runat="server" RenderMode="Auto" >
<Items>
<telerik:RadMenuItem Text="Admin" Visible="true" />
</Items>
</telerik:RadMenu>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RadMenuItem item = this.menu.FindItemByText("Admin");
if (null != item)
{
if (Roles.IsUserInRole("Admin"))
{
item.Visible = true;
}
else
{
item.Visible = false;
}
}
}
}
To give a more up to date answer to this question: yes, .Net includes JSON seriliazer/deserliazer since version 3.5 through the System.Runtime.Serialization.Json Namespace: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json(v=vs.110).aspx
But according to the creator of JSON.Net, the .Net Framework compared to his open source implementation is very much slower.
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.
Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.
You can use Collections.sort(list)
to sort list
if your list
contains Comparable
elements. Otherwise I would recommend you to implement that interface like here:
public class Circle implements Comparable<Circle> {}
and of course provide your own realization of compareTo
method like here:
@Override
public int compareTo(Circle another) {
if (this.getD()<another.getD()){
return -1;
}else{
return 1;
}
}
And then you can again use Colection.sort(list)
as now list contains objects of Comparable type and can be sorted. Order depends on compareTo
method. Check this https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html for more detailed information.
<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>
Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php
I use this function:
# Returns True if End-Of-File is reached
def EOF(f):
current_pos = f.tell()
file_size = os.fstat(f.fileno()).st_size
return current_pos >= file_size
You can just create a shortcut and then right click on it -> properties -> change icon, and just browse for your desired icon. Hope this help.
To set an icon of a shortcut programmatically, see this article using SetIconLocation
:
How Can I Change the Icon for an Existing Shortcut?:
https://devblogs.microsoft.com/scripting/how-can-i-change-the-icon-for-an-existing-shortcut/
Const DESKTOP = &H10&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(DESKTOP)
Set objFolderItem = objFolder.ParseName("Test Shortcut.lnk")
Set objShortcut = objFolderItem.GetLink
objShortcut.SetIconLocation "C:\Windows\System32\SHELL32.dll", 13
objShortcut.Save
Uploading Files using Retrofit is Quite Simple You need to build your api interface as
public interface Api {
String BASE_URL = "http://192.168.43.124/ImageUploadApi/";
@Multipart
@POST("yourapipath")
Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);
}
in the above code image is the key name so if you are using php you will write $_FILES['image']['tmp_name'] to get this. And filename="myfile.jpg" is the name of your file that is being sent with the request.
Now to upload the file you need a method that will give you the absolute path from the Uri.
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Now you can use the below code to upload your file.
private void uploadFile(Uri fileUri, String desc) {
//creating a file
File file = new File(getRealPathFromURI(fileUri));
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
For more detailed explanation you can visit this Retrofit Upload File Tutorial.
What you want is a SQL case statement. The form of these is either:
select case [expression or column]
when [value] then [result]
when [value2] then [result2]
else [value3] end
or:
select case
when [expression or column] = [value] then [result]
when [expression or column] = [value2] then [result2]
else [value3] end
In your example you are after:
declare @temp as varchar(100)
set @temp='Measure'
select case @temp
when 'Measure' then Measure
else OtherMeasure end
from Measuretable
Just drop
<script>
myfunction();
</script>
in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.
This was helpful to use in COGNOS because creating a SQL "Not in" statement in Cognos was allowed, but it took too long to run. I had manually coded table A to join to table B in in Cognos as A.key "not in" B.key, but the query was taking too long/not returning results after 5 minutes.
For anyone else that is looking for a "NOT IN" solution in Cognos, here is what I did. Create a Query that joins table A and B with a LEFT JOIN in Cognos by selecting link type: table A.Key has "0 to N" values in table B, then added a Filter (these correspond to Where Clauses) for: table B.Key is NULL.
Ran fast and like a charm.
There are two related error messages that may tell you something is wrong with declarations and/or imports.
The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.
The second you might see, if you had a method in your States class like:
- (void)logout:(NSTimer *)timer
after adding the #import is this:
No visible @interface for "States" declares the selector 'logout:'
If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.
So in your case, you would need a:
- (void)logout:(NSTimer *)timer;
in your States class's .h to make one or both of these related errors disappear.
Reason for the error:
Column
expands to the maximum size in main axis direction (vertical axis), and so does the ListView
.
Solutions
So, you need to constrain the height of the ListView
. There are many ways of doing it, you can choose that best suits your need.
If you want to allow ListView
to take up all remaining space inside Column
use Expanded
.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
If you want to limit your ListView
to certain height
, you can use SizedBox
.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
If your ListView
is small, you may try shrinkWrap
property on it.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
document.ready (jQuery) document.ready will execute right after the HTML document is loaded property, and the DOM is ready.
DOM: The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents.
$(document).ready(function()
{
// executes when HTML-Document is loaded and DOM is ready
alert("(document).ready was called - document is ready!");
});
window.load (Built-in JavaScript) The window.load however will wait for the page to be fully loaded, this includes inner frames, images etc. * window.load is a built-in JavaScript method, it is known to have some quirks in old browsers (IE6, IE8, old FF and Opera versions) but will generally work in all of them.
window.load can be used in the body's onload event like this (but I would strongly suggest you avoid mixing code like this in the HTML, as it is a source for confusion later on):
$(window).load(function()
{
// executes when complete page is fully loaded, including all frames, objects and images
alert("(window).load was called - window is loaded!");
});
Use DateFormat. For example,
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");
The term 'slug' comes from the world of newspaper production.
It's an informal name given to a story during the production process. As the story winds its path from the beat reporter (assuming these even exist any more?) through to editor through to the "printing presses", this is the name it is referenced by, e.g., "Have you fixed those errors in the 'kate-and-william' story?".
Some systems (such as Django) use the slug as part of the URL to locate the story, an example being www.mysite.com/archives/kate-and-william
.
Even Stack Overflow itself does this, with the GEB-ish(a) self-referential https://stackoverflow.com/questions/427102/what-is-a-slug-in-django/427201#427201
, although you can replace the slug with blahblah
and it will still find it okay.
It may even date back earlier than that, since screenplays had "slug lines" at the start of each scene, which basically sets the background for that scene (where, when, and so on). It's very similar in that it's a precis or preamble of what follows.
On a Linotype machine, a slug was a single line piece of metal which was created from the individual letter forms. By making a single slug for the whole line, this greatly improved on the old character-by-character compositing.
Although the following is pure conjecture, an early meaning of slug was for a counterfeit coin (which would have to be pressed somehow). I could envisage that usage being transformed to the printing term (since the slug had to be pressed using the original characters) and from there, changing from the 'piece of metal' definition to the 'story summary' definition. From there, it's a short step from proper printing to the online world.
(a) "Godel Escher, Bach", by one Douglas Hofstadter, which I (at least) consider one of the great modern intellectual works. You should also check out his other work, "Metamagical Themas".
You can use the rc shell.
First install the package (it's less than 1 MB).
This an example of how you would discard standard output and pipe standard error to grep in rc
:
find /proc/ >[1] /dev/null |[2] grep task
You can do it without leaving Bash:
rc -c 'find /proc/ >[1] /dev/null |[2] grep task'
As you may have noticed, you can specify which file descriptor you want piped by using brackets after the pipe.
Standard file descriptors are numerated as such:
Wouldn't establishing a connection to the database do this for you? If the database isn't up you won't be able to establish a connection.
Traversing the string is probably the most efficient, though using Regex to do this might yield cleaner looking code (though you can always hide your traverse code in a function).
1)In Manifest file mention your activity name and action for it and also category . 2)In your Activity mention your starting contentview and mention your view id's in the activity.
If I understand the question: Couple "\r\n"
to get that new line below in a textbox
. My example worked -
string s1 = comboBox1.Text; // s1 is the variable assigned to box 1, etc.
string s2 = comboBox2.Text;
string both = s1 + "\r\n" + s2;
textBox1.Text = both;
A typical answer could be s1
s2
in the text box
using defined type style.
This is heavily based on the @Galen version above, however, I wanted to add range control that could limit the colour produced to be red, green, blue, lighter or darker. It might be of use to others.
function random_colour_part($lower, $upper)
{
//randomly select colour in range and convert to hexidecimal
return str_pad(dechex(mt_rand($lower, $upper)), 2, '0', STR_PAD_LEFT);
}
function random_colour($colour)
{
//loop through colour
foreach ($colour as $key => $value)
{
//retrieve each r,g,b colour range and generate random hexidecimal colour
if ($key == "r") $r = random_colour_part($value[0], $value[1]);
if ($key == "g") $g = random_colour_part($value[0], $value[1]);
if ($key == "b") $b = random_colour_part($value[0], $value[1]);
}
//return hexidecimal colour
return "#" . $r . $g . $b;
}
//generate a random red-based colour
echo random_colour(["r"=>[0,255], "g"=>[0,0], "b"=>[0,0]]);
//generate a random light green-based colour (use only half of the 255 range)
echo random_colour(["r"=>[0,0], "g"=>[127,255], "b"=>[0,0]]);
//generate a random colour of any sort
echo random_colour(["r"=>[0,255], "g"=>[0,255], "b"=>[0,255]]);
Add
android:configChanges="keyboardHidden|orientation|screenSize"
to your manifest.
That works fine with font icons like 's7 stroke icons' and 'font-awesome':
.mirror {
display: inline-block;
transform: scaleX(-1);
}
And then on target element:
<button>
<span class="s7-back mirror"></span>
<span>Next</span>
</button>
Try this out: its in Kotlin
//button from xml
button.setOnClickListener{
val new=addText.text.toString()//addText is an EditText
if(new=isNotEmpty())
{
//do something
}
else{
new.setError("Enter some msg")
//or
Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
}
}
Thank you
For properties configuration
# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.
Amazon has released SFTP services for S3, but they only do SFTP (not FTP or FTPES) and they can be cost prohibitive depending on your circumstances.
I'm the Founder of DocEvent.io, and we provide FTP/S Gateways for your S3 bucket without having to spin up servers or worry about infrastructure.
There are also other companies that provide a standalone FTP server that you pay by the month that can connect to an S3 bucket through the software configuration, for example brickftp.com.
Lastly there are also some AWS Marketplace apps that can help, here is a search link. Many of these spin up instances in your own infrastructure - this means you'll have to manage and upgrade the instances yourself which can be difficult to maintain and configure over time.
Check out the help command:
svn help copy
-r [--revision] arg : ARG (some commands also take ARG1:ARG2 range)
A revision argument can be one of:
NUMBER revision number
'{' DATE '}' revision at start of the date
'HEAD' latest in repository
'BASE' base rev of item's working copy
'COMMITTED' last commit at or before BASE
'PREV' revision just before COMMITTED
To actually specify this on the command line using your example:
svn copy -r123 http://svn.example.com/repos/calc/trunk \
http://svn.example.com/repos/calc/branches/my-calc-branch
Where 123
would be the revision number in trunk you want to copy. As others have noted, you can also use the @ syntax. I prefer the clearer separation of the revision # from the URL, personally.
As noted in the help, you can replace a revision # with certain words as well:
svn copy -rPREV http://svn.example.com/repos/calc/trunk \
http://svn.example.com/repos/calc/branches/my-calc-branch
Would copy the "revision just before COMMITTED".
if you want to get the first N elements and also remove it from the array, you can use array_splice()
(note the 'p' in "splice"):
http://docs.php.net/manual/da/function.array-splice.php
use it like so: $array_without_n_elements = array_splice($old_array, 0, N)
I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.
import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')
In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,
plt.legend(handles=[red_patch, black_patch])
And the legend ought to appear in the pointplot.
Working example in php.
First Alert then Redirect works....
Enjoy...
echo "<script>";
echo " alert('Import has successfully Done.');
window.location.href='".site_url('home')."';
</script>";
Use this
@Cacheable(value="bookCache", key="#isbn + '_' + #checkWarehouse + '_' + #includeUsed")
There are several ways. One way is to use save()
to save the exact object. e.g. for data frame foo
:
save(foo,file="data.Rda")
Then load it with:
load("data.Rda")
You could also use write.table()
or something like that to save the table in plain text, or dput()
to obtain R code to reproduce the table.
unique and random are mutually exclusive. perhaps you want this?
import random
def uniqueid():
seed = random.getrandbits(32)
while True:
yield seed
seed += 1
Usage:
unique_sequence = uniqueid()
id1 = next(unique_sequence)
id2 = next(unique_sequence)
id3 = next(unique_sequence)
ids = list(itertools.islice(unique_sequence, 1000))
no two returned id is the same (Unique) and this is based on a randomized seed value
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
Try this. For python 2.7.12 we need to define constructor or need to add self to each methods followed by defining an instance of an class called object.
import cv2
class calculator:
# def __init__(self):
def multiply(self, a, b):
x= a*b
print(x)
def subtract(self, a,b):
x = a-b
print(x)
def add(self, a,b):
x = a+b
print(x)
def div(self, a,b):
x = a/b
print(x)
calc = calculator()
calc.multiply(2,3)
calc.add(2,3)
calc.div(10,5)
calc.subtract(2,3)
In the following line.
temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();
You are calling First but the collection returned from db.Responses.Where is empty.
motivated by previous contributors, this is an example of three axes.
import matplotlib.pyplot as plt
x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]
x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]
x_values3=[150,200,250,300,350]
y_values3=[-10,-20,-30,-40,-50]
fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)
ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")
ax2.scatter(x_values2, y_values2, color="C1")
ax2.set_xlabel('x label 2', color="C1")
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 36))
ax2.tick_params(axis='x', colors="C1")
ax2.set_ylabel('y label 2', color="C1")
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.tick_params(axis='y', colors="C1")
ax3.plot(x_values3, y_values3, color="C2")
ax3.set_xlabel('x label 3', color='C2')
ax3.xaxis.set_label_position('bottom')
ax3.spines['bottom'].set_position(('outward', 72))
ax3.tick_params(axis='x', colors='C2')
ax3.set_ylabel('y label 3', color='C2')
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position('right')
ax3.spines['right'].set_position(('outward', 36))
ax3.tick_params(axis='y', colors='C2')
plt.show()
You can use Files#readAllLines()
to get all lines of a text file into a List<String>
.
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
// ...
}
Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files
You can use String#split()
to split a String
in parts based on a regular expression.
for (String part : line.split("\\s+")) {
// ...
}
Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String
You can use Integer#valueOf()
to convert a String
into an Integer
.
Integer i = Integer.valueOf(part);
Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings
You can use List#add()
to add an element to a List
.
numbers.add(i);
Tutorial: Interfaces > The List Interface
So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).
List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
for (String part : line.split("\\s+")) {
Integer i = Integer.valueOf(part);
numbers.add(i);
}
}
If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines()
.
List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
.map(line -> line.split("\\s+")).flatMap(Arrays::stream)
.map(Integer::valueOf)
.collect(Collectors.toList());
Tutorial: Processing data with Java 8 streams
This is a short and crisp answer to your problem:
from __future__ import print_function
import MySQLdb
import numpy as np
import pandas as pd
import xlrd
# Connecting to MySQL Database
connection = MySQLdb.connect(
host="hostname",
port=0000,
user="userID",
passwd="password",
db="table_documents",
charset='utf8'
)
print(connection)
#getting data from database into a dataframe
sql_for_df = 'select * from tabledata'
df_from_database = pd.read_sql(sql_for_df , connection)
Sublime Text -> Preferences -> Setting:
Write your style in right screen:
You'll want to do a transform as such:
with JavaScript:
document.getElementById(yourtarget).setAttribute("transform", "scale(2.0)");
With CSS:
#yourtarget {
transform:scale(2.0);
-webkit-transform:scale(2.0);
}
Wrap your SVG Page in a Group tag as such and target it to manipulate the whole page:
<svg>
<g id="yourtarget">
your svg page
</g>
</svg>
Note: Scale 1.0 is 100%
SHA stands for Secure Hash Algorithm while AES stands for Advanced Encryption Standard. So SHA is a suite of hashing algorithms. AES on the other hand is a cipher which is used to encrypt. SHA algorithms (SHA-1, SHA-256 etc...) will take an input and produce a digest (hash), this is typically used in a digital signing process (produce a hash of some bytes and sign with a private key).
This should work.
int i = 1;
foreach (ListViewItem lvi in listView.Items) {
...
if(++i == 50) break;
}
I'm surprised how nobody has suggested this yet. It's super clean and very explicit about which keys you want to keep.
const unfilteredObj = {a: ..., b:..., c:..., x:..., y:...}
const filterObject = ({a,b,c}) => ({a,b,c})
const filteredObject = filterObject(unfilteredObject)
Or if you want a dirty one liner:
const unfilteredObj = {a: ..., b:..., c:..., x:..., y:...}
const filteredObject = (({a,b,c})=>({a,b,c}))(unfilteredObject);
I would use virtualenv at your HOME directory.
$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...
You could then also alter ~/.(login|profile|bash_profile)
, whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install
would be the one used by default.
Err.. If you are a git noob are you sure you have git commit
before git push
? I made this mistake the first time!
Have a look at frequent-cron - it's old but very stable and you can step down to micro-seconds. At this point in time, the only thing that I would say against it is that I'm still trying to work out how to install it outside of init.d but as a native systemd service, but certainly up to Ubuntu 18 it's running just fine still using init.d (distance may vary on latter versions). It has the added advantage (?) of ensuring that it won't spawn another instance of the PHP script unless a prior one has completed, which reduces potential memory leakage issues.
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
As all answers are great but I didn't want to use a library and each solution with just one line java code made my Activities
and Fragments
very messy.
So I over wrote the TextView
class as follows:
public class FontAwesomeTextView extends TextView {
private static final String TAG = "TextViewFontAwesome";
public FontAwesomeTextView(Context context) {
super(context);
init();
}
public FontAwesomeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fontawesome-webfont.ttf");
setTypeface(tf);
}
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface typeface = null;
try {
typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
what you should do is copy the font ttf
file into assets
folder .And use this cheat sheet for finding each icons string.
hope this helps.
Docker sets the hostname to the container ID by default, but users can override this with --hostname
. Instead, inspect /proc
:
$ more /proc/self/cgroup
14:name=systemd:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
13:pids:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
12:hugetlb:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
11:net_prio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
10:perf_event:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
9:net_cls:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
8:freezer:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
7:devices:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
6:memory:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
5:blkio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
4:cpuacct:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
3:cpu:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
2:cpuset:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
1:name=openrc:/docker
Here's a handy one-liner to extract the container ID:
$ grep "memory:/" < /proc/self/cgroup | sed 's|.*/||'
7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
That's the identity of the location of the object in memory...
This example might help you understand the concept a little more.
foo = 1
bar = foo
baz = bar
fii = 1
print id(foo)
print id(bar)
print id(baz)
print id(fii)
> 1532352
> 1532352
> 1532352
> 1532352
These all point to the same location in memory, which is why their values are the same. In the example, 1
is only stored once, and anything else pointing to 1
will reference that memory location.
//as I understand it, the "this" denotes the current view(focus) in the android program
No, "this" will only work if your MainActivity
referenced by this
implements the View.OnClickListener
, which is the parameter type for the setOnClickListener()
method. It means that you should implement View.OnClickListener
in MainActivity
.
On Visual Studio 2015 the only way I finally got it to work was to run git init
from the root of my directory using the command line. Then I went into Team Explorer and added a local git repository. Then I selected that local git repository, went to Settings->Repository Settings, and added my Remote Repo. That's how I was finally able to integrate Visual Studio to use my existing project with git.
I read all of the answers but none of them worked for me. I went to File->Add To Source Control, which was suppose to basically do the same as git init
, but it didn't seem to initialize my project because when I would then go to Team Explorer all of the options were grayed out. Also nothing would show up in the Changes dialog either. Another answer stated that I just had to create a local repo in Team Explorer and then my changes would show up, but that didn't work either. All the Git options on Team Explorer only worked after I initialized my project through the command line.
I'm new to Visual Studio so I don't know if I just missed something obvious, but it seems like my project wasn't initializing from Visual Studio.
There's many forms of timeout, are you after the connection timeout, request timeout or time to live (time before TCP connection stops).
The default TimeToLive on Firefox is 115s (network.http.keep-alive.timeout)
The default connection timeout on Firefox is 250s (network.http.connection-retry-timeout)
The default request timeout for Firefox is 30s (network.http.pipelining.read-timeout).
The time it takes to do an HttpRequest depends on if a connection has been made this has to be within 250s which I'm guessing you're not after. You're probably after the request timeout which I think is 30,000ms (30s) so to conclude I'd say it's timing out with a connection time out that's why you got a response back after ~150s though I haven't really tested this.
class B is only declared but not defined at the beginning, which is what the compiler complains about. The root cause is that in class A's Call Function, you are referencing instance b of type B
, which is incomplete and undefined. You can modify source like this without introducing new file(just for sake of simplicity, not recommended in practice):
using namespace std;
class A
{
public:
void CallFunction ();
};
class B: public A
{
public:
virtual void bFunction()
{
//stuff done here
}
};
// postpone definition of CallFunction here
void A::CallFunction ()
{
B b;
b.bFunction();
}
If you don't want to use a BackgroundWorker, and just use a regular Thread, then you can fire an event to return data like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ThreadWithDataReturnExample
{
public partial class Form1 : Form
{
private Thread thread1 = null;
public Form1()
{
InitializeComponent();
thread1 = new Thread(new ThreadStart(this.threadEntryPoint));
Thread1Completed += new AsyncCompletedEventHandler(thread1_Thread1Completed);
}
private void startButton_Click(object sender, EventArgs e)
{
thread1.Start();
//Alternatively, you could pass some object
//in such as Start(someObject);
//With apprioriate locking, or protocol where
//no other threads access the object until
//an event signals when the thread is complete,
//any other class with a reference to the object
//would be able to access that data.
//But instead, I'm going to use AsyncCompletedEventArgs
//in an event that signals completion
}
void thread1_Thread1Completed(object sender, AsyncCompletedEventArgs e)
{
if (this.InvokeRequired)
{//marshal the call if we are not on the GUI thread
BeginInvoke(new AsyncCompletedEventHandler(thread1_Thread1Completed),
new object[] { sender, e });
}
else
{
//display error if error occurred
//if no error occurred, process data
if (e.Error == null)
{//then success
MessageBox.Show("Worker thread completed successfully");
DataYouWantToReturn someData = e.UserState as DataYouWantToReturn;
MessageBox.Show("Your data my lord: " + someData.someProperty);
}
else//error
{
MessageBox.Show("The following error occurred:" + Environment.NewLine + e.Error.ToString());
}
}
}
#region I would actually move all of this into it's own class
private void threadEntryPoint()
{
//do a bunch of stuff
//when you are done:
//initialize object with data that you want to return
DataYouWantToReturn dataYouWantToReturn = new DataYouWantToReturn();
dataYouWantToReturn.someProperty = "more data";
//signal completion by firing an event
OnThread1Completed(new AsyncCompletedEventArgs(null, false, dataYouWantToReturn));
}
/// <summary>
/// Occurs when processing has finished or an error occurred.
/// </summary>
public event AsyncCompletedEventHandler Thread1Completed;
protected virtual void OnThread1Completed(AsyncCompletedEventArgs e)
{
//copy locally
AsyncCompletedEventHandler handler = Thread1Completed;
if (handler != null)
{
handler(this, e);
}
}
#endregion
}
}
You can convert the time using the following code.
TimeSpan _time = TimeSpan.Parse("07:35");
But if you want to get the current time of the day you can use the following code:
TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;
The result will be:
03:54:35.7763461
With a object cantain the Hours, Minutes, Seconds, Ticks and etc.
Insert into table(col1,col2) select col1,col2 from table_2;
Please refer to MySQL documentation on INSERT Statement
import csv
with open('input.csv','r') as csvinput:
with open('output.csv', 'w') as csvoutput:
writer = csv.writer(csvoutput)
for row in csv.reader(csvinput):
if row[0] == "Name":
writer.writerow(row+["Berry"])
else:
writer.writerow(row+[row[0]])
Maybe something like that is what you intended?
Also, csv stands for comma separated values. So, you kind of need commas to separate your values like this I think:
Name,Code
blackberry,1
wineberry,2
rasberry,1
blueberry,1
mulberry,2
I had trouble getting this to work and added another solution for anyone wanting/ needing to use FromCollection.
Instead of:
@Html.CheckBoxFor(model => true, item.TemplateId)
Format html helper like so:
@Html.CheckBoxFor(model => model.SomeProperty, new { @class = "form-control", Name = "SomeProperty"})
Then in the viewmodel/model wherever your logic is:
public void Save(FormCollection frm)
{
// to do instantiate object.
instantiatedItem.SomeProperty = (frm["SomeProperty"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);
// to do and save changes in database.
}
string = string.replace(/[\W_]/g, "_");
Maybe just a bit of trivia, but UPnP will use HTTP formatted messages over UDP for device discovery.
There are two different ways of generating a UUID.
If you just need a unique ID, you want a version 1 or version 4.
Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.
Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.
If you need to always generate the same UUID from a given name, you want a version 3 or version 5.
Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.
Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.
I'm not sure what your reasons are, and even if you could pull it off somehow with Reflection Emit (I' not sure that you can), it doesn't sound like a good idea. What is probably a better idea is to have some kind of Dictionary and you can wrap access to the dictionary through methods in your class. That way you can store the data from the database in this dictionary, and then retrieve them using those methods.
A for loop is useful when you have an indication or determination, in advance, of how many times you want a loop to run. As an example, if you need to perform a process for each day of the week, you know you want 7 loops.
A foreach loop is when you want to repeat a process for all pieces of a collection or array, but it is not important specifically how many times the loop runs. As an example, you are formatting a list of favorite books for users. Every user may have a different number of books, or none, and we don't really care how many it is, we just want the loop to act on all of them.
The problem, and the answers, keep changing as FB tightens up the login procedure. Today, I started getting this horror message "The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings."
The answer was: now FB wants the full redirect uri. So for me, where it used to be just https://www.example.com it now wants https://www.example.com/auth/facebook/callback. This has to go in the "Valid OAuth redirect URIs" field (Developer/Facebook login->setting)
Here's my script that runs as LocalSystem on a machine, but needs credentials of a domaim user to access a network file location. It allows you to store the user's password in a "safe-ish" encrypted file; that can only be read by the user that wrote it.
Setting and changing the password is done by copying a file with the plaintext password in it to the machine. When the script is next run it reads the password, encrypts it, then deletes the plaintext password.
$plaintext_password_file = 'C:\plaintext.txt' # Stores the password in plain text - only used once, then deleted
$encryted_password_file = 'C:\copy_pass.txt' # Stores the password in "safe" encrypted form - used for subsequent runs of the script
# - can only be decrypted by the windows user that wrote it
$file_copy_user = 'OURDOMAIN\A_User'
# Check to see if there is a new plaintext password
if (Test-Path $plaintext_password_file)
{
# Read in plaintext password, convert to a secure-string, convert to an encrypted-string, and write out, for use later
get-content $plaintext_password_file | convertto-securestring -asplaintext -force | convertfrom-securestring | out-file $encryted_password_file
# Now we have encrypted password, remove plain text for safety
Remove-Item $plaintext_password_file
}
# Read in the encrypted password, convert to a secure-string
$pass = get-content $encryted_password_file | convertto-securestring
# create a credential object for the other user, using username and password stored in secure-string
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $file_copy_user,$pass
# Connect to network file location as the other user and map to drive J:
New-PSDrive -Name J -PSProvider FileSystem -Root "\\network\file_directory" -Credential $credentials
# Copy the file to J:
Copy-Item -Force -Verbose -Path "C:\a_file.txt" -Destination "J:\"
As an extra refinement: The username could also be encrypted as well, rather than hardcoded.
If you have an appropriate version of Windows and the Windows Server 2003 Resource Kit Tools, it includes a sleep command for batch programs. More at: http://malektips.com/xp_dos_0002.html
Alternatively You can use:
mystring = 'banana'
number = mystring.count('a')
I totally agree with @jemmons:
But this should not be the default pattern you follow when dealing with blocks that call self! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self was deallocated.
//SUSPICIOUS EXAMPLE: __weak MyObject *weakSelf = self; [[SomeOtherObject alloc] initWithCompletion:^{ //By the time this gets called, "weakSelf" might be nil because it's not retained! [weakSelf doSomething]; }];
To overcome this problem one can define a strong reference over the weakSelf
inside the block:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
MyObject *strongSelf = weakSelf;
[strongSelf doSomething];
}];
Follow these steps to change an app's name in Django:
views.py
, urls.py
, 'manage.py' , and settings.py
files.django_content_type
with the following command: UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName
. For mysql too I think it is the same (as mentioned by @null_radix)django_migrations
table to avoid having your previous migrations re-run: UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'
. Note: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.models.py
's Meta Class has app_name
listed, make sure to rename that too (mentioned by @will).static
or templates
folders inside your app, you'll also need to rename those. For example, rename old_app/static/old_app
to new_app/static/new_app
.models
, you'll need to change django_content_type.name
entry in DB. For postgreSQL use UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'
Meta point (If using virtualenv): Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as ImportError: No module named ...
this might be the culprit. (thanks to @danyamachine for providing this).
Other references: you might also want to refer the below links for a more complete picture
The term "bootstrapping" usually applies to a situation where a system depends on itself to start, sort of a chicken and egg problem.
For instance:
In that case, bootstrapping refers to a way of breaking the circular dependency, usually with the help of an external entity, e.g.
etc.
df = df.fillna('')
or just
df.fillna('', inplace=True)
This will fill na's (e.g. NaN's) with ''
.
If you want to fill a single column, you can use:
df.column1 = df.column1.fillna('')
One can use df['column1']
instead of df.column1
.
It's a pity that both of the answers analyze the problem but didn't give a direct answer. Let's see the code.
Z = np.array([1.0, 1.0, 1.0, 1.0])
def func(TempLake, Z):
A = TempLake
B = Z
return A * B
Nlayers = Z.size
N = 3
TempLake = np.zeros((N+1, Nlayers))
kOUT = np.zeros(N + 1)
for i in xrange(N):
# store the i-th result of
# function "func" in i-th item in kOUT
kOUT[i] = func(TempLake[i], Z)
The error shows that you set the ith item of kOUT(dtype:int) into an array. Here every item in kOUT is an int, can't directly assign to another datatype. Hence you should declare the data type of kOUT when you create it. For example, like:
Change the statement below:
kOUT = np.zeros(N + 1)
into:
kOUT = np.zeros(N + 1, dtype=object)
or:
kOUT = np.zeros((N + 1, N + 1))
All code:
import numpy as np
Z = np.array([1.0, 1.0, 1.0, 1.0])
def func(TempLake, Z):
A = TempLake
B = Z
return A * B
Nlayers = Z.size
N = 3
TempLake = np.zeros((N + 1, Nlayers))
kOUT = np.zeros(N + 1, dtype=object)
for i in xrange(N):
kOUT[i] = func(TempLake[i], Z)
Hope it can help you.
PHP allows "hinting" where you supply a class to specify an object. According to the PHP manual, "Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported." The error is confusing because of your choice of "string" - put "myClass" in its place and the error will read differently: "Argument 1 passed to phpwtf() must be an instance of myClass, string given"
PHP's strlen()
function returns the number of ASCII characters.
strlen('borsc')
-> 5 (bytes)
strlen('boršc')
-> 7 (bytes)
$limit_in_kBytes = 20000;
$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
// here you can handle (0 - n) parts of string
$pointer++;
}
$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string
.. or you can use a function like this:
function parseStrToArr($string, $limit_in_kBytes){
$ret = array();
$pointer = 0;
while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
$ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
$pointer++;
}
$ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
return $ret;
}
$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);
If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".
Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.
I had the similar problem. Just after adding below dependency
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
<type>bundle</type>
</dependency>
caused the problem. I deleted that dependency even then I'm getting the same error. I don't know what happened. I tried updating the maven dependency configuration which solved my issue.
In my case it was changes in object value which the ngOnChange
was not capturing. A few object values are modified in response of api call. Reinitializing the object fixed the issue and caused the ngOnChange
to trigger in the child component.
Something like
this.pagingObj = new Paging(); //This line did the magic
this.pagingObj.pageNumber = response.PageNumber;
Well, DNS should be the same worldwide, wouldn't it? Of course it can take up to a day or so until your new DNS record is propagated around the world. So either something is wrong on your colleague's end or the DNS record still takes some time...
I usually use online DNS lookup tools for that, e.g. http://network-tools.com/
It can check your HTTP header as well. Only a proxy located in Europe would be better.
Since ES6 you can do this
let newCodes = function() {
const dCodes = fg.codecsCodes.rs
const dCodes2 = fg.codecsCodes2.rs
return {dCodes, dCodes2}
};
let {dCodes, dCodes2} = newCodes()
Return expression {dCodes, dCodes2}
is property value shorthand and is equivalent to this {dCodes: dCodes, dCodes2: dCodes2}
.
This assignment on last line is called object destructing assignment. It extracts property value of an object and assigns it to variable of same name. If you'd like to assign return values to variables of different name you could do it like this let {dCodes: x, dCodes2: y} = newCodes()
Depending on your version of postgresql you might run into a bug, that makes pg_stat_activity
to omit active connections from dropped users. These connections are also not shown inside pgAdminIII.
If you are doing automatic testing (in which you also create users) this might be a probable scenario.
In this case you need to revert to queries like:
SELECT pg_terminate_backend(procpid)
FROM pg_stat_get_activity(NULL::integer)
WHERE datid=(SELECT oid from pg_database where datname = 'your_database');
NOTE: In 9.2+ you'll have change procpid
to pid
.
The answer appears to be solely related to application size. I created a simple "hello world" app with nothing special in the manifest file, uploaded it to the Play store, and it was reported as compatible with my device.
I changed nothing in this app except for adding more content into the res/drawable
directory. When the .apk
size reached about 32 MB, the Play store started reporting that my app was incompatible with my phone.
I will attempt to contact Google developer support and ask for clarification on the reason for this limit.
UPDATE: Here is Google developer support response to this:
Thank you for your note. Currently the maximum file size limit for an app upload to Google Play is approximately 50 MB.
However, some devices may have smaller than 50 MB cache partition making the app unavailable for users to download. For example, some of HTC Wildfire devices are known for having 35-40 MB cache partitions. If Google Play is able to identify such device that doesn't have cache large enough to store the app, it may filter it from appearing for the user.
I ended up solving my problem by converting all the PNG files to JPG, with a small loss of quality. The .apk
file is now 28 MB, which is below whatever threshold Google Play is enforcing for my phone.
I also removed all the <uses-feature>
stuff, and now have just this:
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
Another way: you can use RedisWorks
library.
pip install redisworks
>>> from redisworks import Root
>>> root = Root()
>>> root.something = {1:"a", "b": {2: 2}} # saves it as Hash type in Redis
...
>>> print(root.something) # loads it from Redis
{'b': {2: 2}, 1: 'a'}
>>> root.something['b'][2]
2
It converts python types to Redis types and vice-versa.
>>> root.sides = [10, [1, 2]] # saves it as list in Redis.
>>> print(root.sides) # loads it from Redis
[10, [1, 2]]
>>> type(root.sides[1])
<class 'list'>
Disclaimer: I wrote the library. Here is the code: https://github.com/seperman/redisworks
What I use (and it's been working great) is a "templates" directory and a "static" directory. I place all my .html files/Flask templates inside the templates directory, and static contains CSS/JS. render_template works fine for generic html files to my knowledge, regardless of the extent at which you used Flask's templating syntax. Below is a sample call in my views.py file.
@app.route('/projects')
def projects():
return render_template("projects.html", title = 'Projects')
Just make sure you use url_for() when you do want to reference some static file in the separate static directory. You'll probably end up doing this anyways in your CSS/JS file links in html. For instance...
<script src="{{ url_for('static', filename='styles/dist/js/bootstrap.js') }}"></script>
Here's a link to the "canonical" informal Flask tutorial - lots of great tips in here to help you hit the ground running.
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
There are a few different ways. If you want to do it yourself on the fly WMI is probably the way to go. RegistryKeyChangeEvent
and its relatives are the ones to look at. There might be a way to monitor it through __InstanceCreationEvent
, __InstanceDeletionEvent
and __InstanceModificationEvent
classes too.
http://msdn.microsoft.com/en-us/library/aa393040(VS.85).aspx
It's the default SSH port and SFTP is usually carried over an SSH tunnel.
Check out the jQuery Outside Events plugin
Lets you do:
$field_hint.bind('clickoutside',function(){
$field_hint.dialog('close');
});
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
It's relative to default browser font-size unless you override it with a value in pt or px.
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
I faced the same issue. Though in my case I was trying to connect my desktop application to a remote db. So for me, all the above didn't work. I solve this problem by just adding the port (as 128.02.39.29:3315
) and it magically works!
The reason why I didn't bother to add the port in the first place is because I used same approach (without the port) in another desktop app and it worked.
So I hope this might help someone as well.
Here, you could use cv2.bitwise_and
function if you already have the mask image.
For check the below code:
img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)
The output will be as follows for a lena image, and for rectangular mask.
You can use new stdClass()
(which is recommended):
$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);
// outputs:
// stdClass Object ( [name] => John )
Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:
$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);
// outputs:
// stdClass Object ( [name] => John )
Or you can convert the null
value to an object which produces a new empty instance of the stdClass built-in class:
$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);
// outputs:
// stdClass Object ( [name] => John )
You have to add a condition in your componentDidUpdate
method.
The example is using fast-deep-equal
to compare the objects.
import equal from 'fast-deep-equal'
...
constructor(){
this.updateUser = this.updateUser.bind(this);
}
componentDidMount() {
this.updateUser();
}
componentDidUpdate(prevProps) {
if(!equal(this.props.user, prevProps.user)) // Check if it's a new user, you can also use some unique property, like the ID (this.props.user.id !== prevProps.user.id)
{
this.updateUser();
}
}
updateUser() {
if (this.props.isManager) {
this.props.dispatch(actions.fetchAllSites())
} else {
const currentUserId = this.props.user.get('id')
this.props.dispatch(actions.fetchUsersSites(currentUserId))
}
}
Using Hooks (React 16.8.0+)
import React, { useEffect } from 'react';
const SitesTableContainer = ({
user,
isManager,
dispatch,
sites,
}) => {
useEffect(() => {
if(isManager) {
dispatch(actions.fetchAllSites())
} else {
const currentUserId = user.get('id')
dispatch(actions.fetchUsersSites(currentUserId))
}
}, [user]);
return (
return <SitesTable sites={sites}/>
)
}
If the prop you are comparing is an object or an array, you should use useDeepCompareEffect
instead of useEffect
.
I suggest you take a look at tiny httpd. If you want to write it from scratch, then you'll want to thoroughly read RFC 2616. Use BSD sockets to access the network at a really low level.
The SHGetFileInfo
(Check pinvoke.net for the signature) lets you retrieve a small or large icon, just as if you were dealing with a file/folder/Shell item.
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ type: "POST",
url: url,
data: { username: value_login.val(), firstname: value_firstname.val(),
lastname: value_lastname.val(), email: value_email.val(),
password: value_password.val()
},
dataType: "json"
success: success// -> call your func here
});
Hope This helps
Sometimes, when all else fails, you just want to tell pandas to shut up about it:
# Ignore DtypeWarnings from pandas' read_csv
warnings.filterwarnings('ignore', message="^Columns.*")
This affects:
This is because Netbeans does not 'see' that tomcat is started, although it started just fine.
I have filed Bug #262749 with NetBeans.
In the server.xml
file, in the Connector
element for HTTP/1.1, add the following attribute: server="Apache-Coyote/1.1"
.
Example:
<Connector
connectionTimeout="20000"
port="8080"
protocol="HTTP/1.1"
redirectPort="8443"
server="Apache-Coyote/1.1"
/>
The reason for that is that prior to 8.5.3, the default was to set the server header as Apache-Coyote/1.1
, while since 8.5.3 this default has now been changed to blank. Apparently Netbeans checks on this header.
Maybe in the future we can expect a fix in netbeans addressing this issue.
I was able to trace it back to a change in documentation.
"Overrides the Server header for the http response. If set, the value for this attribute overrides any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then no Server header is set."
"Overrides the Server header for the http response. If set, the value for this attribute overrides the Tomcat default and any Server header set by a web application. If not set, any value specified by the application is used. If the application does not specify a value then Apache-Coyote/1.1 is used. Unless you are paranoid, you won't need this feature."
That explains the need for explicitly adding the server attribute since version 8.5.3.
Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.
The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.
Its best practice to have TOP 1 1
always.
What if I use SELECT 1
-> If condition matches more than one record then your query will fetch all the columns records and returns 1.
What if I use SELECT TOP 1 1
-> If condition matches more than one record also, it will just fetch the existence of any row (with a self 1-valued column) and returns 1.
IF EXISTS (SELECT TOP 1 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx')
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 2
END
You should use the same encoding on all layers of your application to avoid this problem. It is useful to add a filter to set the encoding:
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws ServletException {
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
To only set the encoding on your JSP pages, add this line to them:
<%@ page contentType="text/html; charset=UTF-8" %>
Configure your database to use the same char encoding as well.
If you need to convert the encoding of a string see:
I would not recommend to store HTML encoded text in your database. For example, if you need to generate a PDF (or anything other than HTML) you need to convert the HTML encoding first.
I had the same problem. In order to modify variables from different classes, I made them extend the class they were to modify. I also made the super class's variables static so they can be changed by anything that inherits them. I also made them protected for more flexibility.
Source: Bad experiences. Good lessons.
I do it this way:
SELECT a.* FROM articles AS a
LEFT JOIN articles AS a2
ON a.section = a2.section AND a.article_date <= a2.article_date
GROUP BY a.article_id
HAVING COUNT(*) <= 10;
update: This example of GROUP BY works in MySQL and SQLite only, because those databases are more permissive than standard SQL regarding GROUP BY. Most SQL implementations require that all columns in the select-list that aren't part of an aggregate expression are also in the GROUP BY.
This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop contraint):
select
concat(table_name, '.', column_name) as 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) as 'references',
constraint_name as 'constraint name'
from
information_schema.key_column_usage
where
referenced_table_name is not null;
If you want to check tables in a specific database, at the end of the query add the schema name:
select
concat(table_name, '.', column_name) as 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) as 'references',
constraint_name as 'constraint name'
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = 'database_name';
Likewise, for a specific column name, add
and table_name = 'table_name
at the end of the query.
Inspired by this post here
I resolved this issue by excluding byte-buddy dependency from springfox
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>