I would check out this tool on CodeProject RTFConverter. This guy gives a great breakdown of how the program works along with details of the conversion.
For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:
range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)
And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")
edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?
My solution, to only hide the navigation bar, is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener (new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
});
}
@Override
protected void onResume() {
super.onResume();
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiOptions);
}
Edit: This does not work cross domain unless the appropriate CORS header is set.
There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:
<iframe name="iframe1" id="iframe1" src="empty.htm"
frameborder="0" border="0" cellspacing="0"
style="border-style: none;width: 100%; height: 120px;"></iframe>
The style of the page embedded in the iframe must be either set by including it in the child page:
<link type="text/css" rel="Stylesheet" href="Style/simple.css" />
Or it can be loaded from the parent page with Javascript:
var cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['iframe1'].document.head.appendChild(cssLink);
Try this solution: https://stackoverflow.com/a/46274919/907576 :
with @BeforeAllMethods
/@AfterAllMethods
annotation you could execute any method in Test class in an instance context, where all injected values are available.
You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.
The command line would be done this way:
c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt
and the java code accesses the value like this:
String context = System.getProperty("myvar");
See this question about argument passing in Java.
It sets how the database server sorts (compares pieces of text). in this case:
SQL_Latin1_General_CP1_CI_AS
breaks up into interesting parts:
latin1
makes the server treat strings using charset latin 1, basically asciiCP1
stands for Code Page 1252CI
case insensitive comparisons so 'ABC' would equal 'abc'AS
accent sensitive, so 'ü' does not equal 'u'P.S. For more detailed information be sure to read @solomon-rutzky's answer.
Based on the answers above, but adding a Func-parameter to let the caller handle the duplicates:
public static Dictionary<TKey, TValue> Merge<TKey, TValue>(this IEnumerable<Dictionary<TKey, TValue>> dicts,
Func<IGrouping<TKey, TValue>, TValue> resolveDuplicates)
{
if (resolveDuplicates == null)
resolveDuplicates = new Func<IGrouping<TKey, TValue>, TValue>(group => group.First());
return dicts.SelectMany<Dictionary<TKey, TValue>, KeyValuePair<TKey, TValue>>(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key, group => resolveDuplicates(group));
}
In Python, indexing starts at 0. Therefore, if you have a list with 53 items, list[52]
will be the last item in the list.
Try This Code :
button.setVisibility(View.INVISIBLE);
i think that is the solution
ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String hql = "FROM table ";
org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();
cat.getLibCat();//table colonm getter
combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());
Yes you can use CASE
UPDATE table
SET columnB = CASE fieldA
WHEN columnA=1 THEN 'x'
WHEN columnA=2 THEN 'y'
ELSE 'z'
END
WHERE columnC = 1
If you can, I strongly suggest you tar
and bzip
(or gzip
, whatever floats your boat) the directory on the remote machine—for a directory of any significant size, the bandwidth savings will probably be worth the time to zip/unzip.
actually you don't need to replace this all....
there are 2 ways to do this. One is to use autoclose property, the other (alternativ) way is to use the on change property thats fired by the input when selecting a Date.
HTML
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">
</div>
<div class="hero-unit">
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">
</div>
</div>
jQuery
$(document).ready(function () {
$('#example1').datepicker({
format: "dd/mm/yyyy",
autoclose: true
});
//Alternativ way
$('#example2').datepicker({
format: "dd/mm/yyyy"
}).on('change', function(){
$('.datepicker').hide();
});
});
this is all you have to do :)
HERE IS A FIDDLE to see whats happening.
Fiddleupdate on 13 of July 2016: CDN wasnt present anymore
According to your EDIT:
$('#example1').datepicker().on('changeDate', function (ev) {
$('#example1').Close();
});
Here you take the Input (that has no Close-Function) and create a Datepicker-Element. If the element changes you want to close it but you still try to close the Input (That has no close-function).
Binding a mouseup event to the document state may not be the best idea because you will fire all containing scripts on each click!
Thats it :)
EDIT: August 2017 (Added a StackOverFlowFiddle aka Snippet. Same as in Top of Post)
$(document).ready(function () {_x000D_
$('#example1').datepicker({_x000D_
format: "dd/mm/yyyy",_x000D_
autoclose: true_x000D_
});_x000D_
_x000D_
//Alternativ way_x000D_
$('#example2').datepicker({_x000D_
format: "dd/mm/yyyy"_x000D_
}).on('change', function(){_x000D_
$('.datepicker').hide();_x000D_
});_x000D_
});
_x000D_
.hero-unit{_x000D_
float: left;_x000D_
width: 210px;_x000D_
margin-right: 25px;_x000D_
}_x000D_
.hero-unit input{_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>_x000D_
<div class="container">_x000D_
<div class="hero-unit">_x000D_
<input type="text" placeholder="Sample 1: Click to show datepicker" id="example1">_x000D_
</div>_x000D_
<div class="hero-unit">_x000D_
<input type="text" placeholder="Sample 2: Click to show datepicker" id="example2">_x000D_
</div>_x000D_
</div>
_x000D_
EDIT: December 2018 Obviously Bootstrap-Datepicker doesnt work with jQuery 3.x see this to fix
First stop the Server if its running. Go to "/Applications/MAMP/bin/", rename the PHP Version you don't need (MAMP is only allowed to use 2 PHP Versions), e.g. "_php5.2.17". Now MAMP will use the php versions that are left. Go to the MAMP Manager and then settings, then switch to the php version you need.
One problem with this solution I encountered was the httpd process (took me a while to figure that out xD). If you have the httpd process running in the background, then the php switch won't work, until you stop those processes (sometimes MAMP has an awkward problem to stop the server, thats why this process can be still alive). Start your Activity Monitor on your Mac (Shortcut: Press Command+Space and type in activity...), go to the Search Function and type in "httpd", close all those processes. Now you should be able to switch your PHP Version with the MAMP Manager.
The equivalent is:
python3 -m http.server
Optimising @Don approach to use only One Query
SELECT * from (
SELECT
@rownum:=@rownum+1 row,
CASE a.id WHEN 'CurrentArticleID' THEN @currentrow:=@rownum ELSE NULL END as 'current_row',
a.*
FROM articles a,
(SELECT @currentrow:=0) c,
(SELECT @rownum:=0) r
ORDER BY `date`, id DESC
) as article_with_row
where row > @currentrow - 2
limit 3
change CurrentArticleID with current article ID like
SELECT * from (
SELECT
@rownum:=@rownum+1 row,
CASE a.id WHEN '100' THEN @currentrow:=@rownum ELSE NULL END as 'current_row',
a.*
FROM articles a,
(SELECT @currentrow:=0) c,
(SELECT @rownum:=0) r
ORDER BY `date`, id DESC
) as article_with_row
where row > @currentrow - 2
limit 3
Confirm "Certificates" category is selected.
Remove expired Apple Worldwide Developer Relations Certificate Authority certificates from "login" tab and "System" tab.
Here's Apple's answer.
Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new WWDR intermediate certificate (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.
if you're on windows, make sure you 'unblock' the lombok.jar before you install it. if you don't do this, it will install but it wont work.
These steps are working on CentOS 6.5 so they should work on CentOS 7 too:
(EDIT - exactly the same steps work for MariaDB 10.3 on CentOS 8)
yum remove mariadb mariadb-server
rm -rf /var/lib/mysql
If your datadir in /etc/my.cnf points to a different directory, remove that directory instead of /var/lib/mysqlrm /etc/my.cnf
the file might have already been deleted at step 1rm ~/.my.cnf
yum install mariadb mariadb-server
[EDIT] - Update for MariaDB 10.1 on CentOS 7
The steps above worked for CentOS 6.5 and MariaDB 10.
I've just installed MariaDB 10.1 on CentOS 7 and some of the steps are slightly different.
Step 1 would become:
yum remove MariaDB-server MariaDB-client
Step 5 would become:
yum install MariaDB-server MariaDB-client
The other steps remain the same.
Your trouble is that you have some code that is expecting datetime
to be a reference to the datetime
module and other code that is expecting datetime
to be a reference to the datetime
class. Obviously, it can't be both.
When you do:
from datetime import datetime
import datetime
You are first setting datetime
to be a reference to the class, then immediately setting it to be a reference to the module. When you do it the other way around, it's the same thing, but it ends up being a reference to the class.
You need to rename one of these references. For example:
import datetime as dt
from datetime import datetime
Then you can change references in the form datetime.xxxx
that refer to the module to dt.xxxx
.
Or else just import datetime
and change all references to use the module name. In other words, if something just says datetime(...)
you need to change that reference to datetime.datetime
.
Python has a fair bit of this kind of thing in its library, unfortunately. If they followed their own naming guidelines in PEP 8, the datetime
class would be named Datetime
and there'd be no problem using both datetime
to mean the module and Datetime
to mean the class.
A different approach. Use Tween.js for the counter. It allows the counter to slow down, speed up, bounce, and a slew of other goodies, as the counter gets to where its going.
http://jsbin.com/ekohep/2/edit#javascript,html,live
Enjoy :)
PS, doesn't use jQuery - but obviously could.
Don't use the ['type']
parameter to validate uploads. That field is user-provided, and can be trivially forged, allowing ANY type of file to be uploaded. The same goes for the ['name']
parameter - that's the name of the file as provided by the user. It is also trivial to forge, so the user's sending nastyvirus.exe
and calling it cutekittens.jpg
.
The proper method for validating uploads is to use server-side mime-type determination, e.g. via fileinfo, plus having proper upload success checking, which you do not:
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['file']['error']);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch ($mime) {
case 'image/jpeg':
case 'application/pdf'
case etc....
$ok = true;
default:
die("Unknown/not permitted file type");
}
move_uploaded_file(...);
You are also using the user-provided filename as part of the final destination of the move_uploaded_files. it is also trivial to embed path data into that filename, which you then blindly use. That means a malicious remote user can scribble on ANY file on your server that they know the path for, plus plant new files.
The recent openssh version deprecated DSA keys by default. You should suggest to your GIT provider to add some reasonable host key. Relying only on DSA is not a good idea.
As a workaround, you need to tell your ssh
client that you want to accept DSA host keys, as described in the official documentation for legacy usage. You have few possibilities, but I recommend to add these lines into your ~/.ssh/config
file:
Host your-remote-host
HostkeyAlgorithms +ssh-dss
Other possibility is to use environment variable GIT_SSH
to specify these options:
GIT_SSH_COMMAND="ssh -oHostKeyAlgorithms=+ssh-dss" git clone ssh://user@host/path-to-repository
I was looking for an example that had default kwargs using type annotation:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
example:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
Firstly remove duplicates:
arrayList1.removeAll(arrayList2);
Then merge two arrayList:
arrayList1.addAll(arrayList2);
Lastly, sort your arrayList if you wish:
collections.sort(arrayList1);
In case you don't want to make any changes on the existing list, first create their backup lists:
arrayList1Backup = new ArrayList(arrayList1);
With \
you escape special characters
Escapes special characters to literal and literal characters to special.
E.g:
/\(s\)/
matches '(s)' while/(\s)/
matches any whitespace and captures the match.
Source: http://www.javascriptkit.com/javatutors/redev2.shtml
Use jsbeautifier instead of trying to do it manually.
end(...[explode('.', $file_name)])
has worked since PHP 5.6. This is documented in the RFC although not in PHP docs themselves.
A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.
Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.
You may then want to run the resulting concatenation through a minification tool like jsmin to have it minified.
Worked liked a charm for me:
matplotlib.rcParams['figure.figsize'] = (20, 10)
I'm using this when creating dynamic array. If you have a class or a struct. And this works. Example:
struct Sprite {
int x;
};
int main () {
int num = 50;
Sprite **spritearray;//a pointer to a pointer to an object from the Sprite class
spritearray = new Sprite *[num];
for (int n = 0; n < num; n++) {
spritearray[n] = new Sprite;
spritearray->x = n * 3;
}
//delete from random position
for (int n = 0; n < num; n++) {
if (spritearray[n]->x < 0) {
delete spritearray[n];
spritearray[n] = NULL;
}
}
//delete the array
for (int n = 0; n < num; n++) {
if (spritearray[n] != NULL){
delete spritearray[n];
spritearray[n] = NULL;
}
}
delete []spritearray;
spritearray = NULL;
return 0;
}
You can achieve this in quite a few different ways.
let foo = {
bar: 'Hello World'
};
foo.bar;
foo['bar'];
The bracket notation is specially powerful as it let's you access a property based on a variable:
let foo = {
bar: 'Hello World'
};
let prop = 'bar';
foo[prop];
This can be extended to looping over every property of an object. This can be seem redundant due to newer JavaScript constructs such as for ... of ..., but helps illustrate a use case:
let foo = {
bar: 'Hello World',
baz: 'How are you doing?',
last: 'Quite alright'
};
for (let prop in foo.getOwnPropertyNames()) {
console.log(foo[prop]);
}
Both dot and bracket notation also work as expected for nested objects:
let foo = {
bar: {
baz: 'Hello World'
}
};
foo.bar.baz;
foo['bar']['baz'];
foo.bar['baz'];
foo['bar'].baz;
Object destructuring
We could also consider object destructuring as a means to access a property in an object, but as follows:
let foo = {
bar: 'Hello World',
baz: 'How are you doing?',
last: 'Quite alright'
};
let prop = 'last';
let { bar, baz, [prop]: customName } = foo;
// bar = 'Hello World'
// baz = 'How are you doing?'
// customName = 'Quite alright'
Here's what I did to get this working with my corporate proxy that uses NTLM authentication. I downloaded NuGet.exe and then ran the following commands (which I found in the comments to this discussion on CodePlex):
nuget.exe config -set http_proxy=http://my.proxy.address:port
nuget.exe config -set http_proxy.user=mydomain\myUserName
nuget.exe config -set http_proxy.password=mySuperSecretPassword
This put the following in my NuGet.config
located at %appdata%\NuGet
(which maps to C:\Users\myUserName\AppData\Roaming on my Windows 7 machine):
<configuration>
<!-- stuff -->
<config>
<add key="http_proxy" value="http://my.proxy.address:port" />
<add key="http_proxy.user" value="mydomain\myUserName" />
<add key="http_proxy.password" value="base64encodedHopefullyEncryptedPassword" />
</config>
<!-- stuff -->
</configuration>
Incidentally, this also fixed my issue with NuGet only working the first time I hit the package source in Visual Studio.
Note that some people who have tried this approach have reported through the comments that they have been able to omit setting the
http_proxy.password
key from the command line, or delete it after-the-fact from the config file, and were still able to have NuGet function across the proxy.
If you find, however, that you must specify your password in the NuGet config file, remember that you have to update the stored password in the NuGet config from the command line when you change your network login, if your proxy credentials are also your network credentials.
The <a>
nchor element is simply an anchor to or from some content. Originally the HTML specification allowed for named anchors (<a name="foo">
) and linked anchors (<a href="#foo">
).
The named anchor format is less commonly used, as the fragment identifier is now used to specify an [id]
attribute (although for backwards compatibility you can still specify [name]
attributes). An <a>
element without an [href]
attribute is still valid.
As far as semantics and styling is concerned, the <a>
element isn't a link (:link
) unless it has an [href]
attribute. A side-effect of this is that an <a>
element without [href]
won't be in the tabbing order by default.
The real question is whether the <a>
element alone is an appropriate representation of a <button>
. On a semantic level, there is a distinct difference between a link
and a button
.
A button is something that when clicked causes an action to occur.
A link is a button that causes a change in navigation in the current document. The navigation that occurs could be moving within the document in the case of fragment identifiers (#foo
) or moving to a new document in the case of urls (/bar
).
As links are a special type of button, they have often had their actions overridden to perform alternative functions. Continuing to use an anchor as a button is ok from a consistency standpoint, although it's not quite accurate semantically.
If you're concerned about the semantics and accessibility of using an <a>
element (or <span>
, or <div>
) as a button, you should add the following attributes:
<a role="button" tabindex="0" ...>...</a>
The button role tells the user that the particular element is being treated as a button as an override for whatever semantics the underlying element may have had.
For <span>
and <div>
elements, you may want to add JavaScript key listeners for Space or Enter to trigger the click
event. <a href>
and <button>
elements do this by default, but non-button elements do not. Sometimes it makes more sense to bind the click
trigger to a different key. For example, a "help" button in a web app might be bound to F1.
String all = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String strLine;
while ((strLine = br.readLine()) != null){
all = all + strLine;
}
} catch (IOException e) {
Log.e("notes_err", e.getLocalizedMessage());
}
There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.
If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.
Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.
Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.
I try with http servlet and I find this issue when I write duplicated @WebServlet ,I encountered with this issue.After I remove or change @WebServlet value it is working.
1.Class
@WebServlet("/display")
public class MyFirst extends HttpServlet {
2.Class
@WebServlet("/display")
public class MySecond extends HttpServlet {
This code is used for the mail from your localhost XAMPP and your Gmail account. This code is very easy and working for me try your self.
Below Change In php.ini File
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
extension=php_openssl.dll
Below Change In sendmail.ini File
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=your-gmail-password
[email protected]
Please write the belove code in your PHP file to send email
<?php
$to = "[email protected]";
$subject = "Test Mail";
$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<img src="//css-tricks.com/examples/WebsiteChangeRequestForm/images/wcrf-header.png" alt="Website Change Request" />';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>Details</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>Details</td></tr>";
$message .= "<tr><td><strong>Type of Change:</strong> </td><td>Details</td></tr>";
$message .= "<tr><td><strong>Urgency:</strong> </td><td>Details</td></tr>";
$message .= "<tr><td><strong>URL To Change (main):</strong> </td><td>Details</td></tr>";
$addURLS = 'google.com';
if (($addURLS) != '') {
$message .= "<tr><td><strong>URL To Change (additional):</strong> </td><td>" . $addURLS . "</td></tr>";
}
$curText = 'dummy text';
if (($curText) != '') {
$message .= "<tr><td><strong>CURRENT Content:</strong> </td><td>" . $curText . "</td></tr>";
}
$message .= "<tr><td><strong>NEW Content:</strong> </td><td>New Text</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
if(mail($to,$subject,$message,$headers))
{
echo "Mail Send Sucuceed";
}
else{
echo "Mail Send Failed";
}
?>
I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable which returned an IEnumerable and the properties couldn't be enumerated. This did the trick:
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
List<IDataRecord> list = data.Cast<IDataRecord>().ToList();
PropertyDescriptorCollection props = null;
DataTable table = new DataTable();
if (list != null && list.Count > 0)
{
props = TypeDescriptor.GetProperties(list[0]);
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
if (props != null)
{
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(values);
}
}
return table;
}
I'd usually do:
use sourcedatabase;
var docs=db.sourcetable.find();
use targetdatabase;
docs.forEach(function(doc) { db.targettable.insert(doc); });
Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo
]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo
, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!
This is what I am using for learning sql: employees-db
this is a sample database with an integrated test suite, used to test your applications and database servers
According to launchpad.net the database has moved to github.
The database contains about 300,000 employee records with 2.8 million salary entries. The export data is 167 MB, which is not huge, but heavy enough to be non-trivial for testing.
The data was generated, and as such there are inconsistencies and subtle problems. Rather than removing them, we decided to leave the contents untouched, and use these issues as data cleaning exercises.
Use json_encode($json_array, JSON_HEX_QUOT);
since php 5.3: http://php.net/manual/en/json.constants.php
For Android 8.0, there is a new API to handle Hotspots. As far as I know, the old way using reflection doesn't work anymore. Please refer to:
void startLocalOnlyHotspot (WifiManager.LocalOnlyHotspotCallback callback,
Handler handler)
Request a local only hotspot that an application can use to communicate between co-located devices connected to the created WiFi hotspot. The network created by this method will not have Internet access.
Stack Overflow
How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo)
onStarted(WifiManager.LocalOnlyHotspotReservation reservation) method will be called if hotspot is turned on.. Using WifiManager.LocalOnlyHotspotReservation reference you call close() method to turn off hotspot.
Your error is in UpdaterServiceManager in onCreate and showNotification method.
You are trying to show notification
from Service using Activity Context
. Whereas Every Service has its own Context,
just use the that. You don't need to pass a Service an Activity's Context.
I don't see why you need a specific Activity's Context to show Notification.
Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.
You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference
You need to do:
import sqlitedbx
def main():
db = sqlitedbx.SqliteDBzz()
db.connect()
if __name__ == "__main__":
main()
All the above solutions are hacky and buggy. Don't even try. Use other libs. The best I have found - http://sachinchoolur.github.io/lightslider Works great with bootstrap, does not add junk html, highly-configurable, responsive, mobile-friendly etc...
$('.multi-item-carousel').lightSlider({
item: 4,
pager: false,
autoWidth: false,
slideMargin: 0
});
There is a second parameter for the callback for collection.insert
that will return the doc or docs inserted, which should have _ids.
Try:
collection.insert(objectToInsert, function(err,docsInserted){
console.log(docsInserted);
});
and check the console to see what I mean.
Could also use a template string:
const num = 123456
`${num}`.length // 6
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
I solved my problem by running below command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
I had a similar issue with Docker for Windows and Hyper-V having reserved ports for its own use- in my case, it was port 3001
that couldn't be accessed.
netstat -ano | findstr 3001
in an Administrator Powershell prompt showed nothing.netsh interface ipv4 show excludedportrange protocol=tcp
showed that the port was in one of the exclusion ranges.I was able to follow the solution described in Docker for Windows issue #3171 (Unable to bind ports: Docker-for-Windows & Hyper-V excluding but not using important port ranges):
Disable Hyper-V:
dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
After the required restarts, reserve the port you want so Hyper-V doesn't reserve it back:
netsh int ipv4 add excludedportrange protocol=tcp startport=3001 numberofports=1
Reenable Hyper-V:
dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All
After this, I was able to start my docker container.
The problem relates to the .Net runtime version of a referenced class library (expaned references, select the library and check the "Runtime Version". I had a problem with Antlr3.Runtime, after upgrading my visual studio project to v4.5. I used NuGet to uninstall Microsoft ASP.NET Web Optimisation Framework (due to a chain of dependencies that prevented me from uninstalling Antlr3 directly)
I then used NuGet to reinstall the Microsoft ASP.NET Web Optimisation Framework. This reinstalled the correct runtime versions.
You've missed the time zone info (already answered, agreed)
arrow
package allows to avoid this torture with datetimes; It is already written, tested, pypi-published, cross-python (2.6 — 3.xx).
All you need: pip install arrow
(or add to dependencies)
dt = datetime(2013,9,1,11)
arrow.get(dt).timestamp
# >>> 1378033200
bc = arrow.get(1378033200).datetime
print(bc)
# >>> datetime.datetime(2013, 9, 1, 11, 0, tzinfo=tzutc())
print(bc.isoformat())
# >>> '2013-09-01T11:00:00+00:00'
On Windows, I solved it by creating a pip.ini file in %APPDATA%\pip\
e.g. C:\Users\asmith\AppData\Roaming\pip\pip.ini
In the pip.ini I put the path to my certificate:
[global]
cert=C:\Users\asmith\SSL\teco-ca.crt
https://pip.pypa.io/en/stable/user_guide/#configuration has more information about the configuration file.
Based on Remi answer for Python 2.7+
use this:
from __future__ import print_function
import time
# status generator
def range_with_status(total):
""" iterate from 0 to total and show progress in console """
import sys
n = 0
while n < total:
done = '#' * (n + 1)
todo = '-' * (total - n - 1)
s = '<{0}>'.format(done + todo)
if not todo:
s += '\n'
if n > 0:
s = '\r' + s
print(s, end='\r')
sys.stdout.flush()
yield n
n += 1
# example for use of status generator
for i in range_with_status(50):
time.sleep(0.2)
Has anyone else noticed that the json string/object is invalid in all answers except for David Hedlund's? :)
JSON objects must be formatted in the following manner: {"key": ("value" | 0 | false)}. Also, writing it out as a string requires much less than stringifying the object...
I assume with the second line you actually mean:
Thing *thing = new Thing("uiae");
which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*
, the other passed a const Thing&
), and then calling the destructor (~Thing()
) on the first object (the const char*
one).
By contrast, this:
Thing thing("uiae");
creates a static object which is destroyed automatically upon exiting the current scope.
A clean example that answers the Title
string output = "Error";
Task task = Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(2000);
output = "Complete";
});
task.Wait();
Console.WriteLine(output);
Question: Is there a simple way to do this in the current release of Python?
Answer: There is no simple (direct) way to do this in the current release of Python.
Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.
Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.
use socket.request.connection.remoteAddress
The exec sp_spaceused
without parameter shows the summary for the whole database. The foreachtable solution generates one result set per table - which SSMS might not be able to handle if you have too many tables.
I created a script which collects the table infos via sp_spaceused
and displays a summary in a single record set, sorted by size.
create table #t
(
name nvarchar(128),
rows varchar(50),
reserved varchar(50),
data varchar(50),
index_size varchar(50),
unused varchar(50)
)
declare @id nvarchar(128)
declare c cursor for
select '[' + sc.name + '].[' + s.name + ']' FROM sysobjects s INNER JOIN sys.schemas sc ON s.uid = sc.schema_id where s.xtype='U'
open c
fetch c into @id
while @@fetch_status = 0 begin
insert into #t
exec sp_spaceused @id
fetch c into @id
end
close c
deallocate c
select * from #t
order by convert(int, substring(data, 1, len(data)-3)) desc
drop table #t
Extending on Tadeck's Django answer above, the use of 'class Meta:' in Django is just normal Python too.
The internal class is a convenient namespace for shared data among the class instances (hence the name Meta for 'metadata' but you can call it anything you like). While in Django it's generally read-only configuration stuff, there is nothing to stop you changing it:
In [1]: class Foo(object):
...: class Meta:
...: metaVal = 1
...:
In [2]: f1 = Foo()
In [3]: f2 = Foo()
In [4]: f1.Meta.metaVal
Out[4]: 1
In [5]: f2.Meta.metaVal = 2
In [6]: f1.Meta.metaVal
Out[6]: 2
In [7]: Foo.Meta.metaVal
Out[7]: 2
You can explore it in Django directly too e.g:
In [1]: from django.contrib.auth.models import User
In [2]: User.Meta
Out[2]: django.contrib.auth.models.Meta
In [3]: User.Meta.__dict__
Out[3]:
{'__doc__': None,
'__module__': 'django.contrib.auth.models',
'abstract': False,
'verbose_name': <django.utils.functional.__proxy__ at 0x26a6610>,
'verbose_name_plural': <django.utils.functional.__proxy__ at 0x26a6650>}
However, in Django you are more likely to want to explore the _meta
attribute which is an Options
object created by the model metaclass
when a model is created. That is where you'll find all of the Django class 'meta' information. In Django, Meta
is just used to pass information into the process of creating the _meta
Options
object.
You could also use this:
if(not(orgs)):
#if orgs is empty
else:
#if orgs is not empty
#pragma
push/pop are often a solution for this kind of problems, but in this case why don't you just remove the unreferenced variable?
try
{
// ...
}
catch(const your_exception_type &) // type specified but no variable declared
{
// ...
}
answer suggested by rakesh is great but still with some discription Singleton in Android is the same as Singleton in Java: The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:
1) Ensure that only one instance of a class is created
2) Provide a global point of access to the object
3) Allow multiple instances in the future without affecting a singleton class's clients
A basic Singleton class example:
public class MySingleton
{
private static MySingleton _instance;
private MySingleton()
{
}
public static MySingleton getInstance()
{
if (_instance == null)
{
_instance = new MySingleton();
}
return _instance;
}
}
The TextBox
has a property called ReadOnly
. If you set that property to true then the TextBox
will still be able to scroll but the user wont be able to change the value.
There are ways to change the default delimiter, as shown by other answers.
There are also ways to convert the raw output to csv with some bash scripting. There are 3 delimiters to consider though, not just \001. Things get a bit more complicated when your hive table has maps.
I wrote a bash script that can handle all 3 default delimiters (\001 \002 and \003) from hive and output a csv. The script and some more info are here:
Hive Default Delimiters to CSV
Hive's default delimiters are
Row Delimiter => Control-A ('\001') Collection Item Delimiter => Control-B ('\002') Map Key Delimiter => Control-C ('\003')
There are ways to change these delimiters when exporting tables but sometimes you might still get stuck needing to convert this to csv.
Here's a quick bash script that can handle a DB export that's segmented in multiple files and has the default delimiters. It will output a single CSV file.
It is assumed that the segments all have the naming convention 000*_0
INDIRECTORY="path/to/input/directory" for f in $INDIRECTORY/000*_0; do echo "Processing $f file.."; cat -v $f | LC_ALL=C sed -e "s/^/\"/g" | LC_ALL=C sed -e "s/\^A/\",\"/g" | LC_ALL=C sed -e "s/\^C\^B/\"\":\"\"\"\",\"\"/g" | LC_ALL=C sed -e "s/\^B/\"\",\"\"/g" | LC_ALL=C sed -e "s/\^C/\"\":\"\"/g" | LC_ALL=C sed -e "s/$/\"/g" > $f-temp done echo "you,can,echo,your,header,here,if,you,like" > $INDIRECTORY/final_output.csv cat $INDIRECTORY/*-temp >> $INDIRECTORY/final_output.csv rm $INDIRECTORY/*-temp
More explanation on the gist
Supose you have the following scenario:
* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit
Where you want to remove d258546 i.e. "bad commit".
You shall try an interactive rebase to remove it: git rebase -i 34c4f95
then your default editor will pop with something like this:
pick bd8aa13 2nd commit
pick 0f1efa9 3rd commit
pick d258546 bad commit
pick 1bd2200 another commit
# Rebase 34c4f95..1bd2200 onto 34c4f95
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
just remove the line with the commit you want to strip and save+exit the editor:
pick bd8aa13 2nd commit
pick 0f1efa9 3rd commit
pick 1bd2200 another commit
...
git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):
* 34fa994 (HEAD, master) another commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit
Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f
option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>
)
Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.
Alternative option:
Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>
. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).
In RStudio, there are (at least) 3 ways:
View
(function_name) (as stated above)A new pane will open with the source code. If you reach .Primitive or .C you'll need another method, sorry.
Your static method should go from:
public static class SimpleUsing
{
public static void DoUsing(Action<MyDataContext> action)
{
using (MyDataContext db = new MyDataContext())
action(db);
}
}
To:
public static class SimpleUsing
{
public static TResult DoUsing<TResult>(Func<MyDataContext, TResult> action)
{
using (MyDataContext db = new MyDataContext())
return action(db);
}
}
This answer grew out of comments so I could provide code. For a complete elaboration, please see @sll's answer below.
You can use git show
with a path from the root of the repository (./
or ../
for relative pathing):
$ git show REVISION:path/to/file
Replace REVISION
with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)
For example, to view the version of file <repository-root>/src/main.c
from 4 commits ago, use:
$ git show HEAD~4:src/main.c
Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show
.
The _id
field is always present unless you explicitly exclude it. Do so using the -
syntax:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select('name -_id');
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
Or explicitly via an object:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
// YouTube video ID
var videoID = "CMNry4PE93Y";
// Fetch video info (using a proxy to avoid CORS errors)
fetch('https://cors-anywhere.herokuapp.com/' + "https://www.youtube.com/get_video_info?video_id=" + videoID).then(response => {
if (response.ok) {
response.text().then(ytData => {
// parse response to find audio info
var ytData = parse_str(ytData);
var getAdaptiveFormats = JSON.parse(ytData.player_response).streamingData.adaptiveFormats;
var findAudioInfo = getAdaptiveFormats.findIndex(obj => obj.audioQuality);
// get the URL for the audio file
var audioURL = getAdaptiveFormats[findAudioInfo].url;
// update the <audio> element src
var youtubeAudio = document.getElementById('youtube');
youtubeAudio.src = audioURL;
});
}
});
function parse_str(str) {
return str.split('&').reduce(function(params, param) {
var paramSplit = param.split('=').map(function(value) {
return decodeURIComponent(value.replace('+', ' '));
});
params[paramSplit[0]] = paramSplit[1];
return params;
}, {});
}
_x000D_
<audio id="youtube" controls></audio>
_x000D_
You can simply iterate through the DbSet context.tablename
foreach(var row in context.tablename)
Console.WriteLn(row.field);
or to evaluate immediately into your own list
var allRows = context.tablename.ToList();
You'll need to do an insert (or update, I believe) in order for getLastInsertId()
to return a value. Could you paste more code?
If you're calling that function from another controller function, you might also be able to use $this->Form->id
to get the value that you want.
this is the best way I used
Go to java file, after onCreate
:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Take instance of Action Bar
// using getSupportActionBar and
// if it is not Null
// then call hide function
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
}
Taken from NSString
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
Parameters
target
The string to replace.
replacement
The string with which to replace target.
Return Value
A new string in which all occurrences of target in the receiver are replaced by replacement.
use SimpleDateFormat df = new SimpleDateFormat("HH:mm");
instead
UPDATE
@Ingo is right. is's better use setTime(d1);
first method getHours()
and getMinutes()
is now deprecated
I test this code
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
Date d1 = df.parse("23:30");
Calendar c1 = GregorianCalendar.getInstance();
c1.setTime(d1);
System.out.println(c1.getTime());
and output is ok Thu Jan 01 23:30:00 FET 1970
try this
SimpleDateFormat df = new SimpleDateFormat("KK:mm aa");
Date d1 = df.parse("10:30 PM");
Calendar c1 = GregorianCalendar.getInstance(Locale.US);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
c1.setTime(d1);
String str = sdf.format(c1.getTime());
System.out.println(str);
The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).
Delete Without Rebooting
The OP's question indeed has been answered extensively, including how to avoid rebooting through powershell, vbscript, or you name it.
However, if you need to stick to cmd commands only and don't have the luxury of being able to call powershell or vbscript, you could use the following approach:
rem remove from current cmd instance
SET FOOBAR=
rem remove from the registry if it's a user variable
REG delete HKCU\Environment /F /V FOOBAR
rem remove from the registry if it's a system variable
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
rem tell Explorer.exe to reload the environment from the registry
SETX DUMMY ""
rem remove the dummy
REG delete HKCU\Environment /F /V DUMMY
So the magic here is that by using "setx" to assign something to a variable you don't need (in my example DUMMY), you force Explorer.exe to reread the variables from the registry, without needing powershell. You then clean up that dummy, and even though that one will stay in Explorer's environment for a little while longer, it will probably not harm anyone.
Or if after deleting variables you need to set new ones, then you don't even need any dummy. Just using SETX to set the new variables will automatically clear the ones you just removed from any new cmd tasks that might get started.
Background information: I just used this approach successfully to replace a set of user variables by system variables of the same name on all of the computers at my job, by modifying an existing cmd script. There are too many computers to do it manually, nor was it practical to copy extra powershell or vbscripts to all of them. The reason I urgently needed to replace user with system variables was that user variables get synchronized in roaming profiles (didn't think about that), so multiple machines using the same windows login but needing different values, got mixed up.
I had the same problem. What I've done: add in my view hidden field with id of a model and in validator check the unique, only if I've get some id from view.
$this->validate(
$request,
[
'index' => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
'name' => 'required',
'surname' => 'required',
]
);
First, knowing where the data directory was for me was the key. /usr/local/var/mysql
In here, there was at least one file with extension .err preceded with my local machine name. It had all info i needed to diagnose.
I think i screwed up by installing mysql 8 first. My app isn't compatible with it so i had to downgrade back to 5.7
My solution that worked for me was going to /usr/local/etc/my.cnf
Find this line if its there. I think its mysql 8 related:
mysqlx-bind-address = 127.0.0.1
Remove it because in the mysql 5.7 says it doesnt like it in the error log
Also add this line in there if its not there under the bind-address.
socket=/tmp/mysql.sock
Go to the /tmp
directory and delete any mysql.sock files in there. On server start, it will recreate the sock files
Trash out the data directory with mySQL in the stopped state. Mine was /usr/local/var/mysql
. This is the same place where the logs are at
From there i ran
>mysqld --initialize
Then everything started working...this command will give you a random password at the end. Save that password for the next step
Running this to assign my own password.
>mysql_secure_installation
Both
>brew services stop [email protected]
and
>mysql.server start
are now working. Hope this helps. It's about 3 hours of trial and error.
hg up -C
This will remove all the changes and update to the latest head in the current branch.
And you can turn on purge extension to be able to remove all unversioned files too.
Open the file .bash_profile
in your Home folder. It is a hidden file.
Add this path below to the end export PATH line in you .bash_profile
file
:/Applications/Postgres.app/Contents/Versions/latest/bin
The symbol :
separates the paths.
If the file contains:
export PATH=/usr/bin:/bin:/usr/sbin:/sbin
it will become:
export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Postgres.app/Contents/Versions/latest/bin
In Terminal, paste the following: defaults write com.apple.finder AppleShowAllFiles YES
For the sake of completeness, here is the ‘one-liner’ corresponding to @prunge’s excellent answer:
User user1 = users.stream()
.filter(user -> user.getId() == 1)
.reduce((a, b) -> {
throw new IllegalStateException("Multiple elements: " + a + ", " + b);
})
.get();
This obtains the sole matching element from the stream, throwing
NoSuchElementException
in case the stream is empty, orIllegalStateException
in case the stream contains more than one matching element.A variation of this approach avoids throwing an exception early and instead represents the result as an Optional
containing either the sole element, or nothing (empty) if there are zero or multiple elements:
Optional<User> user1 = users.stream()
.filter(user -> user.getId() == 1)
.collect(Collectors.reducing((a, b) -> null));
You can use linear indexing to access each element.
for idx = 1:numel(array)
element = array(idx)
....
end
This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()
This is what you wanna do:
var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON
method to recursively build the result
Below, html2json
is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
tagName: _x000D_
e.tagName,_x000D_
textContent:_x000D_
e.textContent,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.children, Elem)_x000D_
})_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
In the previous example, the textContent
gets a little butchered. To remedy this, we introduce another data constructor, TextElem
. We'll have to map over the childNodes
(instead of children
) and choose to return the correct data type based on e.nodeType
– this gets us a littler closer to what we might need
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
toJSON: () => ({_x000D_
type:_x000D_
'TextElem',_x000D_
textContent:_x000D_
e.textContent_x000D_
})_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
type:_x000D_
'Elem',_x000D_
tagName: _x000D_
e.tagName,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.childNodes, fromNode)_x000D_
})_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
switch (e.nodeType) {_x000D_
case 3: return TextElem(e)_x000D_
default: return Elem(e)_x000D_
}_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity
In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^
Related: Recursive methods using JavaScript: building your own version of JSON.stringify
...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...
For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:
When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.
More info:
Try:
html, body {
height: 102%;
}
.wrapper {
position: relative;
height: 100%;
width: 100%;
}
.div {
position: absolute;
top: 0;
bottom: 0;
width: 1000px;
min-height: 100%;
}
Haven't tested it yet...
When you have a 6 digit color code e.g. #ffffff, replace it with #ffffff00. Just add 2 zeros at the end to make the color transparent.
Here is an article describing the new standard in more depth: https://css-tricks.com/8-digit-hex-codes/
using LINQ query expression
IEnumerable<SelectListItem> stores =
from store in database.Stores
where store.CompanyID == curCompany.ID
select new SelectListItem { Value = store.Name, Text = store.ID };
ViewBag.storeSelector = stores;
or using LINQ extension methods with lambda expressions
IEnumerable<SelectListItem> stores = database.Stores
.Where(store => store.CompanyID == curCompany.ID)
.Select(store => new SelectListItem { Value = store.Name, Text = store.ID });
ViewBag.storeSelector = stores;
Yes it makes sense to use requireJS with Angular, I spent several days to test several technical solutions.
I made an Angular Seed with RequireJS on Server Side. Very simple one. I use SHIM notation for no AMD module and not AMD because I think it's very difficult to deal with two different Dependency injection system.
I use grunt and r.js to concatenate js files on server depends on the SHIM configuration (dependency) file. So I refer only one js file in my app.
For more information go on my github Angular Seed : https://github.com/matohawk/angular-seed-requirejs
If this helps. Add the following property with value to your selector:
white-space: pre-wrap;
On Google'e Gson library, for having a JsonObject
, or more abstract a JsonElement
:
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
JsonElement json = JsonParser.parseReader( new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8") );
This is not demanding a given Object structure for receiving/reading the json string.
You can create one file that contains the set schema ...
statement and then include the actual file you want to run:
Create a file run_insert.sql
:
set schema 'my_schema_01';
\i myInsertFile.sql
Then call this using:
psql -d myDataBase -a -f run_insert.sql
Go on the missing declaration with cursor and press alt+enter
There's a RemoveDuplicates
method that you could use:
Sub DeleteRows()
With ActiveSheet
Set Rng = Range("A1", Range("B1").End(xlDown))
Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End With
End Sub
In my case, I was sending input elements instead of their values:
$.post( '',{ registerName: $('#registerName') } )
Instead of:
$.post( '',{ registerName: $('#registerName').val() } )
This froze my Chrome tab to a point it didn't even show me the 'Wait/Kill' dialog for when the page became unresponsive...
The best sorting technique of all generally depends upon the size of an array. Merge sort can be the best of all as it manages better space and time complexity according to the Big-O algorithm (This suits better for a large array).
http://api.jquery.com/jQuery.ajax/
jQuery.ajax()
Description: Perform an asynchronous HTTP (Ajax) request.
The full monty, lets you make any kind of Ajax request.
http://api.jquery.com/jQuery.get/
jQuery.get()
Description: Load data from the server using a HTTP GET request.
Only lets you make HTTP GET requests, requires a little less configuration.
.load()
Description: Load data from the server and place the returned HTML into the matched element.
Specialized to get data and inject it into an element.
Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to create log records matching that level or higher.
You might be using a ConsoleHandler
(I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level Level.INFO
. You will have to configure this handler, to publish log records of level Level.FINER
and higher, for the desired outcome.
I would recommend reading the Java Logging Overview guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.
Editing the handler level
1. Using the Configuration file
The java.util.logging properties file (by default, this is the logging.properties
file in JRE_HOME/lib
) can be modified to change the default level of the ConsoleHandler:
java.util.logging.ConsoleHandler.level = FINER
2. Creating handlers at runtime
This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.
Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINER);
Logger.getAnonymousLogger().addHandler(consoleHandler);
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}
VLookup
You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".
External Reference
To reference a cell of the same Workbook use the following pattern:
<Sheetname>!<Cell>
Example:
Table1!A1
To reference a cell of a different Workbook use this pattern:
[<Workbook_name>]<Sheetname>!<Cell>
Example:
[MyWorkbook]Table1!A1
For better performance use str1.concat(str2)
where str1
and str2
are string variables.
I would recommend identifying the functionality you need from any subclasses, and make a generic method to cast into the right subclass.
I had this same problem, but really didn't feel like creating some mapping class or importing a library.
Let's say you need the 'Authenticate' method to take behavior from the right subclass. In your NetworkClient:
protected bool Authenticate(string username, string password) {
//...
}
protected bool DoAuthenticate<T>(NetworkClient nc, string username, string password) where T : NetworkClient {
//Do a cast into the sub class.
T subInst = (T) nc;
return nc.Authenticate(username, password);
}
There is a quick solution:
x = eval('[ "A","B","C" , " D"]')
Unwanted whitespaces in the list elements may be removed in this way:
x = [x.strip() for x in eval('[ "A","B","C" , " D"]')]
var resizeTimer;
$( window ).resize(function() {
if(resizeTimer){
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function() {
//your code here
resizeTimer = null;
}, 200);
});
This worked for what I was trying to do in chrome. This won't fire the callback until 200ms after last resize event.
Recently I had this problem and none of solutions provided here helped me. Or it completely destroyed it so it could not be shown again. On document ready also did not work but what worked is that I wrapped all my listeners with immediately invoked function like this:
$(function () {
$('#btn-show-modal').click(function () {
$("#modal-lightbox").modal('show');
});
$('#btn-close-modal').click(function () {
$("#modal-lightbox").modal('hide');
});
});
Try this. Here is the code to get the sheet names in order.
private Dictionary<int, string> GetExcelSheetNames(string fileName)
{
Excel.Application _excel = null;
Excel.Workbook _workBook = null;
Dictionary<int, string> excelSheets = new Dictionary<int, string>();
try
{
object missing = Type.Missing;
object readOnly = true;
Excel.XlFileFormat.xlWorkbookNormal
_excel = new Excel.ApplicationClass();
_excel.Visible = false;
_workBook = _excel.Workbooks.Open(fileName, 0, readOnly, 5, missing,
missing, true, Excel.XlPlatform.xlWindows, "\\t", false, false, 0, true, true, missing);
if (_workBook != null)
{
int index = 0;
foreach (Excel.Worksheet sheet in _workBook.Sheets)
{
// Can get sheet names in order they are in workbook
excelSheets.Add(++index, sheet.Name);
}
}
}
catch (Exception e)
{
return null;
}
finally
{
if (_excel != null)
{
if (_workBook != null)
_workBook.Close(false, Type.Missing, Type.Missing);
_excel.Application.Quit();
}
_excel = null;
_workBook = null;
}
return excelSheets;
}
The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean()
function. Therefore, check your data using str(data.frame&column)
function to see what data type you have, and convert it to numeric format if necessary.
For example, if your data is Character convert it with as.numeric(data.frame$column)
, or as a factor with as.numeric(as.character(data.frame$column))
. The mean function does not work with types other than numeric.
You can send the FormData object in ajax request using the following code,
$("form#formElement").submit(function(){
var formData = new FormData($(this)[0]);
});
This is very similar to the accepted answer but an actual answer to the question topic. This will submit the form elements automatically in the FormData and you don't need to manually append the data to FormData variable.
The ajax method looks like this,
$("form#formElement").submit(function(){
var formData = new FormData($(this)[0]);
//append some non-form data also
formData.append('other_data',$("#someInputData").val());
$.ajax({
type: "POST",
url: postDataUrl,
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(data, textStatus, jqXHR) {
//process data
},
error: function(data, textStatus, jqXHR) {
//process error msg
},
});
You can also manually pass the form element inside the FormData object as a parameter like this
var formElem = $("#formId");
var formdata = new FormData(formElem[0]);
Hope it helps. ;)
BETTER SOLUTION
Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git
Thanks@Milche Patern!
I was really looking for reset/default style properties value. My first try was to copy the computed value from the browser Dev tool of the root(html) element. But as it computed, it would have looked/worked different on every system.
For those who encounter a browser crash when trying to use the asterisk * to reset the style of the children elements, and as I knew it didn't work for you, I have replaced the asterisk "*" with all the HTML tags name instead. The browser didn't crash; I am on Chrome Version 46.0.2490.71 m.
At last, it's good to mention that those properties will reset the style to the default style of topest root element but not to the initial value for each HTML element. ?So to correct this, I have taken the "user-agent" styles of webkit based browser and implemented it under the "reset-this" class.
Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git
User-agent style:
Browsers' default CSS for HTML elements
http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css
Css specifity (pay attention to specifity) :
https://css-tricks.com/specifics-on-css-specificity/
If you really want a vba solution you can loop through a range like this:
Sub Check()
Dim dat As Variant
Dim rng As Range
Dim i As Long
Set rng = Range("A1:A100")
dat = rng
For i = LBound(dat, 1) To UBound(dat, 1)
If dat(i, 1) <> "" Then
rng(i, 2).Value = "My Text"
End If
Next
End Sub
*EDIT*
Instead of using varients you can just loop through the range like this:
Sub Check()
Dim rng As Range
Dim i As Long
'Set the range in column A you want to loop through
Set rng = Range("A1:A100")
For Each cell In rng
'test if cell is empty
If cell.Value <> "" Then
'write to adjacent cell
cell.Offset(0, 1).Value = "My Text"
End If
Next
End Sub
Scan your workspace .metadata
directory for files called *.launch
. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core
one.
Tray to add text with html value to textarea but it wil not works
value :
$(document).on('click', '.edit_targets_btn', function() {
$('#add_edit_targets').modal('show');
$('#add_edit_targets_form')[0].reset();
$('#targets_modal_title').text('Doel bijwerken');
$('#action').val('targets_update');
$('#targets_submit_btn').val('Opslaan');
$('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
$('#targets_title').val($(this).attr("title"));
$("#targets_content").append($(this).attr("content"));
tinymce.init({
selector: '#targets_content',
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
},
browser_spellcheck : true,
plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
relative_urls : false,
remove_script_host : false,
image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
min_height: 250,
branding: false
});
});
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
Try this:
SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
FROM TableName
Here is a version, basically the same as a couple of the other answers, but that you can copy paste into your SQL server Management Studio to test, (and without generating any unwanted tables), thanks to some inline values.
WITH [TestData]([ID],[SKU],[PRODUCT]) AS
(
SELECT *
FROM (
VALUES
(1, 'FOO-23', 'Orange'),
(2, 'BAR-23', 'Orange'),
(3, 'FOO-24', 'Apple'),
(4, 'FOO-25', 'Orange')
)
AS [TestData]([ID],[SKU],[PRODUCT])
)
SELECT * FROM [TestData] WHERE [ID] IN
(
SELECT MIN([ID])
FROM [TestData]
GROUP BY [PRODUCT]
)
Result
ID SKU PRODUCT
1 FOO-23 Orange
3 FOO-24 Apple
I have ignored the following ...
WHERE ([SKU] LIKE 'FOO-%')
as its only part of the authors faulty code and not part of the question. It's unlikely to be helpful to people looking here.
function ping($ip){
$output = shell_exec("ping $ip");
var_dump($output);
}
ping('127.0.0.1');
UPDATE: If you pass an hardcoded IP (like in this example and most of the real-case scenarios), this function can be enough.
But since some users seem to be very concerned about safety, please remind to never pass user generated inputs to the shell_exec
function:
If the IP comes from an untrusted source, at least check it with a filter before using it.
First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).
For the method-level stuff, there is [MethodImpl]
:
[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}
This can also be used on accessors (properties and events):
private int i;
public int SomeProperty
{
[MethodImpl(MethodImplOptions.Synchronized)]
get { return i; }
[MethodImpl(MethodImplOptions.Synchronized)]
set { i = value; }
}
Note that field-like events are synchronized by default, while auto-implemented properties are not:
public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized
Personally, I don't like the implementation of MethodImpl
as it locks this
or typeof(Foo)
- which is against best practice. The preferred option is to use your own locks:
private readonly object syncLock = new object();
public void SomeMethod() {
lock(syncLock) { /* code */ }
}
Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a lock(this)
/ lock(Type)
- however, in more recent compilers it uses Interlocked
updates - so thread-safe without the nasty parts.
This allows more granular usage, and allows use of Monitor.Wait
/Monitor.Pulse
etc to communicate between threads.
A related blog entry (later revisited).
Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy
It seems that ssh is not installed on your computer.
You can install openssh from here : http://openssh.en.softonic.com/download
Than you will have to geneate your ssh-key. There's a good tutorial about this here:
https://help.github.com/articles/generating-ssh-keys#platform-windows
To deploy, you just have to push your code over git. Something like this:
git push fort master
If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.
The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication
I just came across this, while looking for something else.
I would recommend to go with the methods in the os
package. This is because you can make it more general, compensating for any weird case.
You can do something like:
import os
the_file = 'aaaa/bbbb/ccc.ddd'
extensions_list = ['ddd', 'eee', 'fff']
if os.path.splitext(the_file)[-1] in extensions_list:
# Do your thing.
There is a super simple way of doing it. I found it on here.
view.clipsToBounds = true
view.layer.cornerRadius = 24
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
It uses the stock cornerRadius
property on the CALayer
of a view. You just need to define the corners. layerMinXMinYCorner
is top left layerMaxXMinYCorner
is top right.
Try this,
Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText();
The accepted answer (as of 2019 JULY 29) is only still valid if you have not started using the more recent SVG-with-JS approach of FontAwesome. In which case you need to follow the instructions on their CSS Pseudo-Elements HowTo. Basically there are three things to watch out for:
My gulp file produces a final compiled-bundle-min.js, hope this helps someone.
//Gulpfile.js
var gulp = require("gulp");
var watch = require("gulp-watch");
var concat = require("gulp-concat");
var rename = require("gulp-rename");
var uglify = require("gulp-uglify");
var del = require("del");
var minifyCSS = require("gulp-minify-css");
var copy = require("gulp-copy");
var bower = require("gulp-bower");
var sourcemaps = require("gulp-sourcemaps");
var path = {
src: "bower_components/",
lib: "lib/"
}
var config = {
jquerysrc: [
path.src + "jquery/dist/jquery.js",
path.src + "jquery-validation/dist/jquery.validate.js",
path.src + "jquery-validation/dist/jquery.validate.unobtrusive.js"
],
jquerybundle: path.lib + "jquery-bundle.js",
ngsrc: [
path.src + "angular/angular.js",
path.src + "angular-route/angular-route.js",
path.src + "angular-resource/angular-resource.js"
],
ngbundle: path.lib + "ng-bundle.js",
//JavaScript files that will be combined into a Bootstrap bundle
bootstrapsrc: [
path.src + "bootstrap/dist/js/bootstrap.js"
],
bootstrapbundle: path.lib + "bootstrap-bundle.js"
}
// Synchronously delete the output script file(s)
gulp.task("clean-scripts", function (cb) {
del(["lib","dist"], cb);
});
//Create a jquery bundled file
gulp.task("jquery-bundle", ["clean-scripts", "bower-restore"], function () {
return gulp.src(config.jquerysrc)
.pipe(concat("jquery-bundle.js"))
.pipe(gulp.dest("lib"));
});
//Create a angular bundled file
gulp.task("ng-bundle", ["clean-scripts", "bower-restore"], function () {
return gulp.src(config.ngsrc)
.pipe(concat("ng-bundle.js"))
.pipe(gulp.dest("lib"));
});
//Create a bootstrap bundled file
gulp.task("bootstrap-bundle", ["clean-scripts", "bower-restore"], function () {
return gulp.src(config.bootstrapsrc)
.pipe(concat("bootstrap-bundle.js"))
.pipe(gulp.dest("lib"));
});
// Combine and the vendor files from bower into bundles (output to the Scripts folder)
gulp.task("bundle-scripts", ["jquery-bundle", "ng-bundle", "bootstrap-bundle"], function () {
});
//Restore all bower packages
gulp.task("bower-restore", function () {
return bower();
});
//build lib scripts
gulp.task("compile-lib", ["bundle-scripts"], function () {
return gulp.src("lib/*.js")
.pipe(sourcemaps.init())
.pipe(concat("compiled-bundle.js"))
.pipe(gulp.dest("dist"))
.pipe(rename("compiled-bundle.min.js"))
.pipe(uglify())
.pipe(sourcemaps.write("./"))
.pipe(gulp.dest("dist"));
});
I experienced an issue where background images with spaces in the filename where causing the style to not be applied. To correct this I had to ensure the string path was encapsulated in single quotes.
Note the escaped \' in my example below.
<div :style="{
height: '100px',
backgroundColor: '#323232',
backgroundImage: 'url(\'' + event.image + '\')',
backgroundPosition: 'center center',
backgroundSize: 'cover'
}">
</div>
This code removes the inner html of an element from the dom when the debugger is open (tested in Chrome and IE)
var currentInnerHtml;
var element = new Image();
var elementWithHiddenContent = document.querySelector("#element-to-hide");
var innerHtml = elementWithHiddenContent.innerHTML;
element.__defineGetter__("id", function() {
currentInnerHtml = "";
});
setInterval(function() {
currentInnerHtml = innerHtml;
console.log(element);
console.clear();
elementWithHiddenContent.innerHTML = currentInnerHtml;
}, 1000);
Here #element-to-hide
is the id of element you want to hide.
It is a hack, but I hope it helps you.
Here is a working version of the "build defs". This is similar to my previous answer but I figured out the build month. (You just can't compute build month in a #if
statement, but you can use a ternary expression that will be compiled down to a constant.)
Also, according to the documentation, if the compiler cannot get the time of day it will give you question marks for these strings. So I added tests for this case, and made the various macros return an obviously wrong value (99) if this happens.
#ifndef BUILD_DEFS_H
#define BUILD_DEFS_H
// Example of __DATE__ string: "Jul 27 2012"
// Example of __TIME__ string: "21:06:19"
#define COMPUTE_BUILD_YEAR \
( \
(__DATE__[ 7] - '0') * 1000 + \
(__DATE__[ 8] - '0') * 100 + \
(__DATE__[ 9] - '0') * 10 + \
(__DATE__[10] - '0') \
)
#define COMPUTE_BUILD_DAY \
( \
((__DATE__[4] >= '0') ? (__DATE__[4] - '0') * 10 : 0) + \
(__DATE__[5] - '0') \
)
#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')
#define COMPUTE_BUILD_MONTH \
( \
(BUILD_MONTH_IS_JAN) ? 1 : \
(BUILD_MONTH_IS_FEB) ? 2 : \
(BUILD_MONTH_IS_MAR) ? 3 : \
(BUILD_MONTH_IS_APR) ? 4 : \
(BUILD_MONTH_IS_MAY) ? 5 : \
(BUILD_MONTH_IS_JUN) ? 6 : \
(BUILD_MONTH_IS_JUL) ? 7 : \
(BUILD_MONTH_IS_AUG) ? 8 : \
(BUILD_MONTH_IS_SEP) ? 9 : \
(BUILD_MONTH_IS_OCT) ? 10 : \
(BUILD_MONTH_IS_NOV) ? 11 : \
(BUILD_MONTH_IS_DEC) ? 12 : \
/* error default */ 99 \
)
#define COMPUTE_BUILD_HOUR ((__TIME__[0] - '0') * 10 + __TIME__[1] - '0')
#define COMPUTE_BUILD_MIN ((__TIME__[3] - '0') * 10 + __TIME__[4] - '0')
#define COMPUTE_BUILD_SEC ((__TIME__[6] - '0') * 10 + __TIME__[7] - '0')
#define BUILD_DATE_IS_BAD (__DATE__[0] == '?')
#define BUILD_YEAR ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_YEAR)
#define BUILD_MONTH ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_MONTH)
#define BUILD_DAY ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_DAY)
#define BUILD_TIME_IS_BAD (__TIME__[0] == '?')
#define BUILD_HOUR ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_HOUR)
#define BUILD_MIN ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_MIN)
#define BUILD_SEC ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_SEC)
#endif // BUILD_DEFS_H
With the following test code, the above works great:
printf("%04d-%02d-%02dT%02d:%02d:%02d\n", BUILD_YEAR, BUILD_MONTH, BUILD_DAY, BUILD_HOUR, BUILD_MIN, BUILD_SEC);
However, when I try to use those macros with your stringizing macro, it stringizes the literal expression! I don't know of any way to get the compiler to reduce the expression to a literal integer value and then stringize.
Also, if you try to statically initialize an array of values using these macros, the compiler complains with an error: initializer element is not constant
message. So you cannot do what you want with these macros.
At this point I'm thinking that your best bet is the Python script that just generates a new include file for you. You can pre-compute anything you want in any format you want. If you don't want Python we can write an AWK script or even a C program.
What I do is give each one of my reusable component a unique custom element name and then create a CSS file for that component, specifically, with all styling options for that component (and only for that component).
var MyDiv = React.createClass({
render: function() {
return <custom-component style={style}> Have a good and productive day! </custom-component>;
}
});
And in file 'custom-component.css', every entry will start with the custom-component tag:
custom-component {
display: block; /* have it work as a div */
color: 'white';
fontSize: 200;
}
custom-component h1 {
font-size: 1.4em;
}
That means you don't lose the critical notion of separating of concern. View vs style. If you share your component, it is easier for others to theme it to match the rest of their web page.
I've left this here for posterity but don't recommend its use as it's not terribly readable. This is especially true now that I've come back to see if after a period of some time and have wondered what I was thinking when I wrote it (I was probably thinking 'crap, must get this written before someone else posts an answer'.)
string s = string.Concat(arr.Cast<object>().ToArray());
Here is the ng repeat with ng click function and to append with slider
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.employees = [
{ 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
{ 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
{ 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
{ 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
{ 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
]
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
</head>
<body>
<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
<div class="MS-content">
<div class="item" ng-repeat="emps in employees" ng-show = "IsVisible">
<div class="subitem">
<p>{{emps.id}}</p>
<p>{{emps.name}}</p>
<p>{{emps.age}}</p>
</div>
</div>
</div>
<div class="MS-controls">
<button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
<button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="js/multislider.js"></script>
<script>
$('#mixedSlider').multislider({
duration: 750,
interval: false
});
</script>
My experience with MATMUL and DOT
I was constantly getting "ValueError: Shape of passed values is (200, 1), indices imply (200, 3)" when trying to use MATMUL. I wanted a quick workaround and found DOT to deliver the same functionality. I don't get any error using DOT. I get the correct answer
with MATMUL
X.shape
>>>(200, 3)
type(X)
>>>pandas.core.frame.DataFrame
w
>>>array([0.37454012, 0.95071431, 0.73199394])
YY = np.matmul(X,w)
>>> ValueError: Shape of passed values is (200, 1), indices imply (200, 3)"
with DOT
YY = np.dot(X,w)
# no error message
YY
>>>array([ 2.59206877, 1.06842193, 2.18533396, 2.11366346, 0.28505879, …
YY.shape
>>> (200, )
Check this:
<?php
if (mysqli_num_rows(mysqli_query($con, sqlselectquery)) > 0)
{
echo "found";
}
else
{
echo "not found";
}
?>
<!----comment ---for select query to know row matching the condition are fetched or not--->
From this link
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using System.Xml;
namespace ClientUtil
{
public class DataTableUtil
{
public static string DataTableToXmlString(DataTable dtData)
{
if (dtData == null || dtData.Columns.Count == 0)
return (string) null;
DataColumn[] primaryKey = dtData.PrimaryKey;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(“<TABLE>”);
stringBuilder.Append(“<TR>”);
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
if (DataTableUtil.IsPrimaryKey(dataColumn.ColumnName, primaryKey))
stringBuilder.Append(“<TH IsPK=’true’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
else
stringBuilder.Append(“<TH IsPK=’false’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
}
stringBuilder.Append(“</TR>”);
int num1 = 0;
foreach (DataRow dataRow in (InternalDataCollectionBase) dtData.Rows)
{
stringBuilder.Append(“<TR>”);
int num2 = 0;
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
string str = Convert.IsDBNull(dataRow[dataColumn.ColumnName]) ? (string) null : Convert.ToString(dataRow[dataColumn.ColumnName]).Replace(“<“, “<”).Replace(“>”, “>”).Replace(“\””, “"”).Replace(“‘”, “'”).Replace(“&”, “&”);
if (!string.IsNullOrEmpty(str))
stringBuilder.Append(“<TD>”).Append(str).Append(“</TD>”);
else
stringBuilder.Append(“<TD>”).Append(“</TD>”);
++num2;
}
stringBuilder.Append(“</TR>”);
++num1;
}
stringBuilder.Append(“</TABLE>”);
return ((object) stringBuilder).ToString();
}
protected static bool IsPrimaryKey(string ColumnName, DataColumn[] PKs)
{
if (PKs == null || string.IsNullOrEmpty(ColumnName))
return false;
foreach (DataColumn dataColumn in PKs)
{
if (dataColumn.ColumnName.ToLower().Trim() == ColumnName.ToLower().Trim())
return true;
}
return false;
}
public static DataTable XmlStringToDataTable(string XmlData)
{
DataTable dataTable = (DataTable) null;
IList<DataColumn> list = (IList<DataColumn>) new List<DataColumn>();
if (string.IsNullOrEmpty(XmlData))
return (DataTable) null;
XmlDocument xmlDocument1 = new XmlDocument();
xmlDocument1.PreserveWhitespace = true;
XmlDocument xmlDocument2 = xmlDocument1;
xmlDocument2.LoadXml(XmlData);
XmlNode xmlNode1 = xmlDocument2.SelectSingleNode(“/TABLE”);
if (xmlNode1 != null)
{
dataTable = new DataTable();
int num = 0;
foreach (XmlNode xmlNode2 in xmlNode1.SelectNodes(“TR”))
{
if (num == 0)
{
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TH”))
{
bool result = false;
string str = xmlNode3.Attributes[“IsPK”].Value;
if (!string.IsNullOrEmpty(str))
{
if (!bool.TryParse(str, out result))
result = false;
}
else
result = false;
Type type = Type.GetType(xmlNode3.Attributes[“ColType”].Value);
DataColumn column = new DataColumn(xmlNode3.InnerText, type);
if (result)
list.Add(column);
if (!dataTable.Columns.Contains(column.ColumnName))
dataTable.Columns.Add(column);
}
if (list.Count > 0)
{
DataColumn[] dataColumnArray = new DataColumn[list.Count];
for (int index = 0; index < list.Count; ++index)
dataColumnArray[index] = list[index];
dataTable.PrimaryKey = dataColumnArray;
}
}
else
{
DataRow row = dataTable.NewRow();
int index = 0;
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TD”))
{
Type dataType = dataTable.Columns[index].DataType;
string s = xmlNode3.InnerText;
if (!string.IsNullOrEmpty(s))
{
try
{
s = s.Replace(“<”, “<“);
s = s.Replace(“>”, “>”);
s = s.Replace(“"”, “\””);
s = s.Replace(“'”, “‘”);
s = s.Replace(“&”, “&”);
row[index] = Convert.ChangeType((object) s, dataType);
}
catch
{
if (dataType == typeof (DateTime))
row[index] = (object) DateTime.ParseExact(s, “yyyyMMdd”, (IFormatProvider) CultureInfo.InvariantCulture);
}
}
else
row[index] = Convert.DBNull;
++index;
}
dataTable.Rows.Add(row);
}
++num;
}
}
return dataTable;
}
}
}
To find a hostname in your local network by IP address you can use:
nmblookup -A <ip>
To find a hostname on the internet you could use the host
program:
host <ip>
Or you can install nbtscan
by running:
sudo apt-get install nbtscan
And use:
nbtscan <ip>
Update 2018-05-13
You can query a name server with nslookup
. It works both ways!
nslookup <IP>
nslookup <hostname>
I do it like this:
git init
git config --global http.sslVerify false
git clone https://myurl/myrepo.git
I know this question is old but the accepted answer does not work anymore and since this is the fist link on google search i'll tell how i solved this problem.
for eclipse using ubuntu:
go to Window->Preferences->Ant->Runtime->Select Ant_Home_Entries and click on add external jars then find in file explorer where your jdk is (default is in /usr/lib/jvm/) and in the lib folder of your jdk you will find the tool.jar. select this one and click apply.
try to build your project and things should work!
note: i hadn't used ant for a long time but needed it for ycsb couchbase workload generator (http://www.couchbase.com/wiki/display/couchbase/Load+Generator+Setup) if anyone is/was stuck on this.
Try this simple function to add an dictionary item if it does not exist or update when it exists:
public void AddOrUpdateDictionaryEntry(string key, int value)
{
if (dict.ContainsKey(key))
{
dict[key] = value;
}
else
{
dict.Add(key, value);
}
}
This is the same as dict[key] = value.
You can set debug(functionName)
to debug functions as well.
https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints#function
Use numpy. array. flatten() to convert a 2D NumPy array into a 1D array
print(array_2d)
array_1d = array_2d. flatten() flatten array_2d
print(array_1d)
I will focus on why using LDAP, not what is LDAP.
The use model is similar like how people use library cards or phonebooks. When you have a task that requires “write/update once, read/query many times”, you might consider using LDAP. LDAP is designed to provide extremely fast read/query performance for a large scale of dataset. Typically you want to store only a small piece of information for each entry. The add/delete/update performance is relatively slower compared with read/query because the assumption is that you don’t do “update” that often.
Imagine you have a website that has a million registered users with thousands of page requests per second. Without LDAP, every time users click a page, even for static page viewing, you will probably need to interact with your database to validate the user ID and its digital signature for this login session. Obviously, the query to your database for user-validation will become your bottleneck. By using LDAP, you can easily offload the user validation and gain significant performance improvement. Essentially, in this example, LDAP is another optimization layer outside your database to enhance performance, not replacing any database functions.
LDAP is not just for user validation, any task that has the following properties might be a good use case for LDAP:
You need to locate ONE piece of data many times and you want it fast
You don’t care about the logic and relations between different data
You don’t update, add, or delete the data very often
The size of each data entry is small
You don’t mind having all these small pieces of data at a centralized place
Mathematically, to get percentage from two numbers:
percentage = (yourNumber / totalNumber) * 100;
And also, to calculate from a percentage :
number = (percentage / 100) * totalNumber;
In my case storage was a problem. My hard drive was full... Make some space in hardware and your site will work fine
These two methods should save you from accidentally joining two strings that both have the delimiter in them.
public static string Combine(string x, string y, char delimiter) {
return $"{ x.TrimEnd(delimiter) }{ delimiter }{ y.TrimStart(delimiter) }";
}
public static string Combine(string[] xs, char delimiter) {
if (xs.Length < 1) return string.Empty;
if (xs.Length == 1) return xs[0];
var x = Combine(xs[0], xs[1], delimiter);
if (xs.Length == 2) return x;
var ys = new List<string>();
ys.Add(x);
ys.AddRange(xs.Skip(2).ToList());
return Combine(ys.ToArray(), delimiter);
}
You can concat origin
and pathname
, if theres present a port such as example.com:80
, that will be included as well.
location.origin + location.pathname
HTML5 does not support .mkv / Matroska files but you can use this code...
<video>
<source src="video.mkv" type="video/mp4">
</video>
But it depends on the browser as to whether it will play or not. This method is known to work with Chrome.
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
Just to clarify, be aware bracket placement is important!
These can be added to any HTML tags... span, div, table, p, tr, td etc.
AngularJS
ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
Angular2+
*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.
boolean check1 = Your conditional check here...
...
Replace
data: { patientID: "1" },
with
data: "{ 'patientID': '1' }",
Further reading: 3 mistakes to avoid when using jQuery with ASP.NET
Also check to see if you are missing the www in the url which was on my case
i was testing on http://www.mywebsite.com and in the facebook app i had set http://mywebsite.com
The frameworks directory is as follow in my computer:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/Frameworks
not the directory
/Developer/SDKs/MacOSXversion.sdk/System/Library/Frameworks
Check out https://github.com/serratus/quaggaJS
"QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."
Abstract classes and interfaces are semantically different, although their usage can overlap.
An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.
An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaIf I were doing this I would probably use WCF REST on the server and a REST library on the Java/Android client.
You provide credentials in a URLRequest
instance, like this in Swift 3:
let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
// create the request
let url = URL(string: "http://www.example.com/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
Or in an NSMutableURLRequest
in Swift 2:
// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
This will work, but the i -> i
is doing some automatic unboxing which is why it "feels" strange. Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:
integers.values().stream().mapToInt(i -> i.intValue()).sum();
integers.values().stream().mapToInt(Integer::intValue).sum();
Check if you are using any sort of jquery/javascript validation on the page and try disabling it and see what happens. You can use your browser's developer tools to see if any javascript file with validate or validation is being loaded. You can also look for hidden form elements (ie. style set to display:none; or something like that) and make sure there isn't a hidden validation error on those that's not being rendered.
i wrote a simple ES6 class that may come handy. inspired by https://stackoverflow.com/a/58580918/4907364 answer
export class IntervalTimer {
private callbackStartTime;
private remaining= 0;
private paused= false;
public timerId = null;
private readonly _callback;
private readonly _delay;
constructor(callback, delay) {
this._callback = callback;
this._delay = delay;
}
pause() {
if (!this.paused) {
this.clear();
this.remaining = new Date().getTime() - this.callbackStartTime;
this.paused = true;
}
}
resume() {
if (this.paused) {
if (this.remaining) {
setTimeout(() => {
this.run();
this.paused = false;
this.start();
}, this.remaining);
} else {
this.paused = false;
this.start();
}
}
}
clear() {
clearInterval(this.timerId);
}
start() {
this.clear();
this.timerId = setInterval(() => {
this.run();
}, this._delay);
}
private run() {
this.callbackStartTime = new Date().getTime();
this._callback();
}
}
usage is pretty straightforward,
const interval = new IntervalTimer(console.log(aaa), 3000);
interval.start();
interval.pause();
interval.resume();
interval.clear();
To set the range of the x-axis, you can use set_xlim(left, right)
, here are the docs
Update:
It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:
ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)
It would most likely process them sequentially (why not just test it). But you can also do this:
make a file called curlrequests.sh
put it in a file like thus:
curl http://example.com/?update_=1
curl http://example.com/?update_=3
curl http://example.com/?update_=234
curl http://example.com/?update_=65
save the file and make it executable with chmod
:
chmod +x curlrequests.sh
run your file:
./curlrequests.sh
or
/path/to/file/curlrequests.sh
As a side note, you can chain requests with &&
, like this:
curl http://example.com/?update_=1 && curl http://example.com/?update_=2 && curl http://example.com?update_=3`
And execute in parallel using &
:
curl http://example.com/?update_=1 & curl http://example.com/?update_=2 & curl http://example.com/?update_=3
Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.
GROUP_CONCAT(artists.artistname SEPARATOR '----')
The way you've written it, you're concatenating artists.artistname
with the '----'
string using the default comma separator.
This works:
SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1
I would like to suggest new EmailAddressAttribute().IsValid(emailTxt)
for additional validation before/after validating using RegEx
Remember EmailAddressAttribute
is part of System.ComponentModel.DataAnnotations namespace
.
Joe Kington's excellent answer is already 4 years old,
Matplotlib has incrementally changed (in particular, the introduction
of the cycler
module) and the new major release, Matplotlib 2.0.x,
has introduced stylistic differences that are important from the point
of view of the colors used by default.
The color of individual lines (as well as the color of different plot
elements, e.g., markers in scatter plots) is controlled by the color
keyword argument,
plt.plot(x, y, color=my_color)
my_color
is either
(0.,0.5,0.5)
),"#008080"
(RGB) or "#008080A0"
),"k"
for black, possible values in "bgrcmykw"
),"teal"
) --- aka HTML color name (in the docs also X11/CSS4 color name),'xkcd:'
(e.g., 'xkcd:barbie pink'
),'T10'
categorical palette, (e.g., 'tab:blue'
, 'tab:olive'
),"C3"
, i.e., the letter "C"
followed by a single digit in "0-9"
).By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).
The color cycle is a property of the axes
object, and in older
releases was simply a sequence of valid color names (by default a
string of one character color names, "bgrcmyk"
) and you could set it
as in
my_ax.set_color_cycle(['kbkykrkg'])
(as noted in a comment this API has been deprecated, more on this later).
In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]
, the Vega category10 palette.
(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)
The following code shows that the color cycle notion has been deprecated
In [1]: from matplotlib import rc_params
In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
warnings.warn(self.msg_depr % (key, alt_key))
Out[2]:
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
Now the relevant property is the 'axes.prop_cycle'
In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])
Previously, the color_cycle
was a generic sequence of valid color
denominations, now by default it is a cycler
object containing a
label ('color'
) and a sequence of valid color denominations. The
step forward with respect to the previous interface is that it is
possible to cycle not only on the color of lines but also on other
line attributes, e.g.,
In [5]: from cycler import cycler
In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}
As you have seen, the cycler
objects are composable and when you iterate on a composed cycler
what you get, at each iteration, is a dictionary of keyword arguments for plt.plot
.
You can use the new defaults on a per axes
object ratio,
my_ax.set_prop_cycle(new_prop_cycle)
or you can install temporarily the new default
plt.rc('axes', prop_cycle=new_prop_cycle)
or change altogether the default editing your .matplotlibrc
file.
Last possibility, use a context manager
with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
...
to have the new cycler
used in a group of different plots, reverting to defaults at the end of the context.
The doc string of the cycler()
function is useful, but the (not so much) gory details about the cycler
module and the cycler()
function, as well as examples, can be found in the fine docs.
Some of the tutorials I found that are easy to understand are:
It makes way more sense to break up your list into page-sized chunks, and only query your database one chunk at a time. This drastically reduces server processing time and page load time, as well as gives your user smaller pieces of info to digest, so he doesn't choke on whatever crap you're trying to feed him. The act of doing this is called pagination.
A basic pagination routine seems long and scary at first, but once you close your eyes, take a deep breath, and look at each piece of the script individually, you will find it's actually pretty easy stuff
The script:
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
This tutorial is intended for developers who wish to give their users the ability to step through a large number of database rows in manageable chunks instead of the whole lot in one go.
On a linux server you can just use this commands to reconfigure Tomcat to listen on port 80:
sed -i 's|port="8080"|port="80"|g' /etc/tomcat?/server.xml
sed -i 's|#AUTHBIND=no|AUTHBIND=yes|g' /etc/default/tomcat?
service tomcat8 restart
sprintf() is the PHP function for all sorts of string formatting http://php.net/manual/en/function.sprintf.php
I use this function:
function formatDollars($dollars){
return '$ '.sprintf('%0.2f', $dollars);
}
You can use OS help for this. Here is a cross-platform solution:
1. The bellow function uses ls
and dir
and does not search recursively but it has relative paths
var exec = require('child_process').exec;
function findFiles(folder,extension,cb){
var command = "";
if(/^win/.test(process.platform)){
command = "dir /B "+folder+"\\*."+extension;
}else{
command = "ls -1 "+folder+"/*."+extension;
}
exec(command,function(err,stdout,stderr){
if(err)
return cb(err,null);
//get rid of \r from windows
stdout = stdout.replace(/\r/g,"");
var files = stdout.split("\n");
//remove last entry because it is empty
files.splice(-1,1);
cb(err,files);
});
}
findFiles("folderName","html",function(err,files){
console.log("files:",files);
})
2. The bellow function uses find
and dir
, searches recursively but on windows it has absolute paths
var exec = require('child_process').exec;
function findFiles(folder,extension,cb){
var command = "";
if(/^win/.test(process.platform)){
command = "dir /B /s "+folder+"\\*."+extension;
}else{
command = 'find '+folder+' -name "*.'+extension+'"'
}
exec(command,function(err,stdout,stderr){
if(err)
return cb(err,null);
//get rid of \r from windows
stdout = stdout.replace(/\r/g,"");
var files = stdout.split("\n");
//remove last entry because it is empty
files.splice(-1,1);
cb(err,files);
});
}
findFiles("folder","html",function(err,files){
console.log("files:",files);
})
For those still searching for a tree with CSS3, this is a fantastic piece of code I found on the net:
http://thecodeplayer.com/walkthrough/css3-family-tree
<div class="tree">
<ul>
<li>
<a href="#">Parent</a>
<ul>
<li>
<a href="#">Child</a>
<ul>
<li>
<a href="#">Grand Child</a>
</li>
</ul>
</li>
<li>
<a href="#">Child</a>
<ul>
<li><a href="#">Grand Child</a></li>
<li>
<a href="#">Grand Child</a>
<ul>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
</ul>
</li>
<li><a href="#">Grand Child</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
* {margin: 0; padding: 0;}
.tree ul {
padding-top: 20px; position: relative;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
.tree li {
float: left; text-align: center;
list-style-type: none;
position: relative;
padding: 20px 5px 0 5px;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
/*We will use ::before and ::after to draw the connectors*/
.tree li::before, .tree li::after{
content: '';
position: absolute; top: 0; right: 50%;
border-top: 1px solid #ccc;
width: 50%; height: 20px;
}
.tree li::after{
right: auto; left: 50%;
border-left: 1px solid #ccc;
}
/*We need to remove left-right connectors from elements without
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
display: none;
}
/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}
/*Remove left connector from first child and
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
border-right: 1px solid #ccc;
border-radius: 0 5px 0 0;
-webkit-border-radius: 0 5px 0 0;
-moz-border-radius: 0 5px 0 0;
}
.tree li:first-child::after{
border-radius: 5px 0 0 0;
-webkit-border-radius: 5px 0 0 0;
-moz-border-radius: 5px 0 0 0;
}
/*Time to add downward connectors from parents*/
.tree ul ul::before{
content: '';
position: absolute; top: 0; left: 50%;
border-left: 1px solid #ccc;
width: 0; height: 20px;
}
.tree li a{
border: 1px solid #ccc;
padding: 5px 10px;
text-decoration: none;
color: #666;
font-family: arial, verdana, tahoma;
font-size: 11px;
display: inline-block;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after,
.tree li a:hover+ul li::before,
.tree li a:hover+ul::before,
.tree li a:hover+ul ul::before{
border-color: #94a0b4;
}
PS: apart from the code, I also like the way the site shows it in action... really innovative.
I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.
Here's a snippet of the code that worked for me:
int pageSize = 4;
int pageNumber = (page ?? 1);
//Used the following two formulas so that it doesn't round down on the returned integer
decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));
ViewBag.TotalPages = Math.Ceiling(totalPages);
//These next two functions could maybe be reduced to one function....would require some testing and building
viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
ViewBag.OnePageofTeachers = viewModel.Teachers;
ViewBag.PageNumber = pageNumber;
return View(viewModel);
I added
using.PagedList;
to my controller as the tutorial states.
Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.
@model CSHM.ViewModels.TeacherIndexData
@using PagedList;
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.
Page @ViewBag.PageNumber of @ViewBag.TotalPages
@Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))
Hope that works for you. Let me know if it works!!
Another alternative to simulating a F5 key press would be to simply host the WebBrowser control in the Window Forms application. You use the WebBrowser.Navigate method to load your web page and then use a standard Timer and on each tick of the timer you just re-Navigate to the url which will reload the page.
As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.
df[cat]=df[cat].astype('category')
And then check df.dtypes and perform label encoding.
Swift 5.3, I believe.
The normal array wasvar myArray = ["Steve", "Bill", "Linus", "Bret"]
and you want to add "Tim"
to the array, then you can use myArray.insert("Tim", at=*index*)
so if you want to add it at the back of the array, then you can use myArray.append("Tim", at: 3)
I usually place commands in parentheses $(commandStr)
, if that doesn't help I find bash debug mode great, run the script as bash -x script
You should look for the MSI setup logs in the temp directory of your system. They will contain detailed inforamtion about why the setup failed. I had a similar installation problem with Visual Studio 2008 which I was able to resolve by studying the logs.
More space:
android:letterSpacing="0.1"
Less space:
android:letterSpacing="-0.07"
If you only want to change form's action, I prefer changing action on-form-submit, rather than on-input-change. It fires only once.
$('#search-form').submit(function(){
var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
$("#search-form").attr("action", "/search/" + formAction);
});
null
removes it:
[attr.checked]="value ? '' : null"
or
[attr.checked]="value ? 'checked' : null"
When the HTML element where you add this binding does not have a property with the name used in the binding (checked
in this case) and also no Angular component or directive is applied to the same element that has an @Input() checked;
, then [xxx]="..."
can not be used.
See also What is the difference between properties and attributes in HTML?
Alternatives are [style.xxx]="..."
, [attr.xxx]="..."
, [class.xxx]="..."
depending on what you try to accomplish.
Because <input>
only has a checked
attribute, but no checked
property [attr.checked]="..."
is the right way for this specific case.
A common pitfall is also that for [attr.xxx]="..."
bindings the value (...
) is always stringified. Only properties and @Input()
s can receive other value types like boolean, number, object, ...
Most properties and attributes of elements are connected and have the same name.
When bound to the attribute the property also only receives the stringified value from the attribute.
When bound to the property the property receives the value bound to it (boolean, number, object, ...) and the attribute again the stringified value.
Two cases where attribute and property names do not match.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor (see the first sentence of the description htmlFor property reflects the value of the for
- for
probably didn't work because it's a keyword in C or JavaScript)
Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [for]="
even though no such property exists (same for colspan
)
This is an old question but there is some newer guidance in PEP 565 that to turn off all warnings if you're writing a python application you should use:
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
The reason this is recommended is that it turns off all warnings by default but crucially allows them to be switched back on via python -W
on the command line or PYTHONWARNINGS
.
@broc.seib has a sophisticated answer, I just want to point out that instead of pressing y
to get the permanent link, github now has a very simple UI that helps you to achieve it
Select line by clicking on the line number or select multiple lines by downholding shift
(same as how you select multiple folders in file explorer)
on the right hand corner of the first line you selected, expand ...
and click copy permalink
https://github.com/python/cpython/blob/c82b7f332aff606af6c9c163da75f1e86514125e/Doc/Makefile#L1-L4
If we want only first 5 characters from any field, then this can be achieved by Left Attribute
Vessel = f.Vessel !=null ? f.Vessel.Left(5) : ""
For a popup javascript is required. Put this in your header:
<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>
And this in your body:
<input type="button" onclick="myFunction()" value="Show alert box">
When the button is pressed a box pops up with the message set in the header.
This can be put in any html or php file without the php tags.
-----EDIT-----
To display it using php try this:
<?php echo '<script>myfunction()</script>'; ?>
It may not be 100% correct but the principle is the same.
To display different messages you can either create lots of functions or you can pass a variable in to the function when you call it.
It is not certain that any global ECMAScript variables have been exported and html/css does not necessarily indicate React. So look in the .js.
Method 1: Look in ECMAScript:
The version number is exported by both modules react-dom and react but those names are often removed by bundling and the version hidden inside an execution context that cannot be accessed. A clever break point may reveal the value directly, or you can search the ECMAScript:
Method 2: Use a DOM breakpoint:
Inspect Element
Elements
paneBreak On… - subtree modifications
Sources
paneCall Stack
sub-panerender
entry, this is ReactDOM.render
render
, ie. the code that invokes renderreact-dom
module exports object
version: "15.6.2"
, ie. all values exported by react-dom
The version is also injected into React dev tools, but as far as I know not displayed anywhere.
Get-WmiObject Win32_Processor | Select LoadPercentage | Format-List
This gives you CPU load.
Get-WmiObject Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select Average
I got tired of dealing with this problem so I wrote a NotNull() function to help me out.
Public Shared Function NotNull(Of T)(ByVal Value As T, ByVal DefaultValue As T) As T
If Value Is Nothing OrElse IsDBNull(Value) Then
Return DefaultValue
Else
Return Value
End If
End Function
Usage:
If NotNull(myItem("sID"), "") = sID Then
' Do something
End If
My NotNull() function has gone through a couple of overhauls over the years. Prior to Generics, I simply specified everything as an Object. But I much prefer the Generic version.
Use parameter expansion, if the value is already stored in a variable.
$ str="GenFiltEff=7.092200e-01"
$ value=${str#*=}
Or use read
$ IFS="=" read name value <<< "GenFiltEff=7.092200e-01"
Either way,
$ echo $value
7.092200e-01
The Host
property will return the domain name you used when accessing the site. So, in your development environment, since you're requesting
http://localhost:950/m/pages/Searchresults.aspx?search=knife&filter=kitchen
It's returning localhost
. You can break apart your URL like so:
Protocol: http
Host: localhost
Port: 950
PathAndQuery: /m/pages/SearchResults.aspx?search=knight&filter=kitchen
Just used the @Uday answer code and build a reverse clock of hr:mm
Was just playing, so thought if anyone would might need this, so sharing the fiddle in comments (Dnt know why stackover flow is not allowing me to paste the link here)
I'm not very familiar with the Visitor pattern. Let's see if I got it right. Suppose you have a hierarchy of animals
class Animal { };
class Dog: public Animal { };
class Cat: public Animal { };
(Suppose it is a complex hierarchy with a well-established interface.)
Now we want to add a new operation to the hierarchy, namely we want each animal to make its sound. As far as the hierarchy is this simple, you can do it with straight polymorphism:
class Animal
{ public: virtual void makeSound() = 0; };
class Dog : public Animal
{ public: void makeSound(); };
void Dog::makeSound()
{ std::cout << "woof!\n"; }
class Cat : public Animal
{ public: void makeSound(); };
void Cat::makeSound()
{ std::cout << "meow!\n"; }
But proceeding in this way, each time you want to add an operation you must modify the interface to every single class of the hierarchy. Now, suppose instead that you are satisfied with the original interface, and that you want to make the fewest possible modifications to it.
The Visitor pattern allows you to move each new operation in a suitable class, and you need to extend the hierarchy's interface only once. Let's do it. First, we define an abstract operation (the "Visitor" class in GoF) which has a method for every class in the hierarchy:
class Operation
{
public:
virtual void hereIsADog(Dog *d) = 0;
virtual void hereIsACat(Cat *c) = 0;
};
Then, we modify the hierarchy in order to accept new operations:
class Animal
{ public: virtual void letsDo(Operation *v) = 0; };
class Dog : public Animal
{ public: void letsDo(Operation *v); };
void Dog::letsDo(Operation *v)
{ v->hereIsADog(this); }
class Cat : public Animal
{ public: void letsDo(Operation *v); };
void Cat::letsDo(Operation *v)
{ v->hereIsACat(this); }
Finally, we implement the actual operation, without modifying neither Cat nor Dog:
class Sound : public Operation
{
public:
void hereIsADog(Dog *d);
void hereIsACat(Cat *c);
};
void Sound::hereIsADog(Dog *d)
{ std::cout << "woof!\n"; }
void Sound::hereIsACat(Cat *c)
{ std::cout << "meow!\n"; }
Now you have a way to add operations without modifying the hierarchy anymore. Here is how it works:
int main()
{
Cat c;
Sound theSound;
c.letsDo(&theSound);
}
If you're only interested in the output from the process, it's easiest to use subprocess' check_output function:
output = subprocess.check_output(["command", "arg1", "arg2"]);
Then output holds the program output to stdout. Check the link above for more info.
There are several approaches.
One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)?
Making a Regex Django URL Token Optional
Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.
urlpatterns = patterns('',
url(r'^project_config/$', views.foo),
url(r'^project_config/(?P<product>\w+)/$', views.foo),
url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
)
Keep in mind that in your view you'll also need to set a default for the optional URL parameter, or you'll get an error:
def foo(request, optional_parameter=''):
# Your code goes here
Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.
//click handler
function add_event(event, paramA, paramB)
{
//do something with your parameters
alert(paramA ? 'paramA:' + paramA : '' + paramB ? ' paramB:' + paramB : '');
}
//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});
//or use variables
var a = 'first',
b = 'second';
$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});
$CurrentFolder = "H:\Documents"
$Query = "Select * from Win32_NetworkConnection where LocalName = '" + $CurrentFolder.Substring( 0, 2 ) + "'"
( Get-WmiObject -Query $Query ).RemoteName
OR
$CurrentFolder = "H:\Documents"
$Tst = $CurrentFolder.Substring( 0, 2 )
( Get-WmiObject -Query "Select * from Win32_NetworkConnection where LocalName = '$Tst'" ).RemoteName
Lets assume you created a Ubuntu VM on your local machine. It's IP address is 192.168.1.104.
You login into VM, and installed Kubernetes. Then you created a pod where nginx image running on it.
1- If you want to access this nginx pod inside your VM, you will create a ClusterIP bound to that pod for example:
$ kubectl expose deployment nginxapp --name=nginxclusterip --port=80 --target-port=8080
Then on your browser you can type ip address of nginxclusterip with port 80, like:
2- If you want to access this nginx pod from your host machine, you will need to expose your deployment with NodePort. For example:
$ kubectl expose deployment nginxapp --name=nginxnodeport --port=80 --target-port=8080 --type=NodePort
Now from your host machine you can access to nginx like:
In my dashboard they appear as:
Below is a diagram shows basic relationship.