Your problem is not actually specific to ejs.
2 things to note here
style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.
In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image
it can be done by
app.use(express.static(__dirname + '/public'));
assuming you put the css files in public folder from in your app root. now you have to refer to the css files in your tamplate files, like
<link href="/css/style.css" rel="stylesheet" type="text/css">
Here i assume you have put the css file in css folder inside your public folder.
So folder structure would be
.
./app.js
./public
/css
/style.css
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
Difference between Read(),Readline() and ReadKey() in C#
Read()
-Accept the string value and return the string value.
Readline()
-Accept the string and return Integer
ReadKey()
-Accept the character and return Character
Summary:
1.The above mentioned three methods are mainly used in Console application and these are used for return the different values . 2.If we use Read line or Read() we need press Enter button to come back to code. 3.If we using Read key() we can press any key to come back code in application
setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").
From the command line, you can type
python setup.py --help
...to get a list of commands. What you are looking to do is...
python setup.py install
The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.
For Safari:
<meta name="format-detection" content="telephone=no">
For BlackBerry:
<meta http-equiv="x-rim-auto-match" content="none">
Source: mobilexweb.com
See the above definition where it states that a callback function is passed off to some other function and at some point it is called.
In C++ it is desirable to have callback functions call a classes method. When you do this you have access to the member data. If you use the C way of defining a callback you will have to point it to a static member function. This is not very desirable.
Here is how you can use callbacks in C++. Assume 4 files. A pair of .CPP/.H files for each class. Class C1 is the class with a method we want to callback. C2 calls back to C1's method. In this example the callback function takes 1 parameter which I added for the readers sake. The example doesn't show any objects being instantiated and used. One use case for this implementation is when you have one class that reads and stores data into temporary space and another that post processes the data. With a callback function, for every row of data read the callback can then process it. This technique cuts outs the overhead of the temporary space required. It is particularly useful for SQL queries that return a large amount of data which then has to be post-processed.
/////////////////////////////////////////////////////////////////////
// C1 H file
class C1
{
public:
C1() {};
~C1() {};
void CALLBACK F1(int i);
};
/////////////////////////////////////////////////////////////////////
// C1 CPP file
void CALLBACK C1::F1(int i)
{
// Do stuff with C1, its methods and data, and even do stuff with the passed in parameter
}
/////////////////////////////////////////////////////////////////////
// C2 H File
class C1; // Forward declaration
class C2
{
typedef void (CALLBACK C1::* pfnCallBack)(int i);
public:
C2() {};
~C2() {};
void Fn(C1 * pThat,pfnCallBack pFn);
};
/////////////////////////////////////////////////////////////////////
// C2 CPP File
void C2::Fn(C1 * pThat,pfnCallBack pFn)
{
// Call a non-static method in C1
int i = 1;
(pThat->*pFn)(i);
}
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
I needed to know this to tell a user what to add to their host machine's host file. This works for me inside vagrant using just bash:
external_ip=$(cat /vagrant/config.yml | grep vagrant_ip | cut -d' ' -f2 | xargs)
echo -e "# Add this line to your host file:\n${external_ip} host.vagrant.vm"
Edit
Solution mentioned by @leftclickben is also effective. We can also use a stored procedure for the same.
CREATE PROCEDURE get_tree(IN id int)
BEGIN
DECLARE child_id int;
DECLARE prev_id int;
SET prev_id = id;
SET child_id=0;
SELECT col3 into child_id
FROM table1 WHERE col1=id ;
create TEMPORARY table IF NOT EXISTS temp_table as (select * from table1 where 1=0);
truncate table temp_table;
WHILE child_id <> 0 DO
insert into temp_table select * from table1 WHERE col1=prev_id;
SET prev_id = child_id;
SET child_id=0;
SELECT col3 into child_id
FROM TABLE1 WHERE col1=prev_id;
END WHILE;
select * from temp_table;
END //
We are using temp table to store results of the output and as the temp tables are session based we wont there will be not be any issue regarding output data being incorrect.
SQL FIDDLE Demo
Try this query:
SELECT
col1, col2, @pv := col3 as 'col3'
FROM
table1
JOIN
(SELECT @pv := 1) tmp
WHERE
col1 = @pv
SQL FIDDLE Demo
:| COL1 | COL2 | COL3 |
+------+------+------+
| 1 | a | 5 |
| 5 | d | 3 |
| 3 | k | 7 |
Note
parent_id
value should be less than thechild_id
for this solution to work.
A fast, simple and accurate (for smaller distances) approximation can be done with a spherical projection. At least in my routing algorithm I get a 20% boost compared to the correct calculation. In Java code it looks like:
public double approxDistKm(double fromLat, double fromLon, double toLat, double toLon) {
double dLat = Math.toRadians(toLat - fromLat);
double dLon = Math.toRadians(toLon - fromLon);
double tmp = Math.cos(Math.toRadians((fromLat + toLat) / 2)) * dLon;
double d = dLat * dLat + tmp * tmp;
return R * Math.sqrt(d);
}
Not sure about MySQL (sorry!).
Be sure you know about the limitation (the third param of assertEquals means the accuracy in kilometers):
float lat = 24.235f;
float lon = 47.234f;
CalcDistance dist = new CalcDistance();
double res = 15.051;
assertEquals(res, dist.calcDistKm(lat, lon, lat - 0.1, lon + 0.1), 1e-3);
assertEquals(res, dist.approxDistKm(lat, lon, lat - 0.1, lon + 0.1), 1e-3);
res = 150.748;
assertEquals(res, dist.calcDistKm(lat, lon, lat - 1, lon + 1), 1e-3);
assertEquals(res, dist.approxDistKm(lat, lon, lat - 1, lon + 1), 1e-2);
res = 1527.919;
assertEquals(res, dist.calcDistKm(lat, lon, lat - 10, lon + 10), 1e-3);
assertEquals(res, dist.approxDistKm(lat, lon, lat - 10, lon + 10), 10);
I arrived at a much simpler and robust solution which is using geodesic
from geopy
package since you'll be highly likely using it in your project anyways so no extra package installation needed.
Here is my solution:
from geopy.distance import geodesic
origin = (30.172705, 31.526725) # (latitude, longitude) don't confuse
dist = (30.288281, 31.732326)
print(geodesic(origin, dist).meters) # 23576.805481751613
print(geodesic(origin, dist).kilometers) # 23.576805481751613
print(geodesic(origin, dist).miles) # 14.64994773134371
Consider using System.Windows.Forms.Timer
instead of System.Threading.Timer
for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.
In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.
The answer given by Simon works fine for me but you have to do it in the right sequence: First you have to be in the server that you want to insert data into which is [DATABASE.WINDOWS.NET].[basecampdev] in your case.
You can try to see if you can select some data out of the Invoice table to make sure you have access.
Select top 10 * from [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
Secondly, execute the query given by Simon in order to link to a different server. This time use the other server:
EXEC sp_addlinkedserver [BC1-PC]; -- this will create a link tempdb that you can access from where you are
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR
[BC1-PC].testdabse.dbo.invoice; -- Make a copy of the table and data that you can use
GO
Now just do your insert statement.
INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
([InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks])
SELECT [InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks] FROM MyInvoice
Hope this helps!
I also made a library for this. It is fully configurable with a Mustache template. That can:
I also made:
More details on Github: https://github.com/tomasbjerre/git-changelog-lib
From command line:
npx git-changelog-command-line -std -tec "
# Changelog
Changelog for {{ownerName}} {{repoName}}.
{{#tags}}
## {{name}}
{{#issues}}
{{#hasIssue}}
{{#hasLink}}
### {{name}} [{{issue}}]({{link}}) {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
{{/hasLink}}
{{^hasLink}}
### {{name}} {{issue}} {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
{{/hasLink}}
{{/hasIssue}}
{{^hasIssue}}
### {{name}}
{{/hasIssue}}
{{#commits}}
**{{{messageTitle}}}**
{{#messageBodyItems}}
* {{.}}
{{/messageBodyItems}}
[{{hash}}](https://github.com/{{ownerName}}/{{repoName}}/commit/{{hash}}) {{authorName}} *{{commitTime}}*
{{/commits}}
{{/issues}}
{{/tags}}
"
Or in Jenkins:
Use Kubernetes Deployment and services.
Modify the definition of the function check_me as::
function check_me(ev) {
Now you can access the methods and parameters of the event, in your case:
ev.preventDefault();
Then, you have to pass the parameter on the onclick in the inline call::
<button type="button" onclick="check_me(event);">Click Me!</button>
A useful link to understand this.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
</script>
</head>
<body>
<button type="button" onclick="check_me(event);">Click Me!</button>
</body>
</html>
Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation
addEventListener
:<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id='my_button' type="button">Click Me!</button>
<!-- put the javascript at the end to guarantee that the DOM is ready to use-->
<script type="text/javascript">
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
<!-- add the event to the button identified #my_button -->
document.getElementById("my_button").addEventListener("click", check_me);
</script>
</body>
</html>
Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.
Just put this two files in the same folder:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id='my_button' type="button">Click Me!</button>
<!-- put the javascript at the end to guarantee that the DOM is ready to use-->
<script type="text/javascript" src="example.js"></script>
</body>
</html>
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);
According to facebooks best practices it is like this (2016)
Use images that are at least 1200 x 630 pixels for the best display on high resolution devices. At the minimum, you should use images that are 600 x 315 pixels to display link page posts with larger images. Images can be up to 8MB in size.
If your image is smaller than 600 x 315 px, it will still display in the link page post, but the size will be much smaller.
We've also redesigned link page posts so that the aspect ratio for images is the same across desktop and mobile News Feed. Try to keep your images as close to 1.91:1 aspect ratio as possible to display the full image in News Feed without any cropping.
The minimum image size is 200 x 200 pixels. If you try to use an image smaller than this you will see an error in the Sharing Debugger.
There are two different image sizes to use for game apps:
Open Graph Stories Images appear in a square format. Image ratios for these apps should be 600 x 600 px. Non-open Graph Stories Images appear in a rectangular format. You should use a 1.91:1 image ratio, such as 600 x 314 px.
If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:
const people = [
{ id: 1, name: 'serdar' },
{ id: 5, name: 'alex' },
{ id: 300, name: 'brittany' }
];
const idToRemove = 5;
const filteredPeople = people.filter((item) => item.id !== idToRemove);
// [
// { id: 1, name: 'serdar' },
// { id: 300, name: 'brittany' }
// [
Watch out though, filter()
is non-mutating, so you'll get a new array back.
You can get the different values with:
set(Article.objects.values_list('comment_id', flat=True))
In Ubuntu you can apply this way,
path = default_storage.save('static/tmp/' + f1.name, ContentFile(f1.read()))
path12 = os.path.join(os.getcwd(), "static/tmp/" + f1.name)
data={} #can be anything u want to pass along with File
file1 = open(path12, 'rb')
header = {"Content-Disposition": "attachment; filename=" + f1.name, "Authorization": "JWT " + token}
res= requests.post(url,data,header)
What worked for me is the following:
Switch to the needed branch:
git checkout -b BranchName
And then I pulled the "master" by:
git pull origin master
Here's an extension method using @Kolman's answer. It's marginally easier to remember to use Path() than GetLeftPart. You might want to rename Path to GetPath, at least until they add extension properties to C#.
Usage:
Uri uri = new Uri("http://www.somewhere.com?param1=foo¶m2=bar");
string path = uri.Path();
The class:
using System;
namespace YourProject.Extensions
{
public static class UriExtensions
{
public static string Path(this Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
return uri.GetLeftPart(UriPartial.Path);
}
}
}
As an alternative to other solutions, we will construct the tiles by generating a grid of coordinates using itertools.product
. We will ignore partial tiles on the edges, only iterating through the Cartesian product between the two intervals, i.e. range(0, h-h%d, d) X range(0, w-w%d, d)
.
Given fp
: the file name to the image, d
: the tile size, opt.path
: the path to the directory containing the images, and opt.out
: is the directory where tiles will be outputted:
def tile(filename, dir_in, dir_out, d):
name, ext = os.path.splitext(filename)
img = Image.open(os.path.join(dir_in, fp))
w, h = img.size
grid = list(product(range(0, h-h%d, d), range(0, w-w%d, d)))
for i, j in grid:
box = (j, i, j+d, i+d)
out = os.path.join(dir_out, f'{name}_{i}_{j}{ext}')
img.crop(box).save(out)
on OpenSUSE 13.1/13.2 its: /usr/lib64/jvm/java-1.6.0-openjdk-(version-number)
version-number can be 1.7.x 1.8.x etc. check software manager witch version you have installed...
André
Source code How to fetch Local Json from Assets folder
https://drive.google.com/open?id=1NG1amTVWPNViim_caBr8eeB4zczTDK2p
{
"responseCode": "200",
"responseMessage": "Recode Fetch Successfully!",
"responseTime": "10:22",
"employeesList": [
{
"empId": "1",
"empName": "Keshav",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9654267338",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "2",
"empName": "Ram",
"empFatherName": "Mr Dasrath ji",
"empSalary": "9999999999",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "3",
"empName": "Manisha",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "8826420999",
"empDesignation": "BusinessMan",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "4",
"empName": "Happy",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9582401701",
"empDesignation": "Two Wheeler",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "5",
"empName": "Ritu",
"empFatherName": "Mr Keshav Gera",
"empSalary": "8888888888",
"empDesignation": "Sararat Vibhag",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
}
]
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee);
emp_recycler_view = (RecyclerView) findViewById(R.id.emp_recycler_view);
emp_recycler_view.setLayoutManager(new LinearLayoutManager(EmployeeActivity.this,
LinearLayoutManager.VERTICAL, false));
emp_recycler_view.setItemAnimator(new DefaultItemAnimator());
employeeAdapter = new EmployeeAdapter(EmployeeActivity.this , employeeModelArrayList);
emp_recycler_view.setAdapter(employeeAdapter);
getJsonFileFromLocally();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = EmployeeActivity.this.getAssets().open("employees.json"); //TODO Json File name from assets folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void getJsonFileFromLocally() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
String responseCode = jsonObject.getString("responseCode");
String responseMessage = jsonObject.getString("responseMessage");
String responseTime = jsonObject.getString("responseTime");
Log.e("keshav", "responseCode -->" + responseCode);
Log.e("keshav", "responseMessage -->" + responseMessage);
Log.e("keshav", "responseTime -->" + responseTime);
if(responseCode.equals("200")){
}else{
Toast.makeText(this, "No Receord Found ", Toast.LENGTH_SHORT).show();
}
JSONArray jsonArray = jsonObject.getJSONArray("employeesList"); //TODO pass array object name
Log.e("keshav", "m_jArry -->" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
EmployeeModel employeeModel = new EmployeeModel();
JSONObject jsonObjectEmployee = jsonArray.getJSONObject(i);
String empId = jsonObjectEmployee.getString("empId");
String empName = jsonObjectEmployee.getString("empName");
String empDesignation = jsonObjectEmployee.getString("empDesignation");
String empSalary = jsonObjectEmployee.getString("empSalary");
String empFatherName = jsonObjectEmployee.getString("empFatherName");
employeeModel.setEmpId(""+empId);
employeeModel.setEmpName(""+empName);
employeeModel.setEmpDesignation(""+empDesignation);
employeeModel.setEmpSalary(""+empSalary);
employeeModel.setEmpFatherNamer(""+empFatherName);
employeeModelArrayList.add(employeeModel);
} // for
if(employeeModelArrayList!=null) {
employeeAdapter.dataChanged(employeeModelArrayList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You need to use backtick instead of single quotes:
Single quote - 'Business Name'
- Wrong
Backtick - `Business Name`
- Correct
There is a nice open source Git stack called Git Blit. It is available for different platform and in different packages. You can also easily deploy it to your existing Tomcat or any other servlet container. Take a look at Setup git server on windows in few clicks tutorial for more details, it will take you around 10 minutes to get basic setup.
In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.
I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.
One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.
private boolean switchComponents;
public boolean isSwitchComponents() {
return switchComponents;
}
public void setSwitchComponents(boolean switchComponents) {
this.switchComponents = switchComponents;
}
When the switch is true, one set of components will be shown and when it is false the other set will be shown.
<h:selectOneRadio value="#{backbean.switchValue}">
<f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
<f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
<f:ajax event="change" execute="@this" render="componentsRoot"/>
</h:selectOneRadio>
<H:panelGroup id="componentsRoot">
<h:panelGroup rendered="#{backbean.switchValue}">
<!--switchValue to be shown on switch value == true-->
</h:panelGroup>
<h:panelGroup rendered="#{!backbean.switchValue}">
<!--switchValue to be shown on switch value == false-->
</h:panelGroup>
</H:panelGroup>
Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.
Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).
Command to put list of all files and folders into a text file is as below:
Eg: dir /b /s | sort > ListOfFilesFolders.txt
my two cents about logic:
syntax is "old date" - :"new date", so:
SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:00', '2018-11-15 15:00:30')
gives 30,
SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:55', '2018-11-15 15:00:15')
gives: -40
A lot of the other solutions that use keypress will not work on mobile, you need to use input.
html
<input type="text" id="name" data-value="" autocomplete="off" spellcheck="true" placeholder="Type your name" autofocus />
jQuery
$('#name').on('input', function() {
var cursor_pos = $(this).getCursorPosition()
if(!(/^[a-zA-Z ']*$/.test($(this).val())) ) {
$(this).val($(this).attr('data-value'))
$(this).setCursorPosition(cursor_pos - 1)
return
}
$(this).attr('data-value', $(this).val())
})
$.fn.getCursorPosition = function() {
if(this.length == 0) return -1
return $(this).getSelectionStart()
}
$.fn.setCursorPosition = function(position) {
if(this.lengh == 0) return this
return $(this).setSelection(position, position)
}
$.fn.getSelectionStart = function(){
if(this.lengh == 0) return -1
input = this[0]
var pos = input.value.length
if (input.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', input.value.length)
if (r.text == '')
pos = input.value.length
pos = input.value.lastIndexOf(r.text)
} else if(typeof(input.selectionStart)!="undefined")
pos = input.selectionStart
return pos
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
if(this.lengh == 0) return this
input = this[0]
if(input.createTextRange) {
var range = input.createTextRange()
range.collapse(true)
range.moveEnd('character', selectionEnd)
range.moveStart('character', selectionStart)
range.select()
}
else if (input.setSelectionRange) {
input.focus()
input.setSelectionRange(selectionStart, selectionEnd)
}
return this
}
If you want to keep it simple, this should suffice:
function parseIsoDatetime(dtstr) {
var dt = dtstr.split(/[: T-]/).map(parseFloat);
return new Date(dt[0], dt[1] - 1, dt[2], dt[3] || 0, dt[4] || 0, dt[5] || 0, 0);
}
note parseFloat is must, parseInt doesn't always work. Map requires IE9 or later.
Works for formats:
Not valid for timezones, see other answers about those.
If the response code isn't 200 or 2xx, use getErrorStream()
instead of getInputStream().
you don't, declare an interface that declares the methods you would like to call:
public interface MyInterface
{
void doStuff();
}
public class MyClass implements MyInterface
{
public void doStuff()
{
System.Console.Writeln("done!");
}
}
then you use
MyInterface mobj = (myInterface)obj;
mobj.doStuff();
If MyClass
is not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).
An easy way to do this with some jQuery and straight JavaScript, just view your console in Chrome or Firefox to see the output...
var queries = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
queries[i[0].toString()] = i[1].toString();
});
console.log(queries);
Im not very familiar with the Android sdk, but it seems that the android-sdk
comes with the BouncyCastle
provider already added to the security.
What you will have to do in the PC environment is just add it manually,
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
if you have access to the policy
file, just add an entry like:
security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider
Notice the .5
it is equal to a sequential number of the already added providers.
Map can contain multiple arguments, the standard way is
map(add, a, b)
In your question, it should be
map(add, a, [2]*len(a))
Using map() instead of zip() fixes the padding issue in J.F. Sebastian's answer:
>>> def chunker(iterable, chunksize):
... return map(None,*[iter(iterable)]*chunksize)
Example:
>>> s = '1234567890'
>>> chunker(s, 3)
[('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9'), ('0', None, None)]
>>> chunker(s, 4)
[('1', '2', '3', '4'), ('5', '6', '7', '8'), ('9', '0', None, None)]
>>> chunker(s, 5)
[('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')]
I try to sort data with query it working fine for me please try this:
select name from user order by name asc
Also try below query for search record by alphabetically
SELECT name FROM `user` WHERE `name` LIKE 'b%'
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).
The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.
Tables that do not meet those requirements will not work with ipairs, use pairs instead.
Examples:
ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}
notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}
ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.
kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }
When printing these tables, these are the outputs. I've also included pairs outputs for comparison.
ipairs + ipairsCompatable
1 AAA
2 BBB
3 CCC
ipairs + ipairsCompatable2
1 DDD
2 EEE
3 FFF
ipairs + ipairsCompatable3
1 this
2 does
3 work
ipairs + notIpairsCompatable
pairs + notIpairsCompatable
2 this
3 does
4 not
ipairs + notIpairsCompatable2
pairs + notIpairsCompatable2
2 this
5 doesnt
24 either
ipairs + kindofIpairsCompatable
1 1
2 2
3 3
pairs + kindofIpairsCompatable
1 1
2 2
3 3
5 5
cool bro
Here is the entire script with an AJAX call to target a single list within a page with multiple lists. None of the other stuff above worked for me until I used the "id" attribute even though my attribute name is "ItemKey". By using the debugger
I was able to see that the selected option had attributes: with a map to the JQuery "id" and the value.
<html>
<head>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<select id="List1"></select>
<select id="List2">
<option id="40000">List item #1</option>
<option id="27888">List item #2</option>
</select>
<div></div>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#List1');
//request the JSON data and parse into the select element
$.ajax({
url: 'list.json',
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.List, function(key, val){
$select.append('<option id="' + val.ItemKey + '">' + val.ItemText + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
$( "#List1" ).change(function () {
var optionSelected = $('#List1 option:selected').attr('id');
$( "div" ).text( optionSelected );
});
</script>
</html>
Here is the JSON File to create...
{
"List":[
{
"Sort":1,
"parentID":0,
"ItemKey":100,
"ItemText":"ListItem-#1"
},
{
"Sort":2,
"parentID":0,
"ItemKey":200,
"ItemText":"ListItem-#2"
},
{
"Sort":3,
"parentID":0,
"ItemKey":300,
"ItemText":"ListItem-#3"
},
{
"Sort":4,
"parentID":0,
"ItemKey":400,
"ItemText":"ListItem-#4"
}
]
}
Hope this helps, thank you all above for getting me this far.
You need to tell the run to wait until the process is finished. Something like:
const DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0, WaitUntilFinished = true
set oShell = WScript.CreateObject("WScript.Shell")
command = "cmd /c C:\windows\system32\wscript.exe <path>\myScript.vbs " & args
oShell.Run command, DontShowWindow, WaitUntilFinished
In the script itself, start Excel like so. While debugging start visible:
File = "c:\test\myfile.xls"
oShell.run """C:\Program Files\Microsoft Office\Office14\EXCEL.EXE"" " & File, 1, true
Both Factory Method
and Abstract Factory
keep the clients decoupled from the concrete types. Both create objects, but Factory
method uses inheritance whereas Abstract Factory
use composition.
The Factory Method
is inherited in subclasses to create the concrete objects(products) whereas Abstract Factory
provide interface for creating the family of related products and subclass of these interface define how to create related products.
Then these subclasses when instantiated is passed into product classes where it is used as abstract type. The related products in an Abstract Factory
are often implemented using Factory Method
.
Use asp:image
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="images/image1.jpg"/>
and codebehind to change image url
Image1.ImageUrl = "/MyProject;component/Images/down.png";
Use a different tool. Something like Wolfram Alpha, Maple, R, Octave, Matlab or any other algebra software package.
As a beginner you should probably not attempt to solve such a non-trivial problem.
Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:
jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.
EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.
select * from left table where key field not in (select key field from right table)
The only thing you have to do is to add in the cshtml file, in the head, the following line:
@Styles.Render("~/Content/Main.css")
The entire head will look somethink like that:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML Page</title>
@Styles.Render("~/Content/main.css")
</head>
Hope it helps!!
You can use class(x) to check the variable type. If requirement is to check all variables type of a data frame then sapply(x, class) can be used.
This is an issue in the Chrome family and has been there forever.
A bug has been raised https://bugs.chromium.org/p/chromium/issues/detail?id=904208
It can be shown here: https://codepen.io/anon/pen/Jedvwj as soon as you add a border to anything button-like (say role="button" has been added to a tag for example) Chrome messes up and sets the focus state when you click with your mouse.
I highly recommend using this fix: https://github.com/wicg/focus-visible.
Just do the following
npm install --save focus-visible
Add the script to your html:
<script src="/node_modules/focus-visible/dist/focus-visible.min.js"></script>
or import into your main entry file if using webpack or something similar:
import 'focus-visible/dist/focus-visible.min';
then put this in your css file:
// hide the focus indicator if element receives focus via mouse, but show on keyboard focus (on tab).
.js-focus-visible :focus:not(.focus-visible) {
outline: none;
}
// Define a strong focus indicator for keyboard focus.
// If you skip this then the browser's default focus indicator will display instead
// ideally use outline property for those users using windows high contrast mode
.js-focus-visible .focus-visible {
outline: magenta auto 5px;
}
You can just set:
button:focus {outline:0;}
but if you have a large number of users, you're disadvantaging those who cannot use mice or those who just want to use their keyboard for speed.
If you really want to check for all those special characters, it's easier to use a regular expression:
var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('Your search string contains illegal characters.');
}
The above will only allow strings consisting entirely of characters on the ranges a-z
, A-Z
, 0-9
, plus the hyphen an space characters. A string containing any other character will cause the alert
.
If you need to use the latest versions of SciPy rather than the packaged version, without going through the hassle of building BLAS and LAPACK, you can follow the below procedure.
Install linear algebra libraries from repository (for Ubuntu),
sudo apt-get install gfortran libopenblas-dev liblapack-dev
Then install SciPy, (after downloading the SciPy source): python setup.py install
or
pip install scipy
As the case may be.
If you want to use objects as keys you need to overwrite their toString Method, as some already mentioned here. The hash functions that were used are all fine, but they only work for the same objects not for equal objects.
I've written a small library that creates hashes from objects, which you can easily use for this purpose. The objects can even have a different order, the hashes will be the same. Internally you can use different types for your hash (djb2, md5, sha1, sha256, sha512, ripemd160).
Here is a small example from the documentation:
var hash = require('es-hash');
// Save data in an object with an object as a key
Object.prototype.toString = function () {
return '[object Object #'+hash(this)+']';
}
var foo = {};
foo[{bar: 'foo'}] = 'foo';
/*
* Output:
* foo
* undefined
*/
console.log(foo[{bar: 'foo'}]);
console.log(foo[{}]);
The package can be used either in browser and in Node-Js.
Repository: https://bitbucket.org/tehrengruber/es-js-hash
It can be convenient to select count with filter by indexed field. Try this
EXPLAIN SELECT * FROM table_name WHERE key < anything;
Try this:
String numberStr = "3.5";
Float number = null;
try {
number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
System.out.println("numberStr is not a number");
}
HAVING
is used to filter on aggregations in your GROUP BY
.
For example, to check for duplicate names:
SELECT Name FROM Usernames
GROUP BY Name
HAVING COUNT(*) > 1
I came up with this one, that supports anchor and image tags, and supports single and double quotes.
<[a|img]+\\s+(?:[^>]*?\\s+)?[src|href]+=[\"']([^\"']*)['\"]
So
<a href="/something.ext">click here</a>
Will match:
Match 1: /something.ext
And
<a href='/something.ext'>click here</a>
Will match:
Match 1: /something.ext
Same goes for img src attributes
I prefer a non blocking approach:
Dim aw1=GenerateCodeAsync().GetAwaiter()
While Not aw1.IsCompleted
Application.DoEvents()
End While
Shortest:
str.slice(-2)
Example:
const str = "test";
const last2 = str.slice(-2);
console.log(last2);
_x000D_
In the interest of actually putting a working solution to this question:
SELECT ... WHERE `myDateColumn` >= DATE(DATE_FORMAT(NOW(),'%Y-%m-%d'));
Obviously, you could change the NOW() function to any date or variable you want.
I would say angular.copy(source);
in your situation is unnecessary if later on you do not use is it without a destination angular.copy(source, [destination]);
.
If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.
Update: in Rails 3.0.9: env method defined in railties/lib/rails.rb
Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());
and then use the methods period.getYears()
, period.getMonths()
, period.getDays()
, duration.toHoursPart()
, duration.toMinutesPart()
, duration.toSecondsPart()
.
I'll answer the original question, i.e. how to get the time difference between two LocalDateTimes
in years, months, days, hours & minutes, such that the "sum" (see note below) of all the values for the different units equals the total temporal difference, and such that the value in each unit is smaller than the next bigger unit—i.e. minutes < 60
, hours < 24
, and so on.
Given two LocalDateTimes
start
and end
, e.g.
LocalDateTime start = LocalDateTime.of(2019, 11, 29, 17, 15);
LocalDateTime end = LocalDateTime.of(2020, 11, 30, 18, 44);
we can represent the absolute timespan between the two with a Duration
—perhaps using Duration.between(start, end)
. But the biggest unit we can extract out of a Duration
is days (as a temporal unit equivalent to 24h)—see the note below for an explanation. To use larger units (months, years) we can represent this Duration
with a pair of (Period
, Duration
), where the Period
measures the difference up to a precision of days and the Duration
represents the remainder:
Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());
Now we can simply use the methods defined on Period
and Duration
to extract the individual units:
System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds",
period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(),
duration.toMinutesPart(), duration.toSecondsPart());
1 years, 0 months, 1 days, 1 hours, 29 minutes, 0 seconds
or, using the default format:
System.out.println(period + " + " + duration);
P1Y1D + PT1H29M
Note that, in java.time
's conception, "units" like "month" or "year" don't represent a fixed, absolute temporal value—they're date- and calendar-dependent, as the following example illustrates:
LocalDateTime
start1 = LocalDateTime.of(2020, 1, 1, 0, 0),
end1 = LocalDateTime.of(2021, 1, 1, 0, 0),
start2 = LocalDateTime.of(2021, 1, 1, 0, 0),
end2 = LocalDateTime.of(2022, 1, 1, 0, 0);
System.out.println(Period.between(start1.toLocalDate(), end1.toLocalDate()));
System.out.println(Duration.between(start1, end1).toDays());
System.out.println(Period.between(start2.toLocalDate(), end2.toLocalDate()));
System.out.println(Duration.between(start2, end2).toDays());
P1Y
366
P1Y
365
To add a column I just had to follow these steps :
rails generate migration add_fieldname_to_tablename fieldname:string
Alternative
rails generate migration addFieldnameToTablename
Once the migration is generated, then edit the migration and define all the attributes you want that column added to have.
Note: Table names in Rails are always plural (to match DB conventions). Example using one of the steps mentioned previously-
rails generate migration addEmailToUsers
rake db:migrate
Or
db/schema.rb
, Add the columns you want in the SQL query. Run this command: rake db:schema:load
Warning/Note
Bear in mind that, running rake db:schema:load
automatically wipes all data in your tables.
I found a good solution for adding/updating the CA certificates on RHEL/CentOS 6 which is the root cause reported issue.
Since they become outdated distros, the cacert authorities in that system has not been updated until executing the command sudo yum update
.
Didn't realize the issue until the GIT_CURL_VERBOSE mode shows the cacert path issue.
To use the array type properly as a function argument or template parameter, make a struct instead of a typedef, then add an operator[]
to the struct so you can keep the array like functionality like so:
typedef struct type24 {
char& operator[](int i) { return byte[i]; }
char byte[3];
} type24;
type24 x;
x[2] = 'r';
char c = x[2];
You can use substring and strpos to accomplish this goal.
You could also use a regular expression to pattern match only what you want. Your mileage may vary on which of these approaches makes more sense.
This post shows an example of a directive that delays the model changes to an input until the blur event fires.
Here is a fiddle that shows the ng-change working with the new ng-model-on-blur directive. Note this is a slight tweak to the original fiddle.
If you add the directive to your code you would change your binding to this:
<input type="text" ng-model="name" ng-model-onblur ng-change="update()" />
Here is the directive:
// override the default input to update on blur
angular.module('app', []).directive('ngModelOnblur', function() {
return {
restrict: 'A',
require: 'ngModel',
priority: 1, // needed for angular 1.2.x
link: function(scope, elm, attr, ngModelCtrl) {
if (attr.type === 'radio' || attr.type === 'checkbox') return;
elm.unbind('input').unbind('keydown').unbind('change');
elm.bind('blur', function() {
scope.$apply(function() {
ngModelCtrl.$setViewValue(elm.val());
});
});
}
};
});
Note: as @wjin mentions in the comments below this feature is supported directly in Angular 1.3 (currently in beta) via ngModelOptions
. See the docs for more info.
array.splice(array.pop(item));
If you're looking for just the instance variables in the object, this might be useful:
obj.instance_variables.map do |var|
puts [var, obj.instance_variable_get(var)].join(":")
end
or as a one-liner for copy and pasting:
obj.instance_variables.map{|var| puts [var, obj.instance_variable_get(var)].join(":")}
Create a role add this role to users, and then you can grant execute to all the routines in one shot to this role.
CREATE ROLE <abc>
GRANT EXECUTE TO <abc>
EDIT
This works in SQL Server 2005, I'm not sure about backward compatibility of this feature, I'm sure anything later than 2005 should be fine.
In my case I was throwing Exception
on a namespaced file, so php tried to catch My\Namespace\Exception
therefore not catching any exceptions at all.
Worth checking if catch (Exception $e)
is finding the right Exception
class.
Just try catch (\Exception $e)
(with that \
there) and see if it works.
After following the steps suggested by previous posters, do the following steps:
You should be good to go now.
this is your first Activity1.
public class Activity1 extends Activity{
private int mRequestCode = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, Activity2.class);
startActivityForResult(intent, mRequestCode);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == mRequestCode && resultCode == RESULT_OK){
String editTextString = data.getStringExtra("editText");
}
}
}
From here you are starting your Activity2.class by using startActivityForResult(mRequestCode, Activity2.class);
Now this is your second Activity, name is Activity2
public class Activity2 extends Activity {
private EditText mEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//mEditText = (EditText)findViewById(R.id.edit_text);
Intent intent = new Intent();
intent.putExtra("editText", mEditText.getText().toString());
setResult(RESULT_OK, intent);
}
}
Now when you done with your second Activity then you call setResult() method, from onBackPress() or from any button click when your Activity2 will destroy then your Activity1's call back method onActivityResult() will call from there you can get your data from intent..
Hope it will help to you...:)
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
<span style='color:blue '> your message/text </span>
So here it is a perfect html css style entry inside a notebook ipynb file.
Of course you can choose your favourite color here and then your text.
include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json
There's no error here. You're printing a function, and that's what functions look like.
To actually call the function, you have to put parens after that. You're already doing that above. If you want to print the result of calling the function, just have the function return the value, and put the print there. For example:
print test.sort_word_list()
On the other hand, if you want the function to mutate the object's state, and then print the state some other way, that's fine too.
Now, your code seems to work in some places, but not others; let's look at why:
parser
sets a variable called word_list
, and you later print test.word_list
, so that works.sort_word_list
sets a variable called sorted_word_list
, and you later print test.sort_word_list
—that is, the function, not the variable. So, you see the bound method. (Also, as Jon Clements points out, even if you fix this, you're going to print None
, because that's what sort
returns.)num_words
sets a variable called num_words
, and you again print the function—but in this case, the variable has the same name as the function, meaning that you're actually replacing the function with its output, so it works. This is probably not what you want to do, however.(There are cases where, at first glance, that seems like it might be a good idea—you only want to compute something once, and then access it over and over again without constantly recomputing that. But this isn't the way to do it. Either use a @property
, or use a memoization decorator.)
I prefer to use an angular filter.
app.filter('num', function() {
return function(input) {
return parseInt(input, 10);
};
});
then you can use this in the dom:
{{'10'|num}}
Here is a fiddle.
Hope this helped!
Here is an alternate solution for version 4.x of Select2. You can use listeners to catch the focus event and then open the select.
$('#test').select2({
// Initialisation here
}).data('select2').listeners['*'].push(function(name, target) {
if(name == 'focus') {
$(this.$element).select2("open");
}
});
Find the working example here based the exampel created by @tonywchen
After trying almost every key on my keyboard:
C:\Users\Tim>cd ^
Mehr? Desktop
C:\Users\Tim\Desktop>
So it seems to be the ^ key.
I had an error with an array getting the max and the min so my solution was:
int max = Arrays.stream(arrayWithInts).max().getAsInt();
int min = Arrays.stream(arrayWithInts).min().getAsInt();
There's the shade maven plugin. It can be used to package and rename dependencies (to omit dependency problems on the classpath).
a) Adding inline style
document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');
b) or a bit harder method - adding "mouseover"
document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };
Note: multi-word styles (i.e.font-size
) in Javascript are written together:
element.style.fontSize="12px"
Go to https://developers.facebook.com/apps and open the app you have created. open setting tab and add platform and insert site url where you want to share facebook button .Its done.
Because you initialize myList with 'new', the list itself will never be null.
But it can be filled with 'null' values.
In that case .Count > 0
and .Any()
will be true. You can check this with the .All(s => s == null)
var myList = new List<object>();
if (myList.Any() || myList.All(s => s == null))
These are identical for printf
but different for scanf
. For printf
, both %d
and %i
designate a signed decimal integer. For scanf
, %d
and %i
also means a signed integer but %i
inteprets the input as a hexadecimal number if preceded by 0x
and octal if preceded by 0
and otherwise interprets the input as decimal.
Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).
df <- data.frame(X=c(), R=c())
x <- x0
continue <- TRUE
while(continue)
{
xi <- (11 * x) %% 16
df <- rbind(df, data.frame(X=x, R=xi))
x <- xi
if(xi == x0)
{
continue <- FALSE
}
}
I note you suggested this formula
=IF(ISNUMBER(FIND("RuhrP";F9));LOOKUP(A9;Ruhrpumpen!A$5:A$100;Ruhrpumpen!I$5:I$100);"")
.....but LOOKUP
isn't appropriate here because I assume you want an exact match (LOOKUP won't guarantee that and also data in lookup range has to be sorted), so VLOOKUP
or INDEX/MATCH
would be better....and you can also use IFERROR to avoid the IF function, i.e
=IFERROR(VLOOKUP(A9;Ruhrpumpen!A$5:Z$100;9;0);"")
Note: VLOOKUP always looks up the lookup value (A9) in the first column of the "table array" and returns a value from the nth column of the "table array" where n is defined by col_index_num, in this case 9
INDEX/MATCH is sometimes more flexible because you can explicitly define the lookup column and the return column (and return column can be to the left of the lookup column which can't be the case in VLOOKUP), so that would look like this:
=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH(A9;Ruhrpumpen!A$5:A$100;0));"")
INDEX/MATCH also allows you to more easily return multiple values from different columns, e.g. by using $ signs in front of A9 and the lookup range Ruhrpumpen!A$5:A$100, i.e.
=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH($A9;Ruhrpumpen!$A$5:$A$100;0));"")
this version can be dragged across to get successive values from column I, column J, column K etc.....
An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.
WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.
The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.
You can use this:
import java.util.Timer;
and for the delay itself, add:
new Timer().schedule(
new TimerTask(){
@Override
public void run(){
//if you need some code to run when the delay expires
}
}, delay);
where the delay
variable is in milliseconds; for example set delay
to 5000 for a 5-second delay.
While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.
So for everyone in need here is a full working example:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)
myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)
## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()
onClose: function(selectedDate) {
$("#dpTodate").datepicker("option", "minDate", selectedDate);
var maxDate = new Date(selectedDate);
maxDate.setDate(maxDate.getDate() + 6); //6 days extra in from date
$("#dpTodate").datepicker("option", "maxDate", maxDate);
}
The way to access a session variable in Twig is:
{{ app.session.get('name_variable') }}
One thing I don't think has been mentioned in the previous answers.
I'm always sensing a "bad smell" in the refactoring sense when people are using such things in their design.
That's a huge array and possibly not the best way to represent your data both from an efficiency point of view and a performance point of view.
cheers,
Rob
being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -
eventually decided to use CLINT as an answer that was given there by great and smart people
The File.Create
method creates the file and opens a FileStream
on the file. So your file is already open. You don't really need the file.Create method at all:
string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
//write to the file
}
The boolean in the StreamWriter
constructor will cause the contents to be appended if the file exists.
private void dtgworkingdays_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
this.FillRecordNo();
}
private void FillRecordNo()
{
for (int i = 0; i < this.dtworkingdays.Rows.Count; i++)
{
this.dtgworkingdays.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
}
Here is a code to get custom cell from index path
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
YourCell *cell = (YourCell *)[tblRegister cellForRowAtIndexPath:indexPath];
For Swift
let indexpath = NSIndexPath(forRow: 2, inSection: 0)
let currentCell = tblTest.cellForRowAtIndexPath(indexpath) as! CellTest
For Swift 4 (for collectionview)
let indexpath = NSIndexPath(row: 2, section: 0)
let cell = self.colVw!.cellForItem(at: indexpath as IndexPath) as? ColViewCell
Had the same problem recently.
I discovered that simply defining DataType as Date in the model works as well (using Code First approach)
[DataType(DataType.Date)]
public DateTime Added { get; set; }
I had the same problem with webapi in ASP.NET core, in my case it was because my application needs authentication, then it assigns the annotation [AllowAnonymous]
and it worked.
[AllowAnonymous]
public async Task <IList <IServic >> GetServices () {
}
You use ComponentScan to scan multiple packages using
@ComponentScan({"com.my.package.first","com.my.package.second"})
See Class Constants:
class MyClass
{
const MYCONSTANT = 'constant value';
function showConstant() {
echo self::MYCONSTANT. "\n";
}
}
echo MyClass::MYCONSTANT. "\n";
$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0
$class = new MyClass();
$class->showConstant();
echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0
In this case echoing MYCONSTANT
by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT"
.
EDIT - Perhaps what you're looking for is this static properties / variables:
class MyClass
{
private static $staticVariable = null;
public static function showStaticVariable($value = null)
{
if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
{
self::$staticVariable = $value;
}
return self::$staticVariable;
}
}
MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"
~$ echo $PATH
/home/jack/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
~$ whereis lshw
lshw: /usr/bin/lshw /usr/share/man/man1/lshw.1.gz
I have created a table of major differences between elasticsearch and Solr and splunk, you can use it as 2016 update:
I've created a new class to handle binding RadioButtons and CheckBoxes to enums. It works for flagged enums (with multiple checkbox selections) and non-flagged enums for single-selection checkboxes or radio buttons. It also requires no ValueConverters at all.
This might look more complicated at first, however, once you copy this class into your project, it's done. It's generic so it can easily be reused for any enum.
public class EnumSelection<T> : INotifyPropertyChanged where T : struct, IComparable, IFormattable, IConvertible
{
private T value; // stored value of the Enum
private bool isFlagged; // Enum uses flags?
private bool canDeselect; // Can be deselected? (Radio buttons cannot deselect, checkboxes can)
private T blankValue; // what is considered the "blank" value if it can be deselected?
public EnumSelection(T value) : this(value, false, default(T)) { }
public EnumSelection(T value, bool canDeselect) : this(value, canDeselect, default(T)) { }
public EnumSelection(T value, T blankValue) : this(value, true, blankValue) { }
public EnumSelection(T value, bool canDeselect, T blankValue)
{
if (!typeof(T).IsEnum) throw new ArgumentException($"{nameof(T)} must be an enum type"); // I really wish there was a way to constrain generic types to enums...
isFlagged = typeof(T).IsDefined(typeof(FlagsAttribute), false);
this.value = value;
this.canDeselect = canDeselect;
this.blankValue = blankValue;
}
public T Value
{
get { return value; }
set
{
if (this.value.Equals(value)) return;
this.value = value;
OnPropertyChanged();
OnPropertyChanged("Item[]"); // Notify that the indexer property has changed
}
}
[IndexerName("Item")]
public bool this[T key]
{
get
{
int iKey = (int)(object)key;
return isFlagged ? ((int)(object)value & iKey) == iKey : value.Equals(key);
}
set
{
if (isFlagged)
{
int iValue = (int)(object)this.value;
int iKey = (int)(object)key;
if (((iValue & iKey) == iKey) == value) return;
if (value)
Value = (T)(object)(iValue | iKey);
else
Value = (T)(object)(iValue & ~iKey);
}
else
{
if (this.value.Equals(key) == value) return;
if (!value && !canDeselect) return;
Value = value ? key : blankValue;
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And for how to use it, let's say you have an enum for running a task manually or automatically, and can be scheduled for any days of the week, and some optional options...
public enum StartTask
{
Manual,
Automatic
}
[Flags()]
public enum DayOfWeek
{
Sunday = 1 << 0,
Monday = 1 << 1,
Tuesday = 1 << 2,
Wednesday = 1 << 3,
Thursday = 1 << 4,
Friday = 1 << 5,
Saturday = 1 << 6
}
public enum AdditionalOptions
{
None = 0,
OptionA,
OptionB
}
Now, here's how easy it is to use this class:
public class MyViewModel : ViewModelBase
{
public MyViewModel()
{
StartUp = new EnumSelection<StartTask>(StartTask.Manual);
Days = new EnumSelection<DayOfWeek>(default(DayOfWeek));
Options = new EnumSelection<AdditionalOptions>(AdditionalOptions.None, true, AdditionalOptions.None);
}
public EnumSelection<StartTask> StartUp { get; private set; }
public EnumSelection<DayOfWeek> Days { get; private set; }
public EnumSelection<AdditionalOptions> Options { get; private set; }
}
And here's how easy it is to bind checkboxes and radio buttons with this class:
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<!-- Using RadioButtons for exactly 1 selection behavior -->
<RadioButton IsChecked="{Binding StartUp[Manual]}">Manual</RadioButton>
<RadioButton IsChecked="{Binding StartUp[Automatic]}">Automatic</RadioButton>
</StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Using CheckBoxes for 0 or Many selection behavior -->
<CheckBox IsChecked="{Binding Days[Sunday]}">Sunday</CheckBox>
<CheckBox IsChecked="{Binding Days[Monday]}">Monday</CheckBox>
<CheckBox IsChecked="{Binding Days[Tuesday]}">Tuesday</CheckBox>
<CheckBox IsChecked="{Binding Days[Wednesday]}">Wednesday</CheckBox>
<CheckBox IsChecked="{Binding Days[Thursday]}">Thursday</CheckBox>
<CheckBox IsChecked="{Binding Days[Friday]}">Friday</CheckBox>
<CheckBox IsChecked="{Binding Days[Saturday]}">Saturday</CheckBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Using CheckBoxes for 0 or 1 selection behavior -->
<CheckBox IsChecked="{Binding Options[OptionA]}">Option A</CheckBox>
<CheckBox IsChecked="{Binding Options[OptionB]}">Option B</CheckBox>
</StackPanel>
</StackPanel>
iif has always been available in VB, even in VB6.
Dim foo as String = iif(bar = buz, cat, dog)
It is not a true operator, as such, but a function in the Microsoft.VisualBasic namespace.
My solution:
public static class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final MainActivity mParentActivity;
private final List<DummyContent.DummyItem> mValues;
private final boolean mTwoPane;
private static int lastClickedPosition=-1;
**private static View viewOld=null;**
private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
DummyContent.DummyItem item = (DummyContent.DummyItem) view.getTag();
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, item.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
mParentActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = view.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, item.id);
context.startActivity(intent);
}
**view.setBackgroundColor(mParentActivity.getResources().getColor(R.color.SelectedColor));
if(viewOld!=null)
viewOld.setBackgroundColor(mParentActivity.getResources().getColor(R.color.DefaultColor));
viewOld=view;**
}
};
viewOld
is null
at the beginning, then points to the last selected view.
With onClick
you change the background of the selected view and redefine the background of the penultimate view selected.
Simple and functional.
In
x ? "yes" : "no"
the ? declares an if sentence. Here: x represents the boolean condition; The part before the : is the then sentence and the part after is the else sentence.
In, for example,
int?
the ? declares a nullable type, and means that the type before it may have a null value.
Both node.js and MongoChef force me to convert to ObjectId. This is what I use to grab a list of users from the DB and fetch a few properties. Mind the type conversion on line 8.
// this will complement the list with userName and userPhotoUrl based on userId field in each item
augmentUserInfo = function(list, callback){
var userIds = [];
var users = []; // shortcut to find them faster afterwards
for (l in list) { // first build the search array
var o = list[l];
if (o.userId) {
userIds.push( new mongoose.Types.ObjectId( o.userId ) ); // for the Mongo query
users[o.userId] = o; // to find the user quickly afterwards
}
}
db.collection("users").find( {_id: {$in: userIds}} ).each(function(err, user) {
if (err) callback( err, list);
else {
if (user && user._id) {
users[user._id].userName = user.fName;
users[user._id].userPhotoUrl = user.userPhotoUrl;
} else { // end of list
callback( null, list );
}
}
});
}
I'd love to post this as a comment to Tendayi Mawushe's answer, but I'm afraid there is not enough space ;)
This is the relevant part from the Apache Commons UrlValidator source:
/**
* This expression derived/taken from the BNF for URI (RFC2396).
*/
private static final String URL_PATTERN =
"/^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
// 12 3 4 5 6 7 8 9
/**
* Schema/Protocol (ie. http:, ftp:, file:, etc).
*/
private static final int PARSE_URL_SCHEME = 2;
/**
* Includes hostname/ip and port number.
*/
private static final int PARSE_URL_AUTHORITY = 4;
private static final int PARSE_URL_PATH = 5;
private static final int PARSE_URL_QUERY = 7;
private static final int PARSE_URL_FRAGMENT = 9;
You can easily build your own validator from there.
Async arrow functions look like this:
const foo = async () => {
// do something
}
Async arrow functions look like this for a single argument passed to it:
const foo = async evt => {
// do something with evt
}
Async arrow functions look like this for multiple arguments passed to it:
const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}
The anonymous form works as well:
const foo = async function() {
// do something
}
An async function declaration looks like this:
async function foo() {
// do something
}
Using async function in a callback:
const foo = event.onCall(async () => {
// do something
})
@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:
//-----------------------------------------
// @param begin Required. The index where
// to begin the extraction.
// 1st character is at index 0
//
// @param end Optional. Where to end the
// extraction. If omitted,
// slice() selects all
// characters from the begin
// position to the end of
// the string.
var str = '123-4';
alert(str.slice(0, -1));
void
is a reserved JavaScript keyword. It evaluates the expression and always returns undefined
.
Try add jQuery
to your project, like
npm i jquery --save
or if you use bower
bower i jquery --save
then
import $ from 'jquery';
For best performance I recommend doing DataFrame.drop_duplicates
followed up aggfunc='count'
.
Others are correct that aggfunc=pd.Series.nunique
will work. This can be slow, however, if the number of index
groups you have is large (>1000).
So instead of (to quote @Javier)
df2.pivot_table('X', 'Y', 'Z', aggfunc=pd.Series.nunique)
I suggest
df2.drop_duplicates(['X', 'Y', 'Z']).pivot_table('X', 'Y', 'Z', aggfunc='count')
This works because it guarantees that every subgroup (each combination of ('Y', 'Z')
) will have unique (non-duplicate) values of 'X'
.
If you place the dollar sign before the letter, you will affect only the column, not the row. If you want to have it affect only a row, place the dollar before the number.
You may want to use =isblank() rather than =""
I'm also confused by your comment "no values throughout spreadsheet - just text" - text is a value.
One more hint - excel has a habit of rewriting rules - I don't know how many rules I've written only to discover that excel has changed the values in the "apply to" or formula entry fields.
If you could post an example, I'll revise the answer. Conditional formatting is very finicky.
Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.
If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)
I got the very same error when trying to access the child FragmentManager
before the fragment was fully initialized (i.e. attached to the Activity or at least onCreateView()
called). Else the FragmentManager
gets initialized with a null
Activity causing the aforementioned exception.
As it's said by "Tim Schmelter" this is the best way : just change in it's code the seconde loop ( GridView2.Columns[i].Count by row.Cells.Count ) so it looks seem's that:
foreach(GridViewRow row in GridView2.Rows)
{
for(int i = 0; i < GridView2.Columns.Count; i++)
{
String header = GridView2.Columns[i].HeaderText;
String cellText = row.Cells[i].Text;
}
}
thank you.
In ASP.NET Core 2 Web API
, using Swashbuckle.AspNetCore package 2.1.0, implement a IDocumentFilter:
SwaggerSecurityRequirementsDocumentFilter.cs
using System.Collections.Generic;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace api.infrastructure.filters
{
public class SwaggerSecurityRequirementsDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument document, DocumentFilterContext context)
{
document.Security = new List<IDictionary<string, IEnumerable<string>>>()
{
new Dictionary<string, IEnumerable<string>>()
{
{ "Bearer", new string[]{ } },
{ "Basic", new string[]{ } },
}
};
}
}
}
In Startup.cs, configure a security definition and register the custom filter:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
// c.SwaggerDoc(.....
c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "Authorization header using the Bearer scheme",
Name = "Authorization",
In = "header"
});
c.DocumentFilter<SwaggerSecurityRequirementsDocumentFilter>();
});
}
In Swagger UI, click on Authorize button and set value for token.
Result:
curl -X GET "http://localhost:5000/api/tenants" -H "accept: text/plain" -H "Authorization: Bearer ABCD123456"
use:
var parsedobj = jQuery.parseJSON( jsonObj);
This will only be useful if you don't need the format to stay in string. otherwise you'd have to convert this back to JSON using the JSON library.
Here's a solution to your problem using dplyr's filter
function.
Although you can pass your data frame as the first argument to any dplyr function, I've used its %>%
operator, which pipes your data frame to one or more dplyr functions (just filter in this case).
Once you are somewhat familiar with dplyr, the cheat sheet is very handy.
> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
sub day
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
6 2 2
7 2 3
8 2 4
9 3 1
10 3 2
11 3 3
12 3 4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
sub day
1 1 1
2 1 3
3 1 4
4 2 1
5 2 2
6 2 3
7 2 4
8 3 1
9 3 2
10 3 3
If you have a common parent div you can use parentsUntil() link
eg: $('#element').parentsUntil('.commonClass')
Advantage is that you need not to remember how many generation are there between this element and the common parent(defined by commonclass).
According to Laravel 5.2 docs, your publicly accessible files should be put in directory
storage/app/public
To make them accessible from the web, you should create a symbolic link from public/storage
to storage/app/public
.
ln -s /path/to/laravel/storage/app/public /path/to/laravel/public/storage
Now you can create in your view an URL to the files using the asset helper:
echo asset('storage/file.txt');
You should use the server-side code in order to secure your MailChimp account.
The following is an updated version of this answer which uses PHP:
The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.
1) Download the PHP 5 jQuery example here...
http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip
If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php
file above.
http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip
2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php
file at the proper locations.
3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php
file using the corresponding Merge Variables.
Here is what my store-address.php
file looks like where I also gather the first name, last name, and email type:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('123456789-us2');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "123456a";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.
Here is something like what my index.html
file looks like:
<form id="signup" action="index.html" method="get">
<input type="hidden" name="ajax" value="true" />
First Name: <input type="text" name="fname" id="fname" />
Last Name: <input type="text" name="lname" id="lname" />
email Address (required): <input type="email" name="email" id="email" />
HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
Text: <input type="radio" name="emailtype" value="text" />
<input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("<span class='error'>Adding your email address...</span>");
$.ajax({
url: 'inc/store-address.php', // proper url to your "store-address.php" file
data: $('#signup').serialize(),
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
Required pieces...
index.html constructed as above or similar. With jQuery, the appearance and options are endless.
store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.
MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.
Example of using a Timer
:
using System;
using System.Timers;
static void Main(string[] args)
{
Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
t.AutoReset = true;
t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
t.Start();
}
// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
Console.WriteLine("...");
}
Add this class: d-flex align-items-center
to the element
If you had this:
<div class="col-3">
change it to this:
<div class="col-3 d-flex align-items-center>
The easiest way to convert a QString to char* is qPrintable(const QString& str),
which is a macro expanding to str.toLocal8Bit().constData()
.
I had the same problem with python3 and pip3. Decision: solving all conflicts with links and other stuff when do
brew doctor
After that
brew reinstall python3
Define a behavior in your .config
file:
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="debug">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
...
</system.serviceModel>
</configuration>
Then apply the behavior to your service along these lines:
<configuration>
<system.serviceModel>
...
<services>
<service name="MyServiceName" behaviorConfiguration="debug" />
</services>
</system.serviceModel>
</configuration>
You can also set it programmatically. See this question.
You should set the 'interactive_timeout' and 'wait_timeout' properties in the mysql config file to the values you need.
Under Flask, this works and handles datatime fields, transforming a field of type
'time': datetime.datetime(2018, 3, 22, 15, 40)
into
"time": "2018-03-22 15:40:00"
:
obj = {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}
# This to get the JSON body
return json.dumps(obj)
# Or this to get a response object
return jsonify(obj)
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
I agree with guys. But sometimes you have to add more things.
IE
1) Add this worker.WorkerSupportsCancellation = true;
2) Add to you class some method to do the following things
public void KillMe()
{
worker.CancelAsync();
worker.Dispose();
worker = null;
GC.Collect();
}
So before close your application your have to call this method.
3) Probably you can Dispose, null
all variables and timers which are inside of the BackgroundWorker
.
Somewhat simpler XPath 1.0 solution, adapted from Tomalek's (posted here) and Dimitre's (here):
concat(substring($s1, 1 div number($cond)), substring($s2, 1 div number(not($cond))))
Note: I found an explicit number() was required to convert the bool to an int otherwise some XPath evaluators threw a type mismatch error. Depending on how strict your XPath processor is type-matching you may not need it.
Also got the same error when using ajax.
If you're using ajax to render forms with select2, the input_html class must be different from those NOT rendered using ajax. Not quite sure why it works this way though.
Here's what worked for me:
select visits, activations, simulations, simulations/activations
as sims_per_visit, activations/visits*100
as adoption_rate, simulations/activations*100
as completion_rate, duration/60
as minutes, m1 as month, Wk1 as week, Yr1 as year
from
(
(select count(*) as visits, year(stamp) as Yr1, week(stamp) as Wk1, month(stamp)
as m1 from sessions group by week(stamp), year(stamp)) as t3
join
(select count(*) as activations, year(stamp) as Yr2, week(stamp) as Wk2,
month(stamp) as m2 from sessions where activated='1' group by week(stamp),
year(stamp)) as t4
join
(select count(*) as simulations, year(stamp) as Yr3 , week(stamp) as Wk3,
month(stamp) as m3 from sessions where simulations>'0' group by week(stamp),
year(stamp)) as t5
join
(select avg(duration) as duration, year(stamp) as Yr4 , week(stamp) as Wk4,
month(stamp) as m4 from sessions where activated='1' group by week(stamp),
year(stamp)) as t6
)
where Yr1=Yr2 and Wk1=Wk2 and Wk1=Wk3 and Yr1=Yr3 and Yr1=Yr4 and Wk1=Wk4
I used joins, not unions (I needed different columns for each query, a join puts it all in the same column) and I dropped the quotation marks (compared to what Liam was doing) because they were giving me errors.
Thanks! I couldn't have pulled that off without this page! PS: Sorry I don't know how you're getting your statements formatted with colors. etc.
I've been to this post about 10 times now and I just wanted to leave my two cents here. You can just unmount it conditionally.
if (renderMyComponent) {
<MyComponent props={...} />
}
All you have to do is remove it from the DOM in order to unmount it.
As long as renderMyComponent = true
, the component will render. If you set renderMyComponent = false
, it will unmount from the DOM.
$('.radio-button-class-name').is('checked') didn't work for me, but the next code worked well:
if(typeof $('.radio-button-class-name:checked').val() !== 'undefined'){
// radio button is checked
}
The answer would slightly tilt towards quicksort w.r.t to changes brought with DualPivotQuickSort for primitive values . It is used in JAVA 7 to sort in java.util.Arrays
It is proved that for the Dual-Pivot Quicksort the average number of
comparisons is 2*n*ln(n), the average number of swaps is 0.8*n*ln(n),
whereas classical Quicksort algorithm has 2*n*ln(n) and 1*n*ln(n)
respectively. Full mathematical proof see in attached proof.txt
and proof_add.txt files. Theoretical results are also confirmed
by experimental counting of the operations.
You can find the JAVA7 implmentation here - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/Arrays.java
Further Awesome Reading on DualPivotQuickSort - http://permalink.gmane.org/gmane.comp.java.openjdk.core-libs.devel/2628
This is good replacement for AngularJs orderby pipe in angular 4. Easy and simple to use.
This is github URL for more information https://github.com/VadimDez/ngx-order-pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderBy'
})
export class OrderPipe implements PipeTransform {
transform(value: any | any[], expression?: any, reverse?: boolean): any {
if (!value) {
return value;
}
const isArray = value instanceof Array;
if (isArray) {
return this.sortArray(value, expression, reverse);
}
if (typeof value === 'object') {
return this.transformObject(value, expression, reverse);
}
return value;
}
/**
* Sort array
*
* @param value
* @param expression
* @param reverse
* @returns {any[]}
*/
private sortArray(value: any[], expression?: any, reverse?: boolean): any[] {
const isDeepLink = expression && expression.indexOf('.') !== -1;
if (isDeepLink) {
expression = OrderPipe.parseExpression(expression);
}
let array: any[] = value.sort((a: any, b: any): number => {
if (!expression) {
return a > b ? 1 : -1;
}
if (!isDeepLink) {
return a[expression] > b[expression] ? 1 : -1;
}
return OrderPipe.getValue(a, expression) > OrderPipe.getValue(b, expression) ? 1 : -1;
});
if (reverse) {
return array.reverse();
}
return array;
}
/**
* Transform Object
*
* @param value
* @param expression
* @param reverse
* @returns {any[]}
*/
private transformObject(value: any | any[], expression?: any, reverse?: boolean): any {
let parsedExpression = OrderPipe.parseExpression(expression);
let lastPredicate = parsedExpression.pop();
let oldValue = OrderPipe.getValue(value, parsedExpression);
if (!(oldValue instanceof Array)) {
parsedExpression.push(lastPredicate);
lastPredicate = null;
oldValue = OrderPipe.getValue(value, parsedExpression);
}
if (!oldValue) {
return value;
}
const newValue = this.transform(oldValue, lastPredicate, reverse);
OrderPipe.setValue(value, newValue, parsedExpression);
return value;
}
/**
* Parse expression, split into items
* @param expression
* @returns {string[]}
*/
private static parseExpression(expression: string): string[] {
expression = expression.replace(/\[(\w+)\]/g, '.$1');
expression = expression.replace(/^\./, '');
return expression.split('.');
}
/**
* Get value by expression
*
* @param object
* @param expression
* @returns {any}
*/
private static getValue(object: any, expression: string[]) {
for (let i = 0, n = expression.length; i < n; ++i) {
const k = expression[i];
if (!(k in object)) {
return;
}
object = object[k];
}
return object;
}
/**
* Set value by expression
*
* @param object
* @param value
* @param expression
*/
private static setValue(object: any, value: any, expression: string[]) {
let i;
for (i = 0; i < expression.length - 1; i++) {
object = object[expression[i]];
}
object[expression[i]] = value;
}
}
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId
.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
I think, that in this case using PYTHONPATH is a better thing, mostly because it doesn't introduce (questionable) unneccessary code.
After all, if you think of it, your user doesn't need that sys.path
thing, because your package will get installed into site-packages, because you will be using a packaging system.
If the user chooses to run from a "local copy", as you call it, then I've observed, that the usual practice is to state, that the package needs to be added to PYTHONPATH manually, if used outside the site-packages.
In my case, reading docs of third party apps properly saved me.
The culprit? django_compressor
I had
{% load compress %}
{% compress css %}
... css files linked here ..
{% endcompress %}
DEBUG = True
always gave me 500. To fix it, I needed a line in my settings to get it running
COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)
How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.
<div class="container">
<div class="row">
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col1
</div>
<div class="col-xs-4 col-sm-2" align="center">
Col2
</div>
<div class="hidden-xs col-sm-6 col-md-5" align="center">
Col3
</div>
<div class="visible-md col-md-3 " align="center">
Col4
</div>
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col5
</div>
</div>
</div>
I came up with this.This seems to work best for me.It converts a string of number and splits it into array of integer:
void splitInput(int arr[], int sizeArr, char num[])
{
for(int i = 0; i < sizeArr; i++)
// We are subtracting 48 because the numbers in ASCII starts at 48.
arr[i] = (int)num[i] - 48;
}
Even though the <head>
and <body>
tags aren't required, the elements are still there - it's just that the browser can work out where the tags would have been from the rest of the document.
The other elements you're using still have to be inside the <body>
I had also the same problem. Please add this line in application tag in manifest. I hope it will also help you.
android:usesCleartextTraffic="true"
JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.
The example he gives declares and initializes the variable i
in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i
would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:
switch(choice) {
case 1:
int i = 10; // i is never used outside of this case
printf("i = %d\n", i);
break;
case 2:
int j = 20; // j is never used outside of this case
printf("j = %d\n", j);
break;
}
One could expect this program to compile, since both i
and j
are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:
, because this would skip the declaration with initialization of i
, and even though case 2
doesn't use i
at all, this is still forbidden in C++.
Interestingly, with some adjustments (an #ifdef
to #include
the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:
// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif
int main() {
int choice;
printf("Please enter 1 or 2: ");
scanf("%d", &choice);
switch(choice) {
case 1:
;
int i = 10; // i is never used outside of this case
printf("i = %d\n", i);
break;
case 2:
;
int j = 20; // j is never used outside of this case
printf("j = %d\n", j);
break;
}
}
Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.
Having had a similar problem with data from 1800 to now, this worked for me:
data2$date=as.character(data2$date)
lct <- Sys.getlocale("LC_TIME");
Sys.setlocale("LC_TIME","C")
data2$date<- as.Date(data2$date, format = "%Y %m %d") # and it works
Swift 3.0
With Swift 3, the name of NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.
let dic = ["2": "B", "1": "A", "3": "C"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Swift 2.x
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// here "decoded" is of type `AnyObject`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}
Swift 1
var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if error != nil {
println(error)
} else {
// here "jsonData" is the dictionary encoded in JSON data
}
}
if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
if error != nil {
println(error)
} else {
// here "decoded" is the dictionary decoded from JSON data
}
}
I encountered this error whenever I omitted a parameter while inflating the view for a fragment in the onCreateView()
method like so:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_reject, container);
return view;
}
The solution is to change the view inflation line to:
View view=inflater.inflate(R.layout.fragment_reject, container,false);
The explanation can be found at the Android guide for fragments
Quoting from the guide, the final parameter in the view initialization statement is false because:
"the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout"
while :; do read; done
no waiting for child sleeping process.
This variant allows getting desired precision:
>>> a = 1234.5678
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
(1234, 0.0)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
(1234, 0.5)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
(1234, 0.5678)
go to sdk folder and right click on SDK manager and run with administrator and enjoy installing.
This will delete the duplicate rows with same values for title, company and site. The first occurrence will be kept and rest all duplicates will be deleted
DELETE t1 FROM tablename t1
INNER JOIN tablename t2
WHERE
t1.id < t2.id AND
t1.title = t2.title AND
t1.company=t2.company AND
t1.site_ID=t2.site_ID;
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
I needed a multilevel dropdown menu in css. I couldn't find an error-free menu that I searched. Then I created a menu instance using the Css hover transition effect.I hope it will be useful for users.
#AnaMenu {
width: 920px; /* Menu width */
height: 30px; /* Menu height */
position: relative;
background: #0080ff;
margin:0 0 0 -30px;
padding: 10px 0 0 15px;
border: 0;
}
#nav { display:block;background:transparent;
margin:0;padding: 0;border: 0 }
#nav ul { float: none; display:block;
height:35px;
margin:16px 0 0 0;border:0;
padding: 15px 0 3px 0;
overflow: visible;
}
#nav ul li{border:0;}
#nav li a, #nav li a:link, #nav li a:visited {height:23px;
-webkit-transition: background-color 1s ease-out;
-moz-transition: background-color 1s ease-out;
-o-transition: background-color 1s ease-out;
transition: background-color 1s ease-out;
color: #fff; /* Change colour of link */
display: block;border:0;border-right:1px solid #efefef;text-decoration:none;
margin: 0;letter-spacing:0.6px;
padding: 2px 10px 2px 10px;
}
#nav li a:hover, #nav li a:active {
color: #fff;
margin: 0;background:#6ab5ff;border:0;
padding: 2px 10px 2px 10px;
}
#nav li li a, #nav li li a:link, #nav li li a:visited {
background: #fafafa;
width: 200px;
color: #05429b; /* Link text color */
float: none;
margin: 0;border-bottom:1px solid #9be6e9;
padding: 8px 15px;
}
#nav li li a:hover, #nav li li a:active {
background: #2793ff; /* Mouse hover color */
color: #fff;
padding: 8px 15px;border:0 ;text-decoration:none}
#nav li {float: none; display: inline-block;margin: 0; padding: 0; border: 0 }
#nav li ul { z-index: 9999; position: absolute; left: -999em; height: auto; width: 200px; margin: 0; padding: 0;background:transparent}
#nav li ul a { width: 170px;border:0;text-decoration:none;font-size:14px }
#nav li ul ul { margin: -40px 0 0 230px }
#nav li:hover ul ul, #nav li:hover ul ul ul, #nav li.sfhover ul ul, #nav li.sfhover ul ul ul {left: -999em; }
#nav li:hover ul, #nav li li:hover ul, #nav li li li:hover ul, #nav li.sfhover ul, #nav li li.sfhover ul, #nav li li li.sfhover ul { left: auto; }
#nav li:hover, #nav li.sfhover {position: static;}
Multilevel dropdown menu can be used in Blogger blogs. Details at : Css multilevel dropdown menu
$('#selectlist').val();
Using the principle of the idea user2620505 got result with implementation of addClass:
...
open: function(){
$('.ui-dialog-titlebar-close').addClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only');
$('.ui-dialog-titlebar-close').append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
},
...
If English is bad forgive me, I am using Google Translate.
×
is better than ✖
as ✖
behaves strangely in Edge and Internet explorer (tested in IE11). It doesn't get the right color and is replaced by an "emoji"
In SQL Server 2016 you can wrap array with [ ] and pass it as JSON see http://blogs.msdn.com/b/sqlserverstorageengine/archive/2015/09/08/passing-arrays-to-t-sql-procedures-as-json.aspx
You need the cat
(short for concatenate) command, with shell redirection (>
) into your output file
cat 1.txt 2.txt 3.txt > 0.txt
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This would also work: hash[hey] = nil
When do I use git rebase
? Almost never, because it rewrites history. git merge
is almost always the preferable choice, because it respects what actually happened in your project.
Based on Wikipedia's articles.
A greedy algorithm is an algorithm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many problems, a greedy strategy does not in general produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a global optimal solution in a reasonable time.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one.
The idea behind dynamic programming is quite simple. In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine the solutions of the subproblems to reach an overall solution. Often when using a more naive method, many of the subproblems are generated and solved many times. The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution is needed, it is simply looked up. This approach is especially useful when the number of repeating subproblems grows exponentially as a function of the size of the input.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices.
This is the main difference from dynamic programming, which is exhaustive and is guaranteed to find the solution. After every stage, dynamic programming makes decisions based on all the decisions made in the previous stage, and may reconsider the previous stage's algorithmic path to solution.
For example, let's say that you have to get from point A to point B as fast as possible, in a given city, during rush hour. A dynamic programming algorithm will look into the entire traffic report, looking into all possible combinations of roads you might take, and will only then tell you which way is the fastest. Of course, you might have to wait for a while until the algorithm finishes, and only then can you start driving. The path you will take will be the fastest one (assuming that nothing changed in the external environment).
On the other hand, a greedy algorithm will start you driving immediately and will pick the road that looks the fastest at every intersection. As you can imagine, this strategy might not lead to the fastest arrival time, since you might take some "easy" streets and then find yourself hopelessly stuck in a traffic jam.
In mathematical optimization, greedy algorithms solve combinatorial problems having the properties of matroids.
Dynamic programming is applicable to problems exhibiting the properties of overlapping subproblems and optimal substructure.
I figured out a way to automagically 'pip install' a GitLab private repository that requires no password prompt. This approach uses GitLab "Deploy Keys" and an SSH configuration file, so you can deploy using keys other than your personal SSH keys (in my case, for use by a 'bot). Perhaps someone kind soul can verify using GitHub.
ssh-keygen -t rsa -C "GitLab_Robot_Deploy_Key"
The file should show up as ~/.ssh/GitLab_Robot_Deploy_Key
and ~/.ssh/GitLab_Robot_Deploy_Key.pub
.
Copy and paste the contents of the ~/.ssh/GitLab_Robot_Deploy_Key.pub
file into the GitLab "Deploy Keys" dialog.
The following command tells SSH to use your new deploy key to set up the connection. On success, you should get the message: "Welcome to GitLab, UserName!"
ssh -T -i ~/.ssh/GitLab_Robot_Deploy_Key [email protected]
Next, use an editor to create a ~/.ssh/config
file. Add the following contents. The 'Host' value can be anything you want (just remember it, because you'll be using it later). The HostName is the URL to your GitLab instance. The IdentifyFile is path to the SSH key file you created in the first step.
Host GitLab
HostName gitlab.mycorp.com
IdentityFile ~/.ssh/GitLab_Robot_Deploy_Key
oxyum gave us the recipe for using pip with SSH:
pip install git+ssh://[email protected]/my_name/my_repo.git
We just need to modify it a bit to make SSH use our new Deploy Key. We do that by pointing SSH to the Host entry in the SSH configuration file. Just replace the 'gitlab.mycorp.com' in the command to the host name we used in the SSH configuration file:
pip install git+ssh://git@GitLab/my_name/my_repo.git
The package should now install without any password prompt.
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);
You can use the free P4Merge from Perforce to do this as well:
http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools
Details on integrating it with Git can be found here and here
but a quick summary from the above links is:
$ git mergetool
and $ git difftool
to use p4merge$ git diff
will still just use the default inline diff viewer :) (tested with git version 1.8.2)[merge]
keepBackup = false
tool = p4merge
[mergetool "p4merge"]
cmd = /Applications/p4merge.app/Contents/Resources/launchp4merge "\"$PWD/$BASE\"" "\"$PWD/$REMOTE\"" "\"$PWD/$LOCAL\"" "\"$PWD/$MERGED\""
keepTemporaries = false
trustExitCode = false
keepBackup = false
[diff]
tool = p4merge
[difftool "p4merge"]
cmd = /Applications/p4merge.app/Contents/Resources/launchp4merge "\"$REMOTE\"" "\"$LOCAL\""
Always keep things easy and simple by creating a class
.bcolor{ background:#F00; }
THEN USE THE addClass() & removeClass() to finish it up
If your listbox is connected to a LIST as the data source, listbox.Items.Clear() will not work.
I typically create a file named "DataAccess.cs" containing a separate class for code that uses or changes data pertaining to my form. The following is a code snippet from the DataAccess class that clears or removes all items in the list "exampleItems"
public List<ExampleItem> ClearExampleItems()
{
List<ExampleItem> exampleItems = new List<ExampleItem>();
exampleItems.Clear();
return examplelistItems;
}
ExampleItem is also in a separate class named "ExampleItem.cs"
using System;
namespace // The namespace is automatically added by Visual Studio
{
public class ExampleItem
{
public int ItemId { get; set; }
public string ItemType { get; set; }
public int ItemNumber { get; set; }
public string ItemDescription { get; set; }
public string FullExampleItem
{
get
{
return $"{ItemId} {ItemType} {ItemNumber} {ItemDescription}";
}
}
}
}
In the code for your Window Form, the following code fragments reference your listbox:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;
namespace // The namespace is automatically added by Visual Studio
{
public partial class YourFormName : Form
{
List<ExampleItem> exampleItems = new List<ExampleItem>();
public YourFormName()
{
InitializeComponent();
// Connect listbox to LIST
UpdateExampleItemsBinding();
}
private void UpdateUpdateItemsBinding()
{
ExampleItemsListBox.DataSource = exampleItems;
ExampleItemsListBox.DisplayMember = "FullExampleItem";
}
private void buttonClearListBox_Click(object sender, EventArgs e)
{
DataAccess db = new DataAccess();
exampleItems = db.ClearExampleItems();
UpdateExampleItemsBinding();
}
}
}
This solution specifically addresses a Windows Form listbox with the datasource connected to a list.
Try looking at the answers to these questions, particularly the second one which has sample code:
How to implement dynamic values on menu item in Android
How to get text on an ActionBar Icon?
From what I see, You'll need to create your own custom ActionView
implementation. An alternative might be a custom Drawable
. Note that there appears to be no native implementation of a notification count for the Action Bar.
EDIT: The answer you were looking for, with code: Custom Notification View with sample implementation
in android 3.1.0 Above use below path to find signed version of APK
home/AndroidStudioProjects/<projedct name>/app/app-release.apk
and in windows
AndroidStudioProjects\{project name}\app\release\app-release.apk
here is a short one liner to accomplish this:
request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '')).split(',')[0].strip()
If you are looking for a simple alternative, this can be done using a loop:
for i in $(find -name 'file_*' -follow -type f); do
zcat $i | agrep -dEOE 'grep'
done
or, more general and easy to understand form:
for i in $(YOUR_FIND_COMMAND); do
YOUR_EXEC_COMMAND_AND_PIPES
done
and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES
Try this, works for me very well:
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
Just to expand on @DRAX's answer, I'd do this:
function isWhitespaceEmptyString(str)
{
//RETURN:
// = 'true' if 'str' is empty string, null, undefined, or consists of white-spaces only
return str ? !(/\S/.test(str)) : (str === "" || str === null || str === undefined);
}
It will account also for null
s and undefined
types, and it will take care of non-string types, such as 0
.
if symfony version less than 2.8
sudo chmod -R 777 app/cache/*
_x000D_
if symfony version great than or equal 3.0
sudo chmod -R 777 var/cache/*
_x000D_
Hi For jQuery You can only use like this
Use async and type="text/javascript" only
You can use mplayer.
mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi
The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.
In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.
getDrawable(int drawable) is deprecated in API level 22. For reference see this link.
Now to resolve this problem we have to pass a new constructer along with id like as :-
getDrawable(int id, Resources.Theme theme)
For Solutions Do like this:-
In Java:-
ContextCompat.getDrawable(getActivity(), R.drawable.name);
or
imgProfile.setImageDrawable(getResources().getDrawable(R.drawable.img_prof, getApplicationContext().getTheme()));
In Kotlin :-
rel_week.background=ContextCompat.getDrawable(this.requireContext(), R.color.colorWhite)
or
rel_day.background=resources.getDrawable(R.drawable.ic_home, context?.theme)
Hope this will help you.Thanks.
I answer this coming from a component-based architecture, where an organisation may be running many components that may rely on each other. During a propagating failure, logging levels should help to identify both which components are affected and which are a root cause.
ERROR - This component has had a failure and the cause is believed to be internal (any internal, unhandled exception, failure of encapsulated dependency... e.g. database, REST example would be it has received a 4xx error from a dependency). Get me (maintainer of this component) out of bed.
WARN - This component has had a failure believed to be caused by a dependent component (REST example would be a 5xx status from a dependency). Get the maintainers of THAT component out of bed.
INFO - Anything else that we want to get to an operator. If you decide to log happy paths then I recommend limiting to 1 log message per significant operation (e.g. per incoming http request).
For all log messages be sure to log useful context (and prioritise on making messages human readable/useful rather than having reams of "error codes")
A nice way to visualise the above logging levels is to imagine a set of monitoring screens for each component. When all running well they are green, if a component logs a WARNING then it will go orange (amber) if anything logs an ERROR then it will go red.
In the event of an incident you should have one (root cause) component go red and all the affected components should go orange/amber.
If you got this problem in Visual Studio 2017, chances are you're working with an MVC 4 project created in a previous version of VS with a reference hint path pointing to C:\Program Files (x86)\Microsoft ASP.NET
. Visual Studio 2017 does not install this directory anymore.
We usually solve this by installing a copy of Visual Studio 2015 alongside our 2017 instance, and that installs the necessary libraries in the above path. Then we update all the references in the affected projects and we're good to go.
I was facing following error with code (nodejs 0.10.13), provided by ampersand:
origin is not allowed by access-control-allow-origin
Issue was resolved changing
response.writeHead(200, {"Content-Type": "text/plain"});
to
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.
one liner solve quadratic equation
from math import sqrt
s = lambda a,b,c: {(-b-sqrt(d))/2*a,(-b+sqrt(d))/2*a} if (d:=b**2-4*a*c)>=0 else {}
roots_set = s(int(input('a=')),int(input('b=')),int(input('c=')))
print(roots_set,f'number of roots {len(roots_set)}')
With Yglu Structural Templating, your example can be written:
foo: !()
!? $.propname:
type: number
default: !? $.default
bar:
!apply .foo:
propname: "some_prop"
default: "some default"
Disclaimer: I am the author or Yglu.
You can use this one:
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
It will show a graphical representation of the current sub-directories without files in a few seconds, e.g. in /var/cache/:
.
|-apache2
|---mod_cache_disk
|-apparmor
|-apt
|---archives
|-----partial
|-apt-xapian-index
|---index.1
|-dbconfig-common
|---backups
|-debconf
Instance variable is the variable declared inside a class, but outside a method: something like:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
Now this IronMan Class can be instantiated in another class to use these variables. Something like:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.
For the listed three conditions only, these expressions might work also:
^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$
If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:
123451234
12345 1234
12345 1234
this expression for instance would be a secondary option with less constraints:
^\d{5}([-]|\s*)?(\d{4})?$
jex.im visualizes regular expressions:
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345 1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
Not sure about "Best Practices" for memory leaks in python, but python should clear it's own memory by it's garbage collector. So mainly I would start by checking for circular list of some short, since they won't be picked up by the garbage collector.
Good question. You will need to modify the HTML itself rather than rely on DOM properties.
var opt = $("option[val=ID]"),
html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);
The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option>
.
It then does a string replace to add the attribute selected="selected"
as a string, before replacing the original option with this new one.
I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/
Some times there are problems with funtion/features that do not interact with the DOM
try to change the value sharply and then assign the $scope
document.getElementById ("textWidget") value = "<NewVal>";
$scope.widget.title = "<NewVal>";
Make sure that you are accessing the WebAPI through HTTPS.
I also enabled cors in the WebApi.config.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
But my CORS request did not work until I used HTTPS urls.
I had compatibility issues with several plugins I tried, this seems to me to be the simplest way of supporting placeholders on text inputs:
function placeholders(){
//On Focus
$(":text").focus(function(){
//Check to see if the user has modified the input, if not then remove the placeholder text
if($(this).val() == $(this).attr("placeholder")){
$(this).val("");
}
});
//On Blur
$(":text").blur(function(){
//Check to see if the use has modified the input, if not then populate the placeholder back into the input
if( $(this).val() == ""){
$(this).val($(this).attr("placeholder"));
}
});
}
I mean it's quite simple. Set it as a double. So lets say
double answer = 3.0/2.0;
System.out.print(answer);