I had this exact problem and this worked:
plt.savefig(output_dir + '/xyz.png', bbox_inches='tight')
Here is the documentation:
[https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html][1]
Your c# will have to do just a bit of work (counting the number of IDs passed in), but try this:
select (select count(*) from players where productid in (1, 10, 100, 1000)) = 4
Edit:
4 can definitely be parameterized, as can the list of integers.
If you're not generating the SQL from string input by the user, you don't need to worry about attacks. If you are, you just have to make sure you only get integers. For example, if you were taking in the string "1, 2, 3, 4", you'd do something like
String.Join(",", input.Split(",").Select(s => Int32.Parse(s).ToString()))
That will throw if you get the wrong thing. Then just set that as a parameter.
Also, be sure be sure to special case if items.Count == 0, since your DB will choke if you send it where ParameterID in ()
.
The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:
+ if not u in self.adj.keys():
+ self.adj[u] = []
self.adj[u].append(edge)
.
.
For opening a file, try this:
objexcel.Workbooks.Open(@"C:\YourPath\YourExcelFile.xls",
missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,missing, missing);
You must supply those stupid looking 'missing' arguments. If you were writing the same code in VB.Net you wouldn't have needed them, but you can't avoid them in C#.
If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:
Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
If you wish more look at: http://developer.android.com/intl/pt-br/guide/topics/resources/string-resource.html#FormattingAndStyling
Just to add , if you are performing a "pip" operation , you might need to add and additional "--proxy=localhost:port_number"
e.g pip install --proxy=localhost:3128 matplotlib
Visit this link to see full details.
I liked Arun's answer better but there is a tiny problem and I could not comment or edit the answer. sparkContext does not have createDeataFrame, sqlContext does (as Thiago mentioned). So:
from pyspark.sql import SQLContext
# assuming the spark environemnt is set and sc is spark.sparkContext
sqlContext = SQLContext(sc)
schemaPeople = sqlContext.createDataFrame(RDDName)
schemaPeople.createOrReplaceTempView("RDDName")
Everything in the g element is positioned relative to the current transform matrix.
To move the content, just put the transformation in the g element:
<g transform="translate(20,2.5) rotate(10)">
<rect x="0" y="0" width="60" height="10"/>
</g>
Links: Example from the SVG 1.1 spec
As I learnd in university most of the answers above are right. In PRACTISE on different platforms (always using python) spawning multiple threads ends up like spawning one process. The difference is the multiple cores share the load instead of only 1 core processing everything at 100%. So if you spawn for example 10 threads on a 4 core pc, you will end up getting only the 25% of the cpus power!! And if u spawn 10 processes u will end up with the cpu processing at 100% (if u dont have other limitations). Im not a expert in all the new technologies. Im answering with own real experience background
You can still use the textmode and force the linefeed-newline with the keyword argument newline
f = open("./foo",'w',newline='\n')
Tested with Python 3.4.2.
Edit: This does not work in Python 2.7.
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
Are you sure it's a driver problem? A device that isn't detected probably has a hardware or firmware problem. If it isn't detected, you won't hear the USB device detected chime. It might not be serious, e.g. some "USB" cables are really only charging cables. Try a USB cable that you know works for data, e.g. the one that came with the phone or one you use for connecting an external hard drive.
Add { } while importing and exporting:
export { ... };
|
import { ... } from './Template';
export → import { ... } from './Template'
export default → import ... from './Template'
Here is a working example:
// ExportExample.js
import React from "react";
function DefaultExport() {
return "This is the default export";
}
function Export1() {
return "Export without default 1";
}
function Export2() {
return "Export without default 2";
}
export default DefaultExport;
export { Export1, Export2 };
// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";
export default function App() {
return (
<>
<strong>
<DefaultExport />
</strong>
<br />
<Export1 />
<br />
<Export2 />
</>
);
}
??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark
One example in order to understand, where the usage of ZEROFILL
might be interesting:
In Germany, we have 5 digit zipcodes. However, those Codes may start with a Zero, so 80337
is a valid zipcode for munic, 01067
is a zipcode of Berlin.
As you see, any German citizen expects the zipcodes to be displayed as a 5 digit code, so 1067
looks strange.
In order to store those data, you could use a VARCHAR(5)
or INT(5) ZEROFILL
whereas the zerofilled integer has two big advantages:
1067
, you still get 01067
backMaybe this example helps understanding the use of ZEROFILL
.
My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface
From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.
create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode
How to spin up a zookeper environment within minutes on docker for windows, linux or mac:
One time set up:
docker network create dn
Run server in a terminal window:
docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper
Run client in a second terminal window:
docker run -it --rm --network dn zookeeper zkCli.sh -server zook
See also documentation of image on dockerhub
I wrote recently a simple function which removes excess white space from string without regular expression implode(' ', array_filter(explode(' ', $str)))
.
the following works for me,
mockMvc.perform(
MockMvcRequestBuilders.post("/api/test/url")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(createItemForm)))
.andExpect(status().isCreated());
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:
function AjaxFeed(){
return $.ajax({
url: 'http://somesite.com/somejsonfile.php',
data: {something: true},
dataType: 'jsonp',
/* Very important */
contentType: 'application/json',
});
}
function GetData() {
AjaxFeed()
/* Everything worked okay. Hooray */
.done(function(data){
return data;
})
/* Okay jQuery is stupid manually fix things */
.fail(function(jqXHR) {
/* Build HTML and update */
var data = jQuery.parseJSON(jqXHR.responseText);
return data;
});
}
I think your question is a bit more general than I originally thought. type()
with one argument returns the type
or class
of the object. So if you have a = 'abc'
and use type(a)
this returns str
because the variable a
is a string. If b = 10
, type(b)
returns int
.
See also python documentation on type().
If you want a comparison you could use: if type(v) == h5py.h5r.Reference
(to check if it is a h5py.h5r.Reference
instance).
But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)
but then also subclasses will evaluate to True
.
If you want to print the class use print v.__class__.__name__
.
More generally: You can compare if two instances have the same class by using type(v) is type(other_v)
or isinstance(v, other_v.__class__)
.
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO
XMLHttpRequest is a built-in object in web browsers.
It is not distributed with Node; you have to install it separately,
Install it with npm,
npm install xmlhttprequest
Now you can require
it in your code.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
That said, the http module is the built-in tool for making HTTP requests from Node.
Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.
In general terms the algorithm for calculating a leap year is as follows...
A year will be a leap year if it is divisible by 4 but not by 100. If a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400.
Thus years such as 1996, 1992, 1988 and so on are leap years because they are divisible by 4 but not by 100. For century years, the 400 rule is important. Thus, century years 1900, 1800 and 1700 while all still divisible by 4 are also exactly divisible by 100. As they are not further divisible by 400, they are not leap years
You can also use printf to pipe the input to your script.
var=val
printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh
function validateForm()
{
var a=document.forms["Form"]["firstname"].value;
var b=document.forms["Form"]["midname"].value;
var c=document.forms["Form"]["lastname"].value;
var d=document.forms["Form"]["tribe"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
{
alert("Please Fill All Required Field");
return false;
}
else{
$.ajax({
type: 'post',
url: 'add.php',
data: $('form').serialize(),
success: function () {
alert('Patient added');
document.getElementById("form").reset();
}
});
}
}
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
validateForm();
});
});
Simply:
$(function(){
$("#my-div").removeClass('hide');
});
Or if you somehow want the class to still be there:
$(function(){
$("#my-div").css('display', 'block !important');
});
You Can use below Simple Code:
function checkDelBoxes(pForm, boxName, parent)
{
for (i = 0; i < pForm.elements.length; i++)
if (pForm.elements[i].name == boxName)
pForm.elements[i].checked = parent;
}
Example for Using:
<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', true);return false;"> Select All
</a>
<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', false);return false;"> Unselect All
</a>
import javax.servlet.annotation.*;
(no one has written this, but need to import this as WebInitparam is not recognized by the other packages)
I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5. Happy coding!
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
Follow the below steps:
I had the same problem & in my case this is what I did
@Html.Partial("~/Views/Cabinets/_List.cshtml", (List<Shop>)ViewBag.cabinets)
and in Partial view
@foreach (Shop cabinet in Model)
{
//...
}
Make use of jquery toggle function which do the task for you
.toggle() - Display or hide the matched elements.
$('#myelement').click(function(){
$('#another-element').toggle('slow');
});
You can use gethostname followed by gethostbyname to get your local interface internal IP.
This returned IP may be different from your external IP though. To get your external IP you would have to communicate with an external server that will tell you what your external IP is. Because the external IP is not yours but it is your routers.
//Example: b1 == 192, b2 == 168, b3 == 0, b4 == 100
struct IPv4
{
unsigned char b1, b2, b3, b4;
};
bool getMyIP(IPv4 & myIP)
{
char szBuffer[1024];
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 0);
if(::WSAStartup(wVersionRequested, &wsaData) != 0)
return false;
#endif
if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
{
#ifdef WIN32
WSACleanup();
#endif
return false;
}
struct hostent *host = gethostbyname(szBuffer);
if(host == NULL)
{
#ifdef WIN32
WSACleanup();
#endif
return false;
}
//Obtain the computer's IP
myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;
#ifdef WIN32
WSACleanup();
#endif
return true;
}
You can also always just use 127.0.0.1 which represents the local machine always.
Subnet mask in Windows:
You can get the subnet mask (and gateway and other info) by querying subkeys of this registry entry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
Look for the registry value SubnetMask.
Other methods to get interface information in Windows:
You could also retrieve the information you're looking for by using: WSAIoctl with this option: SIO_GET_INTERFACE_LIST
bool_series=pd.notnull(dat["x"])
dat=dat[bool_series]
I spent many sad days trying to come up with a way to do this for C++17, which deprecated code_cvt
facets, and this is the best I was able to come up with by combining code from a few different sources:
setlocale( LC_ALL, "en_US.UTF-8" ); //Invoked in main()
std::string wideToMultiByte( std::wstring const & wideString )
{
std::string ret;
std::string buff( MB_CUR_MAX, '\0' );
for ( wchar_t const & wc : wideString )
{
int mbCharLen = std::wctomb( &buff[ 0 ], wc );
if ( mbCharLen < 1 ) { break; }
for ( int i = 0; i < mbCharLen; ++i )
{
ret += buff[ i ];
}
}
return ret;
}
std::wstring multiByteToWide( std::string const & multiByteString )
{
std::wstring ws( multiByteString.size(), L' ' );
ws.resize(
std::mbstowcs( &ws[ 0 ],
multiByteString.c_str(),
multiByteString.size() ) );
return ws;
}
I tested this code on Windows 10, and at least for my purposes, it seems to work fine. Please don't lynch me if this doesn't consider some crazy edge cases that you might need to handle, I'm sure someone with more experience can improve on this! :-)
Also, credit where it's due:
Just want to share another option:
# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)
# commit (or flush)
session.commit()
http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting
In this example, the following codes shall works fine:
obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()
There's a function to find a substring within a string (find
), and a function to replace a particular range in a string with another string (replace
), so you can combine those to get the effect you want:
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
std::string string("hello $name");
replace(string, "$name", "Somename");
In response to a comment, I think replaceAll
would probably look something like this:
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
Other options:
#multi line string
multiline_string = <<EOM
This is a very long string
that contains interpolation
like #{4 + 5} \n\n
EOM
puts multiline_string
#another option for multiline string
message = <<-EOF
asdfasdfsador #{2+2} this month.
asdfadsfasdfadsfad.
EOF
puts message
Here's a CSS-only alternative. I set this up for a search field to get an effect similar to Firefox (& a hundred other apps.)
HTML
<div class="col-md-4">
<input class="form-control" type="search" />
<span class="glyphicon glyphicon-search"></span>
</div>
CSS
.form-control {
padding-right: 30px;
}
.form-control + .glyphicon {
position: absolute;
right: 0;
padding: 8px 27px;
}
You could just do it manually.
NB: might be better to use a HashMap instead of an inner class for the opts.
/** convenient "-flag opt" combination */
private class Option {
String flag, opt;
public Option(String flag, String opt) { this.flag = flag; this.opt = opt; }
}
static public void main(String[] args) {
List<String> argsList = new ArrayList<String>();
List<Option> optsList = new ArrayList<Option>();
List<String> doubleOptsList = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
switch (args[i].charAt(0)) {
case '-':
if (args[i].length < 2)
throw new IllegalArgumentException("Not a valid argument: "+args[i]);
if (args[i].charAt(1) == '-') {
if (args[i].length < 3)
throw new IllegalArgumentException("Not a valid argument: "+args[i]);
// --opt
doubleOptsList.add(args[i].substring(2, args[i].length));
} else {
if (args.length-1 == i)
throw new IllegalArgumentException("Expected arg after: "+args[i]);
// -opt
optsList.add(new Option(args[i], args[i+1]));
i++;
}
break;
default:
// arg
argsList.add(args[i]);
break;
}
}
// etc
}
I have solve this problem by configuring the build path. Here are the steps that I followed: In eclipse.
Now you should be able to run
$filterQuery = $this->queryFactory->create(QueryInterface::TYPE_BOOL, ['must' => $queries,'should'=>$queriesGeo]);
In must
you need to add the query condition array which you want to work with AND
and in should
you need to add the query condition which you want to work with OR
.
You can check this: https://github.com/Smile-SA/elasticsuite/issues/972
Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.
Input
xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???") # Read Note about Python 2
NOTE: In Python 2, when calling the
toString(...)
code, assigningxml
withElementTree.Element("Person", Name="???")
will raise an error...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)
Output
ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="크리스" />'
# Python 3 (John): b'<Person Name="John" />'
# Python 2 (???): <Person Name="크리스" />
# Python 2 (John): <Person Name="John" />
ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" /> <-------- Python 3
# Python 3 (John): <Person Name="John" />
# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode
ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'
# Python 2 (???): <Person Name="???" /> <-------- Python 2
# Python 2 (John): <Person Name="John" />
ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="크리스" />
# Python 3 (John): <Person Name="John" />
# Python 2 (???): <Person Name="크리스" />
# Python 2 (John): <Person Name="John" />
I would expect that on most compilers and target platforms, there will be cases where "if" is faster and cases where ?: is faster. There will also be cases where one form is more or less compact than the other. Which cases favor one form or the other will vary between compilers and platforms. If you're writing performance-critical code on an embedded micro, look at what the compiler is generating in each case and see which is better. On a "mainstream" PC, because of caching issues, the only way to see which is better is to benchmark both forms in something resembling the real application.
I tried a couple of codes, but end up using something as simple as (in Python 3):
from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])
If your start_datetime and end_datetime columns are in datetime64[ns]
format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns]
format.
If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):
df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date
And then run:
df['difference_in_days'] = abs(df['end_date'] - df['start_date'])
In a nutshell:
If you need more details or would like to see difference on example, there is a blog post that comprehensively compare CMD and ENTRYPOINT with lots of examples - http://goinbigdata.com/docker-run-vs-cmd-vs-entrypoint/
Agree with Stphen C & helios. Better way to fetch random element from Enum is:
public enum Letter {
A,
B,
C,
//...
private static final Letter[] VALUES = values();
private static final int SIZE = VALUES.length;
private static final Random RANDOM = new Random();
public static Letter getRandomLetter() {
return VALUES[RANDOM.nextInt(SIZE)];
}
}
If someone not have reference in .NET . COM (tab) or not have office installed on machine where visual was installed can do :
Add references from:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office15
Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks.
An initial setting of a flex container is flex-shrink: 1
. That's why your columns are shrinking.
It doesn't matter what width you specify (it could be width: 10000px
), with flex-shrink
the specified width can be ignored and flex items are prevented from overflowing the container.
I'm trying to set up a flexbox with 3 columns where the left and right columns have a fixed width...
You will need to disable shrinking. Here are some options:
.left, .right {
width: 230px;
flex-shrink: 0;
}
OR
.left, .right {
flex-basis: 230px;
flex-shrink: 0;
}
OR, as recommended by the spec:
.left, .right {
flex: 0 0 230px; /* don't grow, don't shrink, stay fixed at 230px */
}
7.2. Components of Flexibility
Authors are encouraged to control flexibility using the
flex
shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.
More details here: What are the differences between flex-basis and width?
An additional thing I need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space.
Try this:
.center { flex: 1; }
This will allow the center column to consume available space, including the space of its siblings when they are removed.
You can't do this using sharer.php, but you can do something similar using the Dialog API. http://developers.facebook.com/docs/reference/dialogs/
http://www.facebook.com/dialog/feed?
app_id=123050457758183&
link=http://developers.facebook.com/docs/reference/dialogs/&
picture=http://fbrell.com/f8.jpg&
name=Facebook%20Dialogs&
caption=Reference%20Documentation&
description=Dialogs%20provide%20a%20simple,%20consistent%20interface%20for%20applications%20to%20interact%20with%20users.&
message=Facebook%20Dialogs%20are%20so%20easy!&
redirect_uri=http://www.example.com/response
The catch is you must create a dummy Facebook application just to have an app_id
. Note that your Facebook application doesn't have to do ANYTHING at all. Just be sure that it is properly configured, and you should be all set.
From Eclipsepedia on how to set a conditional breakpoint:
First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as
list.size()==0
. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.
Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.
<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<td width="350" >
Foo
</td>
<td width="80" >
Foo1
</td>
<td width="65" >
Foo2
</td>
</tr>
<tr>
<td>
Bar1
</td>
<td>
Bar2
</td>
<td>
Bar3
</td>
</tr>
<tr >
<td>
Bar1
</td>
<td>
Bar2
</td>
<td>
Bar3
</td>
</tr>
</table>
</body>
</html>
intrepidis' answer on this page using a background SVG in CSS has the advantage of scaling nicely to any size or aspect ratio, though the SVG uses <path>
s with a fill that doesn't scale so well.
I've just updated the SVG code to use <line>
instead of <path>
and added non-scaling-stroke
vector-effect to prevent the strokes scaling with the container:
<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'>
<line x1='0' y1='0' x2='100' y2='100' stroke='black' vector-effect='non-scaling-stroke'/>
<line x1='0' y1='100' x2='100' y2='0' stroke='black' vector-effect='non-scaling-stroke'/>
</svg>
Here's that dropped into the CSS from the original answer (with HTML made resizable):
.diag {_x000D_
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><line x1='0' y1='0' x2='100' y2='100' stroke='black' vector-effect='non-scaling-stroke'/><line x1='0' y1='100' x2='100' y2='0' stroke='black' vector-effect='non-scaling-stroke'/></svg>");_x000D_
background-repeat: no-repeat;_x000D_
background-position: center center;_x000D_
background-size: 100% 100%, auto;_x000D_
}
_x000D_
<div class="diag" style="width: 200px; height: 150px; border: 1px solid; resize: both; overflow: auto"></div>
_x000D_
You need to implement the UITableViewDelegate method
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
and return the desired view (e.g. a UILabel with the text you'd like in the footer) for the appropriate section of the table.
If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :
{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}
@JsonProperty("data")
private JsonNode data;
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
I will suggest move all templates to separate files, and don't do spagetti inside repeat
take a look here:
html:
<div ng-repeat = "data in comments">
<div ng-include src="buildUrl(data.type)"></div>
</div>
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.comments = [
{"_id":"52fb84fac6b93c152d8b4569",
"post_id":"52fb84fac6b93c152d8b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"hoot"},
{"_id":"52fb798cc6b93c74298b4568",
"post_id":"52fb798cc6b93c74298b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"story"},
{"_id":"52fb7977c6b93c5c2c8b456b",
"post_id":"52fb7977c6b93c5c2c8b456a",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"article"}
];
$scope.buildUrl = function(type) {
return type + '.html';
}
});
To clarify, the above example does work, my code in the example did not work for unrelated reasons.
If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.
The following will cause the div to show:
$scope.myvar = "Hello World";
or
$scope.myvar = true;
The following will hide the div:
$scope.myvar = null;
or
$scope.myvar = false;
an assignment returns the left-hand side of the assignment. so: yes. it is possible. however, you need to declare the variable outside:
int v = 1;
if((v = someMethod()) != 0) {
System.err.println(v);
}
This answer assumes you understand implementing the perfect algorithm for P1 and discusses how to achieve a win in conditions against ordinary human players, who will make some mistakes more commonly than others.
The game of course should end in a draw if both players play optimally. At a human level, P1 playing in a corner produces wins far more often. For whatever psychological reason, P2 is baited into thinking that playing in the center is not that important, which is unfortunate for them, since it's the only response that does not create a winning game for P1.
If P2 does correctly block in the center, P1 should play the opposite corner, because again, for whatever psychological reason, P2 will prefer the symmetry of playing a corner, which again produces a losing board for them.
For any move P1 may make for the starting move, there is a move P2 may make that will create a win for P1 if both players play optimally thereafter. In that sense P1 may play wherever. The edge moves are weakest in the sense that the largest fraction of possible responses to this move produce a draw, but there are still responses that will create a win for P1.
Empirically (more precisely, anecdotally) the best P1 starting moves seem to be first corner, second center, and last edge.
The next challenge you can add, in person or via a GUI, is not to display the board. A human can definitely remember all the state but the added challenge leads to a preference for symmetric boards, which take less effort to remember, leading to the mistake I outlined in the first branch.
I'm a lot of fun at parties, I know.
this is useful for me:
CREATE FUNCTION dbo.TRIM(@String VARCHAR(MAX))
RETURNS VARCHAR(MAX)
BEGIN
RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@String,CHAR(10),'[]'),CHAR(13),'[]'),char(9),'[]'),CHAR(32),'[]'),'][',''),'[]',CHAR(32))));
END
GO
.
You cannot do multiple inheritance in C# till 3.5. I dont know how it works out on 4.0 since I have not looked at it, but @tbischel has posted a link which I need to read.
C# allows you to do "multiple-implementations" via interfaces which is quite different to "multiple-inheritance"
So, you cannot do:
class A{}
class B{}
class C : A, B{}
But, you can do:
interface IA{}
interface IB{}
class C : IA, IB{}
HTH
In the shell, you can't execute more than one statement at a time:
>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement
You need to execute them one by one:
>>> x = 5
>>> y = 6
>>>
When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.
You need to put the files into an array in order to sort and find the last modified file.
$files = array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort
ksort($files);
// find the last modification
$reallyLastModified = end($files);
foreach($files as $file) {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
if ($file == $reallyLastModified) {
// do stuff for the real last modified file
}
echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}
Not tested, but that's how to do it.
We find ourselves in a universe which appears to progress along a dimension we call "time". We don't really understand what time is, but we have developed abstractions and vocabulary that let us reason and talk about it: "past", "present", "future", "before", "after".
The computer systems we build--more and more--have time as an important dimension. Certain things are set up to happen in the future. Then other things need to happen after those first things eventually occur. This is the basic notion called "asynchronicity". In our increasingly networked world, the most common case of asynchronicity is waiting for some remote system to respond to some request.
Consider an example. You call the milkman and order some milk. When it comes, you want to put it in your coffee. You can't put the milk in your coffee right now, because it is not here yet. You have to wait for it to come before putting it in your coffee. In other words, the following won't work:
var milk = order_milk();
put_in_coffee(milk);
Because JS has no way to know that it needs to wait for order_milk
to finish before it executes put_in_coffee
. In other words, it does not know that order_milk
is asynchronous--is something that is not going to result in milk until some future time. JS, and other declarative languages execute one statement after another without waiting.
The classic JS approach to this problem, taking advantage of the fact that JS supports functions as first-class objects which can be passed around, is to pass a function as a parameter to the asynchronous request, which it will then invoke when it has completed its task sometime in the future. That is the "callback" approach. It looks like this:
order_milk(put_in_coffee);
order_milk
kicks off, orders the milk, then, when and only when it arrives, it invokes put_in_coffee
.
The problem with this callback approach is that it pollutes the normal semantics of a function reporting its result with return
; instead, functions must not reports their results by calling a callback given as a parameter. Also, this approach can rapidly become unwieldy when dealing with longer sequences of events. For example, let's say that I want to wait for the milk to be put in the coffee, and then and only then perform a third step, namely drinking the coffee. I end up needing to write something like this:
order_milk(function(milk) { put_in_coffee(milk, drink_coffee); }
where I am passing to put_in_coffee
both the milk to put in it, and also the action (drink_coffee
) to execute once the milk has been put in. Such code becomes hard to write, and read, and debug.
In this case, we could rewrite the code in the question as:
var answer;
$.ajax('/foo.json') . done(function(response) {
callback(response.data);
});
function callback(data) {
console.log(data);
}
This was the motivation for the notion of a "promise", which is a particular type of value which represents a future or asynchronous outcome of some sort. It can represent something that already happened, or that is going to happen in the future, or might never happen at all. Promises have a single method, named then
, to which you pass an action to be executed when the outcome the promise represents has been realized.
In the case of our milk and coffee, we design order_milk
to return a promise for the milk arriving, then specify put_in_coffee
as a then
action, as follows:
order_milk() . then(put_in_coffee)
One advantage of this is that we can string these together to create sequences of future occurrences ("chaining"):
order_milk() . then(put_in_coffee) . then(drink_coffee)
Let's apply promises to your particular problem. We will wrap our request logic inside a function, which returns a promise:
function get_data() {
return $.ajax('/foo.json');
}
Actually, all we've done is added a return
to the call to $.ajax
. This works because jQuery's $.ajax
already returns a kind of promise-like thing. (In practice, without getting into details, we would prefer to wrap this call so as for return a real promise, or use some alternative to $.ajax
that does so.) Now, if we want to load the file and wait for it to finish and then do something, we can simply say
get_data() . then(do_something)
for instance,
get_data() .
then(function(data) { console.log(data); });
When using promises, we end up passing lots of functions into then
, so it's often helpful to use the more compact ES6-style arrow functions:
get_data() .
then(data => console.log(data));
async
keywordBut there's still something vaguely dissatisfying about having to write code one way if synchronous and a quite different way if asynchronous. For synchronous, we write
a();
b();
but if a
is asynchronous, with promises we have to write
a() . then(b);
Above, we said, "JS has no way to know that it needs to wait for the first call to finish before it executes the second". Wouldn't it be nice if there was some way to tell JS that? It turns out that there is--the await
keyword, used inside a special type of function called an "async" function. This feature is part of the upcoming version of ES but is already available in transpilers such as Babel given the right presets. This allows us to simply write
async function morning_routine() {
var milk = await order_milk();
var coffee = await put_in_coffee(milk);
await drink(coffee);
}
In your case, you would be able to write something like
async function foo() {
data = await get_data();
console.log(data);
}
your validation should be occur before your event suppose you are going to submit your form.
anyway if you want this on onchange, so here is code.
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match(/\S/))
{
alert("Field is blank");
return false;
}
else
{
return true;
}
}
There is the Math.pow(double a, double b)
method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b)
.
Have a look at Neon (4.6) M6 - New and Noteworthy, the milestone release contains some automatic scaling for images (e.g. for toolbar).
SWT provides resolution-based auto-scaling
SWT now automatically scales images on high-DPI monitors on Windows and Linux, similar to the Mac's Retina support on OS X. In the absence of high-resolution images, SWT will auto-scale the available images to ensure that SWT-based applications like Eclipse are scaled proportionately to the resolution of the monitor.
This feature can be disabled on Windows and GTK by setting this VM argument to false in eclipse.ini or on the command line after -vmargs:
-Dswt.enable.autoScale=false
Auto-scaling cannot be disabled on the Mac as it is provided by the OS.
Caveats: We're aware that some scaled images look bad at scale factors less than 200%. This will be improved in M7. Furthermore, we're working on support for high-DPI images in Platform UI, so that plug-in providers can add high-DPI icons without doing any code changes.
Or maybe this helps, in Eclipse Mars API for high resolution was added
New APIs have been added to provide support for rendering high-resolution images on high-DPI monitors. Two constructors have been added to the Image class. They accept image-provider callbacks that allow clients to supply resolution-dependent versions of images:
public interface ImageDataProvider { public ImageData getImageData (int zoom); } public interface ImageFileNameProvider { public String getImagePath (int zoom); }
Depending on the user's monitor configuration, SWT will request images with the corresponding zoom level. Here's an example that displays 3 original images, followed by variants whose resolution changes depending your monitor's resolution: Snippet367.java.
Note that this is just the first step to support high-resolution images in SWT and Eclipse-based applications. Work is underway to adopt the new APIs in the platform. Futhermore, more work in SWT is required to properly support drawing into high-resolution images via GC.
APIs for high-DPI monitor support
http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2FwhatsNew%2Fplatform_isv_whatsnew.html
Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.
It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.
I have the same issue, I tried all the above solutions, but none of them worked for me. Then I searched the keywords in flutter directory, and found the following code. So I tried to delete bin/cache/.upgrade_lock
, and it worked finally.
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
Adding my scenario. Just in case someone has similar problem and not able to identify ACTUAL issue.
I was using vue splitpanes.
Previously it required only "Splitpanes", in latest version, they made another "Pane" component (as children of splitpanes).
Now thing is, if you don't register "Pane" component in latest version of splitpanes, it was showing error for "Splitpanes". as below.
[Vue warn]: Unknown custom element: <splitpanes> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
I had the same problem while trying to commit my working copy. What I did was add the folder that Subversion reports as "path not found" to the ignore list. Commit (should succeed). Then add the same folder back to Subversion. Commit again.
still alloca use is discouraged, why?
I don't perceive such a consensus. Lots of strong pros; a few cons:
while
or for
loop) or in several scopes, the memory accumulates per iteration/scope and is not released until the function exits: this contrasts with normal variables defined in the scope of a control structure (e.g. for {int i = 0; i < 2; ++i) { X }
would accumulate alloca
-ed memory requested at X, but memory for a fixed-sized array would be recycled per iteration).inline
functions that call alloca
, but if you force them then the alloca
will happen in the callers' context (i.e. the stack won't be released until the caller returns)alloca
transitioned from a non-portable feature/hack to a Standardised extension, but some negative perception may persistmalloc
's explicit controlmalloc
encourages thinking about the deallocation - if that's managed through a wrapper function (e.g. WonderfulObject_DestructorFree(ptr)
), then the function provides a point for implementation clean up operations (like closing file descriptors, freeing internal pointers or doing some logging) without explicit changes to client code: sometimes it's a nice model to adopt consistently
WonderfulObject* p = WonderfulObject_AllocConstructor();
- that's possible when the "constructor" is a function returning malloc
-ed memory (as the memory remains allocated after the function returns the value to be stored in p
), but not if the "constructor" uses alloca
WonderfulObject_AllocConstructor
could achieve this, but "macros are evil" in that they can conflict with each other and non-macro code and create unintended substitutions and consequent difficult-to-diagnose problemsfree
operations can be detected by ValGrind, Purify etc. but missing "destructor" calls can't always be detected at all - one very tenuous benefit in terms of enforcement of intended usage; some alloca()
implementations (such as GCC's) use an inlined macro for alloca()
, so runtime substitution of a memory-usage diagnostic library isn't possible the way it is for malloc
/realloc
/free
(e.g. electric fence)On many systems alloca() cannot be used inside the list of arguments of a function call, because the stack space reserved by alloca() would appear on the stack in the middle of the space for the function arguments.
I know this question is tagged C, but as a C++ programmer I thought I'd use C++ to illustrate the potential utility of alloca
: the code below (and here at ideone) creates a vector tracking differently sized polymorphic types that are stack allocated (with lifetime tied to function return) rather than heap allocated.
#include <alloca.h>
#include <iostream>
#include <vector>
struct Base
{
virtual ~Base() { }
virtual int to_int() const = 0;
};
struct Integer : Base
{
Integer(int n) : n_(n) { }
int to_int() const { return n_; }
int n_;
};
struct Double : Base
{
Double(double n) : n_(n) { }
int to_int() const { return -n_; }
double n_;
};
inline Base* factory(double d) __attribute__((always_inline));
inline Base* factory(double d)
{
if ((double)(int)d != d)
return new (alloca(sizeof(Double))) Double(d);
else
return new (alloca(sizeof(Integer))) Integer(d);
}
int main()
{
std::vector<Base*> numbers;
numbers.push_back(factory(29.3));
numbers.push_back(factory(29));
numbers.push_back(factory(7.1));
numbers.push_back(factory(2));
numbers.push_back(factory(231.0));
for (std::vector<Base*>::const_iterator i = numbers.begin();
i != numbers.end(); ++i)
{
std::cout << *i << ' ' << (*i)->to_int() << '\n';
(*i)->~Base(); // optionally / else Undefined Behaviour iff the
// program depends on side effects of destructor
}
}
Here is a solution that doesn't use a loop and uses the Android API only:
InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
byte[] data = new byte[inputStreamObject.available()];
if(inputStreamObject.read(data) == data.length) {
JSONObject jsonObject = new JSONObject(new String(data));
}
You can provide one or multiple event types separated by a space.
So hover
equals mouseenter mouseleave
.
This is my sugession:
$("#foo").on("mouseenter mouseleave", function() {
// do some stuff
});
The tools can now be found ("Hardware IO tools") here: https://developer.apple.com/download/more/
Not sure what the author of that code wanted to achieve. Definining a function inside another function does NOT mean that the inner function is only visible inside the outer function. After calling x() the first time, the y() function will be in global scope as well.
It has a tricky situation: If you submit a post form, then Chrome will open a new tab to send the request. It's right until now, but if it triggers an event to download file(s), this tab will close immediately so that you cannot capture this request in the Dev Tool.
Solution: Before submitting the post form, you need to cut off your network, which makes the request cannot send successfully so that the tab will not be closed. And then you can capture the request message in the Chrome Devtool(Refreshing the new tab if necessary)
Initially it was to be a comma, however as the comma is often used as a decimal point it wouldnt be such good separator, hence others like the semicolon, mostly country dependant
http://en.wikipedia.org/wiki/Comma-separated_values#Lack_of_a_standard
This should work:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
The NIO classes make this pretty simple.
Yes. The sequence doesn't have the 54th item.
Making @sulai suggestion more generic :
@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
asyncTask.execute(params);
}
A .delete_at(3)
3
here being the position.
I used the page-checkout.php template to change the header for my cart page. I renamed it to page-cart.php in my /wp-content/themes/childtheme/woocommerce/. This gives you more control over the wrapping html, header and footer.
May be helpful for somebody. Mocked method must be of mocked class, created with mock(MyService.class)
Use extension for UIImageView to Load URL Images.
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func imageURLLoad(url: URL) {
DispatchQueue.global().async { [weak self] in
func setImage(image:UIImage?) {
DispatchQueue.main.async {
self?.image = image
}
}
let urlToString = url.absoluteString as NSString
if let cachedImage = imageCache.object(forKey: urlToString) {
setImage(image: cachedImage)
} else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
DispatchQueue.main.async {
imageCache.setObject(image, forKey: urlToString)
setImage(image: image)
}
}else {
setImage(image: nil)
}
}
}
}
You are probably storing the value 0xc0 in a char
variable, what is probably a signed type, and your value is negative (most significant bit set). Then, when printing, it is converted to int
, and to keep the semantical equivalence, the compiler pads the extra bytes with 0xff, so the negative int
will have the same numerical value of your negative char
. To fix this, just cast to unsigned char
when printing:
printf("%x", (unsigned char)variable);
import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:
$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session
or
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
You can customize the location of your Toast by using:
setGravity(int gravity, int xOffset, int yOffset)
This allows you to be very specific about where you want the location of your Toast to be.
One of the most useful things about the xOffset and yOffset parameters is that you can use them to place the Toast relative to a certain View.
For example, if you want to make a custom Toast that appears on top of a Button, you could create a function like this:
// v is the Button view that you want the Toast to appear above
// and messageId is the id of your string resource for the message
private void displayToastAboveButton(View v, int messageId)
{
int xOffset = 0;
int yOffset = 0;
Rect gvr = new Rect();
View parent = (View) v.getParent();
int parentHeight = parent.getHeight();
if (v.getGlobalVisibleRect(gvr))
{
View root = v.getRootView();
int halfWidth = root.getRight() / 2;
int halfHeight = root.getBottom() / 2;
int parentCenterX = ((gvr.right - gvr.left) / 2) + gvr.left;
int parentCenterY = ((gvr.bottom - gvr.top) / 2) + gvr.top;
if (parentCenterY <= halfHeight)
{
yOffset = -(halfHeight - parentCenterY) - parentHeight;
}
else
{
yOffset = (parentCenterY - halfHeight) - parentHeight;
}
if (parentCenterX < halfWidth)
{
xOffset = -(halfWidth - parentCenterX);
}
if (parentCenterX >= halfWidth)
{
xOffset = parentCenterX - halfWidth;
}
}
Toast toast = Toast.makeText(getActivity(), messageId, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, xOffset, yOffset);
toast.show();
}
I think it works the other way
<#if object.attribute??>
Do whatever you want....
</#if>
If object.attribute
is NOT NULL, then the content will be printed.
In the Google Maps API v2 Demo there is a MarkerDemoActivity
class in which you can see how a custom Image is set to a GoogleMap.
// Uses a custom icon.
mSydney = mMap.addMarker(new MarkerOptions()
.position(SYDNEY)
.title("Sydney")
.snippet("Population: 4,627,300")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
As this just replaces the marker with an image you might want to use a Canvas
to draw more complex and fancier stuff:
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(80, 80, conf);
Canvas canvas1 = new Canvas(bmp);
// paint defines the text color, stroke width and size
Paint color = new Paint();
color.setTextSize(35);
color.setColor(Color.BLACK);
// modify canvas
canvas1.drawBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.user_picture_image), 0,0, color);
canvas1.drawText("User Name!", 30, 40, color);
// add marker to Map
mMap.addMarker(new MarkerOptions()
.position(USER_POSITION)
.icon(BitmapDescriptorFactory.fromBitmap(bmp))
// Specifies the anchor to be at a particular point in the marker image.
.anchor(0.5f, 1));
This draws the Canvas canvas1
onto the GoogleMap mMap
. The code should (mostly) speak for itself, there are many tutorials out there how to draw a Canvas
. You can start by looking at the Canvas and Drawables from the Android Developer page.
Now you also want to download a picture from an URL.
URL url = new URL(user_image_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
You must download the image from an background thread (you could use AsyncTask or Volley or RxJava for that).
After that you can replace the BitmapFactory.decodeResource(getResources(), R.drawable.user_picture_image)
with your downloaded image bmImg
.
I had port 3306 in Docker container but in Dockerfile it was 33060. I edited the port in Docker container to 33060
Must have been added to the Dockerfile
ENV MYSQL_ROOT_HOST 172.17.0.1
I ran:
lsbom -f -l -s -pf /var/db/receipts/org.nodejs.pkg.bom \
| while read i; do
sudo rm /usr/local/${i}
done
sudo rm -rf /usr/local/lib/node \
/usr/local/lib/node_modules \
/var/db/receipts/org.nodejs.*
Coded into gist 2697848
Update
It seems the receipts .bom
file name may have changed so you may need to replace org.nodejs.pkg.bom
with org.nodejs.node.pkg.bom
in the above. The gist has been updated accordingly.
In my case problem arose due to gradle version upgradation from 6.2 all to 6.6 all in gradle wrapper. So i wiped out data of avd and restarted it and then deleted .gradle folder in android/.gradle and then run yarn start --reset-cache and yarn android. Then it worked for me
I would extend this question with a NDIS driver example on getting time. As one knows, KeQuerySystemTime (mimicked under NdisGetCurrentSystemTime) has a low resolution above milliseconds, and there are some processes like network packets or other IRPs which may need a better timestamp;
The example is just as simple:
LONG_INTEGER data, frequency;
LONGLONG diff;
data = KeQueryPerformanceCounter((LARGE_INTEGER *)&frequency)
diff = data.QuadPart / (Frequency.QuadPart/$divisor)
where divisor is 10^3, or 10^6 depending on required resolution.
Try to use different id and name parameters, currently you have same here. Please visit the link below for the same, this might be help you :
public static String genXmlTag(String tagName, String innerXml, String properties )
{
return String.format("<%s %s>%s</%s>", tagName, properties, innerXml, tagName);
}
public static String genXmlTag(String tagName, String innerXml )
{
return genXmlTag(tagName, innerXml, "");
}
public static <T> String serializeXML(List<T> list)
{
String result = "";
if (list.size() > 0)
{
T tmp = list.get(0);
String clsName = tmp.getClass().getName();
String[] splitCls = clsName.split("\\.");
clsName = splitCls[splitCls.length - 1];
Field[] fields = tmp.getClass().getFields();
for (T t : list)
{
String row = "";
try {
for (Field f : fields)
{
Object value = f.get(t);
row += genXmlTag(f.getName(), value == null ? "" : value.toString());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
row = genXmlTag(clsName, row);
result += row;
}
}
result = genXmlTag("root", result);
return result;
}
If you just deleted the branch, you will see something like this in your terminal:
Deleted branch branch_name(was e562d13)
- where e562d13 is a unique ID (a.k.a. the "SHA" or "hash"), with this you can restore the deleted branch.
To restore the branch, use:
git checkout -b <branch_name> <sha>
for example:
git checkout -b branch_name e562d13
Not sure about open-source, but I've heard good things about http://www.advenio.com/sqlgrinder/ (not tried it, I prefer to write Python scripts to try things out rather than use GUIs;-).
Your methods are missing the static
keyword. Change
function getInstanceByName($name=''){
to
public static function getInstanceByName($name=''){
if you want to call them statically.
Note that static methods (and Singletons) are death to testability.
Also note that you are doing way too much work in the constructor, especially all that querying shouldn't be in there. All your constructor is supposed to do is set the object into a valid state. If you have to have data from outside the class to do that consider injecting it instead of pulling it. Also note that constructors cannot return anything. They will always return void so all these return false
statements do nothing but end the construction.
Try initializing the ks
variable inside your submit function.
(function($){
$(document).ready(function(){
$('#data').submit(function(e){
var ks = $('#keywords').val().split("\n");
e.preventDefault();
alert(ks[0]);
$.each(ks, function(k){
alert(k);
});
});
});
})(jQuery);
This solve my problème:
$description = strip_tags($value['Description']);
$description=preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $description);
$description= preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $description);
$description=str_replace(' & ', ' & ', html_entity_decode((htmlspecialchars_decode($description))));
While you are developing your script, try disabling the Chrome cache.
When you reload the page, the JavaScript should now get refreshed.
You can also access it on the network tab:
$('image').animate({ 'zoom': 1}, 400);
You can write to multiple sheets with the xlsx
package. You just need to use a different sheetName
for each data frame and you need to add append=TRUE
:
library(xlsx)
write.xlsx(dataframe1, file="filename.xlsx", sheetName="sheet1", row.names=FALSE)
write.xlsx(dataframe2, file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)
Another option, one that gives you more control over formatting and where the data frame is placed, is to do everything within R/xlsx code and then save the workbook at the end. For example:
wb = createWorkbook()
sheet = createSheet(wb, "Sheet 1")
addDataFrame(dataframe1, sheet=sheet, startColumn=1, row.names=FALSE)
addDataFrame(dataframe2, sheet=sheet, startColumn=10, row.names=FALSE)
sheet = createSheet(wb, "Sheet 2")
addDataFrame(dataframe3, sheet=sheet, startColumn=1, row.names=FALSE)
saveWorkbook(wb, "My_File.xlsx")
In case you might find it useful, here are some interesting helper functions that make it easier to add formatting, metadata, and other features to spreadsheets using xlsx
:
http://www.sthda.com/english/wiki/r2excel-read-write-and-format-easily-excel-files-using-r-software
Just assign the int
to a char
variable.
int i = 65;
char c = i;
printf("%c", c); //prints A
this might be a solution, i have done something similar but this one does not seem to work for example if the necessary function requires administrator privileges it should ask you to restart it as admin.
@echo off
mkdir C:\Users\cmdfolder
if echo=="Access is denied." (goto :1A) else (goto :A4)
:A1
cls
color 0d
echo restart this program as administator
:A4
pause
when we use the
php artisan serve
it will start with the default HTTP-server port mostly it will be 8000
when we want to run the more site in the localhost we have to change the port. Just add the --port argument:
php artisan serve --port=8081
From what I understand of your request, this should work:
<script>
// var status = document.getElementsByID("uniqueID"); // this works too
var status = document.getElementsByName("status")[0];
var jsonArr = [];
for (var i = 0; i < status.options.length; i++) {
jsonArr.push({
id: status.options[i].text,
optionValue: status.options[i].value
});
}
</script>
I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.
Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.
Pragma Directives It includes "#pragma comment" in the table you'll see.
HTH
I suspect GCC, for example, has their own set of #pragma's.
The old-school way:
GLfloat coordinates[8];
...
GLfloat *p = coordinates;
*p++ = 1.0f; *p++ = 0.0f; *p++ = 1.0f; *p++ = 1.0f;
*p++ = 0.0f; *p++ = 1.0f; *p++ = 0.0f; *p++ = 0.0f;
return coordinates;
Here, I would like to add that if you are reading window handle that is HWND of a process then that process should not be running in a debugging otherwise it will not find the window handle by using FindWindowEx.
Are null and an empty string equivalent? If they are, I would include logic in my application (or maybe a trigger if the app is "out-of-the-box"?) to force the field to be either null or '', but not the other. If you went with '', then you could set the column to NOT NULL as well. Just a data-cleanliness thing.
I know I'm late on this one, but I'll add this comment anyway, as others may well come here in the future with similar questions.
Beware of tweaking column sizes dependent on locale. For a start, it sets you up for a maintenance nightmare, leaving aside the fact that people migrate, and take their names with them.
For example, Spanish people with those extra surnames can move to and live in an English-speaking country, and can reasonably expect their full name to be used. Russians have patronymics in addition to their surnames, some African names can be considerably longer than most European names.
Go with making each column as wide as you can reasonably do, taking into account the potential row count. I use 40 characters each for first name, other given names and surname and have never found any problems.
error:: bash: vi: command not found
run the below command by logging as root user to the container--
docker exec --user="root" -it (container ID) /bin/bash
apt-get update
apt-get install vim
If your input is already sorted, then there may be a simpler way to do it:
from operator import itemgetter
from itertools import groupby
unique_list = list(map(itemgetter(0), groupby(yourList)))
Programmatically, you could use:
textView.setTextAppearance(android.R.style.TextAppearance_Large);
View single commit:
https://github.com/<user>/<project>/commit/<hash>
View log:
https://github.com/<user>/<project>/commits/<hash>
View full repo:
https://github.com/<user>/<project>/tree/<hash>
<hash>
can be any length as long as it is unique.
I know you wanted "free", but I'd seriously consider getting the data from csidata.com for about $300/year, if I were you.
It's what yahoo uses to supply their data.
It comes with a decent API, and the data is (as far as I can tell) very clean.
You get 10 years of history when you subscribe, and then nightly updates afterward.
They also take care of all sorts of nasty things like splits and dividends for you. If you haven't yet discovered the joy that is data-cleaning, you won't realize how much you need this, until the first time your ATS (Automated Trading System) thinks some stock is really really cheap, only because it split 2:1 and you didn't notice.
Run puttygen from Command Prompt
a. Click “Load” button to “Load an existing private key file”
b. Change the file filter to “All Files (.)
c. Select the YourPEMFILE.pem
d. Click Open
e. Puttygen shows a notice saying that it Successfully imported foreign key. Click OK.
f. Click “Save private key” button
g. When asked if you are sure that you want to save without a passphrase entered, answer “Yes”.
h. Enter the file name YourPEMFILE.ppk
i. Click “Save”
A Protocol?
I found this, it appears to be a local setting for a computer...
Looks for the function glob():
<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
echo $jpg, "\n";
}
?>
JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP
is an array and contains elements with a value
property.
If using 4.5+ Framework I would use ReadOnlyDictionary (also ReadOnly Collection for lists) to do readonly mappings/constants. It's implemented in the following way.
static class SomeClass
{
static readonly ReadOnlyDictionary<string,int> SOME_MAPPING
= new ReadOnlyDictionary<string,int>(
new Dictionary<string,int>()
{
{ "One", 1 },
{ "Two", 2 }
}
)
}
If you want to present the values in a map in sorted order, then copy the values from the map to vector and sort the vector.
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
Without jQuery : DEMO
<div id="parentDiv" onclick="alert('parentDiv');">
<div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
AAA
</div>
</div>
It is possible by managing a flag in SharedPreferences or in Application Activity.
On starting of app (on Splash Screen) set the flag = false; On Logout Click event just set the flag true and in OnResume() of every activity, check if flag is true then call finish().
It works like a charm :)
Something a little shorter in syntax but taking what the others have already stated.
int num1, num2 = num1 = 1;
It's 2012, the post-PC era is here, and we still have to struggle with something as basic as this. This ought to be very simple.
Until such time as that dream is fulfilled, here's the best way to do this, cross-browser: use a combination of the input
and onpropertychange
events, like so:
var area = container.querySelector('textarea');
if (area.addEventListener) {
area.addEventListener('input', function() {
// event handling code for sane browsers
}, false);
} else if (area.attachEvent) {
area.attachEvent('onpropertychange', function() {
// IE-specific event handling code
});
}
The input
event takes care of IE9+, FF, Chrome, Opera and Safari, and onpropertychange
takes care of IE8 (it also works with IE6 and 7, but there are some bugs).
The advantage of using input
and onpropertychange
is that they don't fire unnecessarily (like when pressing the Ctrl
or Shift
keys); so if you wish to run a relatively expensive operation when the textarea contents change, this is the way to go.
Now IE, as always, does a half-assed job of supporting this: neither input
nor onpropertychange
fires in IE when characters are deleted from the textarea. So if you need to handle deletion of characters in IE, use keypress
(as opposed to using keyup
/ keydown
, because they fire only once even if the user presses and holds a key down).
Source: http://www.alistapart.com/articles/expanding-text-areas-made-elegant/
EDIT: It seems even the above solution is not perfect, as rightly pointed out in the comments: the presence of the addEventListener
property on the textarea does not imply you're working with a sane browser; similarly the presence of the attachEvent
property does not imply IE. If you want your code to be really air-tight, you should consider changing that. See Tim Down's comment for pointers.
Try this:
par(adj = 0)
plot(1, 1, main = "Title")
or equivalent:
plot(1, 1, main = "Title", adj = 0)
adj = 0
produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1]
is allowed.
However, the issue is that this will also change the position of the label of the x-axis and y-axis.
I had the same problem. This worked for me:
SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1
I've refined this using an extension method on the ListViewItemsCollection. In my opinion it makes the calling code more concise and also promotes more general reuse.
internal static class ListViewItemCollectionExtender
{
internal static void AddWithTextAndSubItems(
this ListView.ListViewItemCollection col,
string text, params string[] subItems)
{
var item = new ListViewItem(text);
foreach (var subItem in subItems)
{
item.SubItems.Add(subItem);
}
col.Add(item);
}
}
Calling the AddWithTextAndSubItems looks like this:
// can have many sub items as it's string array
myListViewControl.Items.AddWithTextAndSubItems("Text", "Sub Item 1", "Sub Item 2");
Hope this helps!
If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object
Ex:
import each from 'foreach-object';
const object = {
firstName: 'Arosha',
lastName: 'Sum',
country: 'Australia'
};
each(object, (value, key, object) => {
console.log(key + ': ' + value);
});
// Console log output will be:
// firstName: Arosha
// lastName: Sum
// country: Australia
For whatever reason, these answers didn't quite work for me. This is what worked for me instead:
In Vim, the :version
command gives you the paths of system and user vimrc and gvimrc files (among other things), and the output looks something like this:
system vimrc file: "$VIM/vimrc"
user vimrc file: "$HOME/.vimrc"
user exrc file: "$HOME/.exrc"
system gvimrc file: "$VIM/gvimrc"
user gvimrc file: "$HOME/.gvimrc"
The one you want is user vimrc file: "$HOME/.vimrc"
So to edit the file: vim $HOME/.vimrc
Source: Open vimrc file
As such, it is desirable to split the dataset into train and test sets in a way that preserves the same proportions of examples in each class as observed in the original dataset.
This is called a stratified train-test split.
We can achieve this by setting the “stratify” argument to the y component of the original dataset. This will be used by the train_test_split() function to ensure that both the train and test sets have the proportion of examples in each class that is present in the provided “y” array.
You want to look into 'Splash' Screens.
Display another 'Splash' form and wait until the processing is done.
Here is an example on how to do it.
Way late, but I just ran into a similar issue.
My solution was pseudo elements - no additional markup, and you get to draw the border without affecting the width.
Position the pseudo element absolutely (with the main positioned relatively) and whammo.
See below, JSFiddle here.
.hello {
position: relative;
/* Styling not important */
background: black;
color: white;
padding: 20px;
width: 200px;
height: 200px;
}
.hello::before {
content: "";
position: absolute;
display: block;
top: 0;
left: -5px;
right: -5px;
bottom: 0;
border-left: 5px solid red;
border-right: 5px solid red;
z-index: -1;
}
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
If you need an empty folder you can loop until you get an empty folder
QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
while(QDir(folder).exists())
{
folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
}
QDir().mkdir(folder);
This case you will get a folder name with a number .
You are using linq's First() method, which as per the documentation throws an InvalidOperationException if you are calling it on an empty collection.
If you expect the result of your query to be empty sometimes, you likely want to use FirstOrDefault(), which will return null if the collection is empty, instead of throwing an exception.
$.each()
works for objects and arrays both:
var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
$.each(data.programs, function (i) {
$.each(data.programs[i], function (key, val) {
alert(key + val);
});
});
...and since you will get the current array element as second argument:
$.each(data.programs, function (i, currProgram) {
$.each(currProgram, function (key, val) {
alert(key + val);
});
});
Checkout this, This is from PHP MANUAL, This may help you.
If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:
<?php
require_once('db.php');
$stmt = $db->query($sql);
while ($row = $stmt->fetchRow()) {
set_time_limit(0);
// your code here
}
?>
For pipeline:
pipeline {
environment {
BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
}
}
The intent of the standalone=yes
declaration is to guarantee that the information inside the document can be faithfully retrieved based only on the internal DTD, i.e. the document can "stand alone" with no external references. Validating a standalone document ensures that non-validating processors will have all of the information available to correctly parse the document.
The standalone declaration serves no purpose if a document has no external DTD, and the internal DTD has no parameter entity references, as these documents are already implicitly standalone.
The following are the actual effects of using standalone=yes
.
Forces processors to throw an error when parsing documents with an external DTD or parameter entity references, if the document contains references to entities not declared in the internal DTD (with the exception of replacement text of parameter entities as non-validating processors are not required to parse this); amp
, lt
, gt
, apos
, and quot
are the only exceptions
When parsing a document not declared as standalone, a non-validating processor is free to stop parsing the internal DTD as soon as it encounters a parameter entity reference. Declaring a document as standalone forces non-validating processors to parse markup declarations in the internal DTD even after they ignore one or more parameter entity references.
Forces validating processors to throw an error if any of the following are found in the document, and their respective declarations are in the external DTD or in parameter entity replacement text:
amp
, lt
, gt
, apos
, and quot
)A non-validating processor might consider retrieving the external DTD and expanding all parameter entity references for documents that are not standalone, even though it is under no obligation to do so, i.e. setting standalone=yes
could theoretically improve performance for non-validating processors (spoiler alert: it probably won't make a difference).
The other answers here are either incomplete or incorrect, the main misconception is that
The standalone declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.
standalone="yes" means that the XML processor must use the DTD for validation only.
Quite the opposite, declaring a document as standalone will actually force a non-validating processor to parse internal declarations it must normally ignore (i.e. those after an ignored parameter entity reference). Non-validating processors must still use the info in the internal DTD to provide default attribute values and normalize tokenized attributes, as this is independent of validation.
Seems in version 4.0.0 of Facebook so many things has changed. This is my code which is working fine. Hope it helps you.
/**
* Facebook does not support sharing content without using their SDK however
* it is possible to share URL
*
* @param content
* @param url
*/
private void shareOnFacebook(String content, String url)
{
try
{
// TODO: This part does not work properly based on my test
Intent fbIntent = new Intent(Intent.ACTION_SEND);
fbIntent.setType("text/plain");
fbIntent.putExtra(Intent.EXTRA_TEXT, content);
fbIntent.putExtra(Intent.EXTRA_STREAM, url);
fbIntent.addCategory(Intent.CATEGORY_LAUNCHER);
fbIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
fbIntent.setComponent(new ComponentName("com.facebook.katana",
"com.facebook.composer.shareintent.ImplicitShareIntentHandler"));
startActivity(fbIntent);
return;
}
catch (Exception e)
{
// User doesn't have Facebook app installed. Try sharing through browser.
}
// If we failed (not native FB app installed), try share through SEND
String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + url;
SupportUtils.doShowUri(this.getActivity(), sharerUrl);
}
Pickle is probably the best option, but in case anyone wonders how to save and load a dictionary to a file using NumPy:
import numpy as np
# Save
dictionary = {'hello':'world'}
np.save('my_file.npy', dictionary)
# Load
read_dictionary = np.load('my_file.npy',allow_pickle='TRUE').item()
print(read_dictionary['hello']) # displays "world"
FYI: NPY file viewer
um responsive is simple
display:table-cell
max-width:700px
do {display:block; width:100%; clear:both}
and that's it no absolute divs ever; divs needs to be 100% then max-width: - desired width -
for inner framming. A true responsive sites has less than 9 lines of css anything passed that you are in a world of shit and over complicated things.
PS : reset.css
style sheets are what makes css blinds there was a logical reason why they gave default styles in the first place.
Try this:
location / {
root /path/to/root;
expires 30d;
access_log off;
}
location ~* ^.*\.php$ {
if (!-f $request_filename) {
return 404;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php
should be forwared to Apache if only a corresponding .php
file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.
I had a similar problem. I had a char*
buffer with the .so name in it.
I could not convert the char*
variable to LPCTSTR
. Here's how I got around it...
char *fNam;
...
LPCSTR nam = fNam;
dll = LoadLibraryA(nam);
See my comment in @gsk3 answer. A simple example:
> m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
> d <- as.data.frame(m)
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 3 NA 3 7 6 6 10 6 5
2 9 8 9 5 10 NA 2 1 7 2
3 1 1 6 3 6 NA 1 4 1 6
4 NA 4 NA 7 10 2 NA 4 1 8
5 1 2 4 NA 2 6 2 6 7 4
6 NA 3 NA NA 10 2 1 10 8 4
7 4 4 9 10 9 8 9 4 10 NA
8 5 8 3 2 1 4 5 9 4 7
9 3 9 10 1 9 9 10 5 3 3
10 4 2 2 5 NA 9 7 2 5 5
> d[is.na(d)] <- 0
> d
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 3 0 3 7 6 6 10 6 5
2 9 8 9 5 10 0 2 1 7 2
3 1 1 6 3 6 0 1 4 1 6
4 0 4 0 7 10 2 0 4 1 8
5 1 2 4 0 2 6 2 6 7 4
6 0 3 0 0 10 2 1 10 8 4
7 4 4 9 10 9 8 9 4 10 0
8 5 8 3 2 1 4 5 9 4 7
9 3 9 10 1 9 9 10 5 3 3
10 4 2 2 5 0 9 7 2 5 5
There's no need to apply apply
. =)
EDIT
You should also take a look at norm
package. It has a lot of nice features for missing data analysis. =)
You can generate a random number with the rand
method. The argument passed to the rand
method should be an integer
or a range
, and returns a corresponding random number within the range:
rand(9) # this generates a number between 0 to 8
rand(0 .. 9) # this generates a number between 0 to 9
rand(1 .. 50) # this generates a number between 1 to 50
#rand(m .. n) # m is the start of the number range, n is the end of number range
There are 3 ways to check for "not null". My recommendation is to use the Strict Not Version.
if (val !== null) { ... }
The Strict Not Version uses the "Strict Equality Comparison Algorithm" http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6. The !==
has faster performance, than the !=
operator because the Strict Equality Comparison Algorithm doesn't typecast values.
if (val != 'null') { ... }
The Non-strict version uses the "Abstract Equality Comparison Algorithm" http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3. The !=
has slower performance, than the !==
operator because the Abstract Equality Comparison Algorithm typecasts values.
if (!!val) { ... }
The Double Not Version !!
has faster performance, than both the Strict Not Version !==
and the Non-Strict Not Version !=
(https://jsperf.com/tfm-not-null/6). However, it will typecast "Falsey" values like undefined
and NaN
into False (http://www.ecma-international.org/ecma-262/5.1/#sec-9.2) which may lead to unexpected results, and it has worse readability because null
isn't explicitly stated.
run
gradle clean
then try
gradle build
it worked for me
File -> Export -> Web -> WAR file
OR in Kepler follow as shown below :
Use the remove/erase idiom:
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
What happens is that remove
compacts the elements that differ from the value to be removed (number_in
) in the beginning of the vector
and returns the iterator to the first element after that range. Then erase
removes these elements (whose value is unspecified).
The 502 error appears because nginx cannot hand off to php5-cgi. You can try reconfiguring php5-cgi to use unix sockets as opposed to tcp .. then adjust the server config to point to the socket instead of the tcp ...
ps auxww | grep php5-cgi #-- is the process running?
netstat -an | grep 9000 # is the port open?
for Lat,Long in zip(Latitudes, Longitudes):
If you want to update / add single style in DOM Element style attribute you can use this function:
function setCssTextStyle(el, style, value) {
var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
idx;
if (result) {
idx = result.index + result[0].indexOf(result[1]);
el.style.cssText = el.style.cssText.substring(0, idx) +
style + ": " + value + ";" +
el.style.cssText.substring(idx + result[1].length);
} else {
el.style.cssText += " " + style + ": " + value + ";";
}
}
style.cssText is supported for all major browsers.
Use case example:
var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");
Button 1 Button 2 Button 3
var reply_click = function() {
alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
No real need for the JSON.NET package. You could use JavaScriptSerializer
. The Serialize
method will turn a managed type instance into a JSON string.
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);
well when i had these problem i faced 2 code errors
{!! Form::model(['method' => 'POST','route' => ['message.store']]) !!}
i corrected it by doing this
{!! Form::open(['method' => 'POST','route' => 'message.store']) !!}
so just to expatiate i changed the form model
to open
and also the route where wrongly placed in square braces.
date +%H:%M
Would be easier, I think :). If you really wanted to chop off the seconds, you could have done
date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'
The Problem is with your code formatting,
inorder to use strtotime()
You should replace '06/Oct/2011:19:00:02'
with 06/10/2011 19:00:02
and date('d/M/Y:H:i:s', $date);
with date('d/M/Y H:i:s', $date);
. Note the spaces in between.
So the final code looks like this
$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);
Earlier...
var labels = document.getElementsByTagName("LABEL"),
lookup = {},
i, label;
for (i = 0; i < labels.length; i++) {
label = labels[i];
if (document.getElementById(label.htmlFor)) {
lookup[label.htmlFor] = label;
}
}
Later...
var myLabel = lookup[myInput.id];
Snarky comment: Yes, you can also do it with JQuery. :-)
There is a simple way:
Android:
String macAddress =
android.provider.Settings.Secure.getString(this.getApplicationContext().getContentResolver(), "android_id");
Xamarin:
Settings.Secure.GetString(this.ContentResolver, "android_id");
Take a look at the INFORMATION_SCHEMA
.TABLES
table. It contains metadata about all your tables.
Example:
SELECT * FROM `INFORMATION_SCHEMA`.`TABLES`
WHERE TABLE_NAME LIKE 'table1'
The advantage of this over other methods is that you can easily use queries like the one above as subqueries in your other queries.
After testing most of the switches this worked for me:
xcopy C:\folder1 C:\folder2\folder1 /t /e /i /y
This will copy the folder folder1
into the folder folder2
. So the directory tree would look like:
C:
Folder1
Folder2
Folder1
I know this is an old thread, but thought I may add on a little extra. In my case I was wanting to pass on the text, val and some other data attr. In this case its better to store the whole option as a prev value rather than just the val.
Example code below:
var $sel = $('your select');
$sel.data("prevSel", $sel.clone());
$sel.on('change', function () {
//grab previous select
var prevSel = $(this).data("prevSel");
//do what you want with the previous select
var prevVal = prevSel.val();
var prevText = prevSel.text();
alert("option value - " + prevVal + " option text - " + prevText)
//reset prev val
$(this).data("prevSel", $(this).clone());
});
EDIT:
I forgot to add .clone() onto the element. in not doing so when you try to pull back the values you end up pulling in the new copy of the select rather than the previous. Using the clone() method stores a copy of the select instead of an instance of it.
The GOPATH should not point to the Go installation, but rather to your workspace (see https://golang.org/doc/code.html#GOPATH). Whenever you install some package with go get or go install, it will land within the GOPATH. That is why it warns you, that you most definitely do not want random packages from the internet to be dumped into your official installation.
As for VS2017
, I found it under C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428\bin\Hostx64\x64
var height = document.body.clientHeight;
var width = document.body.clientWidth;
Check: this article for better explanation.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
How to Use Sockets in JavaScript/HTML?
There is no facility to use general-purpose sockets in JS or HTML. It would be a security disaster, for one.
There is WebSocket in HTML5. The client side is fairly trivial:
socket= new WebSocket('ws://www.example.com:8000/somesocket');
socket.onopen= function() {
socket.send('hello');
};
socket.onmessage= function(s) {
alert('got reply '+s);
};
You will need a specialised socket application on the server-side to take the connections and do something with them; it is not something you would normally be doing from a web server's scripting interface. However it is a relatively simple protocol; my noddy Python SocketServer-based endpoint was only a couple of pages of code.
In any case, it doesn't really exist, yet. Neither the JavaScript-side spec nor the network transport spec are nailed down, and no browsers support it.
You can, however, use Flash where available to provide your script with a fallback until WebSocket is widely available. Gimite's web-socket-js is one free example of such. However you are subject to the same limitations as Flash Sockets then, namely that your server has to be able to spit out a cross-domain policy on request to the socket port, and you will often have difficulties with proxies/firewalls. (Flash sockets are made directly; for someone without direct public IP access who can only get out of the network through an HTTP proxy, they won't work.)
Unless you really need low-latency two-way communication, you are better off sticking with XMLHttpRequest
for now.
The error may have occurred if your table doesn't have a primary key, in this case the table is "read only", and the db.SaveChanges ()
command will always error.
my_var: the variable declared
VAR: the variable, whose value is to be checked
param_1, param_2: values of the variable VAR
value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var
my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"
Somewhere in your initialisation put this code.
Array.prototype.contains = function contains(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] === obj) {
return true;
}
}
return false;
};
Then, you can use it this way:
<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>
Found here:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
if (!$(this).hasClass("test")) {
Using Advanced Search on Github seemed the easiest with a combination of other answers. It's basically a search string builder. https://github.com/search/advanced
For example I wanted to find all commits in Autodesk/maya-usd containing "USD"
Then in the search results can choose Commits from the list on the left:
It is also worth taking a look at:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
You can make use of create-react-class module. Official documentation
Of course you must first install it
npm install create-react-class
Here is a working example
import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')
let Clock = createReactClass({
getInitialState:function(){
return {date:new Date()}
},
render:function(){
return (
<h1>{this.state.date.toLocaleTimeString()}</h1>
)
},
componentDidMount:function(){
this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
},
componentWillUnmount:function(){
clearInterval(this.timerId)
}
})
ReactDOM.render(
<Clock/>,
document.getElementById('root')
)
A very typical approach to this type of problem is to use row_number()
:
select t.*
from (select t.*,
row_number() over (partition by number order by id) as seqnum
from t
) t
where seqnum = 1;
This is more generalizable than using a comparison to the minimum id. For instance, you can get a random row by using order by newid()
. You can select 2 rows by using where seqnum <= 2
.
it's simple, use the "-B" option to add .h files' dir to search path.
E.g. g++ -B /header_file.h your.cpp -o bin/your_command
Here's generally how to select multiple columns from a subquery:
SELECT
A.SalesOrderID,
A.OrderDate,
SQ.Max_Foo,
SQ.Max_Foo2
FROM
A
LEFT OUTER JOIN
(
SELECT
B.SalesOrderID,
MAX(B.Foo) AS Max_Foo,
MAX(B.Foo2) AS Max_Foo2
FROM
B
GROUP BY
B.SalesOrderID
) AS SQ ON SQ.SalesOrderID = A.SalesOrderID
If what you're ultimately trying to do is get the values from the row with the highest value for Foo (rather than the max of Foo and the max of Foo2 - which is NOT the same thing) then the following will usually work better than a subquery:
SELECT
A.SalesOrderID,
A.OrderDate,
B1.Foo,
B1.Foo2
FROM
A
LEFT OUTER JOIN B AS B1 ON
B1.SalesOrderID = A.SalesOrderID
LEFT OUTER JOIN B AS B2 ON
B2.SalesOrderID = A.SalesOrderID AND
B2.Foo > B1.Foo
WHERE
B2.SalesOrderID IS NULL
You're basically saying, give me the row from B where I can't find any other row from B with the same SalesOrderID and a greater Foo.
I'm using a parent pom for my projects and wanted to specify the versions in one place, so I used properties to specify the version:
parent pom:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
....
<properties>
<maven-compiler-plugin-version>2.3.2</maven-compiler-plugin-version>
</properties>
....
</project>
project pom:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
....
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin-version}</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
See also: https://www.allthingsdigital.nl/2011/04/10/maven-3-and-the-versions-dilemma/
For everyone coming to this thread with fractional seconds in your timestamp use:
to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')
Virtualenvs are broken. Sometimes simple way is to delete venv folders and recreate virutalenvs.
The accepted answer works, but if:
use this:
.centered {
position: fixed; /* or absolute */
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
}
More information about centering content in this excellent CSS-Tricks article.
.center{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
Another great guide about flexboxs from CSS Tricks; http://css-tricks.com/snippets/css/a-guide-to-flexbox/
@Shane Arney
performSelector:withObject:withObject:
You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:)
.
kinda weird that apple only supports 2 objects to be send and didnt make it more generic.