feel free to use this tool https://github.com/rooty0/ffmpeg_video_cutter I wrote awhile ago Pretty much that's cli front-end for ffmpeg... you just need to create a yaml what you want to cut out... something like this
cut_method: delete # we're going to delete following video fragments from a video
timeframe:
- from: start # waiting for people to join the conference
to: 4m
- from: 10m11s # awkward silence
to: 15m50s
- from: 30m5s # Off-Topic Discussion
to: end
and then just run a tool to get result
A processor in a computer running Windows has two different modes: user mode and kernel mode. The processor switches between the two modes depending on what type of code is running on the processor. Applications run in user mode, and core operating system components run in kernel mode. While many drivers run in kernel mode, some drivers may run in user mode.
When you start a user-mode application, Windows creates a process for the application. The process provides the application with a private virtual address space and a private handle table. Because an application's virtual address space is private, one application cannot alter data that belongs to another application. Each application runs in isolation, and if an application crashes, the crash is limited to that one application. Other applications and the operating system are not affected by the crash.
In addition to being private, the virtual address space of a user-mode application is limited. A processor running in user mode cannot access virtual addresses that are reserved for the operating system. Limiting the virtual address space of a user-mode application prevents the application from altering, and possibly damaging, critical operating system data.
All code that runs in kernel mode shares a single virtual address space. This means that a kernel-mode driver is not isolated from other drivers and the operating system itself. If a kernel-mode driver accidentally writes to the wrong virtual address, data that belongs to the operating system or another driver could be compromised. If a kernel-mode driver crashes, the entire operating system crashes.
If you are a Windows user once go through this link you will get more.
You need to add a css rule that removes the after content (through a class)..
An update due to some valid comments.
The more correct way to completely remove/disable the :after
rule is to use
p.no-after:after{content:none;}
Original answer
You need to add a css rule that removes the after content (through a class)..
p.no-after:after{content:"";}
and add that class to your p
when you want to with this line
$('p').addClass('no-after'); // replace the p selector with what you need...
a working example at : http://www.jsfiddle.net/G2czw/
You can use: $counter = count($datas);
Is this possible to assign a NaN to a double or float in C ...?
Yes, since C99, (C++11) <math.h>
offers the below functions:
#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);
which are like their strtod("NAN(n-char-sequence)",0)
counterparts and NAN
for assignments.
// Sample C code
uint64_t u64;
double x;
x = nan("0x12345");
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = -strtod("NAN(6789A)",0);
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = NAN;
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
Sample output: (Implementation dependent)
(7ff8000000012345)
(fff000000006789a)
(7ff8000000000000)
You get this error because one of your variables is actually a factor variable . Execute
str(df)
to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:
df$year <- as.numeric(as.character(df$year))
EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:
df <- data.frame(apply(df, 2, unclass))
and plot again?
For those using Select2 4.x, you can disable an individual option by doing:
$('select option:selected').prop('disabled', true);
For those using Select2 4.x, you can disable the entire dropdown with:
$('select').prop('disabled', true);
I would use the built-in ngInclude
directive. In the example below, you don't even need to write any javascript. The templates can just as easily live at a remote url.
Here's a working demo: http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview
<p>Select page content template via dropdown</p>
<select ng-model="template">
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
</select>
<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>
<ng-include src="template"></ng-include>
<script type="text/ng-template" id="page1">
<h1 style="color: blue;">This is the page 1 content</h1>
</script>
<script type="text/ng-template" id="page2">
<h1 style="color:green;">This is the page 2 content</h1>
</script>
This is a 3 years old question but I had the same problem today. I looked your edited solution but I think that it can sacrifice the performance because it has to make a double request. So if anyone needs another solution that doesn't imply to call the service twice then this is the way I did it:
<form id="export-csv-form" method="POST" action="/the/path/to/file">
<input type="hidden" name="anyValueToPassTheServer" value="">
</form>
This form is just used to call the service and avoid to use a window.location(). After that you just simply have to make a form submit from jquery in order to call the service and get the file. It's pretty simple but this way you can make a download using a POST. I now that this could be easier if the service you're calling is a GET, but that's not my case.
If you are asking if you can pair two devices without the user EVER approving the pairing, no it cannot be done, it is a security feature. If you are paired over Bluetooth there is no need to exchange data over NFC, just exchange data over the Bluetooth link.
I don't think you can circumvent Bluetooth security by passing an authentication packet over NFC, but I could be wrong.
you can use unlink in the folder where you have created your symlink
I created a fully automated solution to add PS and CMD context items. Just run set_registry.cmd and it will update registry to add two buttons when click RMB on folder or inside some opened folder:
This will change owner of registry keys to admin and add context menus
Change registry to enable PS and CWD context menus
First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]
Basically this question has the title ...Visual Studio 2012 / 2013
What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.
So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj
project. Now this computer does not yet have sql server installed on it yet.
Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates
Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.
In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396
The problem was that I was going a step too far in calling the parse method of XMLReader. The parse method accepts an InputSource, so there was no reason to even use a FileReader. Changing the last line of the code above to
xr.parse( new InputSource( filename ));
works just fine.
Add flutter_just_toast to your dependencies in your Pubspecs.yaml
dependencies:
flutter_just_toast: ^1.0.1
Next import package into your class:
import 'package:flutter_just_toast/flutter_just_toast.dart';
Implement Toast with message
Toast.show( message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
for all of you who use Dapper 1.12, Here's what you need to do to get this done:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property]
public class ColumnAttribute : Attribute
{
public string Name { get; set; }
public ColumnAttribute(string name)
{
this.Name = name;
}
}
map = new DefaultTypeMap(type);
and comment it out.
map = new CustomPropertyTypeMap(type, (t, columnName) =>
{
PropertyInfo pi = t.GetProperties().FirstOrDefault(prop =>
prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName));
return pi != null ? pi : t.GetProperties().FirstOrDefault(prop => prop.Name == columnName);
});
Try javax.net.ssl.keyStorePassword
instead of javax.net.ssl.keyPassword
: the latter isn't mentioned in the JSSE ref guide.
The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmException
s are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.
You could also use -Djavax.net.debug=ssl
, or at least -Djavax.net.debug=ssl,keymanager
, to get more debugging information, if the information in the stack trace isn't sufficient.
Implement custom readonly like eventHandler
<select id='country' data-changeable=false>
<option selected value="INDIA">India</option>
<option value="USA">United States</option>
<option value="UK">United Kingdom</option>
</select>
<script>
var lastSelected = $("#country option:selected");
$("#country").on("change", function() {
if(!$(this).data(changeable)) {
lastSelected.attr("selected", true);
}
});
$("#country").on("click", function() {
lastSelected = $("#country option:selected");
});
</script>
That will select (by a regex) every book which has a title starting with a number, is that what you want?
SELECT * FROM books WHERE title ~ '^[0-9]'
if you want integers which start with specific digits, you could use:
SELECT * FROM books WHERE CAST(price AS TEXT) LIKE '123%'
or use (if all your numbers have the same number of digits (a constraint would be useful then))
SELECT * FROM books WHERE price BETWEEN 123000 AND 123999;
This should do the trick:
<table width="400" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="50" height="40" valign="top" rowspan="3">
<img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
</td>
</tr>
<tr>
<td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
UPDATE: Adjusted code per the comments:
After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.
Here is an example that will NOT WORK:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="300" bgcolor="#252525">
</td>
<td width="300" bgcolor="#454545">
</td>
</tr>
</table>
Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="600" colspan="2" bgcolor="#353535">
</td>
</tr>
</table>
Not a full tutorial, but I hope that helps steer you in the right direction in the future.
Here is the code you are after:
<table width="900" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="57" height="43" valign="top" rowspan="2">
<img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
</td>
</tr>
<tr>
<td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.
You can create a new blank solution and add your different projects to it.
This will work for original question asked:
DECLARE @Result INT;
SELECT @Result = COUNT(*)
FROM TableName
WHERE Condition
This solution works only if you create in Xcode 7 the directory "10.0" and you have a mistake in your sentence:
ln -s /Applications/Xcode_8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0 \(14A345\) /Applications/Xcode_7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0
Simple Override onBackPressed Method:
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
You mean like this?
> eq = function(x){x*x}
> plot(eq(1:1000), type='l')
(Or whatever range of values is relevant to your function)
There are so many ways:
In terms of direct values a regular char is used when the values are known to be between CHAR_MIN
and CHAR_MAX
while an unsigned char provides double the range on the positive end. For example, if CHAR_BIT
is 8, the range of regular char
is only guaranteed to be [0, 127] (because it can be signed or unsigned) while unsigned char
will be [0, 255] and signed char
will be [-127, 127].
In terms of what it's used for, the standards allow objects of POD (plain old data) to be directly converted to an array of unsigned char. This allows you to examine the representation and bit patterns of the object. The same guarantee of safe type punning doesn't exist for char or signed char.
Largely based on the accepted answer, but with a few tweaks to fit better the definitions taught in some courses:
Here is an example ...
select * from tablename where to_char(added_time, 'YYYY-MM-DD') = to_char( now(), 'YYYY-MM-DD' )
added_time is a column name which I converted to char for match
You can pass any number of arguments to the function that apply
is calling through either unnamed arguments, passed as a tuple to the args
parameter, or through other keyword arguments internally captured as a dictionary by the kwds
parameter.
For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.
s = pd.Series(np.random.randint(0,10, 10))
s
0 5
1 3
2 1
3 1
4 6
5 0
6 3
7 4
8 9
9 6
dtype: int64
s.apply(lambda x: x >= 3 and x <= 6)
0 True
1 True
2 False
3 False
4 True
5 False
6 True
7 True
8 False
9 True
dtype: bool
This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.
def between(x, low, high):
return x >= low and x =< high
We can replicate the output of the first function by passing unnamed arguments to args
:
s.apply(between, args=(3,6))
Or we can use the named arguments
s.apply(between, low=3, high=6)
Or even a combination of both
s.apply(between, args=(3,), high=6)
$(this.parentNode).addClass('newClass');
Put an l
(lowercased letter L) directly before the specifier.
unsigned long n;
long m;
printf("%lu %ld", n, m);
Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).
However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.
Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.
Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.
Here's another good one: http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/
This one shows how to use pip
and a pip requirements file with virtualenv; Scobal's two suggested tutorials are both very helpful but are both easy_install
-centric.
Note that none of these tutorials explain how to run a different version of Python within a virtualenv - for this, see this SO question: Use different Python version with virtualenv
Try wrapping expression with:
$scope.$apply(function() {
$scope.foo.bar=true;
})
You can kill a thread by installing trace into the thread that will exit the thread. See attached link for one possible implementation.
If you want to add a Series and use the Series' index as columns of the DataFrame, you only need to append the Series between brackets:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame()
In [3]: row=pd.Series([1,2,3],["A","B","C"])
In [4]: row
Out[4]:
A 1
B 2
C 3
dtype: int64
In [5]: df.append([row],ignore_index=True)
Out[5]:
A B C
0 1 2 3
[1 rows x 3 columns]
Whitout the ignore_index=True
you don't get proper index.
Here is another option. Use a CTE to define the months of the quarter and then join to it to determine the quarter:
WITH Quarters AS (
SELECT Q = 'Q1', MonthBegin = 1, MonthEnd = 3 UNION
SELECT Q = 'Q2', MonthBegin = 4, MonthEnd = 6 UNION
SELECT Q = 'Q3', MonthBegin = 7, MonthEnd = 9 UNION
SELECT Q = 'Q4', MonthBegin = 10, MonthEnd = 12
)
SELECT
[Year] = DATEPART(yyyy, CONVERT(DATETIME, Dates.[date])),
[Quarter] = CONVERT(VARCHAR(4), DATEPART(yyyy, CONVERT(DATETIME, Dates.[date]))) + '-' + q.Q
FROM
(VALUES
('20080102'),
('20070821')
) AS Dates ([date])
INNER JOIN Quarters q ON
DATEPART(m, CONVERT(DATETIME, Dates.[date])) >= q.MonthBegin AND
DATEPART(m, CONVERT(DATETIME, Dates.[date])) <= q.MonthEnd;
Returns:
Year Quarter
----- ----------
2008 2008-Q1
2007 2007-Q3
Handle column type of int (04/23/2014):
WITH Quarters AS (
SELECT Q = 'Q1', MonthBegin = 1, MonthEnd = 3 UNION
SELECT Q = 'Q2', MonthBegin = 4, MonthEnd = 6 UNION
SELECT Q = 'Q3', MonthBegin = 7, MonthEnd = 9 UNION
SELECT Q = 'Q4', MonthBegin = 10, MonthEnd = 12
)
SELECT
[Year] = DATEPART(yyyy, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))),
[Quarter] = CONVERT(VARCHAR(4), DATEPART(yyyy, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date])))) + '-' + q.Q
FROM
(VALUES
(20080102),
(20070821)
) AS Dates ([date])
INNER JOIN Quarters q ON
DATEPART(m, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))) >= q.MonthBegin AND
DATEPART(m, CONVERT(DATETIME, CONVERT(VARCHAR(8), Dates.[date]))) <= q.MonthEnd;
Have added ErrorHandler to this in case the user hits the cancel button instead of selecting a folder. So instead of getting a horrible error message you get a message that a folder must be selected and then the routine ends. Below code also stores the folder path in a range name (Which is just linked to cell A1 on a sheet).
Sub SelectFolder()
Dim diaFolder As FileDialog
'Open the file dialog
On Error GoTo ErrorHandler
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Title = "Select a folder then hit OK"
diaFolder.Show
Range("IC_Files_Path").Value = diaFolder.SelectedItems(1)
Set diaFolder = Nothing
Exit Sub
ErrorHandler:
Msg = "No folder selected, you must select a folder for program to run"
Style = vbError
Title = "Need to Select Folder"
Response = MsgBox(Msg, Style, Title)
End Sub
I am only submitting this answer because people expressed concerns over browsers and maintaining the order of objects. I recognize that it is not the most efficient way to accomplish the goal.
Having said this, I broke the problem down into two functions for readability.
// The following function is used for each itertion in the function updateObjectsInArr
const newObjInInitialArr = function(initialArr, newObject) {
let id = newObject.id;
let newArr = [];
for (let i = 0; i < initialArr.length; i++) {
if (id === initialArr[i].id) {
newArr.push(newObject);
} else {
newArr.push(initialArr[i]);
}
}
return newArr;
};
const updateObjectsInArr = function(initialArr, newArr) {
let finalUpdatedArr = initialArr;
for (let i = 0; i < newArr.length; i++) {
finalUpdatedArr = newObjInInitialArr(finalUpdatedArr, newArr[i]);
}
return finalUpdatedArr
}
const revisedArr = updateObjectsInArr(arr1, arr2);
Use of the String.toString
:
Whenever you require to explore the constructor called value in the String
form, you can simply use String.toString
...
for an example...
package pack1;
import java.util.*;
class Bank {
String n;
String add;
int an;
int bal;
int dep;
public Bank(String n, String add, int an, int bal) {
this.add = add;
this.bal = bal;
this.an = an;
this.n = n;
}
public String toString() {
return "Name of the customer.:" + this.n + ",, "
+ "Address of the customer.:" + this.add + ",, " + "A/c no..:"
+ this.an + ",, " + "Balance in A/c..:" + this.bal;
}
}
public class Demo2 {
public static void main(String[] args) {
List<Bank> l = new LinkedList<Bank>();
Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
l.add(b1);
l.add(b2);
l.add(b3);
l.add(b4);
l.add(b5);
Iterator<Bank> i = l.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
... copy this program into your Eclipse, and run it... you will get the ideas about String.toString
...
In my opinion, it's better to explicitly mark the end of the function by comment
def func():
# funcbody
## end of subroutine func ##
The point is that some subroutine is very long and is not convenient to scroll up the editor to check for which function is ended. In addition, if you use Sublime, you can right click -> Goto Definition and it will automatically jump to the subroutine declaration.
Maybe
my_qstring.toStdString().c_str();
or safer, as Federico points out:
std::string str = my_qstring.toStdString();
const char* p = str.c_str();
It's far from optimal, but will do the work.
Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.
$('.js-addNew').on('click', function(e) {
e.preventDefault();
var $rows = $('.person'),
$last = $rows.filter(':last'),
$newRow = $last.clone().insertAfter($last);
$last.find($('.js-addNew')).remove(); // remove old button
$newRow.hide().find('input').val('');
$newRow.slideDown(500);
});
What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)
I needed one application to run on multiple subdomains. So in bootstrap/app.php
I added something like:
$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);
If you really want it to look more semantic like having the <body>
in the middle you can use the <main>
element. With all the recent advances the <body>
element is not as semantic as it once was but you just have to think of it as a wrapper in which the view port sees.
<html>
<head>
</head>
<body>
<header>
</header>
<main>
<section></section>
<article></article>
</main>
<footer>
</footer>
<body>
</html>
Thanks for the replies, it works!
And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (sourceFormats
), and on UnicodeDecodeError
I try the next format:
from __future__ import with_statement
import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector
targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()
def get_encoding_type(current_file):
detector.reset()
for line in file(current_file):
detector.feed(line)
if detector.done: break
detector.close()
return detector.result['encoding']
def convertFileBestGuess(filename):
sourceFormats = ['ascii', 'iso-8859-1']
for format in sourceFormats:
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
def convertFileWithDetection(fileName):
print("Converting '" + fileName + "'...")
format=get_encoding_type(fileName)
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
print("Error: failed to convert '" + fileName + "'.")
def writeConversion(file):
with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
for line in file:
targetFile.write(line)
# Off topic: get the file list and call convertFile on each file
# ...
(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)
I realize an answer has been accepted, but I strongly suggest not hacking bootstrap to fix this.
You can pretty easily achieve the same effect by hooking the shown.bs.modal and hidden.bs.modal event handlers and adjusting the z-index there.
A bit more info is available here.
This solution works automatically with arbitrarily deeply stacks modals.
The script source code:
$(document).ready(function() {
$('.modal').on('hidden.bs.modal', function(event) {
$(this).removeClass( 'fv-modal-stack' );
$('body').data( 'fv_open_modals', $('body').data( 'fv_open_modals' ) - 1 );
});
$('.modal').on('shown.bs.modal', function (event) {
// keep track of the number of open modals
if ( typeof( $('body').data( 'fv_open_modals' ) ) == 'undefined' ) {
$('body').data( 'fv_open_modals', 0 );
}
// if the z-index of this modal has been set, ignore.
if ($(this).hasClass('fv-modal-stack')) {
return;
}
$(this).addClass('fv-modal-stack');
$('body').data('fv_open_modals', $('body').data('fv_open_modals' ) + 1 );
$(this).css('z-index', 1040 + (10 * $('body').data('fv_open_modals' )));
$('.modal-backdrop').not('.fv-modal-stack').css('z-index', 1039 + (10 * $('body').data('fv_open_modals')));
$('.modal-backdrop').not('fv-modal-stack').addClass('fv-modal-stack');
});
});
If I'm not mistaken, you should be applying this rule to the li, not the ul.
ul li {list-style-type: disc;}
Depending on your shell implementation (e.g. Busybox vs. grown-up) the [
operator might start a process, changing $?
.
Try
getent passwd $1 > /dev/null 2&>1
RES=$?
if [ $RES -eq 0 ]; then
echo "yes the user exists"
else
echo "No, the user does not exist"
fi
Keys must be unique. Don't do that. Redesign as needed.
(if you are trying to insert, then delete, and the insert fails... just do the delete first. Rollback on error in either statement).
Answer: 165
Method: brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.
from math import sqrt, floor
is_ps = lambda x: floor(sqrt(x)) ** 2 == x
count = 0
for n in range(1002, 10000, 3):
if n % 11 and is_ps(sum(map(int, str(n)))):
count += 1
print "#%i: %s" % (count, n)
You need to be more explicit and add the start and end times as well, down to the milliseconds:
select *
from xxx
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'
The database can very well interpret '2012-10-27'
as '2012-10-27 00:00:00.000'
.
Comparable
is Fegan
.The method compareTo
you are overidding in it should have a Fegan
object as a parameter whereas you are casting it to a FoodItems
. Your compareTo
implementation should describe how a Fegan
compare to another Fegan
.
FoodItems
implement Comparable
aswell and copy paste your actual compareTo
logic in it.This would require me to reformat the data into lists inside lists, which seems to defeat the purpose of using pandas in the first place.
No it doesn't, just convert to a NumPy array:
>>> data = np.asarray(df)
This takes constant time because it just creates a view on your data. Then feed it to scikit-learn:
>>> from sklearn.linear_model import LinearRegression
>>> lr = LinearRegression()
>>> X, y = data[:, 1:], data[:, 0]
>>> lr.fit(X, y)
LinearRegression(copy_X=True, fit_intercept=True, normalize=False)
>>> lr.coef_
array([ 4.01182386e-01, 3.51587361e-04])
>>> lr.intercept_
14.952479503953672
Swift 5, iOS 13
I know this question already has a lot of answers but from my experience this method always works:
let last = IndexPath(row: someArray.count - 1, section: 0)
tableView.scrollToRow(at: last, at: .bottom, animated: true)
And this is especially true if you're working with animations (like keyboard) or certain async tasks—the other answers will often scroll to the almost bottom. If for some reason this doesn't get you all the way to the bottom, it's almost certainly because of a competing animation so the workaround is to dispatch this animation to the end of the main queue:
DispatchQueue.main.async {
let last = IndexPath(row: self.someArray.count - 1, section: 0)
self.tableView.scrollToRow(at: last, at: .bottom, animated: true)
}
This may seem redundant since you're already on the main queue but it's not because it serializes the animations.
Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).
Something like:
StringBuilder b = new StringBuilder(existing_string);
for(int i = 0; i<n; i++){
b.append("other_string");
}
return b.toString();
Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.
One more answer to improve on: https://stackoverflow.com/a/4203897/2804197 and https://stackoverflow.com/a/25476462/1338797 (Tkinter).
Tkinter is nice, because it's either included with Python (Windows) or easy to install (Linux), and thus requires little dependencies for the end user.
Here I have a "full-blown" example, which copies the arguments or the standard input, to clipboard, and - when not on Windows - waits for the user to close the application:
import sys
try:
from Tkinter import Tk
except ImportError:
# welcome to Python3
from tkinter import Tk
raw_input = input
r = Tk()
r.withdraw()
r.clipboard_clear()
if len(sys.argv) < 2:
data = sys.stdin.read()
else:
data = ' '.join(sys.argv[1:])
r.clipboard_append(data)
if sys.platform != 'win32':
if len(sys.argv) > 1:
raw_input('Data was copied into clipboard. Paste and press ENTER to exit...')
else:
# stdin already read; use GUI to exit
print('Data was copied into clipboard. Paste, then close popup to exit...')
r.deiconify()
r.mainloop()
else:
r.destroy()
This showcases:
raw_input
and print()
compatibilityI had the same issue with weblogic 12c and maven I initially while deploying from eclipse (kepler) (deploying from the console gave no errors).
The other solutions given on this page didn't help.
I extracted the spring.tld spring-form.tld files of the spring-webmvc jar (which I found in my repository) in the web\WEB-INF folder of my war module;
I did a fresh build; deployed (from eclipse) into weblogic 12c, tested the application and the error was gone;
I removed the spring.tld spring-form.tld files again and after deleting; rebuilding and redeploying the application the error didn't show up again.
I double checked whether the files were gone in the war and they were indeed not present.
hope this helps others with a similar issue...
You need to reverse the nesting inside the generate block:
genvar c;
generate
for (c = 0; c < ROWBITS; c = c + 1) begin: test
always @(posedge sysclk) begin
temp[c] <= 1'b0;
end
end
endgenerate
Technically, this generates four always blocks:
always @(posedge sysclk) temp[0] <= 1'b0;
always @(posedge sysclk) temp[1] <= 1'b0;
always @(posedge sysclk) temp[2] <= 1'b0;
always @(posedge sysclk) temp[3] <= 1'b0;
In this simple example, there's no difference in behavior between the four always blocks and a single always block containing four assignments, but in other cases there could be.
The genvar-dependent operation needs to be resolved when constructing the in-memory representation of the design (in the case of a simulator) or when mapping to logic gates (in the case of a synthesis tool). The always @posedge
doesn't have meaning until the design is operating.
Subject to certain restrictions, you can put a for loop inside the always block, even for synthesizable code. For synthesis, the loop will be unrolled. However, in that case, the for loop needs to work with a reg
, integer
, or similar. It can't use a genvar
, because having the for loop inside the always block describes an operation that occurs at each edge of the clock, not an operation that can be expanded statically during elaboration of the design.
variable = id if variable.to_s.empty?
You can use below code to create test and train samples :
from sklearn.model_selection import train_test_split
trainingSet, testSet = train_test_split(df, test_size=0.2)
Test size can vary depending on the percentage of data you want to put in your test and train dataset.
Concerning n00b's comment: "I get the following warning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"
I was getting the same error. In my case it was because I was trying to perform the column addition on a dataframe that was created like this:
df_b = df[['colA', 'colB', 'colC']]
instead of:
df_c = pd.DataFrame(df, columns=['colA', 'colB', 'colC'])
df_b is a copy of a slice from df
df_c is an new dataframe. So
df_c['colD'] = df['colA'] + df['colB']+ df['colC']
will add the columns and won't raise any warning. Same if .sum(axis=1) is used.
Android Studio Version 4.0.1 on Mac combination is for me:
Shift + Control + F
The standard definition of an aggregate has changed slightly, but it's still pretty much the same:
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
Ok, what changed?
Previously, an aggregate could have no user-declared constructors, but now it can't have user-provided constructors. Is there a difference? Yes, there is, because now you can declare constructors and default them:
struct Aggregate {
Aggregate() = default; // asks the compiler to generate the default implementation
};
This is still an aggregate because a constructor (or any special member function) that is defaulted on the first declaration is not user-provided.
Now an aggregate cannot have any brace-or-equal-initializers for non-static data members. What does this mean? Well, this is just because with this new standard, we can initialize members directly in the class like this:
struct NotAggregate {
int x = 5; // valid in C++11
std::vector<int> s{1,2,3}; // also valid
};
Using this feature makes the class no longer an aggregate because it's basically equivalent to providing your own default constructor.
So, what is an aggregate didn't change much at all. It's still the same basic idea, adapted to the new features.
PODs went through a lot of changes. Lots of previous rules about PODs were relaxed in this new standard, and the way the definition is provided in the standard was radically changed.
The idea of a POD is to capture basically two distinct properties:
Because of this, the definition has been split into two distinct concepts: trivial classes and standard-layout classes, because these are more useful than POD. The standard now rarely uses the term POD, preferring the more specific trivial and standard-layout concepts.
The new definition basically says that a POD is a class that is both trivial and has standard-layout, and this property must hold recursively for all non-static data members:
A POD struct is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.
Let's go over each of these two properties in detail separately.
Trivial is the first property mentioned above: trivial classes support static initialization.
If a class is trivially copyable (a superset of trivial classes), it is ok to copy its representation over the place with things like memcpy
and expect the result to be the same.
The standard defines a trivial class as follows:
A trivially copyable class is a class that:
— has no non-trivial copy constructors (12.8),
— has no non-trivial move constructors (12.8),
— has no non-trivial copy assignment operators (13.5.3, 12.8),
— has no non-trivial move assignment operators (13.5.3, 12.8), and
— has a trivial destructor (12.4).
A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable.
[ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]
So, what are all those trivial and non-trivial things?
A copy/move constructor for class X is trivial if it is not user-provided and if
— class X has no virtual functions (10.3) and no virtual base classes (10.1), and
— the constructor selected to copy/move each direct base class subobject is trivial, and
— for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;
otherwise the copy/move constructor is non-trivial.
Basically this means that a copy or move constructor is trivial if it is not user-provided, the class has nothing virtual in it, and this property holds recursively for all the members of the class and for the base class.
The definition of a trivial copy/move assignment operator is very similar, simply replacing the word "constructor" with "assignment operator".
A trivial destructor also has a similar definition, with the added constraint that it can't be virtual.
And yet another similar rule exists for trivial default constructors, with the addition that a default constructor is not-trivial if the class has non-static data members with brace-or-equal-initializers, which we've seen above.
Here are some examples to clear everything up:
// empty classes are trivial
struct Trivial1 {};
// all special members are implicit
struct Trivial2 {
int x;
};
struct Trivial3 : Trivial2 { // base class is trivial
Trivial3() = default; // not a user-provided ctor
int y;
};
struct Trivial4 {
public:
int a;
private: // no restrictions on access modifiers
int b;
};
struct Trivial5 {
Trivial1 a;
Trivial2 b;
Trivial3 c;
Trivial4 d;
};
struct Trivial6 {
Trivial2 a[23];
};
struct Trivial7 {
Trivial6 c;
void f(); // it's okay to have non-virtual functions
};
struct Trivial8 {
int x;
static NonTrivial1 y; // no restrictions on static members
};
struct Trivial9 {
Trivial9() = default; // not user-provided
// a regular constructor is okay because we still have default ctor
Trivial9(int x) : x(x) {};
int x;
};
struct NonTrivial1 : Trivial3 {
virtual void f(); // virtual members make non-trivial ctors
};
struct NonTrivial2 {
NonTrivial2() : z(42) {} // user-provided ctor
int z;
};
struct NonTrivial3 {
NonTrivial3(); // user-provided ctor
int w;
};
NonTrivial3::NonTrivial3() = default; // defaulted but not on first declaration
// still counts as user-provided
struct NonTrivial5 {
virtual ~NonTrivial5(); // virtual destructors are not trivial
};
Standard-layout is the second property. The standard mentions that these are useful for communicating with other languages, and that's because a standard-layout class has the same memory layout of the equivalent C struct or union.
This is another property that must hold recursively for members and all base classes. And as usual, no virtual functions or virtual base classes are allowed. That would make the layout incompatible with C.
A relaxed rule here is that standard-layout classes must have all non-static data members with the same access control. Previously these had to be all public, but now you can make them private or protected, as long as they are all private or all protected.
When using inheritance, only one class in the whole inheritance tree can have non-static data members, and the first non-static data member cannot be of a base class type (this could break aliasing rules), otherwise, it's not a standard-layout class.
This is how the definition goes in the standard text:
A standard-layout class is a class that:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions (10.3) and no virtual base classes (10.1),
— has the same access control (Clause 11) for all non-static data members,
— has no non-standard-layout base classes,
— either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
— has no base classes of the same type as the first non-static data member.
A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.
A standard-layout union is a standard-layout class defined with the class-key union.
[ Note: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in 9.2.—end note ]
And let's see a few examples.
// empty classes have standard-layout
struct StandardLayout1 {};
struct StandardLayout2 {
int x;
};
struct StandardLayout3 {
private: // both are private, so it's ok
int x;
int y;
};
struct StandardLayout4 : StandardLayout1 {
int x;
int y;
void f(); // perfectly fine to have non-virtual functions
};
struct StandardLayout5 : StandardLayout1 {
int x;
StandardLayout1 y; // can have members of base type if they're not the first
};
struct StandardLayout6 : StandardLayout1, StandardLayout5 {
// can use multiple inheritance as long only
// one class in the hierarchy has non-static data members
};
struct StandardLayout7 {
int x;
int y;
StandardLayout7(int x, int y) : x(x), y(y) {} // user-provided ctors are ok
};
struct StandardLayout8 {
public:
StandardLayout8(int x) : x(x) {} // user-provided ctors are ok
// ok to have non-static data members and other members with different access
private:
int x;
};
struct StandardLayout9 {
int x;
static NonStandardLayout1 y; // no restrictions on static members
};
struct NonStandardLayout1 {
virtual f(); // cannot have virtual functions
};
struct NonStandardLayout2 {
NonStandardLayout1 X; // has non-standard-layout member
};
struct NonStandardLayout3 : StandardLayout1 {
StandardLayout1 x; // first member cannot be of the same type as base
};
struct NonStandardLayout4 : StandardLayout3 {
int z; // more than one class has non-static data members
};
struct NonStandardLayout5 : NonStandardLayout3 {}; // has a non-standard-layout base class
With these new rules a lot more types can be PODs now. And even if a type is not POD, we can take advantage of some of the POD properties separately (if it is only one of trivial or standard-layout).
The standard library has traits to test these properties in the header <type_traits>
:
template <typename T>
struct std::is_pod;
template <typename T>
struct std::is_trivial;
template <typename T>
struct std::is_trivially_copyable;
template <typename T>
struct std::is_standard_layout;
JSONObject jsonobject=new JSONObject();
jsonobject.put("error","Invalid username");
response.getWriter().write(jsonobject.toString());
in javascript:
f(data!=success){
var errorMessage=jQuery.parseJson(data);
alert(errorMessage.error);
}
As promised, I'm putting an example for how to use annotations to serialize/deserialize polymorphic objects, I based this example in the Animal
class from the tutorial you were reading.
First of all your Animal
class with the Json Annotations for the subclasses.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class, name = "Dog"),
@JsonSubTypes.Type(value = Cat.class, name = "Cat") }
)
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then your subclasses, Dog
and Cat
.
public class Dog extends Animal {
private String breed;
public Dog() {
}
public Dog(String name, String breed) {
setName(name);
setBreed(breed);
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
public class Cat extends Animal {
public String getFavoriteToy() {
return favoriteToy;
}
public Cat() {}
public Cat(String name, String favoriteToy) {
setName(name);
setFavoriteToy(favoriteToy);
}
public void setFavoriteToy(String favoriteToy) {
this.favoriteToy = favoriteToy;
}
private String favoriteToy;
}
As you can see, there is nothing special for Cat
and Dog
, the only one that know about them is the abstract
class Animal
, so when deserializing, you'll target to Animal
and the ObjectMapper
will return the actual instance as you can see in the following test:
public class Test {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
Animal myDog = new Dog("ruffus","english shepherd");
Animal myCat = new Cat("goya", "mice");
try {
String dogJson = objectMapper.writeValueAsString(myDog);
System.out.println(dogJson);
Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);
System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName());
String catJson = objectMapper.writeValueAsString(myCat);
Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class);
System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output after running the Test
class:
{"@type":"Dog","name":"ruffus","breed":"english shepherd"}
Deserialized dogJson Class: Dog
{"@type":"Cat","name":"goya","favoriteToy":"mice"}
Deserialized catJson Class: Cat
Hope this helps,
Jose Luis
The \
(backslash) in the .match
call is not properly escaped. It would be easier to use a regex literal though. Either will work:
var regex = "^\\s+$";
var regex = /^\s+$/;
Also note that +
will require at least one space. You may want to use *
.
The accepted answer only renamed the user but the privileges were left behind.
I'd recommend using:
RENAME USER 'foo'@'1.2.3.4' TO 'foo'@'1.2.3.5';
According to MySQL documentation:
RENAME USER causes the privileges held by the old user to be those held by the new user.
strings = ("string1", "string2", "string3")
for line in file:
if any(s in line for s in strings):
print "yay!"
This acronym might help you to remember the ASP.NET life cycle stages which I wrote about in the below blog post.
R-SIL-VP-RU
- Request
- Start
- Initialization
- Load
- Validation
- Post back handling
- Rendering
- Unload
From my blog: Understand ASP.NET Page life cycle and remember stages in easy way
18 May 2014
This should do it:
[^a-zA-Z\d\s:]
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2)
or using the utility kill(1)
.
If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).
The answer has been covered, but for simplicity...
# To filter out finished threads
threads = [t for t in threads if t.is_alive()]
# Same thing but for QThreads (if you are using PyQt)
threads = [t for t in threads if t.isRunning()]
Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.
But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.
So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.
using System.Text.RegularExpressions;
private void Form1_Shown(object sender, EventArgs e)
{
filterTextBoxContent(textBox1);
}
string pattern = @"[^0-9^+^\-^/^*^(^)]";
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
filterTextBoxContent(textBox1);
}
private bool filterTextBoxContent(TextBox textBox)
{
string text = textBox.Text;
MatchCollection matches = Regex.Matches(text, pattern);
bool matched = false;
int selectionStart = textBox.SelectionStart;
int selectionLength = textBox.SelectionLength;
int leftShift = 0;
foreach (Match match in matches)
{
if (match.Success && match.Captures.Count > 0)
{
matched = true;
Capture capture = match.Captures[0];
int captureLength = capture.Length;
int captureStart = capture.Index - leftShift;
int captureEnd = captureStart + captureLength;
int selectionEnd = selectionStart + selectionLength;
text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);
textBox.Text = text;
int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);
if (boundSelectionStart == -1)
{
if (boundSelectionEnd == 0)
{
selectionLength -= selectionEnd - captureStart;
}
else if (boundSelectionEnd == 1)
{
selectionLength -= captureLength;
}
}
else if (boundSelectionStart == 0)
{
if (boundSelectionEnd == 0)
{
selectionStart = captureStart;
selectionLength = 0;
}
else if (boundSelectionEnd == 1)
{
selectionStart = captureStart;
selectionLength -= captureEnd - selectionStart;
}
}
else if (boundSelectionStart == 1)
{
selectionStart -= captureLength;
}
leftShift++;
}
}
textBox.SelectionStart = selectionStart;
textBox.SelectionLength = selectionLength;
return matched;
}
For business data, if the data is private I would use a secured connection, otherwise a forms authentication is sufficient.
If you do decide to use a secured connection, please note that I do not have experience with securing websites, I am just recanting off what I encountered during my own personal experience. If I am wrong in anyway, please feel free to correct me.
What should I do to prepare my website for https. (Do I need to alter the code / Config)
In order to enable SSL (Secure Sockets Layer) for your website, you would need to set-up a certificate, code or config is not altered.
I have enabled SSL for an internal web-server, by using OpenSSL and ActivePerl from this online tutorial. If this is used for a larger audience (my audience was less than 10 people) and is in the public domain, I suggest seeking professional alternatives.
Is SSL and https one and the same...
Not exactly, but they go hand in hand! SSL ensures that data is encrypted and decrypted back and forth while you are viewing the website, https
is the URI that is need to access the secure website. You will notice when you try to access http://secure.mydomain.com
it displays an error message.
Do I need to apply with someone to get some license or something.
You would not need to obtain a license, but rather a certificate. You can look into companies that offer professional services with securing websites, such as VeriSign as an example.
Do I need to make all my pages secured or only the login page...
Once your certificate is enabled for mydomain.com
every page that falls under *.mydomain.com
will be secured.
The width is being restricted by the size of the body. If you make the width of the body larger you will see it stays on one line with the background color.
To maintain the minimum width: min-width:100%
As another poster macm
mentioned, the fastest way to create a tuple from a generator is tuple([generator])
.
List comprehension:
$ python3 -m timeit "a = [i for i in range(1000)]"
10000 loops, best of 3: 27.4 usec per loop
Tuple from list comprehension:
$ python3 -m timeit "a = tuple([i for i in range(1000)])"
10000 loops, best of 3: 30.2 usec per loop
Tuple from generator:
$ python3 -m timeit "a = tuple(i for i in range(1000))"
10000 loops, best of 3: 50.4 usec per loop
Tuple from unpacking:
$ python3 -m timeit "a = *(i for i in range(1000)),"
10000 loops, best of 3: 52.7 usec per loop
My version of python:
$ python3 --version
Python 3.6.3
So you should always create a tuple from a list comprehension unless performance is not an issue.
I just wrote a simple module to deal with reading and updating the current url query params.
Example usage:
import UrlParams from './UrlParams'
UrlParams.remove('foo') //removes all occurences of foo=?
UrlParams.set('foo', 'bar') //set all occurences of foo equal to bar
UrlParams.add('foo', 'bar2') //add bar2 to foo result: foo=bar&foo=bar2
UrlParams.get('foo') //returns bar
UrlParams.get('foo', true) //returns [bar, bar2]
Here is my code named UrlParams.(js/ts):
class UrlParams {
/**
* Get params from current url
*
* @returns URLSearchParams
*/
static getParams(){
let url = new URL(window.location.href)
return new URLSearchParams(url.search.slice(1))
}
/**
* Update current url with params
*
* @param params URLSearchParams
*/
static update(params){
if(`${params}`){
window.history.replaceState({}, '', `${location.pathname}?${params}`)
} else {
window.history.replaceState({}, '', `${location.pathname}`)
}
}
/**
* Remove key from url query
*
* @param param string
*/
static remove(param){
let params = this.getParams()
if(params.has(param)){
params.delete(param)
this.update(params)
}
}
/**
* Add key value pair to current url
*
* @param key string
* @param value string
*/
static add(key, value){
let params = this.getParams()
params.append(key, value)
this.update(params)
}
/**
* Get value or values of key
*
* @param param string
* @param all string | string[]
*/
static get(param, all=false){
let params = this.getParams()
if(all){
return params.getAll(param)
}
return params.get(param)
}
/**
* Set value of query param
*
* @param key string
* @param value string
*/
static set(key, value){
let params = this.getParams()
params.set(key, value)
this.update(params)
}
}
export default UrlParams
export { UrlParams }
Code for background image of a Button in Swift 3.0
buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)
Hope this will help someone.
Oracle SQL :
select *
from MY_TABLE
where REGEXP_LIKE (company , 'Microsodt industry | goglge auto car | oracles database')
more info at : http://www.techonthenet.com/oracle/regexp_like.php
Os
You can list all files in the current directory using os.listdir
:
import os
for filename in os.listdir(os.getcwd()):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Glob
Or you can list only some files, depending on the file pattern using the glob
module:
import glob
for filename in glob.glob('*.txt'):
with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
It doesn't have to be the current directory you can list them in any path you want:
path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Pipe
Or you can even use the pipe as you specified using fileinput
import fileinput
for line in fileinput.input():
# do your stuff
And then use it with piping:
ls -1 | python parse.py
So, your real question is: "How can JavaScript save to a local file?"
Take a look at http://www.tiddlywiki.com/
They save their HTML page locally after you have "changed" it internally.
[ UPDATE 2016.01.31 ]
TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.
TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(
[ END OF UPDATE
The trick is, you have to open the page as file:// not as http:// to be able to save locally.
The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.
-Jesse
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
Just follow as below:
public class Deletable implements Cloneable{
private String str;
public Deletable(){
}
public void setStr(String str){
this.str = str;
}
public void display(){
System.out.println("The String is "+str);
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
and wherever you want to get another object, simple perform cloning. e.g:
Deletable del = new Deletable();
Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
// object, the changes made to this object will
// not be reflected to other object
In my case the problem was the 32/64 bit driver which I solved by configuring the properties of the sql server job:
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
Python 2.x: docs.python.org/2/library/httplib.html:
Note: HTTPS support is only available if the socket module was compiled with SSL support.
Python 3.x: docs.python.org/3/library/http.client.html:
Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).
#!/usr/bin/env python
import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# =>
# 200 OK
# <!DOCTYPE html ....
To verify if SSL is enabled, try:
>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>
You can also have this simple GoogleDoc approach.
<a style="color: green;" href="http://docs.google.com/gview?url=http://domain//docs/<?php echo $row['docname'] ;?>" target="_blank">View</a>
This would create a new page for you to view the doc without distorting your flow.
In repo_a:
git remote add -f b path/to/repo_b.git
git remote update
git diff master remotes/b/master
git remote rm b
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests
response header, indicating that the browser supports it (and in fact prefers it).
It took me 30mins of Googling, but I finally found it buried in the W3 spec.
The confusion comes because the header in the spec was HTTPS: 1
, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:
"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842
Their fix was to rename it to Upgrade-Insecure-Requests: 1
, and the spec has since been updated to match.
Anyway, here is the explanation from the W3 spec (as it appeared at the time)...
The
HTTPS
HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide....
When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.
When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a
Strict-Transport-Security
header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].
I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.
No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.
A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.
All the above answers technically answer the asker's question, but just thought I'd point out a case where you might encounter problems.
If you declare your struct like this:
typedef struct{
int x;
foo(){};
} foo;
You will have problems trying to declare a constructor. This is of course because you haven't actually declared a struct named "foo", you've created an anonymous struct and assigned it the alias "foo". This also means you will not be able to use "foo" with a scoping operator in a cpp file:
foo.h:
typedef struct{
int x;
void myFunc(int y);
} foo;
foo.cpp:
//<-- This will not work because the struct "foo" was never declared.
void foo::myFunc(int y)
{
//do something...
}
To fix this, you must either do this:
struct foo{
int x;
foo(){};
};
or this:
typedef struct foo{
int x;
foo(){};
} foo;
Where the latter creates a struct called "foo" and gives it the alias "foo" so you don't have to use the struct
keyword when referencing it.
Treb, Matthieu's problem was caused by using Excel in a non-English language. In many language versions ";" is the correct separator. Even functions are translated (SUM can be SOMMA, SUMME or whatever depending on what language you work in). Excel will generally understand these differences and if a French-created workbook is opened by a Brazilian they will normally not have any problem. But VBA speaks only US English so for those of us working in one (or more) foreign langauges, this can be a headache. You and CharlesB both gave answers that would have been OK for a US user but Mikko understod the REAL problem and gave the correct answer (which was also the correct one for me too - I'm a Brit working in Italy for a German-speaking company).
import java.util.Scanner;
class CalculateGCD
{
public static int calGCD(int a, int b)
{
int c=0,d=0;
if(a>b){c=b;}
else{c=a;}
for(int i=c; i>0; i--)
{
if(((a%i)+(b%i))==0)
{
d=i;
break;
}
}
return d;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the nos whose GCD is to be calculated:");
int a=sc.nextInt();
int b=sc.nextInt();
System.out.println(calGCD(a,b));
}
}
Try using viewport (vh, vm) units of measure at the body level
html, body { margin: 0; padding: 0; } body { min-height: 100vh; }
Use vh units for horizontal margins, paddings, and borders on the body and subtract them from the min-height value.
I've had bizarre results using vh,vm units on elements within the body, especially when re-sizing.
there is a way to do this. you have to create a Bitmap and a Canvas and call view.draw(canvas);
here is the code:
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
if the view wasn't displayed before the size of it will be zero. Its possible to measure it like this:
if (v.getMeasuredHeight() <= 0) {
v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.draw(c);
return b;
}
EDIT: according to this post, Passing WRAP_CONTENT
as value to makeMeasureSpec()
doesn't to do any good (although for some view classes it does work), and the recommended method is:
// Either this
int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
// Or this
int specWidth = MeasureSpec.makeMeasureSpec(0 /* any */, MeasureSpec.UNSPECIFIED);
view.measure(specWidth, specWidth);
int questionWidth = view.getMeasuredWidth();
http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Matchers.html
anyObject()
should fit your needs.
Also, you can always consider implementing hashCode()
and equals()
for the Bazoo
class. This would make your code example work the way you want.
modifying the proxy value under
[HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
doesnt need to restart ie
And why not making a HTTP Request on the script and ignoring the response ?
http://php.net/manual/en/function.httprequest-send.php
If you make your request on the script you need to call your webserver will run it in background and you can (in your main script) show a message telling the user that the script is running.
Easy way to Check
if TextField.stringValue.isEmpty {
}
Another solution is to use "ctrl+shift+F". You can change the search location to a local directory rather than a solution or project. This will just take the place of the desktop search and you'll still need to get the latest code, but it will allow you to remain within Visual Studio to do your searching.
find MyDir -iname "*.[j][p][g]"
+
find MyDir -iname "*.[b][m][p]"
=
find MyDir -iname "*.[jb][pm][gp]"
select * from v$session
where sid = to_number(substr(dbms_session.unique_session_id,1,4),'XXXX')
Rather than using the ssh://
protocol prefix, you can continue using the conventional URL form for accessing git over SSH, with one small change. As a reminder, the conventional URL is:
git@host:path/to/repo.git
To specify an alternative port, put brackets around the user@host
part, including the port:
[git@host:port]:path/to/repo.git
But if the port change is merely temporary, you can tell git to use a different SSH command instead of changing your repository’s remote URL:
export GIT_SSH_COMMAND='ssh -p port'
git clone git@host:path/to/repo.git # for instance
The Answer from AaronM using the shell one-liner is good, but actually, there is yet another bug, where spaces will corrupt the user names if there are different amounts of white spaces between the user name and the date. The corrupted user names will give multiple rows for user counts and you have to sum them up yourself.
This small change fixed the issue for me:
git ls-files -z | xargs -0n1 git blame -w --show-email | perl -n -e '/^.*?\((.*?)\s+[\d]{4}/; print $1,"\n"' | sort -f | uniq -c | sort -n
Notice the + after \s which will consume all whitespaces from the name to the date.
Actually adding this answer as much for my own rememberance as for helping anyone else, since this is at least the second time I google the subject :)
--show-email
to git blame -w
to aggregate on email instead, since some people use different Name
formats on different computers, and sometimes two people with the same name are working in the same git.it is a collection which is used to notify mostly UI to change in the collection , it supports automatic notification.
Mainly used in WPF ,
Where say suppose you have UI with a list box and add button and when you click on he button an object of type suppose person will be added to the obseravablecollection and you bind this collection to the ItemSource of Listbox , so as soon as you added a new item in the collection , Listbox will update itself and add one more item in it.
Another Alternative for those who are probing around and/or in interactive mode:
$Error[0].Exception.LoaderExceptions
Note: [0] grabs the most recent Error from the stack
On long lists and rare occurrences its about 3x faster using list.index()
- compared to single step iteration methods presented in the other answers.
def list_replace(lst, old=1, new=10):
"""replace list elements (inplace)"""
i = -1
try:
while 1:
i = lst.index(old, i + 1)
lst[i] = new
except ValueError:
pass
eval('(' + jsonObject + ')')
You could use functions like these:
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
And invoke them like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();
byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
// encrypt
byte[] encryptedData = encrypt(key,b);
// decrypt
byte[] decryptedData = decrypt(key,encryptedData);
This should work, I use similar code in a project right now.
I found some more information from this blog.
str = "hello world!";
str.Substring(10, str.Length-10)
you will need to perform the length checks else this would throw an error
Here is a more developed version of the accepted answer that addresses two common needs:
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter integers. Type 0 to exit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == 0) {
done = true;
}
else {
// do something with the input
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Please enter integers. Type 0 to exit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: 0
Exiting...
Note that without nextLine()
, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next()
instead depending on the circumstance, but know that input like this has spaces
will generate multiple exceptions.
Yes. Try the following in your python interpreter:
and
>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero
or
>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero
<?php
if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
$image_path = array();
$count = count($_FILES[$input_name]['name']);
for($key =0; $key <$count; $key++){
$_FILES['file']['name'] = $_FILES[$input_name]['name'][$key];
$_FILES['file']['type'] = $_FILES[$input_name]['type'][$key];
$_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key];
$_FILES['file']['error'] = $_FILES[$input_name]['error'][$key];
$_FILES['file']['size'] = $_FILES[$input_name]['size'][$key];
$config['file_name'] = $_FILES[$input_name]['name'][$key];
$this->upload->initialize($config);
if($this->upload->do_upload('file')) {
$data = $this->upload->data();
$image_path[$key] = $path ."$data[file_name]";
}else{
$error = $this->upload->display_errors();
$this->session->set_flashdata('msg_error',"image upload! ".$error);
}
}
return json_encode($image_path);
}
?>
_x000D_
As all are given answers I want to add little more. I had also faced the same issue.
Why did your query fail? You have,
SELECT pid FROM planets WHERE userid = NULL;
This will not give you the expected result, because from mysql doc
In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.
Emphasis mine.
To search for column values that are
NULL
, you cannot use anexpr = NULL
test. The following statement returns no rows, becauseexpr = NULL
is never true for any expression
SELECT pid FROM planets WHERE userid IS NULL;
To test for NULL
, use the IS NULL
and IS NOT NULL
operators.
NULL
.NULL
.This is the great description and step-by-step instruction how to create and manage master and slave (gcc and g++) alternatives.
Shortly it's:
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
sudo update-alternatives --config gcc
<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
$('#fire').on('click', function (e) {
//your awesome code here
})
This is the only one right answer on this whole page as people answered about "Visual Studio", not "Visual Studio Code":
To change color theme in "Visual Studio Code", use:
File -> Preferences -> Color Theme -> select any color theme you like
You can also download other custom themes as extensions. To do that, open extensions tab on sidebar and type "theme" into the search field to filter extensions only to themes related ones. Click any you like, click "download" and then "install". After installation and restarting VSC, you can find newly installed themes next to default themes in the same place:
File -> Preferences -> Color Theme -> select newly downloaded color theme
PS - Microsoft made bad naming decision by calling this new editor Visual Studio Code, it's terrible how many wrong links we have in google and stackoverflow. They should rename it to VSCode or something.
Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.
I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.
This happens because both of the classes are referring each other, hence creating a loop which causes this error.
So, check whether any such kind of relationships exist in your program.
rownumber() over(...) is working but I didn't like this solution for 2 reasons. - This function is not available when you using older version of SQL like SQL2000 - Dependency on function and is not really readable.
Another solution is:
SELECT tmpall.[OrderNO] ,
tmpall.[PartCode] ,
tmpall.[Quantity] ,
FROM (SELECT [OrderNO],
[PartCode],
[Quantity],
[DateEntered]
FROM you_table) AS tmpall
INNER JOIN (SELECT [OrderNO],
Max([DateEntered]) AS _max_date
FROM your_table
GROUP BY OrderNO ) AS tmplast
ON tmpall.[OrderNO] = tmplast.[OrderNO]
AND tmpall.[DateEntered] = tmplast._max_date
This is a quick and simple add of a named tab to the current worksheet:
Sheets.Add.Name = "Tempo"
From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):
1.10 Empty Operator -
empty A
The
empty
operator is a prefix operator that can be used to determine if a value is null or empty.To evaluate
empty A
- If
A
isnull
, returntrue
- Otherwise, if
A
is the empty string, then returntrue
- Otherwise, if
A
is an empty array, then returntrue
- Otherwise, if
A
is an emptyMap
, returntrue
- Otherwise, if
A
is an emptyCollection
, returntrue
- Otherwise return
false
So, considering the interfaces, it works on Collection
and Map
only. In your case, I think Collection
is the best option. Or, if it's a Javabean-like object, then Map
. Either way, under the covers, the isEmpty()
method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException
.
Through this example copy and retain can be explained like:
NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];
Person *p = [[[Person alloc] init] autorelease];
p.name = someName;
[someName setString:@"Debajit"];
if the property is of type copy then ,
a new copy will be created for the [Person name]
string that will hold the contents of someName
string. Now any operation on someName
string will have no effect on [Person name]
.
[Person name]
and someName
strings will have different memory addresses.
But in case of retain,
both the [Person name]
will hold the same memory address as of somename string, just the retain count of somename string will be incremented by 1.
So any change in somename string will be reflected in [Person name]
string.
If you simply need to check whether the variable is of type X, or that it conforms to some protocol, then you can use is
, or as?
as in the following:
var unknownTypeVariable = …
if unknownTypeVariable is <ClassName> {
//the variable is of type <ClassName>
} else {
//variable is not of type <ClassName>
}
This is equivalent of isKindOfClass
in Obj-C.
And this is equivalent of conformsToProtocol
, or isMemberOfClass
var unknownTypeVariable = …
if let myClass = unknownTypeVariable as? <ClassName or ProtocolName> {
//unknownTypeVarible is of type <ClassName or ProtocolName>
} else {
//unknownTypeVariable is not of type <ClassName or ProtocolName>
}
Disclaimer: This is just a copy of a comment by bobbaluba made more visible for future visitors. It helped me more than any other answer.
You have to drop the ssh://
prefix when using git clone
as an example
git clone [email protected]:owner/repo.git
where 0 is initial value
Array.reduce((currentValue, value) => currentValue +value,0)
or
Array.reduce((currentValue, value) =>{ return currentValue +value},0)
or
[1,3,4].reduce(function(currentValue, value) { return currentValue + value},0)
The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.
Some reasons why this might happen:
If the problem is related to timeout settings, you may be able to resolve it by investigating the following:
This is for the total beginner... like me:
HTML:
<ul>
<li>
<a href="#"> Home </a>
</li>
<li>
<a href="#Info"> Info </a>
</li>
</ul>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-view>
</div>
</div>
Angular:
//Create App
var app = angular.module("myApp", ["ngRoute"]);
//Configure routes
app.config(function ($routeProvider) {
$routeProvider
.otherwise({ template: "<p>Coming soon</p>" })
.when("/", {
template: "<p>Home information</p>"
})
.when("/Info", {
template: "<p>Basic information</p>"
//templateUrl: "/content/views/Info.html"
});
});
//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
$scope.location = $location.path();
$rootScope.$on('$routeChangeStart', function () {
console.log("routeChangeStart");
//Place code here:....
});
});
Hope this helps a total beginner like me. Here is the full working sample:
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#"> Home </a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#Info"> Info </a>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MainCtrl">_x000D_
<div ng-view>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
<script>_x000D_
//Create App_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
_x000D_
//Configure routes_x000D_
app.config(function ($routeProvider) {_x000D_
$routeProvider_x000D_
.otherwise({ template: "<p>Coming soon</p>" })_x000D_
.when("/", {_x000D_
template: "<p>Home information</p>"_x000D_
})_x000D_
.when("/Info", {_x000D_
template: "<p>Basic information</p>"_x000D_
//templateUrl: "/content/views/Info.html"_x000D_
});_x000D_
});_x000D_
_x000D_
//Controller_x000D_
app.controller('MainCtrl', function ($scope, $rootScope, $location) {_x000D_
$scope.location = $location.path();_x000D_
$rootScope.$on('$routeChangeStart', function () {_x000D_
console.log("routeChangeStart");_x000D_
//Place code here:...._x000D_
});_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
# better than Dumper --you're ready for the WWW....
use JSON::XS;
print encode_json \@some_array
Well that's a very interesting question. I would divide the two constants in your question according to their type. int MAX_COUNT
is a constant of primitive type while Logger log
is a non-primitive type.
When we are making use of a constant of a primitive types, we are mutating the constant only once in our code public static final in MAX_COUNT = 10
and we are just accessing the value of the constant elsewhere for(int i = 0; i<MAX_COUNT; i++)
. This is the reason we are comfortable with using this convention.
While in the case of non-primitive types, although, we initialize the constant in only one place private static final Logger log = Logger.getLogger(MyClass.class);
, we are expected to mutate or call a method on this constant elsewhere log.debug("Problem")
. We guys don't like to put a dot operator after the capital characters. After all we have to put a function name after the dot operator which is surely going to be a camel-case name. That's why LOG.debug("Problem")
would look awkward.
Same is the case with String
types. We are usually not mutating or calling a method on a String
constant in our code and that's why we use the capital naming convention for a String
type object.
Almost there. In your predicate, you want a relative path, so change
./book[/author/name = 'John']
to either
./book[author/name = 'John']
or
./book[./author/name = 'John']
and you will match your element. Your current predicate goes back to the root of the document to look for an author
.
Use traceback.extract_stack()
if you want convenient access to module and function names and line numbers.
Use ''.join(traceback.format_stack())
if you just want a string that looks like the traceback.print_stack()
output.
Notice that even with ''.join()
you will get a multi-line string, since the elements of format_stack()
contain \n
. See output below.
Remember to import traceback
.
Here's the output from traceback.extract_stack()
. Formatting added for readability.
>>> traceback.extract_stack()
[
('<string>', 1, '<module>', None),
('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
('<pyshell#1>', 1, '<module>', None)
]
Here's the output from ''.join(traceback.format_stack())
. Formatting added for readability.
>>> ''.join(traceback.format_stack())
' File "<string>", line 1, in <module>\n
File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
ret = method(*args, **kwargs)\n
File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
exec(code, self.locals)\n File "<pyshell#2>", line 1, in <module>\n'
Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.
In versions pre-G++ 4.7, you'll have to use -std=c++0x
, for more recent versions you can use -std=c++11
.
Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.
com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.
For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:
range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)
And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")
edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?
Fully example to demonstrate how jQuery query all data in HTML table.
Assume there is a table like the following in your HTML code.
<table id="someTable">
<thead>
<tr>
<td>title 0</td>
<td>title 1</td>
<td>title 2</td>
</tr>
</thead>
<tbody>
<tr>
<td>row 0 td 0</td>
<td>row 0 td 1</td>
<td>row 0 td 2</td>
</tr>
<tr>
<td>row 1 td 0</td>
<td>row 1 td 1</td>
<td>row 1 td 2</td>
</tr>
<tr>
<td>row 2 td 0</td>
<td>row 2 td 1</td>
<td>row 2 td 2</td>
</tr>
<tr> ... </tr>
<tr> ... </tr>
...
<tr> ... </tr>
<tr>
<td>row n td 0</td>
<td>row n td 1</td>
<td>row n td 2</td>
</tr>
</tbody>
</table>
Then, The Answer, the code to print all row all column, should like this
$('#someTable tbody tr').each( (tr_idx,tr) => {
$(tr).children('td').each( (td_idx, td) => {
console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());
});
});
After running the code, the result will show
[0,0] => row 0 td 0
[0,1] => row 0 td 1
[0,2] => row 0 td 2
[1,0] => row 1 td 0
[1,1] => row 1 td 1
[1,2] => row 1 td 2
[2,0] => row 2 td 0
[2,1] => row 2 td 1
[2,2] => row 2 td 2
...
[n,0] => row n td 0
[n,1] => row n td 1
[n,2] => row n td 2
Summary.
In the code,
tr_idx is the row index start from 0.
td_idx is the column index start from 0.
From this double-loop code,
you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.
You can also type "top" and look at the list of running processes.
The selector ".nr:first"
is specifically looking for the first, and only the first, element having class "nr"
within the selected table element. If you instead call .find(".nr")
you will get all of the elements within the table having class "nr"
. Once you have all of those elements, you could use the .each method to iterate over them. For example:
$(".use-address").click(function() {
$("#choose-address-table").find(".nr").each(function(i, nrElt) {
var id = nrElt.text();
$("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
});
});
However, that would get you all of the td.nr
elements in the table, not just the one in the row that was clicked. To further limit your selection to the row containing the clicked button, use the .closest method, like so:
$(".use-address").click(function() {
$(this).closest("tr").find(".nr").each(function(i, nrElt) {
var id = nrElt.text();
$("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
});
});
I'm using Java 1.8 and JAXB 2.3.1
First, be sure to be using java 1.8 in pom.xml
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
Then in source code I used: (the key was the internal part)
// remove standalone=yes
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
You may need two or more loops depending on your array:
$arr[$key1][$key2][$key3]=$value1; // ....etc
foreach ($arr as $key1 => $values) {
foreach ($key1 as $key2 => $value) {
unset($arr[$key1][$key2]);
}
}
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
Notice the Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D
class in the exception? That's an Entity Framework proxy. I would recommend you disposing of your EF context to ensure that all your objects are eagerly loaded from the database and no such proxies exist:
[HttpPost]
public ActionResult _EditCategory(CategoriesViewModel viewModel)
{
Categoies category = null;
using (var ctx = new MyentityFrameworkContext())
{
category = ctx.Categoies.Find(viewModel.Id);
}
AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
//category = AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
entity.SaveChanges();
}
If the entity retrieval is performed inside a data access layer (which of course is the correct way) make sure you dispose your EF context before returning instances from your DAL.
There is no need to use AS
, just use:
SELECT table1.price Table1 Price, table2.price Table2 Price, .....
if (!"success".equals(statusCheck))
Same problem, different solution.
One line in the PHP file was printing out XML headers (which use the same begin/end tags as PHP). Looks like the code within these tags set the encoding, and was executed within PHP which resulted in the strange characters. Either way here's the solution:
# Original
$xml_string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
# fixed
$xml_string = "<" . "?xml version=\"1.0\" encoding=\"UTF-8\"?" . ">";
You can use:
if (parentGuest.nextSibling) {
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
parentGuest.parentNode.appendChild(childGuest);
}
But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
You can't use float
inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle
.
So if you want to position child
element to right of parent
element you can use margin-left: auto
but now child
element will also push other div
to the right as you can see here Fiddle
.
What you can do now is change order of elements and set order: 2
on child
element so it doesn't affect second div
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
margin-left: auto;_x000D_
order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">Ignore parent?</div>_x000D_
<div>another child</div>_x000D_
</div>
_x000D_
SELECT * FROM emp a
WHERE n = (SELECT COUNT( _rowid)
FROM emp b
WHERE a. _rowid >= b. _rowid);
in SQL*Plus you could also use a REFCURSOR
variable:
SQL> VARIABLE x REFCURSOR
SQL> DECLARE
2 V_Sqlstatement Varchar2(2000);
3 BEGIN
4 V_Sqlstatement := 'SELECT * FROM DUAL';
5 OPEN :x for v_Sqlstatement;
6 End;
7 /
ProcÚdure PL/SQL terminÚe avec succÞs.
SQL> print x;
D
-
X
I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.
After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.
So to access the variable, I type
string fp = Variables.FilePath;
In the PreExecute() method of the Script Component.
This is a full working example :
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public void callWebService(String soapAction, String soapEnvBody) throws IOException {
// Create a StringEntity for the SOAP XML.
String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://example.com/v1.0/Records\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
StringEntity stringEntity = new StringEntity(body, "UTF-8");
stringEntity.setChunked(true);
// Request parameters and other properties.
HttpPost httpPost = new HttpPost("http://example.com?soapservice");
httpPost.setEntity(stringEntity);
httpPost.addHeader("Accept", "text/xml");
httpPost.addHeader("SOAPAction", soapAction);
// Execute and get the response.
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String strResponse = null;
if (entity != null) {
strResponse = EntityUtils.toString(entity);
}
}
If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs
, and then pop
them right after you use them (unless you need them in upper classes).
class First(object):
def __init__(self, *args, **kwargs):
self.first_arg = kwargs.pop('first_arg')
super(First, self).__init__(*args, **kwargs)
class Second(First):
def __init__(self, *args, **kwargs):
self.second_arg = kwargs.pop('second_arg')
super(Second, self).__init__(*args, **kwargs)
class Third(Second):
def __init__(self, *args, **kwargs):
self.third_arg = kwargs.pop('third_arg')
super(Third, self).__init__(*args, **kwargs)
This is the simplest way to solve those kind of problems.
third = Third(first_arg=1, second_arg=2, third_arg=3)
I got the same problem when accessing mysql with root. The problem I found is that some database files does not have permission by the mysql user, which is the user that started the mysql server daemon.
We can check this with ls -l /var/lib/mysql
command, if the mysql user does not have permission of reading or writing on some files or directories, that might cause problem. We can change the owner or mode of those files or directories with chown/chmod
commands.
After these changes, restart the mysqld daemon and login with root with command:
mysql -u root
Then change passwords or create other users for logging into mysql.
HTH
The reason why Pycharm make it as a warning because Python will pass self as the first argument when calling a none static method (not add @staticmethod). Pycharm knows it.
Example:
class T:
def test():
print "i am a normal method!"
t = T()
t.test()
output:
Traceback (most recent call last):
File "F:/Workspace/test_script/test.py", line 28, in <module>
T().test()
TypeError: test() takes no arguments (1 given)
I'm from Java, in Java "self" is called "this", you don't need write self(or this) as argument in class method. You can just call self as you need inside the method. But Python "has to" pass self as a method argument.
By understanding this you don't need any Workaround as @BobStein answer.
as others said Calendar.MONTH returns int and is zero indexed.
to get the current month as a String
use SimpleDateFormat.format()
method
Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));
returns NOV
The BETWEEN operator is inclusive.
From Books Online:
BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.
DateTime Caveat
NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day.
e.g. to get all values within June 2016 you'd need to run:
where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')
i.e.
where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'
Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one:
where myDateTime >= '20160601' AND myDateTime < '20160701'
The most trivial way to upload a binary file to an FTP server using PowerShell is using WebClient.UploadFile
:
$client = New-Object System.Net.WebClient
$client.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")
If you need a greater control, that WebClient
does not offer (like TLS/SSL encryption, etc), use FtpWebRequest
. Easy way is to just copy a FileStream
to FTP stream using Stream.CopyTo
:
$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()
$fileStream.CopyTo($ftpStream)
$ftpStream.Dispose()
$fileStream.Dispose()
If you need to monitor an upload progress, you have to copy the contents by chunks yourself:
$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()
$buffer = New-Object Byte[] 10240
while (($read = $fileStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
$ftpStream.Write($buffer, 0, $read)
$pct = ($fileStream.Position / $fileStream.Length)
Write-Progress `
-Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) `
-PercentComplete ($pct * 100)
}
$ftpStream.Dispose()
$fileStream.Dispose()
If you want to upload all files from a folder, see
PowerShell Script to upload an entire folder to FTP
you can change them via constraint validation api: http://www.w3.org/TR/html5/constraints.html#dom-cva-setcustomvalidity
if you want an easy solution, you can rock out civem.js, Custom Input Validation Error Messages JavaScript lib download here: https://github.com/javanto/civem.js live demo here: http://jsfiddle.net/hleinone/njSbH/
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers: http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Maybe .value_counts()
?
>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0 1
1 2
2 2
3 3
4 3
5 3
6 fred
7 1.8
8 1.8
>>> counts = my_series.value_counts()
>>> counts
3 3
2 2
1.8 2
fred 1
1 1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}
The first argument should be the path to the executable program. So
gdb progname 12271
Consider using matplotlib.cbook pieces
for example:
import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
print s
Here you go, options have values, label and css classes that gets reflected on parent element upon selection.
$(document).on('click','.update_app_status', function (e) {
let $div = $(this).parent().parent();
let $btn = $div.find('.vBtnMain');
let $btn2 = $div.find('.vBtnArrow');
let cssClass = $(this).data('status_class');
let status_value = $(this).data('status_value');
let status_label = $(this).data('status_label');
$btn.html(status_label);
$btn.removeClass();
$btn2.removeClass();
$btn.addClass('btn btn-sm vBtnMain '+cssClass);
$btn2.addClass('btn btn-sm vBtnArrow dropdown-toggle dropdown-toggle-split '+cssClass);
$div.removeClass('show');
$div.find('.dropdown-menu').removeClass('show');
e.preventDefault();
return false;
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group">
<button type="button" class="btn btn-sm vBtnMain btn-warning">Awaiting Review</button>
<button type="button" class="btn btn-sm vBtnArrow btn-warning dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item update_app_status" data-status_class="btn-warning" data-status_value="1" data-status_label="Awaiting Review" href="#">Awaiting Review</a>
<a class="dropdown-item update_app_status" data-status_class="btn-info" data-status_value="2" data-status_label="Reviewed" href="#">Reviewed</a>
<a class="dropdown-item update_app_status" data-status_class="btn-dark" data-status_value="3" data-status_label="Contacting" href="#">Contacting</a>
<a class="dropdown-item update_app_status" data-status_class="btn-success" data-status_value="4" data-status_label="Hired" href="#">Hired</a>
<a class="dropdown-item update_app_status" data-status_class="btn-danger" data-status_value="5" data-status_label="Rejected" href="#">Rejected</a>
</div>
</div>
_x000D_
I created a function for a Volley Request. You just need to pass the arguments :
public void callvolly(final String username, final String password){
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://your_url.com/abc.php"; // <----enter your post url here
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
@Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("username", username);
MyData.put("password", password);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
Another way to achieve this is using old printf()
function of C language
You can use this like
int dd = 1, mm = 9, yy = 1;
printf("%02d - %02d - %04d", mm, dd, yy);
This will print 09 - 01 - 0001
on the console.
You can also use another function sprintf()
to write formatted output to a string like below:
int dd = 1, mm = 9, yy = 1;
char s[25];
sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
cout << s;
Don't forget to include stdio.h
header file in your program for both of these functions
You can fill blank space either by 0 or by another char (not number).
If you do write something like %24d
format specifier than this will not fill 2
in blank spaces. This will set pad to 24
and will fill blank spaces.
The right answer for this question is "css reset".
* {
margin: 0;
padding: 0;
}
It removes all default margin and padding for every object on the page, no holds barred, regardless of browser.
Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu
Bootstrap 3
I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/
The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..
http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook
The way I like to do this is using the %x
literal, which makes it easy (and readable!) to use quotes in a command, like so:
directorylist = %x[find . -name '*test.rb' | sort]
Which, in this case, will populate file list with all test files under the current directory, which you can process as expected:
directorylist.each do |filename|
filename.chomp!
# work with file
end
If you did literally this:
encodeURIComponent('&')
Then the result is %26
, you can test it here. Make sure the string you are encoding is just &
and not &
to begin with...otherwise it is encoding correctly, which is likely the case. If you need a different result for some reason, you can do a .replace(/&/g,'&')
before the encoding.
I used this:
java.util.List<java.util.Map.Entry<String,Integer>> pairList= new java.util.ArrayList<>();
I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.
Ok, I had the same problem.I came up with this solution.It worked for me the best.I did try atoi() but didn't work well for me.So here is my solution:
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;
}
One way is to leave a raw_input()
at the end so the script waits for you to press Enter before it terminates.
If the data type of the field is date or timestamp, Oracle should always give the correct result if you add the correct number given in number of days (or a the correct fraction of a day in your case). So if you are trying to bump the value in 30 minutes, you should use :
select field + 0.5/24 from table;
Based on the information you provided, I believe this is what you tried to do and I am quite sure it works.
You should use setStroke
to set a stroke of the Graphics2D
object.
The example at http://www.java2s.com gives you some code examples.
The following code produces the image below:
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
Container cp = jf.getContentPane();
cp.add(new JComponent() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
g2.draw(new Line2D.Float(30, 20, 80, 90));
}
});
jf.setSize(300, 200);
jf.setVisible(true);
}
}
(Note that the setStroke
method is not available in the Graphics
object. You have to cast it to a Graphics2D
object.)
This post has been rewritten as an article here.
Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.
Each tab can be converted to a sequence non-breaking spaces which require no wrapping.
" "
This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.
I removed the text-transform: uppercase;
and then set it to bold
/bolder
, and this seemed to work.
2020 simple way :
git reset <commit_hash>
Commit hash of the last commit you want to keep.
You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.
=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))
SNAPSHOT
Enumeration(?):
Enumeration e = new Vector(set).elements();
while (e.hasMoreElements())
{
System.out.println(e.nextElement());
}
Another way (java.util.Collections.enumeration()):
for (Enumeration e1 = Collections.enumeration(set); e1.hasMoreElements();)
{
System.out.println(e1.nextElement());
}
Java 8:
set.forEach(element -> System.out.println(element));
or
set.stream().forEach((elem) -> {
System.out.println(elem);
});
I'm not able to comment first answer to your question, but there's a small mistake. You should use parseInt or Math.floor to convert floating point numbers to integer, i
var days, hours, minutes, seconds, x;
x = ms / 1000;
seconds = Math.floor(x % 60);
x /= 60;
minutes = Math.floor(x % 60);
x /= 60;
hours = Math.floor(x % 24);
x /= 24;
days = Math.floor(x);
Personally, I use CoffeeScript in my projects and my code looks like that:
getFormattedTime : (ms)->
x = ms / 1000
seconds = Math.floor x % 60
x /= 60
minutes = Math.floor x % 60
x /= 60
hours = Math.floor x % 24
x /= 24
days = Math.floor x
formattedTime = "#{seconds}s"
if minutes then formattedTime = "#{minutes}m " + formattedTime
if hours then formattedTime = "#{hours}h " + formattedTime
formattedTime
I use that for all status (update, insert and delete)
CREATE TRIGGER trg_Insert_Test
ON [dbo].[MyTable]
AFTER UPDATE, INSERT, DELETE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Activity NVARCHAR (50)
-- update
IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
BEGIN
SET @Activity = 'UPDATE'
END
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
SET @Activity = 'INSERT'
END
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS(SELECT * FROM inserted)
BEGIN
SET @Activity = 'DELETE'
END
-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl
-- get last 1 row
SELECT * INTO #tmpTbl FROM (SELECT TOP 1 * FROM (SELECT * FROM inserted
UNION
SELECT * FROM deleted
) AS A ORDER BY A.Date DESC
) AS T
-- try catch
BEGIN TRY
INSERT INTO MyTable (
[Code]
,[Name]
.....
,[Activity])
SELECT [Code]
,[Name]
,@Activity
FROM #tmpTbl
END TRY BEGIN CATCH END CATCH
-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl
SET NOCOUNT OFF;
END
For Linux and macOS uses, if you want to get your IP addresses by a synchronous way, try this:
var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
console.log(ips);
The result will be something like this:
['192.168.3.2', '192.168.2.1']
Edit:
Sorry i forgot about pluck()
as many have commented :
Easiest way is :
return DB::table('users')->where('username', $username)->pluck('groupName');
Which will directly return the only the first result for the requested row as a string.
Using the fluent query builder you will obtain an array anyway. I mean The Query Builder has no idea how many rows will come back from that query. Here is what you can do to do it a bit cleaner
$result = DB::table('users')->select('groupName')->where('username', $username)->first();
The first()
tells the queryBuilder to return only one row so no array, so you can do :
return $result->groupName;
Hope it helps
Axios.post solution with IE and other browsers
I've found some incredible solutions here. But they frequently don't take into account problems with IE browser. Maybe it will save some time to somebody else.
axios.post("/yourUrl"
, data,
{responseType: 'blob'}
).then(function (response) {
let fileName = response.headers["content-disposition"].split("filename=")[1];
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE variant
window.navigator.msSaveOrOpenBlob(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}),
fileName);
} else {
const url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', response.headers["content-disposition"].split("filename=")[1]);
document.body.appendChild(link);
link.click();
}
}
);
example above is for excel files, but with little changes can be applied to any format.
And on server I've done this to send an excel file.
response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=exceptions.xlsx")
To avoid using curl or Chrome plugins you can just use the the built in windows Powershell. From the Powershell command window run
Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:9200/sampleindex/sampleType/" -
Method POST -ContentType "application/json" -Body '{
"user" : "Test",
"post_date" : "2017/11/13 11:07:00",
"message" : "trying out Elasticsearch"
}'
Note the Index name MUST be in lowercase.
If someone is in search for a quick minimal solution,
import signal
# The code which crashes program on interruption
signal.signal(signal.SIGINT, call_this_function_if_interrupted)
# The code skipped if interrupted
Here's how I do file upload in react using axios
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
this.setState({file:e.target.files[0]})
}
fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
Object.entries()
returns an array whose elements are arrays corresponding to the enumerable property[key, value]
pairs found directly uponobject
. The ordering of the properties is the same as that given by looping over the property values of the object manually.
The Object.entries
function returns almost the exact output you're asking for, except the keys are strings instead of numbers.
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
console.log(Object.entries(obj));
_x000D_
If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
const toNumericPairs = input => {_x000D_
const entries = Object.entries(input);_x000D_
return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));_x000D_
}_x000D_
_x000D_
console.log(toNumericPairs(obj));
_x000D_
I use an arrow function and Object.assign
for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign
returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.
This is equivalent to:
entry => {
entry[0] = +entry[0];
return entry;
}
As mentioned by @TravisClarke in the comments, the map function could be shortened to:
entry => [ +entry[0], entry[1] ]
However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.
Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.
You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
const toNumericPairs = input => {_x000D_
const entries = Object.entries(obj);_x000D_
entries.forEach(entry => entry[0] = +entry[0]);_x000D_
return entries;_x000D_
}_x000D_
_x000D_
console.log(toNumericPairs(obj));
_x000D_
Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.
While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for
), conditionals (<% if
) and transforms (<%= myString | uppercase %>
) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).
One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script>
type
, e.g. <script type="text/template">
. For your case:
<script type="text/template" data-template="listitem">
<a href="${url}" class="list-group-item">
<table>
<tr>
<td><img src="${img}"></td>
<td><p class="list-group-item-text">${title}</p></td>
</tr>
</table>
</a>
</script>
On document load, read your template and tokenize it using a simple String#split
var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);
Notice that with our token, you get it in the alternating [text, property, text, property]
format. This lets us nicely map it using an Array#map
, with a mapping function:
function render(props) {
return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}
Where props
could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }
.
Putting it all together assuming you've parsed and loaded your itemTpl
as above, and you have an items
array in-scope:
$('.search').keyup(function () {
$('.list-items').append(items.map(function (item) {
return itemTpl.map(render(item)).join('');
}));
});
This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector
and .innerHTML
.
A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.
In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html
method above.
const Item = ({ url, img, title }) => `
<a href="${url}" class="list-group-item">
<div class="image">
<img src="${img}" />
</div>
<p class="list-group-item-text">${title}</p>
</a>
`;
Then you could easily render it, even mapped from an array, like so:
$('.list-items').html([
{ url: '/foo', img: 'foo.png', title: 'Foo item' },
{ url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));
Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.
Apple's FixIt supplied %hhd, which correctly gave me the value of my BOOL.
Swift 3 Answer: In my case, I wanted to have an outlet in my custom class that I could modify:
class MyClassView: UIView {
@IBOutlet weak var myLabel: UILabel!
class func createMyClassView() -> MyClass {
let myClassNib = UINib(nibName: "MyClass", bundle: nil)
return myClassNib.instantiate(withOwner: nil, options: nil)[0] as! MyClassView
}
}
When in the .xib, make sure that the Custom Class field is MyClassView. Don't bother with the File's Owner.
Also, make sure that you connect the outlet in MyClassView to the label:
To instantiate it:
let myClassView = MyClassView.createMyClassView()
myClassView.myLabel.text = "Hello World!"
Typically, for passing arguments to a command line script, you will use either argv
global variable or getopt:
// bash command:
// php -e myscript.php hello
echo $argv[1]; // prints hello
// bash command:
// php -e myscript.php -f=world
$opts = getopt('f:');
echo $opts['f']; // prints world
$_GET refers to the HTTP GET method parameters, which are unavailable in command line, since they require a web server to populate.
If you really want to populate $_GET anyway, you can do this:
// bash command:
// export QUERY_STRING="var=value&arg=value" ; php -e myscript.php
parse_str($_SERVER['QUERY_STRING'], $_GET);
print_r($_GET);
/* outputs:
Array(
[var] => value
[arg] => value
)
*/
You can also execute a given script, populate $_GET
from the command line, without having to modify said script:
export QUERY_STRING="var=value&arg=value" ; \
php -e -r 'parse_str($_SERVER["QUERY_STRING"], $_GET); include "index.php";'
Note that you can do the same with $_POST
and $_COOKIE
as well.
PDFminer gave me perhaps one line [page 1 of 7...] on every page of a pdf file I tried with it.
The best answer I have so far is pdftoipe, or the c++ code it's based on Xpdf.
see my question for what the output of pdftoipe looks like.
I know this is an old post, in SQL Server:
select isnull(town,'TOTAL') Town, count(*) cnt
from user
group by town WITH ROLLUP
Town cnt
Copenhagen 58
NewYork 58
Athens 58
TOTAL 174