You can use DataSet.Tables(0).Columns.Contains(name)
to check whether the DataTable
contains a column with a particular name.
You need something like this:
foreach(DataColumn c in dr.Table.Columns)
{
MessageBox.Show(c.ColumnName);
}
try table.Rows.add(row);
after your for
statement.
Try avoiding unnecessary loops and go for this if needed.
string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
//your logic goes here
}
else
{
//your logic goes here
}
If you want to search by specific ID then there should be a primary key in a table.
I've done this a lot myself. If you just need a comma separated list for all of row values you can do this:
StringBuilder sb = new StringBuilder();
foreach (DataRow row in results.Tables[0].Rows)
{
sb.AppendLine(string.Join(",", row.ItemArray));
}
A StringBuilder is the preferred method as string concatenation is significantly slower for large amounts of data.
for (int i=0; i<dt_pattern.Rows.Count; i++)
{
DataRow dr = dt_pattern.Rows[i];
}
In the loop, you can now reference row i+1 (assuming there is an i+1)
You can use
try {
user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
// do something if you want
}
You need to loop over loadDT.Columns
, like this:
foreach (DataColumn column in loadDT.Columns)
{
Console.Write("Item: ");
Console.Write(column.ColumnName);
Console.Write(" ");
Console.WriteLine(row[column]);
}
Be careful on datatype. If not match it will throw an error.
var fieldName = dataRow.Field<DataType>("fieldName");
DataTable Assetdaterow =
(
from s in dtResourceTable.AsEnumerable()
where s.Field<DateTime>("Date") == Convert.ToDateTime(AssetDate)
select s
).CopyToDataTable();
You can simply use DataColumnCollection.IndexOf
So that you can get the index of the required column by name then use it with your row:
row[dt.Columns.IndexOf("ColumnName")] = columnValue;
You can use ImportRow
method to copy Row from DataTable to DataTable with the same schema:
var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);
Update:
With your new Edit, I believe:
var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];
will work
Just keep going with your code - you're on the right track:
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", typeof(System.Int32));
foreach(DataRow row in dt.Rows)
{
//need to set value to NewColumn column
row["NewColumn"] = 0; // or set it to some other value
}
// possibly save your Dataset here, after setting all the new values
I know this has been answered already and it's an old question, but here's an extension method to do the same:
public static class DataExtensions
{
public static bool AreAllCellsEmpty(this DataRow row)
{
var itemArray = row.ItemArray;
if(itemArray==null)
return true;
return itemArray.All(x => string.IsNullOrWhiteSpace(x.ToString()));
}
}
And you use it like so:
if (dr.AreAllCellsEmpty())
// etc
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]
index=spell_list.index("Annual")
print(index)
It sounds like you need to some background reading on what an FFT is (e.g. http://en.wikipedia.org/wiki/FFT). But to answer your questions:
Why does the x-axis (frequency) end at 500?
Because the input vector is length 1000. In general, the FFT of a length-N
input waveform will result in a length-N
output vector. If the input waveform is real, then the output will be symmetrical, so the first 501 points are sufficient.
Edit: (I didn't notice that the example padded the time-domain vector.)
The frequency goes to 500 Hz because the time-domain waveform is declared to have a sample-rate of 1 kHz. The Nyquist sampling theorem dictates that a signal with sample-rate fs
can support a (real) signal with a maximum bandwidth of fs/2
.
How do I know the frequencies are between 0 and 500?
See above.
Shouldn't the FFT tell me, in which limits the frequencies are?
No.
Does the FFT only return the amplitude value without the frequency?
The FFT simply assigns an amplitude (and phase) to every frequency bin.
Drawbacks of using TCP for live video:
FYI, please don't use the word "packages" when describing networks. Networks send "packets".
UPDATE - Even less wordy version
INSERT INTO tableName (col1, col2, col3, col4, col5)
VALUES ('val1', 'val2', 'val3', 'val4', 'val5'),
('val1', 'val2', 'val3', 'val4', 'val5'),
('val1', 'val2', 'val3', 'val4', 'val5'),
('val1', 'val2', 'val3', 'val4', 'val5')
The following also works for DB2 and is slightly less wordy
INSERT INTO tableName (col1, col2, col3, col4, col5)
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5')
Adding on to what has been already answered by Guna Sekaran. Jenkins need the user jenkins to be present in order to run the jenkins as a service.
To add user fire 'useradd jenkins' as root and fire 'passwd jenkins' as root before starting Jenkins as a service.
As Jake points out, TARGET_IPHONE_SIMULATOR
is a subset of TARGET_OS_IPHONE
.
Also, TARGET_OS_IPHONE
is a subset of TARGET_OS_MAC
.
So a better approach might be:
#ifdef _WIN64
//define something for Windows (64-bit)
#elif _WIN32
//define something for Windows (32-bit)
#elif __APPLE__
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
// define something for simulator
#elif TARGET_OS_IPHONE
// define something for iphone
#else
#define TARGET_OS_OSX 1
// define something for OSX
#endif
#elif __linux
// linux
#elif __unix // all unices not caught above
// Unix
#elif __posix
// POSIX
#endif
Few ways of declaring a typed array in TypeScript
are
const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];
// or, if you have values to initialize
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];
From @NHG comment — works perfectly
{% for post in posts|slice(0,10) %}
That's no struts related problem but rather plain HMTL/CSS.
I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.
int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
imageView.setImageResource(id);
someLinearLayout.addView(imageView);
Just add extra data to the Intent you use to call your activity.
In the caller activity :
Intent i = new Intent(this, TheNextActivity.class);
i.putExtra("id", id);
startActivity(i);
Inside the onCreate() of the activity you call :
Bundle b = getIntent().getExtras();
int id = b.getInt("id");
On bitbucket.org the voted solution wouldn't work. Instead, when using headers (with ##), it is possible to reference them as anchors by prefixing them as #markdown-header-my-header-name, where #markdown-header- is an implicit prefix generated by the renderer, and the rest is the lower-cased header title with dashes replacing spaces.
Example
## My paragraph title
will produce an implicit anchor like this
#markdown-header-my-paragraph-title
The whole URL before each anchor reference is optional, i.e.
[Some text](#markdown-header-my-paragraph-title)
is equivalent of
[Some text](https://bitbucket.org/some_project/some_page#markdown-header-my-paragraph-title)
provided that they are in the same page.
Source: https://bitbucket.org/tutorials/markdowndemo/overview (edit source of this .md file and look at how anchors are made).
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd
, although in practice almost all browsers also support yyyy/mm/dd
as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy
, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split
splits a string on the given delimiter. Then we use parseInt
to convert the strings into numbers, and we use the new Date
constructor to build a Date
from those parts: The third part will be the year, the second part the month, and the first part the day. Date
uses zero-based month numbers, and so we have to subtract one from the month number.
Use the various urlparse
functions to tear apart the existing URL, urllib.urlencode()
on the combined dictionary, then urlparse.urlunparse()
to put it all back together again.
Or just take the result of urllib.urlencode()
and concatenate it to the URL appropriately.
No need of storing resultSet values into String and again setting into POJO class. Instead set at the time you are retrieving.
Or best way switch to ORM tools like hibernate instead of JDBC which maps your POJO object direct to database.
But as of now use this:
List<User> users=new ArrayList<User>();
while(rs.next()) {
User user = new User();
user.setUserId(rs.getString("UserId"));
user.setFName(rs.getString("FirstName"));
...
...
...
users.add(user);
}
Here's a quick step through.
Assume you have a folder called deploy
, with your lambda file inside call lambda_function.py
. Let's assume this file looks something like this. (p1
and p2
represent third-party packages.)
import p1
import p2
def lambda_handler(event, context):
# more code here
return {
"status": 200,
"body" : "Hello from Lambda!",
}
For every third-party dependency, you need to pip install <third-party-package> --target .
from within the deploy
folder.
pip install p1 --target .
pip install p2 --target .
Once you've done this, here's what your structure should look like.
deploy/
+-- lambda_function.py
+-- p1/
¦ +-- __init__.py
¦ +-- a.py
¦ +-- b.py
¦ +-- c.py
+-- p2/
+-- __init__.py
+-- x.py
+-- y.py
+-- z.py
Finally, you need to zip
all the contents within the deploy
folder to a compressed file. On a Mac or Linux, the command would look like zip -r ../deploy.zip *
from within the deploy
folder. Note that the -r
flag is for recursive subfolders.
The structure of the file zip file should mirror the original folder.
deploy.zip/
+-- lambda_function.py
+-- p1/
¦ +-- __init__.py
¦ +-- a.py
¦ +-- b.py
¦ +-- c.py
+-- p2/
+-- __init__.py
+-- x.py
+-- y.py
+-- z.py
Upload the zip file and specify the <file_name>.<function_name>
for Lambda to enter into your process, such as lambda_function.lambda_handler
for the example above.
I know that in order to use certain features of the gridview in .NET, you need a primary key in order for the gridview to know which row needs updating/deleting. General practice should be to have a primary key or primary key cluster. I personally prefer the former.
This is really easy: Example
//my object
var sendData = {field1:value1, field2:value2};
//add element
sendData['field3'] = value3;
It can be done simply using PGPASSWORD. I am using psql 9.5.10. In your case the solution would be
PGPASSWORD=password psql -U myuser < myscript.sql
Could not commit JPA transaction: Transaction marked as rollbackOnly
This exception occurs when you invoke nested methods/services also marked as @Transactional
. JB Nizet explained the mechanism in detail. I'd like to add some scenarios when it happens as well as some ways to avoid it.
Suppose we have two Spring services: Service1
and Service2
. From our program we call Service1.method1()
which in turn calls Service2.method2()
:
class Service1 {
@Transactional
public void method1() {
try {
...
service2.method2();
...
} catch (Exception e) {
...
}
}
}
class Service2 {
@Transactional
public void method2() {
...
throw new SomeException();
...
}
}
SomeException
is unchecked (extends RuntimeException) unless stated otherwise.
Scenarios:
Transaction marked for rollback by exception thrown out of method2
. This is our default case explained by JB Nizet.
Annotating method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating both method1
and method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating method2
with @Transactional(noRollbackFor = SomeException)
prevents marking transaction for rollback (no exception thrown when exiting from method1
).
Suppose method2
belongs to Service1
. Invoking it from method1
does not go through Spring's proxy, i.e. Spring is unaware of SomeException
thrown out of method2
. Transaction is not marked for rollback in this case.
Suppose method2
is not annotated with @Transactional
. Invoking it from method1
does go through Spring's proxy, but Spring pays no attention to exceptions thrown. Transaction is not marked for rollback in this case.
Annotating method2
with @Transactional(propagation = Propagation.REQUIRES_NEW)
makes method2
start new transaction. That second transaction is marked for rollback upon exit from method2
but original transaction is unaffected in this case (no exception thrown when exiting from method1
).
In case SomeException
is checked (does not extend RuntimeException), Spring by default does not mark transaction for rollback when intercepting checked exceptions (no exception thrown when exiting from method1
).
See all scenarios tested in this gist.
If your mock involves a network request, another alternative is to have a real test server to hit. You can use a service to generate a request and response for your testing.
setting the overflow
should take care of it, but you need to set the height of Content
also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.
See Example: http://jsfiddle.net/ftkbL/1/
I have created this Plunker based on your example that updates the object equal to newItem.id
Here's the snippet of my functions:
showUpdatedItem(newItem){
let updateItem = this.itemArray.items.find(this.findIndexToUpdate, newItem.id);
let index = this.itemArray.items.indexOf(updateItem);
this.itemArray.items[index] = newItem;
}
findIndexToUpdate(newItem) {
return newItem.id === this;
}
Hope this helps.
it's very easy
Search for
<Directory "C:/xampp/phpMyAdmin">
AllowOverride AuthConfig
**Require local** Replace with **Require all granted**
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>```
Go to xampp > config > click on service and port setting and change apache port 8080
It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.
If you want to fade to black(ish), you'll need a black container around the image. Something like:
.ctr {
margin: 0;
padding: 0;
background-color: black;
display: inline-block;
}
and
<div class="ctr"><img ... /></div>
FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:
ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg
Let's explain the options:
-i input file the path to the input file
-ss 01:23:45 seek the position to the specified timestamp
-vframes 1 only handle one video frame
output.jpg output filename, should have a well-known extension
The -ss
parameter accepts a value in the form HH:MM:SS[.xxx]
or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.
I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.
This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.
If you're ever dynamically generating page content or loading content through AJAX, the following example is really the way you should go:
body
of the document, so regardless of what elements are added, moved, removed and re-added, all descendants of body
matching the selector specified will retain proper binding.The Code:
// Define the element we wish to bind to.
var bind_to = ':input';
// Prevent double-binding.
$(document.body).off('change', bind_to);
// Bind the event to all body descendants matching the "bind_to" selector.
$(document.body).on('change keyup', bind_to, function(event) {
alert('something happened!');
});
Please notice! I'm making use of $.on()
and $.off()
rather than other methods for several reasons:
$.live()
and $.die()
are deprecated and have been omitted from more recent versions of jQuery.$.change()
and $.keyup()
separately, or pass the same function declaration to each function called; Duplicating logic... Which is absolutely unacceptable.$.bind()
does not dynamically bind to elements as they are created. Therefore if you bind to :input
and then add an input to the DOM, that bind method is not attached to the new input. You'd then need to explicitly un-bind and then re-bind to all elements in the DOM (otherwise you'll end up with binds being duplicated). This process would need to be repeated each time an input was added to the DOM.Right click on your project > Open Module Setting > Select "Project" in "Project Setting" section
Change the Project SDK to latest(may be API 21) and Project language level to 7+
If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.
At first courtesy goes to @Charuka .
You can use android:progressDrawable="@drawable/seekbar"
instead of android:background="@drawable/seekbar"
.
progressDrawable used for the progress mode.
You should try with
Defines the minimum height of the view. It is not guaranteed the view will be able to achieve this minimum height (for example, if its parent layout constrains it with less available height).
Defines the minimum width of the view. It is not guaranteed the view will be able to achieve this minimum width (for example, if its parent layout constrains it with less available width)
android:minHeight="25p"
android:maxHeight="25dp"
FYI:
Using android:minHeight and android:maxHeight is not good solutions .Need to rectify your Custom Seekbar (From Class Level) .
What happens in reality in case you pass string as a first parameter of function
setTimeout(
'string'
,number
)
is value of first param got evaluated when it is time to run (after number
of miliseconds passed).
Basically it is equal to
setTimeout(
eval('string')
,number
)
This is
an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.
So samples which you refer are not good samples, and may be given in different context or just simple typo.
If you invoke like this setTimeout(something, number)
, first parameter is not string, but pointer to a something called something
. And again if something
is string - then it will be evaluated. But if it is function, then function will be executed.
jsbin sample
For a fresh new Mac, you need to follow below steps:-
Xcode
sudo easy_install pip
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew doctor
brew doctor
brew install python3
And you are done, just type python3
on terminal and you will see python 3 installed.
What about using a tabular inside \author{}
, just like in IEEE macros:
\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c}
I. M. Author & M. Y. Coauthor \\
My Department & Coauthor Department \\
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle
\end{document}
This will produce two columns authors with any documentclass
.
Results:
You can always try this:
/home/user/anaconda3/bin/pip install -r requirements.txt
This simply uses the pip installed in the conda environment. If pip is not preinstalled in your environment you can always run the following command
conda install pip
Here is another usage :
#!/bin/bash
array=( "$@" )
arraylength=${#array[@]}
for (( i=0; i<${arraylength}; i++ ));
do
echo "${array[$i]}"
done
Make a new folder inside htdocs and access it in browser.Like this or this. Always start Apache when you start working or check whether it has started (in Control panel of xampp).
The problem of most of the answers, that they are good for unique items in list. If items are not unique and you still want to know whether there is an intersection, you should count items:
from collections import Counter as count
def listContains(l1, l2):
list1 = count(l1)
list2 = count(l2)
return list1&list2 == list1
print( listContains([1,1,2,5], [1,2,3,5,1,2,1]) ) # Returns True
print( listContains([1,1,2,8], [1,2,3,5,1,2,1]) ) # Returns False
You can also return the intersection by using ''.join(list1&list2)
There's a way which maybe not perfect, but can meet your requirement. The main point here is use a special dimension to restrict the height. But at the same time, width actually is free, as the max width is big enough.
package test;
import java.awt.*;
import javax.swing.*;
public final class TestFrame extends Frame{
public TestFrame(){
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setPreferredSize(new Dimension(500, 200));
p.setMaximumSize(new Dimension(10000, 200));
p.add(new JLabel("TEST: "));
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
p1.setMaximumSize(new Dimension(10000, 200));
p1.add(new JTextField(50));
p.add(p1);
this.setLayout(new BorderLayout());
this.add(p, BorderLayout.CENTER);
}
//TODO: GUI CREATE
}
That work fine in Ajax call back to update select from JSON object
function UpdateList() {
var lsUrl = '@Url.Action("Action", "Controller")';
$.get(lsUrl, function (opdata) {
$.each(opdata, function (key, value) {
$('#myselect').append('<option value=' + key + '>' + value + '</option>');
});
});
}
A lot of the middleware was pulled out of the Express core in v4, and put into separate modules. The basic auth module is here: https://github.com/expressjs/basic-auth-connect
Your example would just need to change to this:
var basicAuth = require('basic-auth-connect');
app.use(basicAuth('username', 'password'));
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox): http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
I prefer not to alter the path hierarchy, but instead deal with git specifically...knowing that I'm never going to use old git to do what new git will now manage. This is a brute force solution.
NOTE: I installed XCode on Yosemite (10.10.2) clean first.
I then installed from the binary available on git-scm.com.
$ which git
/usr/bin/git
$ cd /usr/bin
$ sudo ln -sf /usr/local/git/bin/git
$ sudo ln -sf /usr/local/git/bin/git-credential-osxkeychain
$ sudo ln -sf /usr/local/git/bin/git-cvsserver
$ sudo ln -sf /usr/local/git/bin/git-receive-pack
$ sudo ln -sf /usr/local/git/bin/git-shell
$ sudo ln -sf /usr/local/git/bin/git-upload-archive
$ sudo ln -sf /usr/local/git/bin/git-upload-pack
$ ls -la
(you should see your new symlinks)
You can get access token using FB.getAuthResponse()['accessToken']
:
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Edit:
Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse();
If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log
lines or use a log-failsafe script such as:
if (typeof(console) == "undefined") { console = {}; }
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }
If you ever have a choice between a reflective solution and a non-reflective solution, never pick the reflective one (involving Class objects). It's not that it's "Wrong" or anything, but anything involving reflection is generally less obvious and less clear.
all of you can test this example and easy to understand.
Name: <input type="text" id="text" class ="input">
<input type="text" id="text1" class ="input">
Gender: <input type="radio" id="m" class="Rm" name="Rmale" value="Male">
<input type="radio" id="f" class="Rm" name="Rfemale" value="Female">
Course: <input type="checkbox" id="math" class="cm" name="Cmath" value="Math">
<input type="checkbox" id="physic" class="cm" name="Cphysic" value="Physic">
<input type="checkbox" id="eng" class="cm" name="Ceng" value="English">
<button type="button" id="b1">show</button>
// javascript
<script>
function getData(input){
return document.getElementById(input).value;
}
function dataByClassName(st){
var value=document.getElementsByClassName(st)
for(var i=0;i < value.length;i++){
if(value[i].checked){
return value[i].value;
}
}
}
document.getElementById("b1").onclick = function ()
{
var st={
name : getData("text")+getData("text1"),
gender : dataByClassName("Rm"),
course : dataByClassName("cm")
};
alert(st.name+" "+st.gender+" "+st.course);
};
</script>
Ubuntu 10.04 comes with the Suhosin patch only, which does not give you configuration options. But you can install php5-suhosin to solve this:
apt-get update
apt-get install php5-suhosin
Now you can edit /etc/php5/conf.d/suhosin.ini and set:
suhosin.memory_limit = 1G
Then using ini_set will work in a script:
ini_set('memory_limit', '256M');
If you use require.js AMD loader:
// path config
requirejs.config({
paths: {
jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js',
tether: '//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min',
bootstrap: '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min',
},
shim: {
bootstrap: {
deps: ['jquery']
}
}
});
//async loading
requirejs(['tether'], function (Tether) {
window.Tether = Tether;
requirejs(['bootstrap']);
});
Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \
escapes, etc.
Example:
$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")
The Bash manual has this to say:
Enclosing characters in single quotes (
'
) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.Enclosing characters in double quotes (
"
) preserves the literal value of all characters within the quotes, with the exception of$
,`
,\
, and, when history expansion is enabled,!
. The characters$
and`
retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters:$
,`
,"
,\
, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an!
appearing in double quotes is escaped using a backslash. The backslash preceding the!
is not removed.The special parameters
*
and@
have special meaning when in double quotes (see Shell Parameter Expansion).
constructor() is the default method in the Component life cycle and is used for dependency injection. Constructor is a Typescript Feature.
ngOnInit() is called after the constructor and ngOnInit is called after the first ngOnChanges.
i.e.:
Constructor() --> ngOnChanges() --> ngOnInit()
as mentioned above ngOnChanges()
is called when an input or output binding value changes.
Have you tried DATENAME(MONTH, S0.OrderDateTime)
?
Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.
For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).
add it in your index.php file, and it will work on all over your site
if ( function_exists( 'date_default_timezone_set' ) ) {
date_default_timezone_set('Asia/Kolkata');
}
I agree that it is not possible in general.
The only thing CSS3 can do (which helped in my case) is to select elements that have no children:
table td:empty
{
background-color: white;
}
Or have any children (including text):
table td:not(:empty)
{
background-color: white;
}
cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n'
A short explanation:
find
finds files (quite obviously)
.
is the current directory, which after the cd
is /tmp
(IMHO this is more flexible than having /tmp
directly in the find
command. You have only one place, the cd
, to change, if you want more actions to take place in this folder)
-maxdepth 1
and -mindepth 1
make sure that find
only looks in the current directory and doesn't include .
itself in the result
-type d
looks only for directories
-printf '%f\n
prints only the found folder's name (plus a newline) for each hit.
Et voilà!
I am using an ImageView in an RelativeLayout that overlays with my normal layout. No code required. It sizes the image to the full height of the screen (or any other layout you use) and then crops the picture left and right to fit the width. In my case, if the user turns the screen, the picture may be a tiny bit too small. Therefore I use match_parent, which will make the image stretch in width if too small.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/main_backgroundImage"
android:layout_width="match_parent"
//comment: Stretches picture in the width if too small. Use "wrap_content" does not stretch, but leaves space
android:layout_height="match_parent"
//in my case I always want the height filled
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
//will crop picture left and right, so it fits in height and keeps aspect ratio
android:contentDescription="@string/image"
android:src="@drawable/your_image" />
<LinearLayout
android:id="@+id/main_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
I've found the best method is to write your default CSS for the older browsers, as older browsers including i.e. 5.5, 6, 7 and 8. Can't read @media. When I use @media I use it like this:
<style type="text/css">
/* default styles here for older browsers.
I tend to go for a 600px - 960px width max but using percentages
*/
@media only screen and (min-width: 960px) {
/* styles for browsers larger than 960px; */
}
@media only screen and (min-width: 1440px) {
/* styles for browsers larger than 1440px; */
}
@media only screen and (min-width: 2000px) {
/* for sumo sized (mac) screens */
}
@media only screen and (max-device-width: 480px) {
/* styles for mobile browsers smaller than 480px; (iPhone) */
}
@media only screen and (device-width: 768px) {
/* default iPad screens */
}
/* different techniques for iPad screening */
@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
/* For portrait layouts only */
}
@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
/* For landscape layouts only */
}
</style>
But you can do whatever you like with your @media, This is just an example of what I've found best for me when building styles for all browsers.
Also! If you're looking for printability you can use @media print{}
.crop {
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
width:100px;
}?
compgen -c python | grep -P '^python\d'
This lists some other python things too, But hey, You can identify all python versions among them.
Putty doesn't use openssh key files - there is a utility in putty suite to convert them.
edit: it is called puttygen
git log --grep=<pattern>
Limit the commits output to ones with log message that matches the
specified pattern (regular expression).
Try this,
this.props.router.push('/foo')
warning works for versions prior to v4
and
this.props.history.push('/foo')
for v4 and above
There are few steps to overcome this problem:
The problem solved: The problem raised to me at the uninstallation on openfire server.
You need to transform your data to long format and shouldn't use $
inside aes
:
DF <- read.table(text="Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10", header=TRUE)
library(reshape2)
DF1 <- melt(DF, id.var="Rank")
library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +
geom_bar(stat = "identity")
This should work in most cases.
SELECT * FROM myTable WHERE concat('',col1 * 1) = col1
It doesn't work for non-standard numbers like
1e4
1.2e5
123.
(trailing decimal)I did this plunker to explore one way to do what you want.
Here I get mystyle
from the parent component but you can get it from a service.
import {Component, View} from 'angular2/angular2'
@Component({
selector: '[my-person]',
inputs: [
'name',
'mystyle: customstyle'
],
host: {
'[style.backgroundColor]': 'mystyle.backgroundColor'
}
})
@View({
template: `My Person Component: {{ name }}`
})
export class Person {}
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
Put your style.css
directly into the webapp/css
folder, not into the WEB-INF
folder.
Then add the following code into your spring-dispatcher-servlet.xml
<mvc:resources mapping="/css/**" location="/css/" />
and then add following code into your jsp page
<link rel="stylesheet" type="text/css" href="css/style.css"/>
I hope it will work.
Try this:
ORDER BY 1, 2
OR
ORDER BY rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService
Here is how I got it to work if you just want to get it back to your first option e.g. "Choose an option" "Select_id_wrap" is obviously the div around the select, but I just want to make that clear just in case it has any bearing on how this works. Mine resets to a click function but I'm sure it will work inside of an on change as well...
$("#select_id_wrap").find("select option").prop("selected", false);
Try find
. You can look it up exactly in the man page, but it's sorta like this:
find [start directory] -name [what to find]
so for your example
find . -name "*.txt"
should give you what you want.
If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Note- position really matters add google() before jcenter()
And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
check these links below for more details-
As one would expect, WebKit's support of tel:
extends to the Android mobile browser as well - FYI
If your emulator x86 this method works your me.
Download and install http://opengapps.org/app/opengapps-app-v16.apk. And select nano pack
More info http://opengapps.org/app/
Lets give an example that would explain the difference between hashtable and dictionary.
Here is a method that implements hashtable
public void MethodHashTable()
{
Hashtable objHashTable = new Hashtable();
objHashTable.Add(1, 100); // int
objHashTable.Add(2.99, 200); // float
objHashTable.Add('A', 300); // char
objHashTable.Add("4", 400); // string
lblDisplay1.Text = objHashTable[1].ToString();
lblDisplay2.Text = objHashTable[2.99].ToString();
lblDisplay3.Text = objHashTable['A'].ToString();
lblDisplay4.Text = objHashTable["4"].ToString();
// ----------- Not Possible for HashTable ----------
//foreach (KeyValuePair<string, int> pair in objHashTable)
//{
// lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
//}
}
The following is for dictionary
public void MethodDictionary()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
//dictionary.Add(1, -2); // Compilation Error
foreach (KeyValuePair<string, int> pair in dictionary)
{
lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
}
}
Very simple:
import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']
No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/
directory, or Scripts\
on Windows).
The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.
This should work:
reload(my.module)
From the Python docs
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.
If running Python 3.4 and up, do import importlib
, then do importlib.reload(nameOfModule)
.
Don't forget the caveats of using this method:
When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.
If a module imports objects from another module using from ... import ...
, calling reload()
for the other module does not redefine the objects imported from it — one way around this is to re-execute the from
statement, another is to use import
and qualified names (module.*name*
) instead.
If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.
Yes, compare it to the value it was before it changed.
var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
Another option is to only trigger your changed function on certain keys. Use e.KeyCode
to figure out what key was pressed.
Just dump the data in delimited-text format.
The boolean
values are compiled to int
data type in JVM. See here.
Try it:
int rc=dgvDataRc.CurrentCell.RowIndex;** //for find the row index number
MessageBox.Show("Current Row Index is = " + rc.ToString());
I hope it will help you.
If you want to add custom ObjectMapper for registering custom serializers, try my answer.
In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="serializers">
<array>
<bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
</array>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
was in unexplained way overwritten back to default by something.
This worked for me:
@JsonSerialize(using = CustomObjectSerializer.class)
public class CustomObject {
private Long value;
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
}
public class CustomObjectSerializer extends JsonSerializer<CustomObject> {
@Override
public void serialize(CustomObject value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("y", value.getValue());
jgen.writeEndObject();
}
@Override
public Class<CustomObject> handledType() {
return CustomObject.class;
}
}
No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>
) is needed in my solution.
In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions.
The export
command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.
I was seeing this same error when trying to save an excel file. The code worked fine when I was using MS Office 2003, but after upgrading to MS Office 2007 I started seeing this. It would happen anytime I tried to save an Excel file to a server or remote fie share.
My solution, though rudimentary, worked well. I just had the program save the file locally, like to the user's C:\ drive. Then use the "System.IO.File.Copy(File, Destination, Overwrite)" method to move the file to the server. Then you can delete the file on the C:\ drive.
Works great, and simple. But admittedly not the most elegant approach.
Hope this helps! I was having a ton of trouble finding any solutions on the web till this idea popped into my head.
The simplest way is as this example:
<div>
<div style=' height:300px;'>
SOME LOGO OR CONTENT HERE
</div>
<div style='overflow-x: hidden;overflow-y: scroll;'>
THIS IS SOME TEXT
</DIV>
You can see the test cases on: https://www.w3schools.com/css/css_overflow.asp
First you have to create a li
(with id and value as you required) then add it to your ul
.
Javascript ::
addAnother = function() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var children = ul.children.length + 1
li.setAttribute("id", "element"+children)
li.appendChild(document.createTextNode("Element "+children));
ul.appendChild(li)
}
Check this example that add li
element to ul
.
Click these links to see these more flexible and robust solutions. They're answers to a similar question:
window.location.search = jQuery.query.set('single', true);
parse
and stringify
on window.location.search
These allow you to programmatically set the parameter, and, unlike the other hacks suggested for this question, won't break for URLs that already have a parameter, or if something else isn't quite what you thought might happen.
$spinTime: 3;
html, body { height: 100%; }
* { user-select: none; }
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: 'Raleway', sans-serif;
font-size: 72px;
input {
display: none;
+ div > span {
display: inline-block;
position: relative;
white-space: nowrap;
color: rgba(#fff, 0);
transition: all 0.5s ease-in-out;
span {
display: inline-block;
position: absolute;
left: 50%;
text-align: center;
color: rgba(#000, 1);
transform: translateX(-50%);
transform-origin: left;
transition: all 0.5s ease-in-out;
&:first-of-type {
transform: rotateY(0deg) translateX(-50%);
}
&:last-of-type {
transform: rotateY(0deg) translateX(0%) scaleX(0.75) skew(23deg,0deg);
}
}
}
&#fat:checked ~ div > span span {
&:first-of-type {
transform: rotateY(0deg) translateX(-50%);
}
&:last-of-type {
transform: rotateY(0deg) translateX(0%) scaleX(0.75) skew(23deg,0deg);
}
}
&#fit:checked ~ div > span {
margin: 0 -10px;
span {
&:first-of-type {
transform: rotateY(90deg) translateX(-50%);
}
&:last-of-type {
transform: rotateY(0deg) translateX(-50%) scaleX(1) skew(0deg,0deg);
}
}
}
+ div + div {
width: 280px;
margin-top: 10px;
label {
display: block;
padding: 20px 10px;
text-align: center;
transition: all 0.15s ease-in-out;
background: #fff;
border-radius: 10px;
box-sizing: border-box;
width: 48%;
font-size: 64px;
cursor: pointer;
&:first-child {
float: left;
box-shadow:
inset 0 0 0 4px #1597ff,
0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
}
&:last-child { float: right; }
}
}
&#fat:checked ~ div + div label {
&:first-child {
box-shadow:
inset 0 0 0 4px #1597ff,
0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
}
&:last-child {
box-shadow:
inset 0 0 0 0px #1597ff,
0 10px 15px -20px rgba(#1597ff, 0);
}
}
&#fit:checked ~ div + div label {
&:first-child {
box-shadow:
inset 0 0 0 0px #1597ff,
0 10px 15px -20px rgba(#1597ff, 0);
}
&:last-child {
box-shadow:
inset 0 0 0 4px #1597ff,
0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
}
}
}
}
<input type="radio" id="fat" name="fatfit">
<input type="radio" id="fit" name="fatfit">
<div>
GET F<span>A<span>A</span><span>I</span></span>T
</div>
<div>
<label for="fat"></label>
<label for="fit"></label>
</div>
Adding my 2 cents to the @kad81 answer,
Go to Visual Studio -> BUILD -> Configuration Manager
In the "Active Solution Platform" drop down in top right hand corner (mine is VS 2012), if it is "Mixed Platforms", change it to the appropriate platform based upon your reference third party assemblies.
Then in each of the project in the list, make sure you select same platform for all the project. (if x86 not exist, then select "", then you can select "x86".)
Rebuild the library projects first and then referencing projects. Hope this helps.
Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;
. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.
>>> x = 'foo'
>>> x
'foo'
So the name x
is attached to 'foo'
string. When you call for example repr(x)
the interpreter puts 'foo'
instead of x
and then calls repr('foo')
.
>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"
repr
actually calls a magic method __repr__
of x
, which gives the string containing the representation of the value 'foo'
assigned to x
. So it returns 'foo'
inside the string ""
resulting in "'foo'"
. The idea of repr
is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr
.
>>> eval("'foo'")
'foo'
When we call eval("'foo'")
, it's the same as we type 'foo'
in the interpreter. It's as we directly type the contents of the outer string ""
in the interpreter.
>>> eval('foo')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eval('foo')
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
If we call eval('foo')
, it's the same as we type foo
in the interpreter. But there is no foo
variable available and an exception is raised.
>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>>
str
is just the string representation of the object (remember, x
variable refers to 'foo'
), so this function returns string.
>>> str(5)
'5'
String representation of integer 5
is '5'
.
>>> str('foo')
'foo'
And string representation of string 'foo'
is the same string 'foo'
.
From the Documentation
As with components, you can add as many directive property bindings as you need by stringing them along in the template.
Add an input property to
HighlightDirective
calleddefaultColor
:@Input() defaultColor: string;
Markup
<p [myHighlight]="color" defaultColor="violet"> Highlight me too! </p>
Angular knows that the
defaultColor
binding belongs to theHighlightDirective
because you made it public with the@Input
decorator.Either way, the
@Input
decorator tells Angular that this property is public and available for binding by a parent component. Without@Input
, Angular refuses to bind to the property.
For your example
With many parameters
Add properties into the Directive
class with @Input()
decorator
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('first') f;
@Input('second') s;
...
}
And in the template pass bound properties to your li
element
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[first]='YourParameterHere'
[second]='YourParameterHere'
(selectedOption) = 'onOptionSelection($event)'>
{{opt.option}}
</li>
Here on the li
element we have a directive with name selectable
. In the selectable
we have two @Input()
's, f
with name first
and s
with name second
. We have applied these two on the li
properties with name [first]
and [second]
. And our directive will find these properties on that li
element, which are set for him with @Input()
decorator. So selectable
, [first]
and [second]
will be bound to every directive on li
, which has property with these names.
With single parameter
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('params') params;
...
}
Markup
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[params]='{firstParam: 1, seconParam: 2, thirdParam: 3}'
(selectedOption) = 'onOptionSelection($event)'>
{{opt.option}}
</li>
This will print 76.66
:
print("Number: ", f"{76.663254: .2f}")
Here is a simple generic C++11 function contains
which works for both arrays and containers:
using namespace std;
template<class C, typename T>
bool contains(C&& c, T e) { return find(begin(c), end(c), e) != end(c); };
Simple usage contains(arr, el)
is somewhat similar to in
keyword semantics in Python.
Here is a complete demo:
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <iostream>
template<typename C, typename T>
bool contains(C&& c, T e) {
return std::find(std::begin(c), std::end(c), e) != std::end(c);
};
template<typename C, typename T>
void check(C&& c, T e) {
std::cout << e << (contains(c,e) ? "" : " not") << " found\n";
}
int main() {
int a[] = { 10, 15, 20 };
std::array<int, 3> b { 10, 10, 10 };
std::vector<int> v { 10, 20, 30 };
std::string s { "Hello, Stack Overflow" };
check(a, 10);
check(b, 15);
check(v, 20);
check(s, 'Z');
return 0;
}
Output:
10 found
15 not found
20 found
Z not found
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
I agree the --exclude flag is the right approach.
$ tar --exclude='./folder_or_file' --exclude='file_pattern' --exclude='fileA'
A word of warning for a side effect that I did not find immediately obvious: The exclusion of 'fileA' in this example will search for 'fileA' RECURSIVELY!
Example:A directory with a single subdirectory containing a file of the same name (data.txt)
data.txt
config.txt
--+dirA
| data.txt
| config.docx
If using --exclude='data.txt'
the archive will not contain EITHER data.txt file. This can cause unexpected results if archiving third party libraries, such as a node_modules directory.
To avoid this issue make sure to give the entire path, like --exclude='./dirA/data.txt'
I combined the two best solutions to cover all the possibilities:
BufferedReader br = new BufferedReader(new FileReader(fileName));
File file = new File(fileName);
if (br.readLine() == null && file.length() == 0)
{
System.out.println("No errors, and file empty");
}
else
{
System.out.println("File contains something");
}
Try this, edit the file with:
notepad foo.ps1:Zone.Identifier
And set 'ZoneId=0'
The magic method __getitem__
is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.
Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__
method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.
import copy
# Constants that can be used to index date of birth's Date-Month-Year
D = 0; M = 1; Y = -1
class Person(object):
def __init__(self, name, age, dob):
self.name = name
self.age = age
self.dob = dob
def __getitem__(self, indx):
print ("Calling __getitem__")
p = copy.copy(self)
p.name = p.name.split(" ")[indx]
p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
return p
Suppose one user input is as follows:
p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))
With the help of __getitem__
method, the user can access the indexed attributes. e.g.,
print p[0].name # print first (or last) name
print p[Y].dob # print (Date or Month or ) Year of the 'date of birth'
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
It seems everybody has different solution. I solved my problem like:
When I install 64bit mingw it installed itself to : "C:\Program Files\mingw-w64\x86_64-5.1.0-posix-seh-rt_v4-rev0\mingw64\bin"
Eventhough mingw-make.exe was under the path above, one invalid charecter or long path name confused CMake. I try to add path to environment path, try to give CMAKE as paramater it didn't work for me .
Finally I moved complex path of mingw-w64 to "C:/mingw64", than set the environment path, restarted CMake. Problem solved for me .
I have posted this as a separate answer as it is unrelated to my existing answer.
This issue recently cropped up again for accessing a parent from an iframe referencing a subdomain and the existing fixes did not work.
This time the answer was to modify the document.domain of the parent page and the iframe to be the same. This will fool the same origin policy checks into thinking they co-exist on exactly the same domain (subdomains are considered a different host and fail the same origin policy check).
Insert the following to the <head>
of the page in the iframe to match the parent domain (adjust for your doctype).
<script>
document.domain = "mydomain.com";
</script>
Please note that this will throw an error on localhost development, so use a check like the following to avoid the error:
if (!window.location.href.match(/localhost/gi)) {
document.domain = "mydomain.com";
}
Please try this, if you want to fetch first/last.
{{#each list}}
{{#if @first}}
<div class="active">
{{else}}
<div>
{{/if}}
{{/each}}
{{#each list}}
{{#if @last}}
<div class="last-element">
{{else}}
<div>
{{/if}}
{{/each}}
/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
g.setColor(Color.RED);
g.fillOval(50,50,20,20);
}
g.fillOval(x-axis,y-axis,width,height);
SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD
You can try the following
^\d{1,2}([:.]?\d{1,2})?([ ]?[a|p]m)?$
It can detect the following patterns :
2300
23:00
4 am
4am
4pm
4 pm
04:30pm
04:30 pm
4:30pm
4:30 pm
04.30pm
04.30 pm
4.30pm
4.30 pm
23:59
0000
00:00
If you're having this problem with Amazon S3 as me, try to paste this on your info.plist as a direct child of your top level tag
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>amazonaws.com</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>amazonaws.com.cn</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
You can find more info at:
http://docs.aws.amazon.com/mobile/sdkforios/developerguide/ats.html#resolving-the-issue
The solution of prijin worked perfectly for me. It is just fair to mention that two additional permissions are needed:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
When these are added, enabling and disabling works flawless with the default bluetooth adapter.
If the answer from falsetru didn't work you could also try:
>>> b'a string'.decode('utf-8')
'a string'
git rm --cached remove_file
git add .gitignore
git commit -m "Excluding"
I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell
and change the date manually.
I made a POC for an Angular application using multiple modules and router-outlets to nest sub apps in a single page app. You can get the source code at: https://github.com/AhmedBahet/ng-sub-apps
Hope this will help
First of all: Don't put secrets in clear text unless you know why it is a safe thing to do (i.e. you have assessed what damage can be done by an attacker knowing the secret).
If you are ok with putting secrets in your script, you could ship an ssh key with it and execute in an ssh-agent
shell:
#!/usr/bin/env ssh-agent /usr/bin/env bash
KEYFILE=`mktemp`
cat << EOF > ${KEYFILE}
-----BEGIN RSA PRIVATE KEY-----
[.......]
EOF
ssh-add ${KEYFILE}
# do your ssh things here...
# Remove the key file.
rm -f ${KEYFILE}
A benefit of using ssh keys is that you can easily use forced commands to limit what the keyholder can do on the server.
A more secure approach would be to let the script run ssh-keygen -f ~/.ssh/my-script-key
to create a private key specific for this purpose, but then you would also need a routine for adding the public key to the server.
This will horizontally center an inline-block element without needing to modify its parent's styles:
display: inline-block;
position: relative;
// Move the element to the left by 50% of the container's width
left: 50%;
// Calculates 50% of the element's width, and moves it by that
// amount across the X-axis to the left
transform: translateX(-50%);
You could also use find_by_sql
# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
An alternative approach is to set the width of the html element to 100vw. On many if not most browsers, this negates the effect of scrollbars on the width.
html { width: 100vw; }
Updated using look-behind support in line with ECMAScript2018 changes.
For backwards compatibility, scroll further down to see the original solution.
A regular expression may be used - notably useful in dealing with big numbers stored as strings.
const format = num => _x000D_
String(num).replace(/(?<!\..*)(\d)(?=(?:\d{3})+(?:\.|$))/g, '$1,')_x000D_
_x000D_
;[_x000D_
format(100), // "100"_x000D_
format(1000), // "1,000"_x000D_
format(1e10), // "10,000,000,000" _x000D_
format(1000.001001), // "1,000.001001"_x000D_
format('100000000000000.001001001001') // "100,000,000,000,000.001001001001_x000D_
]_x000D_
.forEach(n => console.log(n))
_x000D_
» Verbose regex explanation (regex101.com)
This original answer may not be required but can be used for backwards compatibility.
Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.
const format = num => {_x000D_
const n = String(num),_x000D_
p = n.indexOf('.')_x000D_
return n.replace(_x000D_
/\d(?=(?:\d{3})+(?:\.|$))/g,_x000D_
(m, i) => p < 0 || i < p ? `${m},` : m_x000D_
)_x000D_
}_x000D_
_x000D_
;[_x000D_
format(100), // "100"_x000D_
format(1000), // "1,000"_x000D_
format(1e10), // "10,000,000,000" _x000D_
format(1000.001001), // "1,000.001001"_x000D_
format('100000000000000.001001001001') // "100,000,000,000,000.001001001001_x000D_
]_x000D_
.forEach(n => console.log(n))
_x000D_
EDIT:
This answer will not work for Python3 and will give a RuntimeError
.
RuntimeError: dictionary changed size during iteration.
This happens because mydict.keys()
returns an iterator not a list.
As pointed out in comments simply convert mydict.keys()
to a list by list(mydict.keys())
and it should work.
A simple test in the console shows you cannot modify a dictionary while iterating over it:
>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> for k, v in mydict.iteritems():
... if k == 'two':
... del mydict[k]
...
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the keys()
method to get a list of the keys and work with that:
>>> for k in mydict.keys():
... if k == 'two':
... del mydict[k]
...
>>> mydict
{'four': 4, 'three': 3, 'one': 1}
If you need to delete based on the items value, use the items()
method instead:
>>> for k, v in mydict.items():
... if v == 3:
... del mydict[k]
...
>>> mydict
{'four': 4, 'one': 1}
"usecols" should help, use range of columns (as per excel worksheet, A,B...etc.) below are the examples
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A,C,F")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H,J:N")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:N")
You can do it with something like this, so if no arguments are specified it will continue anyway:
public static void main(String[] args) {
try {
String one = args[0];
String two = args[1];
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException caught");
}
finally {
}
}
And then launch the application:
java -jar myapp.jar arg1 arg2
Dynamic programming problems can be solved using either bottom-up or top-down approaches.
Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.
But you can also have bottom-up and top-down approaches using recursion as shown below.
Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.
int n = 5;
fibBottomUp(1, 1, 2, n);
private int fibBottomUp(int i, int j, int count, int n) {
if (count > n) return 1;
if (count == n) return i + j;
return fibBottomUp(j, i + j, count + 1, n);
}
Top-Down: Start with the final condition and recursively get the result of its sub-problems.
int n = 5;
fibTopDown(n);
private int fibTopDown(int n) {
if (n <= 1) return 1;
return fibTopDown(n - 1) + fibTopDown(n - 2);
}
One of the simplest way I found is to use pynput module.can be found here with nice examples as well
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
above is the example worked out for me and to install, go
for python 2:
pip install pynput
for python 3:
pip3 install pynput
Can you try this:
select convert(nvarchar(max),convert(varbinary(max),blob_column)) from table_name
run
gradle clean
then try
gradle build
it worked for me
Based on various answers on Stack Overflow and blogs I've come across, this is the method I'm using, and it seems to return real words quite well. The idea is to split the incoming text into an array of words (use whichever method you'd like), and then find the parts of speech (POS) for those words and use that to help stem and lemmatize the words.
You're sample above doesn't work too well, because the POS can't be determined. However, if we use a real sentence, things work much better.
import nltk
from nltk.corpus import wordnet
lmtzr = nltk.WordNetLemmatizer().lemmatize
def get_wordnet_pos(treebank_tag):
if treebank_tag.startswith('J'):
return wordnet.ADJ
elif treebank_tag.startswith('V'):
return wordnet.VERB
elif treebank_tag.startswith('N'):
return wordnet.NOUN
elif treebank_tag.startswith('R'):
return wordnet.ADV
else:
return wordnet.NOUN
def normalize_text(text):
word_pos = nltk.pos_tag(nltk.word_tokenize(text))
lemm_words = [lmtzr(sw[0], get_wordnet_pos(sw[1])) for sw in word_pos]
return [x.lower() for x in lemm_words]
print(normalize_text('cats running ran cactus cactuses cacti community communities'))
# ['cat', 'run', 'ran', 'cactus', 'cactuses', 'cacti', 'community', 'community']
print(normalize_text('The cactus ran to the community to see the cats running around cacti between communities.'))
# ['the', 'cactus', 'run', 'to', 'the', 'community', 'to', 'see', 'the', 'cat', 'run', 'around', 'cactus', 'between', 'community', '.']
Make sure mode_rewrite is enabled in APACHE settings. See link here https://github.com/h5bp/server-configs-apache/wiki/How-to-enable-Apache-modules
Then make sure you have correct .htaccess https://wordpress.org/support/topic/404-errors-with-permalinks-set-to-postname/
And correct virtual host settings in either Apache settings How to Set AllowOverride all
It's the new feature in C# 6 called Interpolated Strings
.
The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.
For more details about this, please take a look at MSDN.
Now, think a little bit more about it. Why this feature is great?
For example, you have class Point
:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
Create 2 instances:
var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };
Now, you want to output it to the screen. The 2 ways that you usually use:
Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");
As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format()
to make it nicer:
Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));
This creates a new problem:
For those reasons, we should use new feature:
Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");
The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
For the full post, please read this blog.
Here is Kotlin version.
Thanks you :)
fun unSafeOkHttpClient() :OkHttpClient.Builder {
val okHttpClient = OkHttpClient.Builder()
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
if (trustAllCerts.isNotEmpty() && trustAllCerts.first() is X509TrustManager) {
okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
okHttpClient.hostnameVerifier { _, _ -> true }
}
return okHttpClient
} catch (e: Exception) {
return okHttpClient
}
}
Use malloc()
when you don't know the amount of memory needed during compile time. In case if you have read-only strings then you can use const char* str = "something";
. Note that the string is most probably be stored in a read-only memory location and you'll not be able to modify it. On the other hand if you know the string during compiler time then you can do something like: char str[10]; strcpy(str, "Something");
Here the memory is allocated from stack and you will be able to modify the str. Third case is allocating using malloc. Lets say you don'r know the length of the string during compile time. Then you can do char* str = malloc(requiredMem); strcpy(str, "Something"); free(str);
You have multiple options, each with different general use cases.
The first would be to use a for
loop, as you described, but in the following way.
for value in array:
print(value, end=' ')
You could also use str.join
for a simple, readable one-liner using comprehension. This method would be good for storing this value to a variable.
print(' '.join(str(value) for value in array))
My favorite method, however, would be to pass array
as *args
, with a sep
of ' '
. Note, however, that this method will only produce a print
ed output, not a value that may be stored to a variable.
print(*array, sep=' ')
Use:
sed -n '1,100p' filename > output.txt
Here, 1 and 100 are the line numbers which you will capture in output.txt
.
//this will work for user in time zone MST with 7 off set or UTC with saving time
//I have tried all the above and they fail the only solution is to use some math
//the trick is to rely on $newdate is time() //strtotime is corrupt it tries to read to many minds
//convert to time to use with javascript*1000
$dnol = strtotime('today')*1000;
$dn = ($newdate*1000)-86400000;
$dz=$dn/86400000; //divide into days
$dz=floor($dz); //filter off excess time
$dzt=$dz*86400000; // put back into days UTC
$jsDate=$dzt*1+(7*3600000); // 7 is the off set you can store the 7 in database
$dzt=$dzt-3600000; //adjusment for summerTime UTC additional table for these dates will drive you crazy
//solution get users [time off sets] with browser, up date to data base for user with ajax when they ain't lookin
<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
echo '<BR>'.$dnol;
echo '<BR>'.$dzt.'<BR>';
echo(date("Y-m-d",$dzt/1000)); //convert back for php /1000
echo '<BR>';
echo(date('Y-m-d h:i:s',$dzt/1000));
?>
@OP, you were awfully close with your "non-elegant" solution.
How about:
<div class="month" *ngFor="let item of [].constructor(10); let i = index">
...
</div>
Here I'm getting the Array
constructor from an empty array: [].constructor
, because Array
isn't a recognized symbol in the template syntax, and I'm too lazy to do Array=Array
or counter = Array
in the component typescript like @pardeep-jain did in his 4th example. And I'm calling it without new
because new
isn't necessary for getting an array out the Array
constructor.
Array(30)
and new Array(30)
are equivalent.
The array will be empty, but that doesn't matter because you really just want to use i
from ;let i = index
in your loop.
if your class is not in current assambly you must give qualifiedName and this code shows how to get qualifiedname of class
string qualifiedName = typeof(YourClass).AssemblyQualifiedName;
and then you can get type with qualifiedName
Type elementType = Type.GetType(qualifiedName);
As simply as:
if (numbers.isEmpty()) {...}
Note that a quick look at the documentation would have given you that information.
I'm able to run an SQL query by piping it to SQL*Plus:
@echo select count(*) from table; | sqlplus username/password@database
Give
@echo execute some_procedure | sqlplus username/password@databasename
a try.
Check this: https://github.com/angular/material2/issues/5808
Since material2 is using flex layout, you can just set fxFlex="40"
(or the value you want for fxFlex) to md-cell
and md-header-cell
.
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
In our scenario, its a single VB.NET project (Windows Desktop application) in a single solution. However we wanted to take advantage of C# features like signed/unsigned integers and XML literals and string features in VB.NET. So depending on the features, at runtime we build the code file, compile using respective Rosalyn compiler (VB/CS) into DLL and dynamically load into current assembly. Of course we had to work on delinking, unloading, reloading, naming etc of the dynamic DLLs and the memory management were we largely used dynamic GUID for naming to avoid conflict. It works fine where app user may connect to any DB from our desktop app, write SQL query, convert the connection to LINQ connection and write LINQ queries too which all requires dynamic building of source code, compiling into DLL and attaching to current assembly.
Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
for Ruby 1.9+ use colon.
gem install sinatra:1.4.4 prawn:0.13.0
String.equals()
requires invoking instanceof
operator while compareTo()
requires not. My colleague has noted large performance drop-down caused by excessive numbers of instanceof
calls in equals()
method, however my test has proved compareTo()
to be only slightly faster.
I was using, however, Java 1.6. On other versions (or other JDK vendors) the difference could be larger.
The test compared each-to-each string in 1000 element arrays, repeated 10 times.
The generic view of a loop is
for (initialization; condition; increment-decrement){}
The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.
I had both the Lombok plugin installed and Annotation Processing enabled within IntelliJ and my syntax highlighting still wasn't working properly. This could have been due to the 2017 to 2018 IDEA upgrade. I was getting warnings "access exceeds rights" on private fields within classes I had used @Getter and @Setter on.
I had to uninstall the Lombok plugin, restart IntelliJ, then reinstall the plugin, and restart IntelliJ once more.
Everything is working good now.
I used
String template = "Hello %s Please find attached %s which is due on %s";
String message = String.format(template, name, invoiceNumber, dueDate);
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
mysql_query
function is used for executing mysql query in php. mysql_query
returns false if query execution fails.Alternatively you can try using mysql_error()
function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
Much easier way to view the signing certificate:
jarsigner.exe -verbose -verify -certs myapk.apk
This will only show the DN, so if you have two certs with the same DN, you might have to compare by fingerprint.
Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.
As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.
The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.
Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.
One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.
Add this to you PageLoad and it will solve your problem:
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.lblbtndoc1);
In pgAdmin you can also use
SET search_path TO your_db_name;
As noted by other answers, the general solution is to use an index expression in an assignment of the special form:
v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
var v, ok T = a[x]
This is nice and clean. It has some restrictions though: it must be an assignment of special form. Right-hand side expression must be the map index expression only, and the left-hand expression list must contain exactly 2 operands, first to which the value type is assignable, and a second to which a bool
value is assignable. The first value of the result of this special form will be the value associated with the key, and the second value will tell if there is actually an entry in the map with the given key (if the key exists in the map). The left-hand side expression list may also contain the blank identifier if one of the results is not needed.
It's important to know that if the indexed map value is nil
or does not contain the key, the index expression evaluates to the zero value of the value type of the map. So for example:
m := map[int]string{}
s := m[1] // s will be the empty string ""
var m2 map[int]float64 // m2 is nil!
f := m2[2] // f will be 0.0
fmt.Printf("%q %f", s, f) // Prints: "" 0.000000
Try it on the Go Playground.
So if we know that we don't use the zero value in our map, we can take advantage of this.
For example if the value type is string
, and we know we never store entries in the map where the value is the empty string (zero value for the string
type), we can also test if the key is in the map by comparing the non-special form of the (result of the) index expression to the zero value:
m := map[int]string{
0: "zero",
1: "one",
}
fmt.Printf("Key 0 exists: %t\nKey 1 exists: %t\nKey 2 exists: %t",
m[0] != "", m[1] != "", m[2] != "")
Output (try it on the Go Playground):
Key 0 exists: true
Key 1 exists: true
Key 2 exists: false
In practice there are many cases where we don't store the zero-value value in the map, so this can be used quite often. For example interfaces and function types have a zero value nil
, which we often don't store in maps. So testing if a key is in the map can be achieved by comparing it to nil
.
Using this "technique" has another advantage too: you can check existence of multiple keys in a compact way (you can't do that with the special "comma ok" form). More about this: Check if key exists in multiple maps in one condition
Getting the zero value of the value type when indexing with a non-existing key also allows us to use maps with bool
values conveniently as sets. For example:
set := map[string]bool{
"one": true,
"two": true,
}
fmt.Println("Contains 'one':", set["one"])
if set["two"] {
fmt.Println("'two' is in the set")
}
if !set["three"] {
fmt.Println("'three' is not in the set")
}
It outputs (try it on the Go Playground):
Contains 'one': true
'two' is in the set
'three' is not in the set
See related: How can I create an array that contains unique strings?
We had the same issue, in making a websocket connection to the Load Balancer. The issue is in LB, accepting http connection on port 80 and forwarding the request to node (tomcat app on port 8080). We have changed this to accept tcp (http has been changed as 'tcp') connection on port 80. So the first handshake request is forwarded to Node and a websocket connection is made successfully on some random( as far as i know, may be wrong) port.
below command has been used to test the websocket handshake process.
curl -v -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost" -H "Origin: http://LB URL:80" http://LB URL
GET / HTTP/1.1 Host: localhost User-Agent: curl/7.60.0 Accept: / Connection: Upgrade Upgrade: websocket Origin: http://LB URL:80
I think part of what confuses new Rubyists/programmers (like myself) is:
"Why can't I just tell the instance it has any given attribute (e.g., name) and give that attribute a value all in one swoop?"
A little more generalized, but this is how it clicked for me:
Given:
class Person
end
We haven't defined Person as something that can have a name or any other attributes for that matter.
So if we then:
baby = Person.new
...and try to give them a name...
baby.name = "Ruth"
We get an error because, in Rubyland, a Person class of object is not something that is associated with or capable of having a "name" ... yet!
BUT we can use any of the given methods (see previous answers) as a way to say, "An instance of a Person class (baby
) can now have an attribute called 'name', therefore we not only have a syntactical way of getting and setting that name, but it makes sense for us to do so."
Again, hitting this question from a slightly different and more general angle, but I hope this helps the next instance of class Person who finds their way to this thread.
I solved this problem by using the the data-cache="false" attribute in the page div on the pages I wanted refreshed.
<div data-role="page" data-cache="false">
/*content goes here*/
</div>
In my case it was my shopping cart. If a customer added an item to their cart and then continued shopping and then added another item to their cart the cart page would not show the new item. Unless they refreshed the page. Setting data-cache to false instructs JQM not to cache that page as far as I understand.
Hope this helps others in the future.
You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php
Then in your ajax call change the success function to this:
$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');
For anyone landing here who is trying to upgrade from MVC 4 to MVC5, I was able to resolve this issue by following the instructions at http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2.
I also had to install the "Microsoft.AspNet.WebApi.WebHost" package from nuget. But that's it.
Oh, and I had to create this appSetting: <add key="owin:AutomaticAppStartup" value="false" />
:)
In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:
Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")
This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.
I had this exact same problem. For me, this was the only thing that worked:
div.mainContainer { padding-top: 1px; }
It actually works with any number that's not zero. I really have no idea why this took care of it. I'm not that knowledgeable about CSS and HTML and it seems counterintuitive. Setting the body, html, h1
margins and paddings to 0 had no effect for me. I also had an h1
at the top of my page
You can try something like this, if you use jQuery.
$("form").bind("keydown", function(e) {
if (e.keyCode === 13) return false;
});
That will wait for a keydown, if it is Enter, it will do nothing.
Straightforward way? No, but I've used the reverse. Literally.
In prior routines, to find the last occurence of a given string, I used the REVERSE() function, followed CHARINDEX, followed again by REVERSE to restore the original order. For instance:
SELECT
mf.name
,mf.physical_name
,reverse(left(reverse(physical_name), charindex('\', reverse(physical_name)) -1))
from sys.master_files mf
shows how to extract the actual database file names from from their "physical names", no matter how deeply nested in subfolders. This does search for only one character (the backslash), but you can build on this for longer search strings.
The only downside is, I don't know how well this will work on TEXT data types. I've been on SQL 2005 for a few years now, and am no longer conversant with working with TEXT -- but I seem to recall you could use LEFT and RIGHT on it?
Philip
Check for missing folders that are required by the server, in my case it was UPLOADS folder in programData which was deleted by empty folder cleaner utility that I used earlier.
How did I find out:
run the server config file my.ini(in my case it was in programData) as the defaults-file param for mysqld (don't forget to use --console option to view error log on screen) 'mysqld --defaults-file="C:\ProgramData\MySQL\MySQL Server 8.0\my.ini" --console'
Error:
mysqld: Can't read dir of 'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\' (OS errno 2 - No such file or directory)
Solution:
Once I manually created the Uploads folder the server started successfully.
Removing some unnecessary SQL and then COUNT(*)
will be faster than SQL_CALC_FOUND_ROWS
. Example:
SELECT Person.Id, Person.Name, Job.Description, Card.Number
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
LEFT JOIN Card ON Card.Person_Id = Person.Id
WHERE Job.Name = 'WEB Developer'
ORDER BY Person.Name
Then count without unnecessary part:
SELECT COUNT(*)
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
WHERE Job.Name = 'WEB Developer'
You can't solve it. Simply answer1.sum()==0
, and you can't perform a division by zero.
This happens because answer1
is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.
nan
is returned in this case because of the division by zero.
Now to solve your problem you could:
scipy/numpy
function that does exactly what you want! Check out @Warren Weckesser answer.Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:
exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
= exp(log(exp(-x)*[1+exp(-y+x)]))
= exp(log(exp(-x) + log(1+exp(-y+x)))
= exp(-x + log(1+exp(-y+x)))
where above x=3* 1089
and y=3* 1093
. Now, the argument of this exponential is
-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06
For the denominator you could proceed similarly but obtain that log(1+exp(-z+k))
is already rounded to 0
, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000
. You then have that your result is
exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x))
= exp(-266.99999385580668)
which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089
in the numerator and the first number 1000
at the denominator):
exp(3*(1089-1000))=exp(-267)
For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):
Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523
The difference between this number and the exponent above is +1.7053025658242404e-13
, so the approximation we made at the denominator was fine.
The final result is
'exp(-266.99999385580668) = 1.1050349147204485e-116
From wolfram alpha is (link)
1.105034914720621496.. × 10^-116 # Wolfram alpha.
and again, it is safe to use numpy here too.
If appears to me that rows where Visible is set to false won't be accessible, that they are removed from the DOM rather than hidden, so I also used the Display: None approach. In my case, I wanted to have a hidden column that contained the key of the Row. To me, this declarative approach is a little cleaner than some of the other approaches that use code.
<style>
.HiddenCol{display:none;}
</style>
<%--ROW ID--%>
<asp:TemplateField HeaderText="Row ID">
<HeaderStyle CssClass="HiddenCol" />
<ItemTemplate>
<asp:Label ID="lblROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" CssClass="HiddenCol" />
<EditItemTemplate>
<asp:TextBox ID="txtROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:TextBox>
</EditItemTemplate>
<FooterStyle CssClass="HiddenCol" />
</asp:TemplateField>
I use this small method to read Arduino serial monitor with Python
import serial
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.
It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult.
You may want to consider posting your second question in another topic.
SqlConnection conn = null;
SqlDataReader rdr = null;
conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand("CustOrderHist", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]);
}
Put text inside
Your Text Here
and copy the script inside your js file. You are ready to go. Working code for see more.. and see less.. options. Works for dynamic as well as static texts
<div class="item">
Your Text Here
</div>
<script type="text/javascript">
$(function(){ /* to make sure the script runs after page load */
$('.item').each(function(event){ /* select all divs with the item class */
var max_length = 150; /* set the max content length before a read more link will be added */
if($(this).html().length > max_length){ /* check for content length */
var short_content = $(this).html().substr(0,max_length); /* split the content in two parts */
var long_content = $(this).html().substr(max_length);
$(this).html(short_content+'<a href="#" class="read_more">Show More</a>'+
'<span class="more_text" style="display:none;">'+long_content+'</span>'+'<a href="#" class="read_less" style="display:none;">Show Less</a>'); /* Alter the html to allow the read more functionality */
$(this).find('a.read_more').click(function(event){ /* find the a.read_more element within the new html and bind the following code to it */
event.preventDefault(); /* prevent the a from changing the url */
$(this).hide(); /* hide the read more button */
$('.read_less').show(); /* show read less button */
$(this).parents('.item').find('.more_text').show(); /* show the .more_text span */
});
$(this).find('a.read_less').click(function(event){
event.preventDefault();
$(this).hide(); /* hide the read more button */
$('.read_less').hide();
$('.read_more').show();
$(this).parents('.item').find('.more_text').hide();
});
}
});
});
</script>
If you create a user with the advanced user management (from command line: netplwiz
), then modify the group, remove users, and add iis_users. They will be able to authenticate to your web page, but not the computer.
You can go with POSTMAN, an application who makes APIs easy. Fill request fields and then it will generate code for you in different languages. Just click code on the right side and select your prefered language.
In MySQL, this works if there are multiple '=' characters in the string
SUBSTRING(supplier_reference FROM (LOCATE('=',supplier_reference)+1))
It returns the substring after(+1) having found the the first =
The instances of the new HttpHeader
class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
or
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
Update: adding multiple headers
let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');
or
const headers = new HttpHeaders({'h1':'v1','h2':'v2'});
Update: accept object map for HttpClient headers & params
Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders
object an directly pass an object map as argument. So now its possible to do the following:
http.get('someurl',{
headers: {'header1':'value1','header2':'value2'}
});
Using Accept header is really easy to get the format json or xml from the REST service.
This is my Controller, take a look produces section.
@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
public UIProperty getProperties() {
return uiProperty;
}
In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or MediaType.APPLICATION_XML_VALUE
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", header);
HttpEntity entity = new HttpEntity(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
return response.getBody();
Edit 01:
In order to work with application/xml
, add this dependency
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
EDIT: Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder
-attribute and a javascript fallback for browsers which don't support it yet.
If you are looking for a Mootools equivalent to the JQuery fallback in MvanGeest's reply, here is one.
--
You should probably use onfocus
and onblur
events in order to support keyboard users who tab through forms.
Here's an example:
<input type="text" value="[email protected]" name="Email" id="Email"
onblur="if (this.value == '') {this.value = '[email protected]';}"
onfocus="if (this.value == '[email protected]') {this.value = '';}" />
Node manages dependencies ie; third party code using package.json so that 3rd party modules names and versions can be kept stable for all installs of the project. This also helps keep the file be light-weight as only actual program code is present in the code repository. Whenever repository is cloned, for it to work(as 3rd party modules may be used in the code), you would need to install all dependencies.
Use npm install
on CMD within root of the project structure to complete installing all dependencies. This should resolve all dependencies issues if dependencies get properly installed.
In my dimens.xml I have
<dimen name="test">48dp</dimen>
In code If I do
int valueInPixels = (int) getResources().getDimension(R.dimen.test)
this will return 72 which as docs state is multiplied by density of current phone (48dp x 1.5 in my case)
exactly as docs state :
Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.
so if you want exact dp value just as in xml just divide it with DisplayMetrics density
int dp = (int) (getResources().getDimension(R.dimen.test) / getResources().getDisplayMetrics().density)
dp will be 48 now
You should watch this: Node Tuts episode 19 - Asynchronous Iteration Patterns
It should answers your questions.
You can do this:
> ddply(df,.(name,type),transform,count = NROW(piece))
name type num count
1 black chair 4 2
2 black chair 5 2
3 black sofa 12 1
4 red plate 3 1
5 red sofa 4 1
or perhaps more intuitively,
> ddply(df,.(name,type),transform,count = length(num))
name type num count
1 black chair 4 2
2 black chair 5 2
3 black sofa 12 1
4 red plate 3 1
5 red sofa 4 1
It sounds less like a Java synchronization issue and more like a database locking problem.
I don't know if adding a version to all your persistent classes will sort it out, but that's one way that Hibernate can provide exclusive access to rows in a table.
Could be that isolation level needs to be higher. If you allow "dirty reads", maybe you need to bump up to serializable.
<script type="text/javascript" runat="server">
public void Page_Load(object Sender, System.EventArgs e)
{
double rad=0.0;
TextBox1.Attributes.Add("Visible", "False");
if (TextBox1.Text != "")
rad = Convert.ToDouble(TextBox1.Text);
Button1.Attributes.Add("OnClick","alert("+ rad +")");
}
</script>
<asp:Button ID="Button1" runat="server" Text="Diameter"
style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server"
AutoPostBack="true"
style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>
use the help of this, hope it will be usefull
First, install Homebrew (The missing package manager for macOS) if you haven': Type this in your terminal
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Now you can update your Python to python 3 by this command
brew install python3 && cp /usr/local/bin/python3 /usr/local/bin/python
Python 2 and python 3 can coexist so to open python 3, type python3
instead of python
That's the easiest and the best way.
cors unblock works great for chrome 78 [COrs unb] [1] https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino
it's a plugin for google chrome called "cors unblock"
Summary: No more CORS error by appending 'Access-Control-Allow-Origin: *' header to local and remote web requests when enabled
This extension provides control over XMLHttpRequest and fetch methods by providing custom "access-control-allow-origin" and "access-control-allow-methods" headers to every requests that the browser receives. A user can toggle the extension on and off from the toolbar button. To modify how these headers are altered, use the right-click context menu items. You can customize what method are allowed. The default option is to allow 'GET', 'PUT', 'POST', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH' methods. You can also ask the extension not to overwrite these headers when the server already fills them.
In perl 5.10, there's the close-to-magic ~~ operator:
sub invite_in {
my $vampires = [ qw(Angel Darla Spike Drusilla) ];
return ($_[0] ~~ $vampires) ? 0 : 1 ;
}
See here: http://dev.perl.org/perl5/news/2007/perl-5.10.0.html
You'd be surprised to find out that 80/20 is quite a commonly occurring ratio, often referred to as the Pareto principle. It's usually a safe bet if you use that ratio.
However, depending on the training/validation methodology you employ, the ratio may change. For example: if you use 10-fold cross validation, then you would end up with a validation set of 10% at each fold.
There has been some research into what is the proper ratio between the training set and the validation set:
The fraction of patterns reserved for the validation set should be inversely proportional to the square root of the number of free adjustable parameters.
In their conclusion they specify a formula:
Validation set (v) to training set (t) size ratio, v/t, scales like ln(N/h-max), where N is the number of families of recognizers and h-max is the largest complexity of those families.
What they mean by complexity is:
Each family of recognizer is characterized by its complexity, which may or may not be related to the VC-dimension, the description length, the number of adjustable parameters, or other measures of complexity.
Taking the first rule of thumb (i.e.validation set should be inversely proportional to the square root of the number of free adjustable parameters), you can conclude that if you have 32 adjustable parameters, the square root of 32 is ~5.65, the fraction should be 1/5.65 or 0.177 (v/t). Roughly 17.7% should be reserved for validation and 82.3% for training.
It's trying to bring in some Ruby Goodness :)
Concept: This is some sample Ruby Code that prints out each element of the array
rubyArray = [1,2,3,4,5,6,7,8,9,10]
rubyArray.each{|x|
puts x # do whatever with x
}
The Array's each method implementation yields control over to the caller (the 'puts x') with each element of the array neatly presented as x. The caller can then do whatever it needs to do with x.
However .Net doesn't go all the way here.. C# seems to have coupled yield with IEnumerable, in a way forcing you to write a foreach loop in the caller as seen in Mendelt's response. Little less elegant.
//calling code
foreach(int i in obCustomClass.Each())
{
Console.WriteLine(i.ToString());
}
// CustomClass implementation
private int[] data = {1,2,3,4,5,6,7,8,9,10};
public IEnumerable<int> Each()
{
for(int iLooper=0; iLooper<data.Length; ++iLooper)
yield return data[iLooper];
}
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
Something that is not relevant for the OP, but maybe for someone else in the future:
For pixels (px
), if the value is "0", the unit can be omitted: right: 0
and right: 0px
both work.
However I noticed that in Firefox and Chrome this is not the case for the seconds unit (s
). While transition: right 1s ease 0s
works, transition: right 1s ease 0
(missing unit s
for last value transition-delay
) does not (it does work in Edge however).
In the following example, you'll see that right
works for both 0px
and 0
, but transition
only works for 0s
and it doesn't work with 0
.
#box {_x000D_
border: 1px solid black;_x000D_
height: 240px;_x000D_
width: 260px;_x000D_
margin: 50px;_x000D_
position: relative;_x000D_
}_x000D_
.jump {_x000D_
position: absolute;_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
color: white;_x000D_
padding: 5px;_x000D_
}_x000D_
#jump1 {_x000D_
background-color: maroon;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
transition: right 1s ease 0s;_x000D_
}_x000D_
#jump2 {_x000D_
background-color: green;_x000D_
top: 60px;_x000D_
right: 0;_x000D_
transition: right 1s ease 0s;_x000D_
}_x000D_
#jump3 {_x000D_
background-color: blue;_x000D_
top: 120px;_x000D_
right: 0px;_x000D_
transition: right 1s ease 0;_x000D_
}_x000D_
#jump4 {_x000D_
background-color: gray;_x000D_
top: 180px;_x000D_
right: 0;_x000D_
transition: right 1s ease 0;_x000D_
}_x000D_
#box:hover .jump {_x000D_
right: 50px;_x000D_
}
_x000D_
<div id="box">_x000D_
<div class="jump" id="jump1">right: 0px<br>transition: right 1s ease 0s</div>_x000D_
<div class="jump" id="jump2">right: 0<br>transition: right 1s ease 0s</div>_x000D_
<div class="jump" id="jump3">right: 0px<br>transition: right 1s ease 0</div>_x000D_
<div class="jump" id="jump4">right: 0<br>transition: right 1s ease 0</div>_x000D_
</div>
_x000D_
I find converting to the binary representation easier to grasp this problem.
float f = 0.27f;
double d2 = (double) f;
double d3 = 0.27d;
System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d2)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d3)));
You can see the float is expanded to the double by adding 0s to the end, but that the double representation of 0.27 is 'more accurate', hence the problem.
111110100010100011110101110001
11111111010001010001111010111000100000000000000000000000000000
11111111010001010001111010111000010100011110101110000101001000
Matlab help says this- For M-files that run a long time, or that call built-ins or MEX-files that run a long time, Ctrl+C does not always effectively stop execution. Typically, this happens on Microsoft Windows platforms rather than UNIX[1] platforms. If you experience this problem, you can help MATLAB break execution by including a drawnow, pause, or getframe function in your M-file, for example, within a large loop. Note that Ctrl+C might be less responsive if you started MATLAB with the -nodesktop option.
So I don't think any option exist. This happens with many matlab functions that are complex. Either we have to wait or don't use them!.
In addition to the potential locking problems you might cause you will also find that your transaction logs begin to grow as they can not be truncated past the minimum LSN for an active transaction and if you are using snapshot isolation your version store in tempdb will grow for similar reasons.
You can use dbcc opentran
to see details of the oldest open transaction.
If you're using Angular 1, I would recommend using Angular's built-in method:
angular.isDefined(value);
reference : https://docs.angularjs.org/api/ng/function/angular.isDefined
the problem is that there is no built in method (or at least none of us could find one) to do this in vb. However, there is one to split a string on the spaces, so I just rebuild the string and added in spaces....
Private Function characterArray(ByVal my_string As String) As String()
'create a temporary string to store a new string of the same characters with spaces
Dim tempString As String = ""
'cycle through the characters and rebuild my_string as a string with spaces
'and assign the result to tempString.
For Each c In my_string
tempString &= c & " "
Next
'return return tempString as a character array.
Return tempString.Split()
End Function
The above answer only adds the sqljdbc4.jar to the local repository. As a result, when creating the final project jar for distribution, sqljdbc4 will again be missing as was indicated in the comment by @Tony regarding runtime error.
Microsoft (and Oracle and other third party providers) restrict the distribution of their software as per the ENU/EULA. Therefore those software modules do not get added in Maven produced jars for distribution. There are hacks to get around it (such as providing the location of the 3rd party jar file at runtime), but as a developer you must be careful about violating the licensing.
A better approach for jdbc connectors/drivers is to use jTDS, which is compatible to most DBMS's, more reliable, faster (as per benchmarks), and distributed under GNU license. It will make your life much easier to use this than trying to pound the square peg into the round hole following any of the other techniques above.
If using WORD for mac enable 'use maths autocorrect rules outside maths regions' Type \therefore