The question mark is used to define wildcards. Checkout the Oracle documentation about them: http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html
Just ran into this problem after installing material-ui.
Solved it by simply running npm install
again.
Using 2nd signature of $.fn.removeClass
:
// Considering:
var $el = $('<div class=" foo-1 a b foo-2 c foo"/>');
function makeRemoveClassHandler(regex) {
return function (index, classes) {
return classes.split(/\s+/).filter(function (el) {return regex.test(el);}).join(' ');
}
}
$el.removeClass(makeRemoveClassHandler(/^foo-/));
//> [<div class=?"a b c foo">?</div>?]
This is very possible. It just takes a little CSS trickery!
div.border {_x000D_
border: 1px solid #000;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
div.border:before {_x000D_
position: absolute;_x000D_
display: block;_x000D_
content: '';_x000D_
border: 1px solid red;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
-webkit-box-sizing: border-box;_x000D_
}
_x000D_
<div class="border">Hi I have two border colors<br />I am also Fluid</div>
_x000D_
Is that what you are looking for?
Ctrl + Enter
%matplotlib inline
Magic Line :D
See: Plotting with Matplotlib.
Here is something cool if you want to go the extra mile with this. in the url, you can use a link or save an image png and use the path. for example:
url('assets/imgs/theGoods.png');
below is the code:
.cursor{
cursor:url(http://www.icon100.com/up/3772/128/425-hand-pointer.png), auto;
}
So this will only work under the size 128 X 128, any bigger and the image wont load. But you can practically use any image you want! This would be consider pure css3, and some html. all you got to do in html is
<div class='cursor'></div>
and only in that div, that cursor will show. So I usually add it to the body tag.
Open angular.json file and find budgets
keyword.
It should look like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
As you’ve probably guessed you can increase the maximumWarning
value to prevent this warning, i.e.:
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
}
]
A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.
In our case budget is the limit for bundle sizes.
See also:
For users on mac, I solved an issue similar to this by modifying my zshrc file and adding the following (although your java_home might be configured differently) :
export JAVA_HOME=$(/usr/libexec/java_home)
export ANDROID_HOME=/Users/YOURUSER/Library/Android/sdk
export PATH=$PATH:/Users/YOURUSER/Library/Android/sdk/tools
export PATH=$PATH:%ANDROID_HOME%\tools
export PATH=$PATH:/Users/YOURUSER/Library/Android/sdk
I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):
Mark Miller said... June 28, 2010 12:13 PM
Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.
For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.
This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.
It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.
Hope it helps future readers.
For your property example do:
mvn install "-Dmyproperty=my property from command line"
Note quotes around whole property definition. You'll need them if your property contains spaces.
That seems to me the easiest way. Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.
struct Point
{
int x, y;
};
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
There is good information about structs in c++ - https://www.geeksforgeeks.org/structures-in-cpp/
var body: some View {
var body: some View {
NavigationView {
ZStack {
// Background
Color.blue.edgesIgnoringSafeArea(.all)
content
}
//.navigationTitle(Constants.navigationTitle)
//.navigationBarItems(leading: cancelButton, trailing: doneButton)
//.navigationViewStyle(StackNavigationViewStyle())
}
}
}
var content: some View {
// your content here; List, VStack etc - whatever you want
VStack {
Text("Hello World")
}
}
I have found the solution else where:
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)
Download source code from here (Open Pdf from url in Android Programmatically)
MainActivity.java
package com.deepshikha.openpdf;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressBar progressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
webview.getSettings().setJavaScriptEnabled(true);
String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
progressbar.setVisibility(View.GONE);
}
});
}
}
Thanks!
What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.
Using the same key you can generate, & reverify, edit, etc.
For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.
Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length
you can use online generator, or manually write
I prefer using openssl
C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg
generate, then encode with base 64
C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20
The generated value is saved inside the file named "openssl-secret.txt"
generate, & store into a file.
One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.
I recommend reading this article
In order to determine the aspect ratio, you need to have a ratio to aim for.
function getHeight(length, ratio) {
var height = ((length)/(Math.sqrt((Math.pow(ratio, 2)+1))));
return Math.round(height);
}
function getWidth(length, ratio) {
var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
return Math.round(width);
}
In this example I use 16:10
since this the typical monitor aspect ratio.
var ratio = (16/10);
var height = getHeight(300,ratio);
var width = getWidth(height,ratio);
console.log(height);
console.log(width);
Results from above would be 147
and 300
This is the simplest solution working for me.
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
A less orthodox approach might be
SELECT * FROM table_name
WHERE LEFT(table_name.date, 7) = LEFT(CURDATE(), 7)
AND table_name.date <= CURDATE();
as a date being between the first of a month and now is equivalent to a date being in this month, and before now. I do feel that this is a bit easier on the eyes than some other approaches, though.
Put the command
yum install php-gd
and restart the server (httpd, nginx, etc)
service httpd restart
Let's not use NOW()
as you're losing any query caching or optimization because the query is different every time. See the list of functions you should not use in the MySQL documentation.
In the code below, let's assume this table is growing with time. New stuff is added and you want to show just the stuff in the last 30 days. This is the most common case.
Note that the date has been added as a string. It is better to add the date in this way, from your calling code, than to use the NOW()
function as it kills your caching.
SELECT * FROM table WHERE exec_datetime >= DATE_SUB('2012-06-12', INTERVAL 30 DAY);
You can use BETWEEN
if you really just want stuff from this very second to 30 days before this very second, but that's not a common use case in my experience, so I hope the simplified query can serve you well.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 150, 44);
[btn setBackgroundImage:[UIImage imageNamed:@"buttonimage.png"]
forState:UIControlStateNormal];
[btn addTarget:self
action:@selector(btnSendComment_pressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
If you used the Visual Studio 2012 ASP.NET Web Forms Application template then you would have gotten that reference. I'm assuming it's the one you would get via Nuget instead of the framework System.Data.Entity reference.
Setting background-blend-mode
to darken
would be the most direct and shortest way to achieve the purpose however you must set a background-color
first for the blend mode to work.
This is also the best way if you need to manipulate the values in javascript later on.
background: rgba(0, 0, 0, .65) url('http://fc02.deviantart.net/fs71/i/2011/274/6/f/ocean__sky__stars__and_you_by_muddymelly-d4bg1ub.png');
background-blend-mode: darken;
Simple copy & paste example with subqueries, Note, that both queries should return 1 row:
select
(select sum(items_1) from items_table_1 where ...)
-
(select count(items_2) from items_table_1 where ...)
as difference
Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;
. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.
@GitaarLAB and @Jukka elaborate that <xmp>
tag is obsolete, but still the best. When I use it like this
<xmp>
<div>Lorem ipsum</div>
<p>Hello</p>
</xmp>
then the first EOL is inserted in the code, and it looks awful.
It can be solved by removing that EOL
<xmp><div>Lorem ipsum</div>
<p>Hello</p>
</xmp>
but then it looks bad in the source. I used to solve it with wrapping <div>
, but recently I figured out a nice CSS3 rule, I hope it also helps somebody:
xmp { margin: 5px 0; padding: 0 5px 5px 5px; background: #CCC; }
xmp:before { content: ""; display: block; height: 1em; margin: 0 -5px -2em -5px; }
This looks better.
Also you could use
${pageContext.request.requestURI}
I found this presentation to be very helpfull.
How I Distribute Python applications on Windows - py2exe & InnoSetup
From the site:
There are many deployment options for Python code. I'll share what has worked well for me on Windows, packaging command line tools and services using py2exe and InnoSetup. I'll demonstrate a simple build script which creates windows binaries and an InnoSetup installer in one step. In addition, I'll go over common errors which come up when using py2exe and hints on troubleshooting them. This is a short talk, so there will be a follow-up Open Space session to share experience and help each other solve distribution problems.
Assuming a
is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
On Ubuntu with OpenJDK, it installed in /usr/lib/jvm/default-java/jre/lib/ext/jfxrt.jar
(technically its a symlink to /usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
, but it is probably better to use the default-java
link)
Change the return type of your GetResults to be List<Person>
.
Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically.
Using your definition for the Person class, this code works for me:
public List<Person> GetPlayers()
{
List<Person> players = new List<Person>();
players.Add(new Person { FirstName="Peyton", LastName="Manning", Age=35 } );
players.Add(new Person { FirstName="Drew", LastName="Brees", Age=31 } );
players.Add(new Person { FirstName="Brett", LastName="Favre", Age=58 } );
return players;
}
results:
[{"Age":35,"FirstName":"Peyton","LastName":"Manning"},
{"Age":31,"FirstName":"Drew","LastName":"Brees"},
{"Age":58,"FirstName":"Brett","LastName":"Favre"}]
(All on one line)
I also used this attribute on the method:
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "players")]
WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency.
The UriTemplate sets the URL at which the method is available. So I can do a GET on
http://myserver/myvdir/JsonService.svc/players
and it just works.
Also check out IIRF or another URL rewriter to get rid of the .svc in the URI.
Use a ternary operator:
echo '<option value="'.$value.'"'.($value=='United States' ? 'selected="selected"' : '').'>'.$value.'</option>';
And while you're at it, you could use printf
to make your code more readable/manageable:
printf('<option value="%s" %s>%s</option>',
$value,
$value == 'United States' ? 'selected="selected"' : ''
$value);
if mysql is okay for you:
SELECT flights.*,
fromairports.city as fromCity,
toairports.city as toCity
FROM flights
LEFT JOIN (airports as fromairports, airports as toairports)
ON (fromairports.code=flights.fairport AND toairports.code=flights.tairport )
WHERE flights.fairport = '?' OR fromairports.city = '?'
edit: added example to filter the output for code or city
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
private static void getRepeatedNumbers() {
int [] numArray = {2,5,3,8,1,2,8,3,3,1,5,7,8,12,134};
Set<Integer> nums = new HashSet<Integer>();
for (int i =0; i<numArray.length; i++) {
if(nums.contains(numArray[i]))
continue;
int count =1;
for (int j = i+1; j < numArray.length; j++) {
if(numArray[i] == numArray[j]) {
count++;
}
}
System.out.println("The "+numArray[i]+ " is repeated "+count+" times.");
nums.add(numArray[i]);
}
}
If you have a datatype which is bigger than the one you want to test (say you do a 32-bit add and you have a 64-bit type), then this will detect if an overflow occurred. My example is for an 8-bit add. But it can be scaled up.
uint8_t x, y; /* Give these values */
const uint16_t data16 = x + y;
const bool carry = (data16 > 0xFF);
const bool overflow = ((~(x ^ y)) & (x ^ data16) & 0x80);
It is based on the concepts explained on this page: http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/Comb/overflow.html
For a 32-bit example, 0xFF
becomes 0xFFFFFFFF
and 0x80
becomes 0x80000000
and finally uint16_t
becomes a uint64_t
.
NOTE: this catches integer addition/subtraction overflows, and I realized that your question involves multiplication. In which case, division is likely the best approach. This is commonly a way that calloc
implementations make sure that the parameters don't overflow as they are multiplied to get the final size.
I think you can use the nrows
parameter. From the docs:
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):
In [1]: import pandas as pd
In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s
In [3]: len(z)
Out[3]: 20
In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s
It is worth noting that if you use the setContentOffset
approach, it may cause your table view/collection view to jump a little. I would honestly try to go about this another way. A recommendation is to use the scroll view delegate methods you are given for free.
Added here for future reference (for users who might fall into the same case): This error happens when working on Windows (which introduces extra characters because of different line separator than Linux system) and trying to run this script (with extra characters inserted) in Linux. The error message is misleading.
In Windows, the line separator is CRLF (\r\n) whereas in linux it is LF (\n). This can be usually be chosen in text editor.
In my case, this happened due to working on Windows and uploading to Unix server for execution.
Here's how you would do it in Kotlin
fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
//your code here
}
If i
is the int
, then
char c = i;
makes it a char
. You might want to add a check that the value is <128
if it comes from an untrusted source. This is best done with isascii
from <ctype.h>
, if available on your system (see @Steve Jessop's comment to this answer).
To find specific process on command line use below command here 8080 is port used by process
netstat -ano | findstr 8080
to kill process use below command here 21424 is process id
taskkill /pid 21424 /F
I got this error message from using an oracle database in a docker despite the fact i had publish port to host option "-p 1521:1521". I was using jdbc url that was using ip address 127.0.0.1, i changed it to the host machine real ip address and everything worked then.
The chunks below work at least for sending an int over UDP.
int to byte array:
public byte[] intToBytes(int my_int) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeInt(my_int);
out.close();
byte[] int_bytes = bos.toByteArray();
bos.close();
return int_bytes;
}
byte array to int:
public int bytesToInt(byte[] int_bytes) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
int my_int = ois.readInt();
ois.close();
return my_int;
}
I think you're saying you want to remove all non-numeric characters. If so, \D
means "anything that isn't a digit":
preg_replace('/\D/', '', $c)
I liked Marc's answer, but needed the Contains matching to be CaSe InSenSiTiVe.
This was the solution:
bool b = listOfStrings.Any(s => myString.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0))
Set table-layout
to auto
and define an extreme width on .absorbing-column
.
Here I have set the width
to 100%
because it ensures that this column will take the maximum amount of space allowed, while the columns with no defined width will reduce to fit their content and no further.
This is one of the quirky benefits of how tables behave. The table-layout: auto
algorithm is mathematically forgiving.
You may even choose to define a min-width
on all td
elements to prevent them from becoming too narrow and the table will behave nicely.
table {_x000D_
table-layout: auto;_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
table td {_x000D_
border: 1px solid #ccc;_x000D_
}_x000D_
table .absorbing-column {_x000D_
width: 100%;_x000D_
}
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column A</th>_x000D_
<th>Column B</th>_x000D_
<th>Column C</th>_x000D_
<th class="absorbing-column">Column D</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data A.1 lorem</td>_x000D_
<td>Data B.1 ip</td>_x000D_
<td>Data C.1 sum l</td>_x000D_
<td>Data D.1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.2 ipsum</td>_x000D_
<td>Data B.2 lorem</td>_x000D_
<td>Data C.2 some data</td>_x000D_
<td>Data D.2 a long line of text that is long</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.3</td>_x000D_
<td>Data B.3</td>_x000D_
<td>Data C.3</td>_x000D_
<td>Data D.3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
In [14]: b = np.reshape(a, (np.product(a.shape),))
In [15]: b
Out[15]: array([1, 2, 3, 4, 5, 6])
or, simply:
In [16]: a.flatten()
Out[16]: array([1, 2, 3, 4, 5, 6])
I'll try to explain what has already been said in a simpler way.
Whenever a shared lib is loaded, the loader (the code on the OS which load any program you run) changes some addresses in the code depending on where the object was loaded to.
In the above example, the "111" in the non-PIC code is written by the loader the first time it was loaded.
For not shared objects, you may want it to be like that because the compiler can make some optimizations on that code.
For shared object, if another process will want to "link" to that code he must read it to the same virtual addresses or the "111" will make no sense. but that virtual-space may already be in use in the second process.
You can use qTip for this; However you'd have to code a little for launching it on mouseover event; And in case you want a default watermark on your text fields, you'd have to use the watermark plugin...
I realized that this leads to lot of repetitive code; So I wrote a plugin on top of qTip that makes it really easy to attach informational popup to form fields. You can check it out here: https://bitbucket.org/gautamtandon/jquery.attachinfo
Hope this helps.
We usually use One Main Window
for the application and other windows can be used in situations like when you need popups because instead of using popup controls in XAML which are not visible we can use a Window that is visible at design time so that'll be easy to work with
on the other hand we use many pages to navigate from one screen to another like User management screen to Order Screen etc In the main Window we can use Frame
control for navigation like below
XAML
<Frame Name="mainWinFrame" NavigationUIVisibility="Hidden" ButtonBase.Click="mainWinFrame_Click">
</Frame>
C#
private void mainWinFrame_Click(object sender, RoutedEventArgs e)
{
try
{
if (e.OriginalSource is Button)
{
Button btn = (Button)e.OriginalSource;
if ((btn.CommandParameter != null) && (btn.CommandParameter.Equals("Order")))
{
mainWinFrame.Navigate(OrderPage);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
That's one way of doing it We can also use a Tab Control instead of Fram and Add pages to it using a Dictionary while adding new page check if the control already exists then only navigate otherwise add and navigate. I hope that'll help someone
Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0
first, then cd %~dp0
. This will change the directory to the batch file's drive, then change to its folder.
Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0
will change both the drive and directory :)
Hope this helps someone.
Beside the solutions listed in the answers, you can use the Linux command "top". It provides a dynamic real-time view of the running system, and it gives the CPU and memory usage for the whole system, along with for every program, in percentage:
top
to filter by a program PID:
top -p <PID>
To filter by a program name:
top | grep <PROCESS NAME>
"top" provides also some fields such as:
VIRT -- Virtual Image (kb): The total amount of virtual memory used by the task
RES -- Resident size (kb): The non-swapped physical memory a task has used ; RES = CODE + DATA.
DATA -- Data+Stack size (kb): The amount of physical memory devoted to other than executable code, also known as the 'data resident set' size or DRS.
SHR -- Shared Mem size (kb): The amount of shared memory used by a task. It simply reflects memory that could be potentially shared with other processes.
Reference here.
Ask them how they ensure their pages continue to be usable when the user has JavaScript turned off or JavaScript isn't available.
There's no One True Answer, but you're fishing for an answer talking about some strategies for Progressive Enhancement.
Progressive Enhancement consists of the following core principles:
- basic content should be accessible to all browsers
- basic functionality should be accessible to all browsers
- sparse, semantic markup contains all content
- enhanced layout is provided by externally linked CSS
- enhanced behavior is provided by [[Unobtrusive JavaScript|unobtrusive]], externally linked JavaScript
- end user browser preferences are respected
Selectors are an internal representation of a method name in Objective-C. In Objective-C "@selector(methodName)" would convert a source-code method into a data type of SEL. Since you can't use the @selector syntax in Swift (rickster is on point there), you have to manually specify the method name as a String object directly, or by passing a String object to the Selector type. Here is an example:
var rightBarButton = UIBarButtonItem(
title: "Logout",
style: UIBarButtonItemStyle.Plain,
target: self,
action:"logout"
)
or
var rightBarButton = UIBarButtonItem(
title: "Logout",
style: UIBarButtonItemStyle.Plain,
target: self,
action:Selector("logout")
)
Just do a \r with a find and replace with a blank in the replace field so everything goes up to one line. Then do a find and replace (in my case by semi colon) and replace with ;\n
:) -T&C
I'm using FontAwesome Pro, and the solution for me was to embed all.min.css
instead of fontawesome.min.css
.
Download java-json.jar from here, which contains org.json.JSONArray
http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip
nzip and add to your project's library: Project > Build Path > Configure build path> Select Library tab > Add External Libraries > Select the java-json.jar file.
You can always use System.Resources.ResourceManager
which returns the cached ResourceManager
used by this class. Since chan1
and chan2
represent two different images, you may use System.Resources.ResourceManager.GetObject(string name)
which returns an object matching your input with the project resources
Example
object O = Resources.ResourceManager.GetObject("chan1"); //Return an object from the image chan1.png in the project
channelPic.Image = (Image)O; //Set the Image property of channelPic to the returned object as Image
Notice: Resources.ResourceManager.GetObject(string name)
may return null
if the string specified was not found in the project resources.
Thanks,
I hope you find this helpful :)
$('#select_id').append($('<option>',{ value: v, text: t }));
You have to escape the backslash, so try this:
str = "Hello\\nWorld";
Here are more escaped characters in Javascript.
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
You could do it in one line (useful for ci-environments):
taskkill /fi "Services eq SERVICE_NAME" /F
Filter -> Services -> ServiceName equals SERVICE_NAMES -> Force
Source: https://technet.microsoft.com/en-us/library/bb491009.aspx
First check with dmesg | grep tty
if system recognize your adapter.
Then try to run minicom with sudo minicom -s
, go to "Serial port setup" and change the first line to /dev/ttyUSB0
.
Don't forget to save config as default with "Save setup as dfl". It works for me on Ubuntu 11.04 on VirtualBox.
If your xml is written by java.lang.String
you can just using HttpClient
in this way
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
pay attention to the Exceptions.
BTW, the example is written by the httpclient version 4.x
On Windows, pip
lives in C:\[pythondir]\scripts
.
So you'll need to add that to your system path in order to run it from the command prompt. You could alternatively cd
into that directory each time, but that's a hassle.
See the top answer here for info on how to do that: Adding Python Path on Windows 7
Also, that is a terrifying way to install pip
. Grab it from Christophe Gohlke. Grab everything else from there for that matter.
http://www.lfd.uci.edu/~gohlke/pythonlibs/
You can use
var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)
Something like:
class TestClass {
private $var1;
private $var2;
private function TestClass($var1, $var2){
$this->var1 = $var1;
$this->var2 = $var2;
}
public static function create($var1, $var2){
if (is_numeric($var1)){
return new TestClass($var1, $var2);
}
else return NULL;
}
}
$myArray = array();
$myArray[] = TestClass::create(15, "asdf");
$myArray[] = TestClass::create(20, "asdfa");
$myArray[] = TestClass::create("a", "abcd");
print_r($myArray);
$myArray = array_filter($myArray, function($e){ return !is_null($e);});
print_r($myArray);
I think that there are situations where this constructions are preferable to arrays. You can move all the checking logic to the class.
Here, before the call to array_filter $myArray has 3 elements. Two correct objects and a NULL. After the call, only the 2 correct elements persist.
I'm able to make it in a native way @ jsfiddle. Hope it will help.
Post improved answer when it work, and help others.
$(function () {
$(".example").multiselect({
checkAllText : 'Select All',
uncheckAllText : 'Deselect All',
selectedText: function(numChecked, numTotal, checkedItems){
return numChecked + ' of ' + numTotal + ' checked';
},
minWidth: 325
});
$(".example").multiselect("checkAll");
});
I did not read all of the answers, but I did not find the answer I was looking for.
I use Python and don't want to do find/replace or 'blank operations' each time I want to compile code...
So the best solution for me is that it happens on the fly!
Here is the simple solution I found:
Go to:
Using the rowid()
function in data.table
:
> set.seed(100)
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]
> df$num <- data.table::rowid(df$cat)
> df
cat val num
4 aaa 0.05638315 1
2 aaa 0.25767250 2
1 aaa 0.30776611 3
5 aaa 0.46854928 4
3 aaa 0.55232243 5
10 bbb 0.17026205 1
8 bbb 0.37032054 2
6 bbb 0.48377074 3
9 bbb 0.54655860 4
7 bbb 0.81240262 5
13 ccc 0.28035384 1
14 ccc 0.39848790 2
11 ccc 0.62499648 3
15 ccc 0.76255108 4
12 ccc 0.88216552 5
$(function() {
$("#datepicker").datepicker({
//showOn: both - datepicker will come clicking the input box as well as the calendar icon
//showOn: button - datepicker will come only clicking the calendar icon
showOn: 'button',
//you can use your local path also eg. buttonImage: 'images/x_office_calendar.png'
buttonImage: 'http://theonlytutorials.com/demo/x_office_calendar.png',
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
showAnim: 'slideDown',
duration: 'fast',
dateFormat: 'dd-mm-yy'
});
});
The above code belongs to this link
MySQLdb does not support Python 3 but it is not the only MySQL driver for Python.
mysqlclient is essentially just a fork of MySQLdb with Python 3 support merged in (and a few other improvements).
PyMySQL is a pure python MySQL driver, which means it is slower, but it does not require a compiled C component or MySQL libraries and header files to be installed on client machines. It has Python 3 support.
Another option is simply to use another database system like PostgreSQL.
I know that you're currently using jQuery, but what if you defined the onclick handler inline. Then you could do:
<a href='/link/for/non-js-users.htm' onclick='loadContent(5);return false;'>
Article 5</a>
Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large.
It might be that you've got UI components that you think are cleaned up but haven't been Disposed.
Here's a link about this that might be helpful.
Good Luck!
Arrays are not very dynamic in VBScript. You'll have to use the ReDim Preserve statement to grow the existing array so it can accommodate an extra item:
ReDim Preserve yourArray(UBound(yourArray) + 1)
yourArray(UBound(yourArray)) = "Watermelons"
There are two methods that come to mind:
You could use Contains like so:
if (ddlCustomerNumber.Items.Contains(new
ListItem(GetCustomerNumberCookie().ToString())))
{
// ... code here
}
or modifying your current strategy:
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != null)
{
// ... code here
}
EDIT: There's also a DropDownList.Items.FindByValue
that works the same way as FindByText, except it searches based on values instead.
For what it's worth, the source code for Stream.Close
explains why there are two methods:
// Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup now.
In short, Close
is only there because it predates Dispose
, and it can't be deleted for compatibility reasons.
The best way to handle the LazyInitializationException
is to fetch it upon query time, like this:
select t
from Topic t
left join fetch t.comments
You should ALWAYS avoid the following anti-patterns:
FetchType.EAGER
hibernate.enable_lazy_load_no_trans
Hibernate configuration propertyTherefore, make sure that your FetchType.LAZY
associations are initialized at query time or within the original @Transactional
scope using Hibernate.initialize
for secondary collections.
worked with adding $request_uri proxy_pass http://apache/$request_uri;
I used StoredProcedureEFCore nuget package by https://github.com/verdie-g/StoredProcedureEFCore,EnterpriseLibrary.Data.NetCore,EFCor.SqlServer,EFCore.Tools
I tried DbFirst approach with {Repository pattern}.. i think so
startup.cs
ConfigureServices(IServiceCollection services){
services.AddDbContext<AppDbContext>(opt => opt
.UseSqlServer(Configuration.GetConnectionString("SampleConnectionString")));
services.AddScoped<ISomeDAL, SomeDAL>();
}
public class AppDbContext : DbContext{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{}
}
ISomeDAl Interface has {GetPropertiesResponse GetAllPropertiesByCity(int CityId);}
public class SomeDAL : ISomeDAL
{
private readonly AppDbContext context;
public SomeDAL(AppDbContext context)
{
this.context = context;
}
public GetPropertiesResponse GetAllPropertiesByCity(int CityId)
{
//Create Required Objects for response
//wont support ref Objects through params
context.LoadStoredProc(SQL_STATEMENT)
.AddParam("CityID", CityId).Exec( r =>
{
while (r.Read())
{
ORMapping<GenericRespStatus> orm = new ORMapping<GenericRespStatus>();
orm.AssignObject(r, _Status);
}
if (r.NextResult())
{
while (r.Read())
{
Property = new Property();
ORMapping<Property> orm = new ORMapping<Property>();
orm.AssignObject(r, Property);
_propertyDetailsResult.Add(Property);
}
}
});
return new GetPropertiesResponse{Status=_Status,PropertyDetails=_propertyDetailsResult};
}
}
public class GetPropertiesResponse
{
public GenericRespStatus Status;
public List<Property> PropertyDetails;
public GetPropertiesResponse()
{
PropertyDetails = new List<Property>();
}
}
public class GenericRespStatus
{
public int ResCode { get; set; }
public string ResMsg { get; set; }
}
internal class ORMapping<T>
{
public void AssignObject(IDataReader record, T myClass)
{
PropertyInfo[] propertyInfos = typeof(T).GetProperties();
for (int i = 0; i < record.FieldCount; i++)
{
if (propertyInfos.Any(obj => obj.Name == record.GetName(i))) //&& record.GetValue(i) != DBNull.Value
{
propertyInfos.Single(obj => obj.Name == record.GetName(i)).SetValue(myClass, Convert.ChangeType(record.GetValue(i), record.GetFieldType(i)));
}
}
}
}
HttpClient 4.4 suffered from a bug in this area relating to validating possibly stale connections before returning to the requestor. It didn't validate whether a connection was stale, and this then results in an immediate NoHttpResponseException
.
This issue was resolved in HttpClient 4.4.1. See this JIRA and the release notes
If you are getting this error in Workbench but you are able to log in from terminal then follow this steps.
First simply log in with your current password:
sudo mysql -u root -p
Then change your password because having low strength password gives error sometimes.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new-strong-password';
FLUSH PRIVILEGES;
Then simply exit and again login with your new password:
quit
sudo mysql -u root -p
Once you successfully logged in type the command:
use mysql;
It should show a message like 'Database changed' then type:
UPDATE user SET plugin='mysql_native_password' WHERE User='root';
After that type:
UPDATE mysql.user set authentication_string=PASSWORD('new-strong-password') where user='root';
Then type:
FLUSH PRIVILEGES;
Then simply exit:
quit
Now try to log in with your new password in your WORKBENCH. Hope it will work. Thank you.
A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.
Please enter your username and password for
<realm name>
:
When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.
Unique at any time:
int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
Since you can scp
you should be ok to ssh
,
either script the following or login and execute...
# After reaching the server of interest
cd /usr/some/unknown/number/of/sub/folders
tar cfj pack.tar.bz2 $(find . -type f -name *.class)
return back (logout) to local server and scp
,
# from the local machine
cd /usr/project/backup/some/unknown/number/of/sub/folders
scp you@server:/usr/some/unknown/number/of/sub/folders/pack.tar.bz2 .
tar xfj pack.tar.bz2
If you find the $(find ...)
is too long for your tar change to,
find . -type f -name *.class | xargs tar cfj pack.tar.bz2
Finally, since you are keeping it in /usr/project/backup/
,
why bother extraction? Just keep the tar.bz2
, with maybe a date+time stamp.
Here's what I use on my site:
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
The best approach to this problem is first making the database column UNIQUE
ALTER TABLE table_name ADD UNIQUE KEY
THEN INSERT IGNORE INTO table_name
,the value won't be inserted if it results in a duplicate key/already exists in the table.
You can have Read only or Read and Write only on the volume
docker -v /on/my/host/1:/on/the/container/1:ro \
docker -v /on/my/host/2:/on/the/container/2:rw \
sns.boxplot() function returns Axes(matplotlib.axes.Axes) object. please refer the documentation you can add title using 'set' method as below:
sns.boxplot('Day', 'Count', data=gg).set(title='lalala')
you can also add other parameters like xlabel, ylabel to the set method.
sns.boxplot('Day', 'Count', data=gg).set(title='lalala', xlabel='its x_label', ylabel='its y_label')
There are some other methods as mentioned in the matplotlib.axes.Axes documentaion to add tile, legend and labels.
<?php
function is_valid_domain_name($domain_name)
{
return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name) //valid chars check
&& preg_match("/^.{1,253}$/", $domain_name) //overall length check
&& preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name) ); //length of each label
}
?>
Test cases:
is_valid_domain_name? [a] Y
is_valid_domain_name? [0] Y
is_valid_domain_name? [a.b] Y
is_valid_domain_name? [localhost] Y
is_valid_domain_name? [google.com] Y
is_valid_domain_name? [news.google.co.uk] Y
is_valid_domain_name? [xn--fsqu00a.xn--0zwm56d] Y
is_valid_domain_name? [goo gle.com] N
is_valid_domain_name? [google..com] N
is_valid_domain_name? [google.com ] N
is_valid_domain_name? [google-.com] N
is_valid_domain_name? [.google.com] N
is_valid_domain_name? [<script] N
is_valid_domain_name? [alert(] N
is_valid_domain_name? [.] N
is_valid_domain_name? [..] N
is_valid_domain_name? [ ] N
is_valid_domain_name? [-] N
is_valid_domain_name? [] N
I tried it this way and I am getting the results in IE*, and Mozilla 3.6.16, didnt check in older versions.
<img id="myImage" src="" style="display:none;"><br>
<button onclick="findSize();">Image Size</button>
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="findSize()" />
<script type="text/javascript">
function findSize() {
if ( $.browser.msie ) {
var a = document.getElementById('loadfile').value;
$('#myImage').attr('src',a);
var imgbytes = document.getElementById('myImage').size;
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}else {
var fileInput = $("#loadfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}
}
</script>
Add Jquery library also.
The postgresql port is defined in your postgresql.conf
file.
For me in Ubuntu 14.04 it is: /etc/postgresql/9.3/main/postgresql.conf
Inside there is a line:
port = 5432
Changing the number there requires restart of postgresql for it to take effect.
http://www.example.com/* has worked for me after days and days of trying.
As Umesh Patil answer have comment say that there is problem. I try to edit answer and get reject. And get suggest to post new answer. This code should solve problem they have (Shashi Roy, Gaven, John Higgins).
<html>
<head>
<script type="text/javascript">
function CheckColors(val){
var element=document.getElementById('othercolor');
if(val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</head>
<body>
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="othercolor" id="othercolor" style='display:none;'/>
</body>
</html>
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
I solved this issue by redirecting the user to the FQDN of the server hosting the intranet.
IE probably uses the world's worst algorithm for detecting "intranet" sites ... indeed, specifying server.domain.tld solves the problem for me.
Yes, you read that correctly, IE detects intranet sites not by private IP address, like any dev who has heard of TCP/IP would do, no, by the "host" part of the URL, if it has no domain part, must be internal.
Scary to know the IE devs do not understand the most basic TCP/IP concepts.
Note that this was at a BIG enterprise customer, getting them to change GPO for you is like trying to move the Alps east by 4 meters, not gonna happen.
Try
import platform platform.python_version()
Should give you a string like "2.3.1". If this is not exactly waht you want there is a rich set of data available through the "platform" build-in. What you want should be in there somewhere.
You can use JPQL as well as JPA Criteria API for any kind of DTO projection(Mapping only selected columns to a DTO class) . Look at below code snippets showing how to selectively select various columns instead of selecting all columns . These example also show how to select various columns from joining multiple columns . I hope this helps .
JPQL code :
String dtoProjection = "new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto"
+ "(i.id, i.name, i.fatherName, i.address, id.proofNo, "
+ " v.vehicleNumber, v.vechicleType, s.name, s.fatherName, "
+ " si.name, sv.vehicleNumber , svd.name) ";
List<InstructorDto> instructors = queryExecutor.fetchListForJpqlQuery(
"select " + dtoProjection + " from Instructor i " + " join i.idProof id " + " join i.vehicles v "
+ " join i.students s " + " join s.instructors si " + " join s.vehicles sv "
+ " join sv.documents svd " + " where i.id > :id and svd.name in (:names) "
+ " order by i.id , id.proofNo , v.vehicleNumber , si.name , sv.vehicleNumber , svd.name ",
CollectionUtils.mapOf("id", 2, "names", Arrays.asList("1", "2")), InstructorDto.class);
if (Objects.nonNull(instructors))
instructors.forEach(i -> i.setName("Latest Update"));
DataPrinters.listDataPrinter.accept(instructors);
JPA Criteria API code :
@Test
public void fetchFullDataWithCriteria() {
CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
CriteriaQuery<InstructorDto> cq = cb.createQuery(InstructorDto.class);
// prepare from expressions
Root<Instructor> root = cq.from(Instructor.class);
Join<Instructor, IdProof> insIdProofJoin = root.join(Instructor_.idProof);
Join<Instructor, Vehicle> insVehicleJoin = root.join(Instructor_.vehicles);
Join<Instructor, Student> insStudentJoin = root.join(Instructor_.students);
Join<Student, Instructor> studentInsJoin = insStudentJoin.join(Student_.instructors);
Join<Student, Vehicle> studentVehicleJoin = insStudentJoin.join(Student_.vehicles);
Join<Vehicle, Document> vehicleDocumentJoin = studentVehicleJoin.join(Vehicle_.documents);
// prepare select expressions.
CompoundSelection<InstructorDto> selection = cb.construct(InstructorDto.class, root.get(Instructor_.id),
root.get(Instructor_.name), root.get(Instructor_.fatherName), root.get(Instructor_.address),
insIdProofJoin.get(IdProof_.proofNo), insVehicleJoin.get(Vehicle_.vehicleNumber),
insVehicleJoin.get(Vehicle_.vechicleType), insStudentJoin.get(Student_.name),
insStudentJoin.get(Student_.fatherName), studentInsJoin.get(Instructor_.name),
studentVehicleJoin.get(Vehicle_.vehicleNumber), vehicleDocumentJoin.get(Document_.name));
// prepare where expressions.
Predicate instructorIdGreaterThan = cb.greaterThan(root.get(Instructor_.id), 2);
Predicate documentNameIn = cb.in(vehicleDocumentJoin.get(Document_.name)).value("1").value("2");
Predicate where = cb.and(instructorIdGreaterThan, documentNameIn);
// prepare orderBy expressions.
List<Order> orderBy = Arrays.asList(cb.asc(root.get(Instructor_.id)),
cb.asc(insIdProofJoin.get(IdProof_.proofNo)), cb.asc(insVehicleJoin.get(Vehicle_.vehicleNumber)),
cb.asc(studentInsJoin.get(Instructor_.name)), cb.asc(studentVehicleJoin.get(Vehicle_.vehicleNumber)),
cb.asc(vehicleDocumentJoin.get(Document_.name)));
// prepare query
cq.select(selection).where(where).orderBy(orderBy);
DataPrinters.listDataPrinter.accept(queryExecutor.fetchListForCriteriaQuery(cq));
}
The proper way to install an MSI silently is via the msiexec.exe command line
as follows:
msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"
Quick explanation:
/L*V "C:\Temp\msilog.log"= verbose logging
/QN = run completely silently
/i = run install sequence
There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.
In my case after downgrading from .NET 4.5 to .NET 4.0 project was working fine on a local machine, but was failing on server after publishing.
Turns out that destination had some old assemblies, which were still referencing .NET 4.5.
Fixed it by enabling publishing option "Delete all existing files prior to publish"
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
Note that a select list is posted as null, hence your error complains that the viewdata property cannot be found.
Always reinitialize your select list within a POST action.
For further explanation: Persist SelectList in model on Post
just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.
let's play a bit ;) :
import cv2
import numpy as np
>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168, 58, 2, 1], # uninitialized memory counts as random, too ? fun ;)
[ 0, 100, 2, 0, 101],
[ 0, 0, 106, 2, 0],
[131, 2, 0, 90, 3],
[ 0, 100, 1, 0, 83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99)) # normal
array([[ 0, 76, 0, 129, 0],
[ 0, 0, 0, 188, 27],
[ 0, 152, 0, 0, 0],
[ 0, 0, 134, 79, 0],
[ 0, 181, 36, 128, 0]], dtype=uint8)
>>> cv2.randu(im,(0),(99)) # uniform
array([[19, 53, 2, 86, 82],
[86, 73, 40, 64, 78],
[34, 20, 62, 80, 7],
[24, 92, 37, 60, 72],
[40, 12, 27, 33, 18]], dtype=uint8)
to apply it to an existing image, just generate noise in the desired range, and add it:
img = ...
noise = ...
image = img + noise
I have shamelessly pulled some pretty big datasets in memory, and altough it did get sluggish it took maybe 15 Mo of data upwards with pretty intense calculations on the dataset. I doubt you will run into problems with memory unless you have intense calculations on the data and many many rows. Profiling and benchmarking with different mock resultsets will be your best bet to evaluate performance.
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
I'm assuming you're using Windows, and GitBASH.
You can just delete the folder "C:...\project" with no adverse effects.
Then in git bash, you can do cd c\:
. This changes the directory you're working in to C:\
Then you can do git clone [url]
This will create a folder called "project" on C:\ with the contents of the repo.
If you'd like to name it something else, you can do
git clone [url] [something else]
For example
cd c\:
git clone [email protected]:username\repo.git MyRepo
This would create a folder at "C:\MyRepo" with the contents of the remote repository.
I went through all answers, but doesn't satisfied my exact needed answer, so here is an example that I wrote and perfectly works, even user clicks the Don't ask again checkbox.
Create a method that will be called when you want to ask for runtime permission like readContacts()
or you can also have openCamera()
as shown below:
private void readContacts() {
if (!askContactsPermission()) {
return;
} else {
queryContacts();
} }
Now we need to make askContactsPermission()
, you can also name it as askCameraPermission()
or whatever permission you are going to ask.
private boolean askContactsPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(parentLayout, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
}).show();
} else if (contactPermissionNotGiven) {
openPermissionSettingDialog();
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
contactPermissionNotGiven = true;
}
return false;
}
Before writing this function make sure you have defined the below instance variable as shown:
private View parentLayout;
private boolean contactPermissionNotGiven;;
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
Now final step to override the onRequestPermissionsResult
method as shown below:
/**
* Callback received when a permissions request has been completed.
*/
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
queryContacts();
}
}
}
Here we are done with the RunTime permissions, the addon is the openPermissionSettingDialog()
which simply open the Setting screen if user have permanently disable the permission by clicking Don't ask again checkbox. below is the method:
private void openPermissionSettingDialog() {
String message = getString(R.string.message_permission_disabled);
AlertDialog alertDialog =
new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
.setMessage(message)
.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
dialog.cancel();
}
}).show();
alertDialog.setCanceledOnTouchOutside(true);
}
What we missed ?
1. Defining the used strings in strings.xml
<string name="permission_rationale">"Contacts permissions are needed to display Contacts."</string>_x000D_
<string name="message_permission_disabled">You have disabled the permissions permanently,_x000D_
To enable the permissions please go to Settings -> Permissions and enable the required Permissions,_x000D_
pressing OK you will be navigated to Settings screen</string>
_x000D_
Initializing the parentLayout
variable inside onCreate
method
parentLayout = findViewById(R.id.content);
Defining the required permission in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
_x000D_
The queryContacts
method, based on your need or the runtime permission you can call your method before which the permission
was needed. in my case I simply use the loader to fetch the contact as shown below:
private void queryContacts() {
getLoaderManager().initLoader(0, null, this);}
This works great happy coding :)
You can use Class#getDeclaredFields()
to get all declared fields of the class. You can use Field#get()
to get the value.
In short:
Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
field.setAccessible(true); // You might want to set modifier to public first.
Object value = field.get(someObject);
if (value != null) {
System.out.println(field.getName() + "=" + value);
}
}
To learn more about reflection, check the Sun tutorial on the subject.
That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get
or is
and then invoke it to grab the real property values.
for (Method method : someObject.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& (method.getName().startsWith("get") || method.getName().startsWith("is"))
) {
Object value = method.invoke(someObject);
if (value != null) {
System.out.println(method.getName() + "=" + value);
}
}
}
That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.
You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.
It should look like that :
#!/usr/bin/env python
or the real path
#!/usr/bin/python
You should also check the file have the right to be execute. chmod +x file.py
As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)
You need to set the flags after the project
command in your CMakeLists.txt.
Also, if you're calling include(${QT_USE_FILE})
or add_definitions(${QT_DEFINITIONS})
, you should include these set
commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb")
You can do the same in Razor or in the Controller, like so..
@{
//do this on the top most of your View, immediately after `using` statement
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}
Or in the Controller..
public ActionResult Receipt() {
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
return View();
}
I tried this in Chrome and IE9, both is downloading the pdf file.
I probably should add I am using RazorPDF to generate my PDFs. Here is a blog about it: http://nyveldt.com/blog/post/Introducing-RazorPDF
I shall refer to the same sample of data as posted in the question:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))
Running this code will give you
The original data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc
to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append
returns a view of the dataframe and does not modify its contents. Following is the code:
row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))
Following would be the new output:
The new data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
3 10.000000 20.000000 30.000000 40.000000
That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.
Try this:
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $str);
In case it's UTF-16 based C/C++/Java/Json-style:
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
}, $str);
Determine the application pool used by the application and set the property of by setting Enable 32 bit applications to True. This can be done through advance settings of the application pool.
Python or Python3 with MySQL, you will need these. These libraries use MySQL's connector for C and Python (you need the C libraries installed as well), which overcome some of the limitations of the mysqldb libraries.
sudo apt-get install libmysqlclient-dev
sudo apt-get install python-mysql.connector
sudo apt-get install python3-mysql.connector
Most people recommend using notifyDataSetChanged()
, but I found this link pretty useful. In fact using clear
and add
you can accomplish the same goal using less memory footprint, and more responsibe app.
For example:
notesListAdapter.clear();
notes = new ArrayList<Note>();
notesListAdapter.add(todayNote);
if (birthdayNote != null) notesListAdapter.add(birthdayNote);
/* no need to refresh, let the adaptor do its job */
(123456789).toString(10).split("")
^^ this will return an array of strings
(123456789).toString(10).split("").map(function(t){return parseInt(t)})
^^ this will return an array of ints
I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)
Easy to scale horizontally by just adding more nodes.
Query on large data set
Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.
Disk I/O bottleneck
If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.
I had such crash on Samsung devices even though the activity did use Theme.AppCompat. The root cause was related to weird optimizations on Samsung side:
- if one activity of your app has theme not inherited from Theme.AppCompat
- and it has also `android:launchMode="singleTask"`
- then all the activities that are launched from it will share the same Theme
My solution was just removing android:launchMode="singleTask"
Look at the filter
function.
If you just need a 1-pole low-pass filter, it's
xfilt = filter(a, [1 a-1], x);
where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.
Here's the corresponding high-pass filter:
xfilt = filter([1-a a-1],[1 a-1], x);
If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.
Even though it's an old question I'd like to show another solution:
Just define your own operation using java generics and java 8 streams:
public static <S, T> List<T> map(Collection<S> collection, Function<S, T> mapFunction) {
return collection.stream().map(mapFunction).collect(Collectors.toList());
}
Than you can write code like this:
List<String> hex = map(Arrays.asList(10, 20, 30, 40, 50), Integer::toHexString);
This worked for me:
git branch
Copy the current branch name to clipboard
git pull origin <paste-branch-name>
git push
Here's what I use at the top of all my batch files. I just copy/paste from my template folder.
@echo off
:: --HAS ENDING BACKSLASH
set batdir=%~dp0
:: --MISSING ENDING BACKSLASH
:: set batdir=%CD%
pushd "%batdir%"
Setting current batch file's path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file's path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. "%batdir%ExtraDir"). You can always use PUSHD %~dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%~) parameters.
Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. < > | etc) in that comment.
:: ORIG STMT WAS: dir *.* | find /v "1917" > outfile.txt
Of course, Powershell does this and lots more.
Add this class
css
to your style sheet
.border_gradient {
border: 8px solid #000;
-moz-border-bottom-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-top-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-left-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-right-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
padding: 5px 5px 5px 15px;
width: 300px;
}
set width
to the width
of your image. and use this html
for image
<div class="border_gradient">
<img src="image.png" />
</div>
though it may not give the same exact border, it will some gradient looks on the border.
source: CSS3 Borders
Wrap time
and the command you are timing in a set of brackets.
For example, the following times ls
and writes the result of ls
and the results of the timing into outfile
:
$ (time ls) > outfile 2>&1
Or, if you'd like to separate the output of the command from the captured output from time
:
$ (time ls) > ls_results 2> time_results
If you need to increase MySQL Connections without MySQL restart do like below, also if you don't know configuration file, below use the mysqlworkbench or phpmyadmin or command prompt to run below queries.
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 151 |
+-----------------+-------+
1 row in set (0.00 sec)
mysql> SET GLOBAL max_connections = 250;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 250 |
+-----------------+-------+
1 row in set (0.00 sec)
These settings will change at MySQL Restart.
For permanent changes add below line in my.cnf and restart MySQL.
max_connections = 151
Here is one more way you can do
/*
one more way of declaring constants in a class,
Note - the constants have to be declared after the class is defined
*/
class Auto{
//other methods
}
Auto.CONSTANT1 = "const1";
Auto.CONSTANT2 = "const2";
console.log(Auto.CONSTANT1)
console.log(Auto.CONSTANT2);
_x000D_
Note - the Order is important, you cannot have the constants above
Usage
console.log(Auto.CONSTANT1);
There is a great library to make your life easier Dapper.Contrib.Extensions. After including this you can just write:
public int Add(Transaction transaction)
{
using (IDbConnection db = Connection)
{
return (int)db.Insert(transaction);
}
}
Your other option is to initialize j
:
j = [None] * len(i)
break
interacts solely with the closest enclosing loop or switch, whether it be a for
, while
or do .. while
type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:
for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:
while (B) D; // Simply doesn't have A or C
do { D; } while (B); // Omits initial goto test
continue; // goto iter;
break; // goto end;
The difference is, continue
and break
interact with virtual labels automatically placed by the compiler. This is similar to what return
does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.
The programming error the notice refers to is misunderstanding break
as interacting with an enclosing block rather than an enclosing loop. Consider:
for (A; B; C) {
D;
if (E) {
F;
if (G) break; // Incorrectly assumed to break if(E), breaks for()
H;
}
I;
}
J;
Someone thought, given such a piece of code, that G
would cause a jump to I
, but it jumps to J
. The intended function would use if (!G) H;
instead.
You can use the string format operator %
, similar to sprintf.
mystring = "%.2f" % 5.5999
Before using v-html
, you have to make sure that the element which you escape is sanitized in case you allow user input, otherwise you expose your app to xss vulnerabilities.
More info here: https://vuejs.org/v2/guide/security.html
I highly encourage you that instead of using v-html
to use this npm package
Check who the group and owner are of the folder where the script runs. If the group id or user id are wrong, for example, set to root, it will cause sessions to not be saved properly.
Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.
So what you do is register the driver so that the JDBC system can know what to do with the URL:
DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());
Then you form the URL:
String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"
And finally, use it to get a connection:
Connection c = DriverManager.getConnection(url);
In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.
In terms of what properties MySQL supports, see here.
EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.
You should probably consider using css3 for this though it does include the use of vendor prefixes.
I've knocked up a quick fiddle to demo but the crux is this.
<style>
.3col
{
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-moz-column-count: 3;
-moz-column-gap: 10px;
column-count:3;
column-gap:10px;
}
</style>
<div class="3col">
<p>col1</p>
<p>col2</p>
<p>col3</p>
</div>
If you forget to provide a "name" string as the second argument to the constructor, it creates an "in-memory" database which gets erased when you close the app.
Try:
if (isset($_FILES['uploaded_file']) &&
$_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
$_FILES['uploaded_file']['name']);
}
Basic example can also be found here.
The function definition for AddAttachment
is:
public function AddAttachment($path,
$name = '',
$encoding = 'base64',
$type = 'application/octet-stream')
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)
The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential
If you want your loop to be executed in parallel you could simply write
joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
You will have to write some extra code for thread handling etc.
Note: For my answer I assumed joins implementing the java.util.Stream
interface. If joins implements only the java.util.Iterable
interface this is no longer true.
Bootstrap 4.3 - use code from below snippet - more here
$('#exampleModal').on('show.bs.modal', function (event) {_x000D_
let bookId = $(event.relatedTarget).data('bookid') _x000D_
$(this).find('.modal-body input').val(bookId)_x000D_
})
_x000D_
a.btn.btn-primary.open-AddBookDialog {color: white }
_x000D_
<!-- Initialize Bootstrap 4 -->_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
<!-- BUTTON -->_x000D_
_x000D_
<a _x000D_
class="btn btn-primary open-AddBookDialog" _x000D_
data-toggle="modal" _x000D_
data-target="#exampleModal" _x000D_
data-bookid="@book.Id" _x000D_
title="Add this item"_x000D_
>Open</a>_x000D_
_x000D_
<!-- MODAL -->_x000D_
_x000D_
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog">_x000D_
<div class="modal-dialog" role="document">_x000D_
<div class="modal-content">_x000D_
_x000D_
<div class="modal-body">_x000D_
<input type="hidden" name="bookId" id="bookId" value=""/>_x000D_
<input type="text" class="form-control" id="recipient-name"> _x000D_
</div>_x000D_
_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
There are several possibilities.
More information is needed about your configuration. What distro are you using? Can you connect via 127.0.0.1?
If the issue is with the firewall/iptables, you can add the following lines to /etc/sysconfig/iptables:
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
(Second line is only needed for https)
Make sure this is above any lines that would globally restrict access, like the following:
-A INPUT -j REJECT --reject-with icmp-host-prohibited
Tested on CentOS 6.3
And finally
service iptables restart
//Note: if you have access to Java5+,
//use StringBuilder in preference to StringBuffer.
//All that has to be replaced is the class name.
//StringBuffer will work in Java 1.4, though.
appendWithDelimiter( StringBuffer buffer, String addition,
String delimiter ) {
if ( buffer.length() == 0) {
buffer.append(addition);
} else {
buffer.append(delimiter);
buffer.append(addition);
}
}
StringBuffer parameterBuffer = new StringBuffer();
if ( condition ) {
appendWithDelimiter(parameterBuffer, "elementName", "," );
}
if ( anotherCondition ) {
appendWithDelimiter(parameterBuffer, "anotherElementName", "," );
}
//Finally, to return a string representation, call toString() when returning.
return parameterBuffer.toString();
Assumptions
cat
, may be overlapping, but all dataframes may not contain all values of cat
hue='cat'
Because dataframes are being iterated through, there's not guarantee that colors will be mapped the same for each plot
'cat'
values for all the dataframesimport pandas as pd
import numpy as np # used for random data
import random # used for random data
import matplotlib.pyplot as plt
from matplotlib.patches import Patch # for custom legend
import seaborn as sns
import math import ceil # determine correct number of subplot
# synthetic data
df_dict = dict()
for i in range(1, 7):
np.random.seed(i)
random.seed(i)
data_length = 100
data = {'cat': [random.choice(['A', 'B', 'C']) for _ in range(data_length)],
'x': np.random.rand(data_length),
'y': np.random.rand(data_length)}
df_dict[i] = pd.DataFrame(data)
# display(df_dict[1].head())
cat x y
0 A 0.417022 0.326645
1 C 0.720324 0.527058
2 A 0.000114 0.885942
3 B 0.302333 0.357270
4 A 0.146756 0.908535
# create color mapping based on all unique values of cat
unique_cat = {cat for v in df_dict.values() for cat in v.cat.unique()} # get unique cats
colors = sns.color_palette('husl', n_colors=len(unique_cat)) # get a number of colors
cmap = dict(zip(unique_cat, colors)) # zip values to colors
# iterate through dictionary and plot
col_nums = 3 # how many plots per row
row_nums = math.ceil(len(df_dict) / col_nums) # how many rows of plots
plt.figure(figsize=(10, 5)) # change the figure size as needed
for i, (k, v) in enumerate(df_dict.items(), 1):
plt.subplot(row_nums, col_nums, i) # create subplots
p = sns.scatterplot(data=v, x='x', y='y', hue='cat', palette=cmap)
p.legend_.remove() # remove the individual plot legends
plt.title(f'DataFrame: {k}')
plt.tight_layout()
# create legend from cmap
patches = [Patch(color=v, label=k) for k, v in cmap.items()]
# place legend outside of plot; change the right bbox value to move the legend up or down
plt.legend(handles=patches, bbox_to_anchor=(1.06, 1.2), loc='center left', borderaxespad=0)
plt.show()
If using MySQL Workbench, simply look in the Session tab in the Information pane located in the sidebar.
it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.
jcomeau@aspire:/tmp$ cat test.java; javac test.java; java test
import java.awt.event.*;
import java.awt.Robot;
public class test {
public static void main(String args[]) {
Robot bot = null;
try {
bot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instantiating Robot: " + failed);
}
int mask = InputEvent.BUTTON1_DOWN_MASK;
bot.mouseMove(100, 100);
bot.mousePress(mask);
bot.mouseRelease(mask);
}
}
I'm assuming InputEvent.MOUSE_BUTTON1_DOWN
in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK
in mine; I'm using 1.6.
otherwise, that could be your problem. I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).
[added later after cogitating on it today] it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?
You could use the heapq module:
>>> el = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
>>> import heapq
>>> heapq.nlargest(2, el)
[90.8, 74]
And go from there...
Here's what works for me as of Gradle 4.0.
sourceSets {
integrationTest {
compileClasspath += sourceSets.test.compileClasspath
runtimeClasspath += sourceSets.test.runtimeClasspath
}
}
task integrationTest(type: Test) {
description = "Runs the integration tests."
group = 'verification'
testClassesDirs = sourceSets.integrationTest.output.classesDirs
classpath = sourceSets.integrationTest.runtimeClasspath
}
As of version 4.0, Gradle now uses separate classes directories for each language in a source set. So if your build script uses sourceSets.integrationTest.output.classesDir
, you'll see the following deprecation warning.
Gradle now uses separate output directories for each JVM language, but this build assumes a single directory for all classes from a source set. This behaviour has been deprecated and is scheduled to be removed in Gradle 5.0
To get rid of this warning, just switch to sourceSets.integrationTest.output.classesDirs
instead. For more information, see the Gradle 4.0 release notes.
You could create a unique index with a coalesce on the MenuId:
CREATE UNIQUE INDEX
Favorites_UniqueFavorite ON Favorites
(UserId, COALESCE(MenuId, '00000000-0000-0000-0000-000000000000'), RecipeId);
You'd just need to pick a UUID for the COALESCE that will never occur in "real life". You'd probably never see a zero UUID in real life but you could add a CHECK constraint if you are paranoid (and since they really are out to get you...):
alter table Favorites
add constraint check
(MenuId <> '00000000-0000-0000-0000-000000000000')
Confirmed that this is related to the Spark build against Hadoop 2.60. Just installed Spark 1.4.0 "Pre built for Hadoop 2.4 and later" (instead of Hadoop 2.6). And the code now works OK.
sc.textFile("s3n://bucketname/Filename")
now raises another error:
java.lang.IllegalArgumentException: AWS Access Key ID and Secret Access Key must be specified as the username or password (respectively) of a s3n URL, or by setting the fs.s3n.awsAccessKeyId or fs.s3n.awsSecretAccessKey properties (respectively).
The code below uses the S3 URL format to show that Spark can read S3 file. Using dev machine (no Hadoop libs).
scala> val lyrics = sc.textFile("s3n://MyAccessKeyID:MySecretKey@zpub01/SafeAndSound_Lyrics.txt")
lyrics: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[3] at textFile at <console>:21
scala> lyrics.count
res1: Long = 9
Even Better: the code above with AWS credentials inline in the S3N URI will break if the AWS Secret Key has a forward "/". Configuring AWS Credentials in SparkContext will fix it. Code works whether the S3 file is public or private.
sc.hadoopConfiguration.set("fs.s3n.awsAccessKeyId", "BLABLA")
sc.hadoopConfiguration.set("fs.s3n.awsSecretAccessKey", "....") // can contain "/"
val myRDD = sc.textFile("s3n://myBucket/MyFilePattern")
myRDD.count
i usually use ng-show
<li ng-show="variable.length"></li>
where variable you define for example
<div class="list-group-item" ng-repeat="product in store.products">
<li ng-show="product.length">show something</li>
</div>
6.5.5 Multiplicative operators
...
6 When integers are divided, the result of the/
operator is the algebraic quotient with any fractional part discarded.105) If the quotienta/b
is representable, the expression(a/b)*b + a%b
shall equala
; otherwise, the behavior of botha/b
anda%b
is unde?ned.
105) This is often called ‘‘truncation toward zero’’.
Dividing an integer by an integer gives an integer result. 1/2 yields 0; assigning this result to a floating-point variable gives 0.0. To get a floating-point result, at least one of the operands must be a floating-point type. b = a / 350.0f;
should give you the result you want.
An other regex
-based solution:
>>> strs = "foo\tbar\t\tspam"
>>> r = re.compile(r'([^\t]*)\t*')
>>> r.findall(strs)[:-1]
['foo', 'bar', 'spam']
Microsoft's documented way to add script extensibility to anything is IActiveScript. You can use IActiveScript from within anyt .NET app, to call script logic. The logic can party on .NET objects that you've placed into the scripting context.
This answer provides an application that does it, with code:
int atoi(const char* str){
int num = 0;
int i = 0;
bool isNegetive = false;
if(str[i] == '-'){
isNegetive = true;
i++;
}
while (str[i] && (str[i] >= '0' && str[i] <= '9')){
num = num * 10 + (str[i] - '0');
i++;
}
if(isNegetive) num = -1 * num;
return num;
}
**This is a simple way of getting the DAYS between two dates**
var d1 = moment($("#StartDate").data("DateTimePicker").date());
var d2 = moment($("#EndDate").data("DateTimePicker").date());
var diffInDays = d2.diff(d1, 'days');
if (diffInDays > 0)
{
$("#Total").val(diffInDays);
}
else
{
$("#Total").val(0);
}
Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.
Here are some providers which have a "free-tier" (may change in future):
Open source solutions:
$(window).scroll(function () {
var ControlDivTop = $('#cs_controlDivFix');
$(window).scroll(function () {
if ($(this).scrollTop() > 50) {
ControlDivTop.stop().animate({ 'top': ($(this).scrollTop() - 62) + "px" }, 600);
} else {
ControlDivTop.stop().animate({ 'top': ($(this).scrollTop()) + "px" },600);
}
});
});
You can use the .complete property of the Javascript image class.
I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:
var gAllImages = [];
function makeThumbDivs(thumbnailsBegin, thumbnailsEnd)
{
gAllImages = [];
for (var i = thumbnailsBegin; i < thumbnailsEnd; i++)
{
var theImage = new Image();
theImage.src = "thumbs/" + getFilename(globals.gAllPageGUIDs[i]);
gAllImages.push(theImage);
setTimeout('checkForAllImagesLoaded()', 5);
window.status="Creating thumbnail "+(i+1)+" of " + thumbnailsEnd;
// make a new div containing that image
makeASingleThumbDiv(globals.gAllPageGUIDs[i]);
}
}
function checkForAllImagesLoaded()
{
for (var i = 0; i < gAllImages.length; i++) {
if (!gAllImages[i].complete) {
var percentage = i * 100.0 / (gAllImages.length);
percentage = percentage.toFixed(0).toString() + ' %';
userMessagesController.setMessage("loading... " + percentage);
setTimeout('checkForAllImagesLoaded()', 20);
return;
}
}
userMessagesController.setMessage(globals.defaultTitle);
}
Formats like
date9.
or
mmddyy10.
are not valid for input command while converting text to a sas date. You can use
Date = input( cdate , ANYDTDTE11.);
or
Date = input( cdate , ANYDTDTE10.);
for conversion.
In Python3
pip list
Empty venv is
Package Version
---------- -------
pip 19.2.3
setuptools 41.2.0
To start a new environment
python3 -m venv your_foldername_here
Activate
cd your_foldername_here
source bin/activate
Deactivate
deactivate
You can also stand in the folder and give the virtual environment a name/folder (python3 -m venv name_of_venv).
Venv is a subset of virtualenv that is shipped with Python after 3.3.
A = filename
ftp = ftplib.FTP("IP")
ftp.login("USR Name", "Pass")
ftp.cwd("/Dir")
try:
ftp.retrbinary("RETR " + filename ,open(A, 'wb').write)
except:
print "Error"
Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the "
characters, and so part of the actual XML data.
Try like that may you get your solution
String table = "beaconTable";
String whereClause = "_id=?";
String[] whereArgs = new String[] { String.valueOf(row) };
db.delete(table, whereClause, whereArgs);
If you want to due this in component.ts
HTML:
<button class="class1 class2" (click)="clicked($event)">Click me</button>
Component:
clicked(event) {
event.target.classList.add('class3'); // To ADD
event.target.classList.remove('class1'); // To Remove
event.target.classList.contains('class2'); // To check
event.target.classList.toggle('class4'); // To toggle
}
For more options, examples and browser compatibility visit this link.
What you have should work but can be reduced to:
select * from table where concat_ws(' ',first_name,last_name)
like '%$search_term%';
Can you provide an example name and search term where this doesn't work?
You could add the default rule with the alter table,
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()
then immediately set to null all the current existing rows:
UPDATE mytable SET created_at = NULL
Then from this point on the DEFAULT
will take effect.
This is what works for me:
I had to put my local server address in the PHP Server configuration like this:
Note: that address, is the one I configure in my Apache .conf file.
Note: the only breakpoint that was working was the 'Break at first line', after that, the breakpoints didn't work.
Note: check your xdebug properties in your php.ini file, and remove any you think is not required.
Set a zero height table footer view (perhaps in your viewDidLoad
method), like so:
Swift:
tableView.tableFooterView = UIView()
Objective-C:
tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
Because the table thinks there is a footer to show, it doesn't display any cells beyond those you explicitly asked for.
Interface builder pro-tip:
If you are using a xib/Storyboard, you can just drag a UIView (with height 0pt) onto the bottom of the UITableView.
Assuming RestTemplate
is configured to use HttpClient 4.x, you can read up on HttpClient's logging documentation here. The loggers are different than those specified in the other answers.
The logging configuration for HttpClient 3.x is available here.
def ipcheck():
# 1.Validate the ip adderess
input_ip = input('Enter the ip:')
flag = 0
pattern = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
match = re.match(pattern, input_ip)
if (match):
field = input_ip.split(".")
for i in range(0, len(field)):
if (int(field[i]) < 256):
flag += 1
else:
flag = 0
if (flag == 4):
print("valid ip")
else:
print('No match for ip or not a valid ip')
In urls.py I added this line:
from django.views.static import serve
add those two urls in urlpatterns:
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
and both static and media files were accesible when DEBUG=FALSE.
Hope it helps :)
In addition to the accepted answer (https://stackoverflow.com/a/4501084/6276704):
Since Java 1.7, if you want to compare two Objects which might be null, I recommend this function:
Objects.equals(onePossibleNull, twoPossibleNull)
java.util.Objects
This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
Since: 1.7
This should do it:
<StackPanel>
<TextBox x:Name="TheTextBox" />
<Button Content="Click Me">
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
Update alpha 47
As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows
http
.get('Some Url')
.map(res => res.json())
.subscribe(
(data) => this.data = data,
(err) => this.error = err); // Reach here if fails
Alpha 46 and below
You can handle the response in the map(...)
, before the subscribe
.
http
.get('Some Url')
.map(res => {
// If request fails, throw an Error that will be caught
if(res.status < 200 || res.status >= 300) {
throw new Error('This request has failed ' + res.status);
}
// If everything went fine, return the response
else {
return res.json();
}
})
.subscribe(
(data) => this.data = data, // Reach here if res.status >= 200 && <= 299
(err) => this.error = err); // Reach here if fails
Here's a plnkr with a simple example.
Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.
IIF
is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END
. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.
CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.
IOC - DIP - DI
1- IOC: abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming.
2-DIP: is Object Oriented Programming(OOP) principle(D of SOLID).
3-DI: is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle.
IOC & DIP are two disjoint sets and DIP is the super set of DI, service locator and some other patterns
I was searching for a fix on this and the folder i was ADD or COPY'ing was not in the build folder, multiple directories above or referenced from /
Moving the folder from outside the build folder into the build folder fixed my issue.
You can do it either way.
Put an '&' symbol in front and the variable you are passing becomes one and the same as its origin i.e. you can pass by reference, rather than make a copy of it.
so
$fred = 5;
$larry = & $fred;
$larry = 8;
echo $fred;//this will output 8, as larry and fred are now the same reference.
To call a function inside a same controller in any laravel version follow as bellow
$role = $this->sendRequest('parameter');
// sendRequest is a public function
After trying to add the path using:
pip show
on command prompt and using
sys.path.insert(0, "/home/myname/pythonfiles")
and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.
I simply copied the module that wasn't found from the path "Mine was in
C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages
so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'
Generally, yes, serialize and unserialize are the way to go.
If your data is something simple, though, saving as a comma-delimited string would probably be better for storage space. If you know that your array will just be a list of numbers, for example, then you should use implode/explode. It's the difference between 1,2,3
and a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}
.
If not, then serialize and unserialize work for all cases.
It seems to mean your node server's connection to your MongoDB instance was interrupted while it was trying to write to it.
Take a look at the Mongo source code that generates that error
Mongos.prototype.insert = function(ns, ops, options, callback) {
if(typeof options == 'function') callback = options, options = {};
if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
// Topology is not connected, save the call in the provided store to be
// Executed at some point when the handler deems it's reconnected
if(!this.isConnected() && this.s.disconnectHandler != null) {
callback = bindToCurrentDomain(callback);
return this.s.disconnectHandler.add('insert', ns, ops, options, callback);
}
executeWriteOperation(this.s, 'insert', ns, ops, options, callback);
}
This does not appear to be related to the Sails issue cited in the comments, as no upgrades were installed to precipitate the crash or the "fix"
I tried a couple of solution but I thing easy way like this (you are in the local folder):
#!/bin/bash
git fetch
var_local=`cat .git/refs/heads/master`
var_remote=`git log origin/master -1 | head -n1 | cut -d" " -f2`
if [ "$var_remote" = "$var_local" ]; then
echo "Strings are equal." #1
else
echo "Strings are not equal." #0 if you want
fi
Then you did compare local git and remote git last commit number....
With me this error ocurred when I copied and pasted a code in text format to my editor (gedit). The code was in a text document (.odt) and I copied it and pasted it into gedit. If you did the same, you have manually rewrite the code.
Add a reference to Microsoft.VisualBasic
, InputBox
is in the Microsoft.VisualBasic.Interaction
namespace:
using Microsoft.VisualBasic;
string input = Interaction.InputBox("Prompt", "Title", "Default", x_coordinate, y_coordinate);
Only the first argument for prompt
is mandatory
I found one Solution :
echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));
use utf8_encode()
Mine happens as soon as I add a new binding inside the applicationhost.config, running as administrator fixed the problem.
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
This will work. Link to your SVG using the following pattern:
https://cdn.rawgit.com/<repo-owner>/<repo>/<branch>/path/to.svg
The downside is hardcoding the owner and repo in the path, meaning the svg will break if either of those are renamed.
Here is How you can do in Spring Boot 2.0 by creating custom MongoClient adding Providing more control for Connection ,
Please follow github Link for Full Source Code
@Configuration
@EnableMongoRepositories(basePackages = { "com.frugalis.repository" })
@ComponentScan(basePackages = { "com.frugalis.*" })
@PropertySource("classpath:application.properties")
public class MongoJPAConfig extends AbstractMongoConfiguration {
@Value("${com.frugalis.mongo.database}")
private String database;
@Value("${com.frugalis.mongo.server}")
private String host;
@Value("${com.frugalis.mongo.port}")
private String port;
@Value("${com.frugalis.mongo.username}")
private String username;
@Value("${com.frugalis.mongo.password}")
private String password;
@Override
protected String getDatabaseName() {
return database;
}
@Override
protected String getMappingBasePackage() {
return "com.frugalis.entity.mongo";
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoClient(), getDatabaseName());
}
@Override
@Bean
public MongoClient mongoClient() {
List<MongoCredential> allCred = new ArrayList<MongoCredential>();
System.out.println("???????????????????"+username+" "+database+" "+password+" "+host+" "+port);
allCred.add(MongoCredential.createCredential(username, database, password.toCharArray()));
MongoClient client = new MongoClient((new ServerAddress(host, Integer.parseInt(port))), allCred);
client.setWriteConcern(WriteConcern.ACKNOWLEDGED);
return client;
}}
For anyone else who came here looking to do the same with docker-compose
you just need to prepend bash -c
and enclose multiple commands in quotes, joined together with &&
.
So in the OPs example docker-compose run image bash -c "cd /path/to/somewhere && python a.py"
In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.
Note that in an XML Declaration the encoding
and standalone
are both optional. Only the version
is mandatory. Also, these are not attributes, so if they are present they must be in that order: version
, followed by any encoding
, followed by any standalone
.
<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" standalone="yes"?>
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.
The standalone
indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.
Update:
A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.
Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?>
which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding
and simply say <?xml version="1.0"?>
. You could also edit it to say encoding="UTF-16"
but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.
Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!
You can use jquery attr method
$("#delete").attr("hidden",true);
in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.
$data = [
'hello',
'world'
];
$key = array_search('world', $data);
if ($key) {
echo 'Key is ' . $key;
} else {
echo 'Key not found';
}
This will print "Key is 1"