DROP and TRUNC do different things:
TRUNCATE TABLE
Removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.
DROP TABLE
Removes one or more table definitions and all data, indexes, triggers, constraints, and permission specifications for those tables.
As far as speed is concerned the difference should be small. And anyway if you don't need the table structure at all, certainly use DROP.
When finding user table, in case if want the table owner name also, you can use the following:
select su.name + '.' + so.name
from sysobjects so,
sysusers su
where so.type = 'U' and
so.uid = su.uid
order by su.name,
so.name
Be very wary of setting IDENTITY_INSERT to ON. This is a poor practice unless the database is in maintenance mode and set to single user. This affects not only your insert, but those of anyone else trying to access the table.
Why are you trying to put a value into an identity field?
Use the convert function, for example:
select * from data
where dateVal < convert(datetime, '01/01/2008', 103)
Where the convert style (103) determines the date format to use.
Use the convert function.
SELECT CONVERT(varchar(10), field_name) FROM table_name
A nice short Swift function to find the hairline in the subviews is this one:
func findHairLineInImageViewUnder(view view: UIView) -> UIImageView? {
if let hairLineView = view as? UIImageView where hairLineView.bounds.size.height <= 1.0 {
return hairLineView
}
if let hairLineView = view.subviews.flatMap({self.findHairLineInImageViewUnder(view: $0)}).first {
return hairLineView
}
return nil
}
I'm also facing this type of problem. After trying all solutions I got final solution on this problem. Reasons for this type of problem is per-defined global fonts. Use !important keyword for each line in @font-face is the solution for this problem.
Full description and example for Solution of this problem is here :- http://answerdone.blogspot.com/2017/06/font-face-not-working-solution.html
Very short code for transferring minutes in two formats!
let format1 = (n) => `${n / 60 ^ 0}:` + n % 60_x000D_
_x000D_
console.log(format1(135)) // "2:15"_x000D_
console.log(format1(55)) // "0:55"_x000D_
_x000D_
let format2 = (n) => `0${n / 60 ^ 0}`.slice(-2) + ':' + ('0' + n % 60).slice(-2)_x000D_
_x000D_
console.log(format2(135)) // "02:15"_x000D_
console.log(format2(5)) // "00:05"
_x000D_
Go to src/enviroments/enviroments.ts
and enable the production mode
export const environment = {
production: true
};
for Angular 2
For Java SE 5: According to Garbage Collector Ergonomics [Oracle]:
initial heap size:
Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.
maximum heap size:
Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.
UPDATE:
As pointed out by Tom Anderson in his comment, the above is for server-class machines. From Ergonomics in the 5.0 JavaTM Virtual Machine:
In the J2SE platform version 5.0 a class of machine referred to as a server-class machine has been defined as a machine with
- 2 or more physical processors
- 2 or more Gbytes of physical memory
with the exception of 32 bit platforms running a version of the Windows operating system. On all other platforms the default values are the same as the default values for version 1.4.2.
In the J2SE platform version 1.4.2 by default the following selections were made
- initial heap size of 4 Mbyte
- maximum heap size of 64 Mbyte
There is an excellent eluceo/ical package that allows you to easily create ics files.
Here is an example usage from docs:
// 1. Create new calendar
$vCalendar = new \Eluceo\iCal\Component\Calendar('www.example.com');
// 2. Create an event
$vEvent = new \Eluceo\iCal\Component\Event();
$vEvent->setDtStart(new \DateTime('2012-12-24'));
$vEvent->setDtEnd(new \DateTime('2012-12-24'));
$vEvent->setNoTime(true);
$vEvent->setSummary('Christmas');
// Adding Timezone (optional)
$vEvent->setUseTimezone(true);
// 3. Add event to calendar
$vCalendar->addComponent($vEvent);
// 4. Set headers
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="cal.ics"');
// 5. Output
echo $vCalendar->render();
select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName1')
and
t.name like '%YourSearchDataType%'
union
(select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName2')
and
t.name like '%YourSearchDataType%')
union
(select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName3')
and
t.name like '%YourSearchDataType%')
order by tbl.name
To search which column is in which table based on your search data type for three different table in one database. This query is expandable to 'n' tables.
using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
writer.WriteLine("whatever you text is");
}
The second "true" parameter tells it to append.
CGFloat is a regular float on 32-bit systems and a double on 64-bit systems
typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit
So you won't get any performance penalty.
This may be a sideways answer, but if you download Virtuemart (A Joomla component), it has a countries table and all the related states all set up for you included in the installation SQL. They're called jos_virtuemart_countries
and jos_virtuemart_states
. It also includes the 2 and 3 character country codes. I'd attach it to my answer, but don't see a way of doing it.
As many have said, you can't stop someone from downloading content. You just can't.
But you can make it harder.
You can overlay images with a transparent div
, which will prevent people from right clicking on them (or, setting the background of a div
to the image will have the same effect).
If you're worried about cross-linking (ie, other people linking to your images, you can check the HTTP referrer and redirect requests which come from a domain which isn't yours to "something else".
Angular 8 HttpClient Service example with Error Handling and Custom Header
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Student } from '../model/student';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
// API path
base_path = 'http://localhost:3000/students';
constructor(private http: HttpClient) { }
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
// Handle API errors
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
// Create a new item
createItem(item): Observable<Student> {
return this.http
.post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
.pipe(
retry(2),
catchError(this.handleError)
)
}
....
....
Check complete example tutorial here
All 3 of them represent the end of a line. But...
\r
(Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line\n
(Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n
moves to the beginning of the line.\r\n
(End Of Line) → a combination of \r
and \n
Normally, for internal commands PowerShell does wait before starting the next command. One exception to this rule is external Windows subsystem based EXE. The first trick is to pipeline to Out-Null
like so:
Notepad.exe | Out-Null
PowerShell will wait until the Notepad.exe process has been exited before continuing. That is nifty but kind of subtle to pick up from reading the code. You can also use Start-Process with the -Wait parameter:
Start-Process <path to exe> -NoNewWindow -Wait
If you are using the PowerShell Community Extensions version it is:
$proc = Start-Process <path to exe> -NoNewWindow -PassThru
$proc.WaitForExit()
Another option in PowerShell 2.0 is to use a background job:
$job = Start-Job { invoke command here }
Wait-Job $job
Receive-Job $job
Meld (http://meldmerge.org/) does a great job at comparing directories and the files within.
I find the existing explanations too gobbledygook. Here's my explanation in plain English:
STA: If a thread creates a COM object that's set to STA (when calling CoCreateXXX you can pass a flag that sets the COM object to STA mode), then only this thread can access this COM object (that's what STA means - Single Threaded Apartment), other thread trying to call methods on this COM object is under the hood silently turned into delivering messages to the thread that creates(owns) the COM object. This is very much like the fact that only the thread that created a UI control can access it directly. And this mechanism is meant to prevent complicated lock/unlock operations.
MTA: If a thread creates a COM object that's set to MTA, then pretty much every thread can directly call methods on it.
That's pretty much the gist of it. Although technically there're some details I didn't mention, such as in the 'STA' paragraph, the creator thread must itself be STA. But this is pretty much all you have to know to understand STA/MTA/NA.
You can learn some tutorials for JSP page direct access database (mysql) here
Notes:
import sql tag library in jsp page
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
then set datasource on page
<sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
Now query what you want on page
<sql:query dataSource="${ds}" var="result"> //ref defined 'ds'
SELECT * from <your-table>;
</sql:query>
Finally you can populate dropdowns on page using c:forEach
tag to iterate result rows in select
element
<c:forEach var="row" items="${result.rows}"> //ref set var 'result'
<option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option>
</c:forEach>
Illumination in case of confusion...
def quit(self):
self.destroy()
exit()
A) destroy() stops the mainloop and kills the window, but leaves python running
B) exit() stops the whole process
Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.
You can use $http.get()
method to fetch your JSON
file. Then assign response data to a $scope
object. In HTML
to create table use ng-repeat for $scope object. ng-repeat
will loop the rows in-side this loop you can bind data to columns dynamically.
I have checked your code and you have created static table
<table>
<tr>
<th>Name</th>
<th>Relationship</th>
</tr>
<tr ng-repeat="indivisual in members">
<td>{{ indivisual.Name }}</td>
<td>{{ indivisual.Relation }}</td>
</tr>
</table>
so better your can go to my code to create dynamic table as per data you column and row will be increase or decrease..
If someone else needs a generic utility type to do this, I came up with the following solution:
/**
* Returns object T, but with T[K] overridden to type U.
* @example
* type MyObject = { a: number, b: string }
* OverrideProperty<MyObject, "a", string> // returns { a: string, b: string }
*/
export type OverrideProperty<T, K extends keyof T, U> = Omit<T, K> & { [P in keyof Pick<T, K>]: U };
I needed this because in my case, the key to override was a generic itself.
If you don't have Omit
ready, see Exclude property from type.
Simpler solution:
var dt = $('#table_scroll').dataTable();
$.getJSON(url, null, function (json) {
dt.fnClearTable();
dt.fnAddData(json.aaData);
dt.fnDraw();
});
If you want all the paths, use recursion.
Using an adjacency list, preferably, create a function f() that attempts to fill in a current list of visited vertices. Like so:
void allPaths(vector<int> previous, int current, int destination)
{
previous.push_back(current);
if (current == destination)
//output all elements of previous, and return
for (int i = 0; i < neighbors[current].size(); i++)
allPaths(previous, neighbors[current][i], destination);
}
int main()
{
//...input
allPaths(vector<int>(), start, end);
}
Due to the fact that the vector is passed by value (and thus any changes made further down in the recursive procedure aren't permanent), all possible combinations are enumerated.
You can gain a bit of efficiency by passing the previous vector by reference (and thus not needing to copy the vector over and over again) but you'll have to make sure that things get popped_back() manually.
One more thing: if the graph has cycles, this won't work. (I assume in this case you'll want to find all simple paths, then) Before adding something into the previous vector, first check if it's already in there.
If you want all shortest paths, use Konrad's suggestion with this algorithm.
When the lists aren't extremely long, this is the best way I know:
function getIndex(val) {
for (var i = 0; i < imageList.length; i++) {
if (imageList[i] === val) {
return i;
}
}
}
var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);
If the file is text, and you want to get the text line by line, the easiest way is to use fgets().
char buffer[100];
FILE *fp = fopen("filename", "r"); // do not use "rb"
while (fgets(buffer, sizeof(buffer), fp)) {
... do something
}
fclose(fp);
The problem seems to happen when you have an alias the same name as the objects property. Hibernate seems to pick up the alias and use it in the sql. I found this documented here and here, and I believe it to be a bug in Hibernate, although I am not sure that the Hibernate team agrees.
Either way, I have found a simple work around that works in my case. Your mileage may vary. The details are below, I tried to simplify the code for this sample so I apologize for any errors or typo's:
Criteria criteria = session.createCriteria(MyClass.class)
.setProjection(Projections.projectionList()
.add(Projections.property("sectionHeader"), "sectionHeader")
.add(Projections.property("subSectionHeader"), "subSectionHeader")
.add(Projections.property("sectionNumber"), "sectionNumber"))
.add(Restrictions.ilike("sectionHeader", sectionHeaderVar)) // <- Problem!
.setResultTransformer(Transformers.aliasToBean(MyDTO.class));
Would produce this sql:
select
this_.SECTION_HEADER as y1_,
this_.SUB_SECTION_HEADER as y2_,
this_.SECTION_NUMBER as y3_,
from
MY_TABLE this_
where
( lower(y1_) like ? )
Which was causing an error: java.sql.SQLException: ORA-00904: "Y1_": invalid identifier
But, when I changed my restriction to use "this", like so:
Criteria criteria = session.createCriteria(MyClass.class)
.setProjection(Projections.projectionList()
.add(Projections.property("sectionHeader"), "sectionHeader")
.add(Projections.property("subSectionHeader"), "subSectionHeader")
.add(Projections.property("sectionNumber"), "sectionNumber"))
.add(Restrictions.ilike("this.sectionHeader", sectionHeaderVar)) // <- Problem Solved!
.setResultTransformer(Transformers.aliasToBean(MyDTO.class));
It produced the following sql and my problem was solved.
select
this_.SECTION_HEADER as y1_,
this_.SUB_SECTION_HEADER as y2_,
this_.SECTION_NUMBER as y3_,
from
MY_TABLE this_
where
( lower(this_.SECTION_HEADER) like ? )
Thats, it! A pretty simple fix to a painful problem. I don't know how this fix would translate to the query by example problem, but it may get you closer.
How about something based on Douglas Crockford idea:
function Shape(){}
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function(){
return this.constructor.parent
? this.constructor.parent.toString() + ',' + this.name
: this.name;
};
function TwoDShape(){}
var F = function(){};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.parent = Shape.prototype;
TwoDShape.prototype.name = '2D Shape';
var my = new TwoDShape();
console.log(my.toString()); ===> Shape,2D Shape
It should be pretty straightforward when to use one or the other, but complex wordings are a source of confusion for many of us.
Use PUT
when you want to modify a singular resource that is already a part of resource collection. PUT
replaces the resource in its entirety. Example: PUT /resources/:resourceId
Sidenote: Use PATCH
if you want to update a part of the resource.
POST
when you want to add a child resource under a collection of resources.POST => /resources
PUT
for UPDATE operations.POST
for CREATE operations.GET
/company/reports => Get all reports
GET
/company/reports/{id} => Get the report information identified by "id"
POST
/company/reports => Create a new report
PUT
/company/reports/{id} => Update the report information identified by "id"
PATCH
/company/reports/{id} => Update a part of the report information identified by "id"
DELETE
/company/reports/{id} => Delete report by "id"
None of the other answers worked for me.
This did: (in Startup.cs)
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
// Here:
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
(or you can put it in WebApiConfig.cs):
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Here:
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
go to menu option Code > Folding to access all code folding related options and their shortcuts.
For the chosen answer version in Swift 3:
var isLoadingTableView = true
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableData.count > 0 && isLoadingTableView {
if let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows, let lastIndexPath = indexPathsForVisibleRows.last, lastIndexPath.row == indexPath.row {
isLoadingTableView = false
//do something after table is done loading
}
}
}
I needed the isLoadingTableView variable because I wanted to make sure the table is done loading before I make a default cell selection. If you don't include this then every time you scroll the table it will invoke your code again.
If you have the option of giving a fixed width to the table cells (and a fixed height to the header), you can used the position: fixed
option:
http://jsfiddle.net/thundercracker/ZxPeh/23/
You would just have to stick it in an iframe
. You could also have horizontal scrolling by giving the iframe
a scrollbar (I think).
Edit 2015
If you can live with a pre-defining the width of your table cells (by percentage), then here's a bit more elegant (CSS-only) solution:
As the other answers point out, once the resources are inside a jar file, things get really ugly. In our case, this solution:
https://stackoverflow.com/a/13227570/516188
works very well in the tests (since when the tests are run the code is not packed in a jar file), but doesn't work when the app actually runs normally. So what I've done is... I hardcode the list of the files in the app, but I have a test which reads the actual list from disk (can do it since that works in tests) and fails if the actual list doesn't match with the list the app returns.
That way I have simple code in my app (no tricks), and I'm sure I didn't forget to add a new entry in the list thanks to the test.
I think your problem is that you assume that the bytes that represent the utf8 string will result in the same string when interpreted as something else (iso-8859-1). And that is simply just not the case. I recommend that you read this excellent article by Joel spolsky.
You should learn about EAFP vs LBYL.
from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
if isinstance(infile, basestring):
infile=open(infile,'r')
if isinstance(outfile, basestring):
outfile=open(outfile,'w')
for lineno, line in enumerate(infile, 1):
line = line.strip()
try:
print >>outfile, int(line,16)
except ValueError:
return "Bad value at line %i: %r" % (lineno, line)
if __name__ == "__main__":
from sys import argv, exit
exit(main(*argv[1:]))
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param
to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
For the sake of completion:
apply(people[,-1], 2, function(x) sum(x))
#Height Weight
# 199 425
Try MM/dd/yyyy hh:mm:ss a format.
Java code to create XML file.
xmlResponse.append("mydate>").append(this.formatDate(resultSet.getTimestamp("date"), "MM/dd/yyyy hh:mm:ss a")).append("");
public String formatDate(Date date, String format)
{
String dateString = "";
if(null != date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateString = dateFormat.format(date);
}
return dateString;
}
HTML frames, but it is not an ideal solution. You would essentially be accessing 3 separate HTML pages at once.
Your other option is to use AJAX I think.
DUMPBIN /EXPORTS Will get most of that information and hitting MSDN will get the rest.
Get one of the Visual Studio packages; C++
Got it. Kind of a hack, but it works pretty nice:
var params = document.body.getElementsByTagName('script');
query = params[0].classList;
var param_a = query[0];
var param_b = query[1];
var param_c = query[2];
I pass the params in the script tag as classes:
<script src="http://path.to/widget.js" class="2 5 4"></script>
This article helped a lot.
If you want integer i.e. number of days:
SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int
Yes, you are using it incorrectly, Series.replace()
is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace
keyword argument as True
Example -
data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)
Also, you can combine the above into a single replace
function call by using list
for both to_replace
argument as well as value
argument , Example -
data['sex'].replace([0,1],['Female','Male'],inplace=True)
Example/Demo -
In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)
In [12]: data
Out[12]:
sex split
0 Male 0
1 Female 1
2 Male 0
3 Female 1
You can also use a dictionary, Example -
In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)
In [17]: data
Out[17]:
sex split
0 Male 0
1 Female 1
2 Male 0
3 Female 1
Unfortunately, it's not completely portable. It's usually integral, but it can be any "integer or real-floating type".
name1 = input("What's your name? ")
age1 = int(input ("how old are you? "))
twentyone = str(21 - int(age1))
if age1<21:
print ("Hi, " + name1+ " you will be 21 in: " + twentyone + " years.")
else:
print("You are over the age of 21")
For a soft impact animation solution:
Swift 3:
let indexPath = IndexPath(item: row, section: 0)
tableView.reloadRows(at: [indexPath], with: .fade)
Swift 2.x:
let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
This is another way to protect the app from crashing:
Swift 3:
let indexPath = IndexPath(item: row, section: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
if visibleIndexPaths != NSNotFound {
tableView.reloadRows(at: [indexPath], with: .fade)
}
}
Swift 2.x:
let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.indexOf(indexPath) {
if visibleIndexPaths != NSNotFound {
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
Months in Calendar object start from 0
0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
If you're using PHP you can test your PUT upload using the code below:
#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo
#one
{
background-color: #EEE;
margin: 62px 258px;
padding: 5px;
width: 200px;
position: relative;
}
#two
{
background-color: #F00;
display: inline-block;
height: 30px;
position: absolute;
width: 100px;
top:10px;
}?
You can delete newlines with tr
:
var=`hg st -R "$path" | tr -d '\n'`
if [ -n $var ]; then
echo $var
done
The stack is "implemented" by means of the stack pointer, which (assuming x86 architecture here) points into the stack segment. Every time something is pushed on the stack (by means of pushl, call, or a similar stack opcode), it is written to the address the stack pointer points to, and the stack pointer decremented (stack is growing downwards, i.e. smaller addresses). When you pop something off the stack (popl, ret), the stack pointer is incremented and the value read off the stack.
In a user-space application, the stack is already set up for you when your application starts. In a kernel-space environment, you have to set up the stack segment and the stack pointer first...
I always use this
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.requestAnimationFrame(functionToBeCalled)
NOTE
combining clearRect and requestAnimationFrame allows for more fluid animation if that is what you're going for
Heres a tidy solution in TypeScript:
import { Readable } from 'stream'
class ReadableString extends Readable {
private sent = false
constructor(
private str: string
) {
super();
}
_read() {
if (!this.sent) {
this.push(Buffer.from(this.str));
this.sent = true
}
else {
this.push(null)
}
}
}
const stringStream = new ReadableString('string to be streamed...')
Many of the other answers here seem to address this issue from the perspective of a JavaScript function running in the browser. I'll shoot and answer assuming that when the asker said "Shell Script" he meant a Node.js backend JavaScript. Possibly using commander.js to use frame your code :)
You could use the child_process module from node's API. I pasted the example code below.
var exec = require('child_process').exec, child;
child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
child();
Hope this helps!
You might wanna use include method in JS.
var sentence = "This is my line";
console.log(sentence.includes("my"));
//returns true if substring is present.
PS: includes is case sensitive.
Seems like this is the obvious answer:
String empty = org.apache.commons.lang.StringUtils.EMPTY;
Awesome because "empty initialization" code no longer has a "magic string" and uses a constant.
Did you try using t.Text
?
char c = '5'
A char
(1 byte) is allocated on stack at address 0x12345678
.
char *d = &c;
You obtain the address of c
and store it in d
, so d = 0x12345678
.
int *e = (int*)d;
You force the compiler to assume that 0x12345678
points to an int
, but an int is not just one byte (sizeof(char) != sizeof(int)
). It may be 4 or 8 bytes according to the architecture or even other values.
So when you print the value of the pointer, the integer is considered by taking the first byte (that was c
) and other consecutive bytes which are on stack and that are just garbage for your intent.
This worked for me!
To run projects like http://localhost/projectName
<VirtualHost localhost:80>
ServerAdmin localhost
DocumentRoot path/to/htdocs/
ServerName localhost
</VirtualHost>
To run projects like http://somewebsite.com
locally
<VirtualHost somewebsite.com:80>
ServerAdmin [email protected]
DocumentRoot /path/to/htdocs/somewebsiteFolder
ServerName www.somewebsite.com
ServerAlias somewebsite.com
</VirtualHost>
Same for other websites
<VirtualHost anothersite.local:80>
ServerAdmin [email protected]
DocumentRoot /path/to/htdocs/anotherSiteFolder
ServerName www.anothersite.local
ServerAlias anothersite.com
</VirtualHost>
The question is you want write the name just one times.
I have an ider like this:
#define __ENUM(situation,num) \
int situation = num; const char * __##situation##_name = #situation;
const struct {
__ENUM(get_other_string, -203);//using a __ENUM Mirco make it ease to write,
__ENUM(get_negative_to_unsigned, -204);
__ENUM(overflow,-205);
//The following two line showing the expanding for __ENUM
int get_no_num = -201; const char * __get_no_num_name = "get_no_num";
int get_float_to_int = -202; const char * get_float_to_int_name = "float_to_int_name";
}eRevJson;
#undef __ENUM
struct sIntCharPtr { int value; const char * p_name; };
//This function transform it to string.
inline const char * enumRevJsonGetString(int num) {
sIntCharPtr * ptr = (sIntCharPtr *)(&eRevJson);
for (int i = 0;i < sizeof(eRevJson) / sizeof(sIntCharPtr);i++) {
if (ptr[i].value == num) {
return ptr[i].p_name;
}
}
return "bad_enum_value";
}
it uses a struct to insert enum, so that a printer to string could follows each enum value define.
int main(int argc, char *argv[]) {
int enum_test = eRevJson.get_other_string;
printf("error is %s, number is %d\n", enumRevJsonGetString(enum_test), enum_test);
>error is get_other_string, number is -203
The difference to enum is builder can not report error if the numbers are repeated.
if you don't like write number, __LINE__
could replace it:
#define ____LINE__ __LINE__
#define __ENUM(situation) \
int situation = (____LINE__ - __BASELINE -2); const char * __##situation##_name = #situation;
constexpr int __BASELINE = __LINE__;
constexpr struct {
__ENUM(Sunday);
__ENUM(Monday);
__ENUM(Tuesday);
__ENUM(Wednesday);
__ENUM(Thursday);
__ENUM(Friday);
__ENUM(Saturday);
}eDays;
#undef __ENUM
inline const char * enumDaysGetString(int num) {
sIntCharPtr * ptr = (sIntCharPtr *)(&eDays);
for (int i = 0;i < sizeof(eDays) / sizeof(sIntCharPtr);i++) {
if (ptr[i].value == num) {
return ptr[i].p_name;
}
}
return "bad_enum_value";
}
int main(int argc, char *argv[]) {
int d = eDays.Wednesday;
printf("day %s, number is %d\n", enumDaysGetString(d), d);
d = 1;
printf("day %s, number is %d\n", enumDaysGetString(d), d);
}
>day Wednesday, number is 3
>day Monday, number is 1
For PHP, look for https://developer.hyvor.com/php/image-upload-ajax-php-mysql
HTML
<html>
<head>
<title>Image Upload with AJAX, PHP and MYSQL</title>
</head>
<body>
<form onsubmit="submitForm(event);">
<input type="file" name="image" id="image-selecter" accept="image/*">
<input type="submit" name="submit" value="Upload Image">
</form>
<div id="uploading-text" style="display:none;">Uploading...</div>
<img id="preview">
</body>
</html>
JAVASCRIPT
var previewImage = document.getElementById("preview"),
uploadingText = document.getElementById("uploading-text");
function submitForm(event) {
// prevent default form submission
event.preventDefault();
uploadImage();
}
function uploadImage() {
var imageSelecter = document.getElementById("image-selecter"),
file = imageSelecter.files[0];
if (!file)
return alert("Please select a file");
// clear the previous image
previewImage.removeAttribute("src");
// show uploading text
uploadingText.style.display = "block";
// create form data and append the file
var formData = new FormData();
formData.append("image", file);
// do the ajax part
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var json = JSON.parse(this.responseText);
if (!json || json.status !== true)
return uploadError(json.error);
showImage(json.url);
}
}
ajax.open("POST", "upload.php", true);
ajax.send(formData); // send the form data
}
PHP
<?php
$host = 'localhost';
$user = 'user';
$password = 'password';
$database = 'database';
$mysqli = new mysqli($host, $user, $password, $database);
try {
if (empty($_FILES['image'])) {
throw new Exception('Image file is missing');
}
$image = $_FILES['image'];
// check INI error
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
// check if the file exists
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
$maxFileSize = 2 * 10e6; // in bytes
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
// check if uploaded file is an image
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
$mimeType = $imageData['mime'];
// validate mime type
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
// nice! it's a valid image
// get file extension (ex: jpg, png) not (.jpg)
$fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));
// create random name for your image
$fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg
// Create the path starting from DOCUMENT ROOT of your website
$path = '/examples/image-upload/images/' . $fileName;
// file path in the computer - where to save it
$destination = $_SERVER['DOCUMENT_ROOT'] . $path;
if (!move_uploaded_file($image['tmp_name'], $destination))
throw new Exception('Error in moving the uploaded file');
// create the url
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$domain = $protocol . $_SERVER['SERVER_NAME'];
$url = $domain . $path;
$stmt = $mysqli -> prepare('INSERT INTO image_uploads (url) VALUES (?)');
if (
$stmt &&
$stmt -> bind_param('s', $url) &&
$stmt -> execute()
) {
exit(
json_encode(
array(
'status' => true,
'url' => $url
)
)
);
} else
throw new Exception('Error in saving into the database');
} catch (Exception $e) {
exit(json_encode(
array (
'status' => false,
'error' => $e -> getMessage()
)
));
}
You could use Trigger.io's UI module to use the native Android date / time picker with a regular HTML5 input. Doing that does require using the overall framework though (so won't work as a regular mobile web page).
You can see before and after screenshots in this blog post: date time picker
private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}
For better performance if this will be called repeatedly, create the start
and gen
(and maybe even range
) variables outside of the function.
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install --user -r requirements.txt
My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.
Just add overflow:hidden
in the first div
style. That should be enough.
I realise this is an old question but for anyone who does come across it this can be done using contenteditable
as shown in this JSFiddle.
Kudos to Alex who mentioned this in the comments (I didn't see that until now!)
The requested jar is probably not jackson-annotations-x.y.z.jar but jackson-core-x.y.z.jar which could be found here: http://www.java2s.com/Code/Jar/j/Downloadjacksoncore220rc1jar.htm
Selected answer works for one drop down menu only. For multiple solution would be:
$('body').click(function(event){
$dropdowns.not($dropdowns.has(event.target)).hide();
});
Try this code:
CONVERT(varchar(15), date_started, 103)
This worked for me. Stolen from here: How do you get the name of the first page of an excel workbook?
object opt = System.Reflection.Missing.Value;
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(WorkBookToOpen,
opt, opt, opt, opt, opt, opt, opt,
opt, opt, opt, opt, opt, opt, opt);
Excel.Worksheet worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
string firstSheetName = worksheet.Name;
Turns out that to copy a complete directory structure gulp
needs to be provided with a base for your gulp.src()
method.
So gulp.src( [ files ], { "base" : "." })
can be used in the structure above to copy all the directories recursively.
If, like me, you may forget this then try:
gulp.copy=function(src,dest){
return gulp.src(src, {base:"."})
.pipe(gulp.dest(dest));
};
The reason this was happening to me (with Photon) was easily fixed by changing an Eclipse general preference:
Window -> Preferences -> General: Uncheck: "Always run in background"
Once you make that change, whenever you shutdown Eclipse, it will no longer leave the javaw.exe process running in the background. I’m guessing this is a bug in Photon (or a bug with using the Amazon Corretto OpenJDK version of Java with Eclipse) that will one day be fixed.
A nice simple solution for parsing a JSON Response to HTML.
var json_response = jQuery.parseJSON(data);
html_response += 'JSON Response:<br />';
jQuery.each(json_response, function(k, v) {
html_response += outputJSONReponse(k, v);
});
function outputJSONReponse(k, v) {
var html_response = k + ': ';
if(jQuery.isArray(v) || jQuery.isPlainObject(v)) {
jQuery.each(v, function(j, w) {
html_response += outputJSONReponse(j, w);
});
} else {
html_response += v + '<br />';
}
return html_response;
}
here's what six is:
pip search six
six - Python 2 and 3 compatibility utilities
to install:
pip install six
though if you did install python-dateutil
from pip six should have been set as a dependency.
N.B.: to install pip run easy_install pip
from command line.
EXEC sp_helpuser
or
SELECT * FROM sysusers
Both of these select all the users of the current database (not the server).
By using transform: works like a charm!
<div class="parent">
<span>center content using transform</span>
</div>
//CSS
.parent {
position: relative;
height: 200px;
border: 1px solid;
}
.parent span {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
To run in Windows, copy this *.bat file to each directory you wish to use and run the ipython notebook by executing the batch file. This assumes you have ipython installed in windows.
set "var=%cd%"
cd var
ipython notebook
Maybe I am 6.5 years late. But I'm answering because others maybe searching still now. I faced the same problem and was searching everywhere. But then I realized I had written my code in an empty file. If you create a project and write your code in there, there won't be this error.
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
CREATE DATE USING MONTH YEAR IN SQL::
DECLARE @FromMonth int=NULL,
@ToMonth int=NULL,
@FromYear int=NULL,
@ToYear int=NULL
/**Region For Create Date**/
DECLARE @FromDate DATE=NULL
DECLARE @ToDate DATE=NULL
SET @FromDate=DateAdd(day,0, DateAdd(month, @FromMonth - 1,DateAdd(Year, @FromYear-1900, 0)))
SET @ToDate=DateAdd(day,-1, DateAdd(month, @ToMonth - 0,DateAdd(Year, @ToYear-1900, 0)))
/**Region For Create Date**/
In Ruby, the Windows version anyways, I just checked and __FILE__
does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.
In PHP __FILE__
is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:
File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")
I should note that in Ruby 1.9.1 __FILE__
contains the full path to the file, the above description was for when I used Ruby 1.8.7.
In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.
Here is the answer to the question here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Facing the same HIPAA issue and found a relatively easy solution,
Create a hidden password field with the field name as an array.
<input type="password" name="password[]" style="display:none" />
Use the same array for the actual password field.
<input type="password" name="password[]" />
The browser (Chrome) may prompt you to "Save password" but regardless if the user selects save, the next time they login the password will auto-populate the hidden password field, the zero slot in the array, leaving the 1st slot blank.
I tried defining the array, such as "password[part2]" but it still remembered. I think it throws it off if it's an unindexed array because it has no choice but to drop it in the first spot.
Then you use your programming language of choice to access the array, PHP for example,
echo $_POST['password'][1];
Assuming the ID is unique:
var result = xmldoc.Element("Customers")
.Elements("Customer")
.Single(x => (int?)x.Attribute("ID") == 2);
You could also use First
, FirstOrDefault
, SingleOrDefault
or Where
, instead of Single
for different circumstances.
By searching for my userid in the registry, I found
HKEY_CURRENT_USER\Volatile Environment\Username
Think of it as enforcing Eager-Loading in a scenario where you sub-items would otherwise be lazy-loading.
The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.
On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.
I am doing this for my email in the following way:
git config --global alias.hobbyprofile 'config user.email "[email protected]"'
Then when I clone a new work project, I have only to run git hobbyprofile
and it will be configured to use that email.
As referred to in the first answer, there are 32/64 bit scenarios which introduce build and runtime pitfalls for developers.
The solution is always to try to get right: What kind of software and OS you have installed.
For a small list of scenarios with the Oracle driver and the solution, you can visit this post.
If you can't REINDEX a workaround is to use aliases. From the official documentation:
APIs in elasticsearch accept an index name when working against a specific index, and several indices when applicable. The index aliases API allow to alias an index with a name, with all APIs automatically converting the alias name to the actual index name. An alias can also be mapped to more than one index, and when specifying it, the alias will automatically expand to the aliases indices. An alias can also be associated with a filter that will automatically be applied when searching, and routing values. An alias cannot have the same name as an index.
Be aware that this solution does not work if you're using More Like This feature. https://github.com/elastic/elasticsearch/issues/16560
Not related to this specific example, but I came across a challenge when trying to use EF and a DateTime field as the concurrency check field. It appears the EF concurrency code doesn't honor the precision setting from the metadata (edmx) i.e. Type="DateTime" Precision="3". The database datetime field will store a millisecond component within the field (i.e. 2020-10-18 15:49:02.123). Even if you set the original value of the Entity to a DateTime that includes the millisecond component, the SQL EF generates is this:
UPDATE [dbo].[People]
SET [dateUpdated] = @0
WHERE (([PeopleID] = @1) AND ([dateUpdated] = @2))
-- @0: '10/19/2020 1:07:00 AM' (Type = DateTime2)
-- @1: '3182' (Type = Int32)
-- @2: '10/19/2020 1:06:10 AM' (Type = DateTime2)
As you can see, @2 is a STRING representation without a millisecond component. This will cause your updates to fail.
Therefore, if you're going to use a DateTime field as a concurrency key, you must STRIP off the milliseconds/Ticks from the database field when retrieving the record and only pass/update the field with a similar stripped DateTime.
//strip milliseconds due to EF concurrency handling
PeopleModel p = db.people.Where(x => x.PeopleID = id);
if (p.dateUpdated.Millisecond > 0)
{
DateTime d = new DateTime(p.dateUpdated.Ticks / 10000000 * 10000000);
object[] b = {p.PeopleID, d};
int upd = db.Database.ExecuteSqlCommand("Update People set dateUpdated=@p1 where peopleId=@p0", b);
if (upd == 1)
p.dateUpdated = d;
else
return InternalServerError(new Exception("Unable to update dateUpdated"));
}
return Ok(p);
And when updating the field with a new value, strip the milliseconds also
(param)int id, PeopleModel person;
People tbl = db.People.Where(x => x.PeopleID == id).FirstOrDefault();
db.Entry(tbl).OriginalValues["dateUpdated"] = person.dateUpdated;
//strip milliseconds from dateUpdated since EF doesn't preserve them
tbl.dateUpdated = new DateTime(DateTime.Now.Ticks / 10000000 * 10000000);
Or you can do that with ES6 template literal:
<a :href="`/job/${r.id}`"
Statically built WITH ssl for windows:
http://sourceforge.net/projects/curlforwindows/files/?source=navbar
You need curl-7.35.0-openssl-libssh2-zlib-x64.7z
..and for ssl all you need to do is add "-k" in addition to any other of your parameters and the bundle BS problem is gone; no CA verification.
mysql 5.7 exposes metadata lock information through the performance_schema.metadata_locks
table.
Documentation here
Set the UINavigationBar's delegate, and then use:
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
//handle the action here
}
I'm now using RxJS 5.5.7 in an Angular application and using finalize
operator has a weird behavior for my use case since is fired before success or error callbacks.
Simple example:
// Simulate an AJAX callback...
of(null)
.pipe(
delay(2000),
finalize(() => {
// Do some work after complete...
console.log('Finalize method executed before "Data available" (or error thrown)');
})
)
.subscribe(
response => {
console.log('Data available.');
},
err => {
console.error(err);
}
);
I have had to use the add
medhod in the subscription to accomplish what I want. Basically a finally
callback after the success or error callbacks are done. Like a try..catch..finally
block or Promise.finally
method.
Simple example:
// Simulate an AJAX callback...
of(null)
.pipe(
delay(2000)
)
.subscribe(
response => {
console.log('Data available.');
},
err => {
console.error(err);
}
);
.add(() => {
// Do some work after complete...
console.log('At this point the success or error callbacks has been completed.');
});
You can copy and past this will help you
<?php
$file = '/test1/example.txt';
$newfile = '/test2/example.txt';
if(!copy($file,$newfile)){
echo "failed to copy $file";
}
else{
echo "copied $file into $newfile\n";
}
?>
In my case, the folder which served the files was a symbolic link to another folder, made with
ln -sf /origin /var/www/destination
Even though the permissions (user and group) where correct on the destination folder (the symbolic link), I still had the error because Nginx needed to have permissions to the origin folder whole's hierarchy as well.
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
This will return all of the factors, very quickly, of a number n
.
Why square root as the upper limit?
sqrt(x) * sqrt(x) = x
. So if the two factors are the same, they're both the square root. If you make one factor bigger, you have to make the other factor smaller. This means that one of the two will always be less than or equal to sqrt(x)
, so you only have to search up to that point to find one of the two matching factors. You can then use x / fac1
to get fac2
.
The reduce(list.__add__, ...)
is taking the little lists of [fac1, fac2]
and joining them together in one long list.
The [i, n/i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0
returns a pair of factors if the remainder when you divide n
by the smaller one is zero (it doesn't need to check the larger one too; it just gets that by dividing n
by the smaller one.)
The set(...)
on the outside is getting rid of duplicates, which only happens for perfect squares. For n = 4
, this will return 2
twice, so set
gets rid of one of them.
If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:
Markup:
<a href="#" id="link1" >click</a>
Javascript:
$(document).ready(function(){
$("#link1").click(clickWithEvent); //Bind the click event to the link
});
function clickWithEvent(evt){
myFunc('p1', 'p2', 'p3');
function myFunc(p1,p2,p3){ //Defined as local function, but has access to evt
alert(evt.type);
}
}
Since the event ob
we can write the UTF-8 encoded file with java using use PrintWriter to write UTF-8 encoded xml
Or Click here
PrintWriter out1 = new PrintWriter(new File("C:\\abc.xml"), "UTF-8");
For anyone who is also trying to call .format()
on a long string, and is unable to use some of the most popular string wrapping techniques without breaking the subsequent .format(
call, you can do str.format("", 1, 2)
instead of "".format(1, 2)
. This lets you break the string with whatever technique you like. For example:
logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title))
can be
logger.info(str.format(("Skipping {0} because its thumbnail was already"
+ "in our system as {1}"), line[indexes['url']], video.title))
Otherwise, the only possibility is using line ending continuations, which I personally am not a fan of.
datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.
Suppose we have a datetime
object and date is represented as:
"2017-05-04"
>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59
Two ways:
public static byte[] StrToByteArray(this string s)
{
List<byte> value = new List<byte>();
foreach (char c in s.ToCharArray())
value.Add(c.ToByte());
return value.ToArray();
}
And,
public static byte[] StrToByteArray(this string s)
{
s = s.Replace(" ", string.Empty);
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
I tend to use the bottom one more often than the top, haven't benchmarked them for speed.
I recently saw this error in a context that didn't match any of the previously listed answers. It turned out to be a conflict with AutoVer. Workaround: temporarily disable AutoVer.
If you have previously run mvn install on project B it will have been installed to your local repository, so when you build package A Maven can resolve the dependency. So as long as you install project B each time you change it your builds for project A will be up to date.
You can define a multi-module project with an aggregator pom to build a set of projects.
It's also worthwhile mentioning m2eclipse, it integrates Maven into Eclipse and allows you to (optionally) resolve dependencies from the workspace. So if you are hacking away on multiple projects, the workspace content will be used for compilation. Once you are happy with your changes, run mvn install (on each project in turn, or using an aggregator) to put them in your local repository.
In Swift 5, in order to sort Dictionary by KEYS
let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.0 < $1.0 })
In order to sort Dictionary by VALUES
let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.1 < $1.1 })
By default, it's not in your PATH. You need to use the "Visual Studio 2005 Command Prompt". Alternatively, you can run the vsvars32 batch file, which will set up your environment correctly.
Conveniently, the path to this is stored in the VS80COMNTOOLS environment variable.
if input == 'a':
for char in 'abc':
if char in some_list:
some_list.remove(char)
Using jdk7-u221, I was need to install the Java Cryptography Extension (JCE)
To append the output of the command to a text filename which includes the current date you can do something like this:
$winupdfile = 'Windows-Update-' + $(get-date -f MM-dd-yyyy) + '.txt'
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`"" -Verb RunAs; exit } else { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`""; exit }
Ahti Kitsik's plugin is mentioned above, but there's a newer plugin by another author that works with newer versions of Eclipse (up to Juno, at least), and also fixed the line numbering issue in the older plugin.
Full installation instructions are at Eclipse version to download the word wrap plug-in
This always works fine for me:
for url in list_of_urls:
urls.setdefault(url, 0)
urls[url] += 1
Use fabs()
(in math.h) to get absolute-value for double
:
double d1 = fabs(-3.8951);
you can use
SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1
assuming you want also to sort by timestamp
?
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
You need to render it as block level;
img {
display: block;
width: auto;
margin: auto;
}
Use this, If it shows the error of UTF-8
pd.read_csv('File_name.csv',encoding='latin-1')
If you're inserting text from a database or such (which one usually do), convert all "<br />
"'s to &vbCrLf. Works great for me :)
protected void btnsubmit_Click(object sender, EventArgs e)
{
string s = @"SELECT * FROM tbl1 WHERE CodNo = @CodNo";
SqlCommand cmd1 = new SqlCommand(s, con);
cmd1.Parameters.AddWithValue("@CodNo", txtid.Text);
con.Open();
int records = (int)cmd1.ExecuteScalar();
if (records > 0)
{
Response.Write("<script>alert('Record not Exist')</script>");
}
else
{
Response.Write("<script>alert('Record Exist')</script>");
}
}
private void insert_data()
{
SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(@CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',@image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',@NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con);
flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName);
string img = @"~/File/" + flpimage.FileName;
flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName);
string img1 = @"~/Tazkiera/" + flpnidcard.FileName;
comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text));
comm.Parameters.AddWithValue("image", flpimage.FileName);
comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName);
comm.ExecuteNonQuery();
con.Close();
Response.Redirect("~/SecondPage.aspx");
//Response.Write("<script>alert('Record Inserted')</script>");
}
}
As Sebastian Redl points out the most straight forward now java.nio.file.Files.write. Details for this can be found in the Reading, Writing, and Creating Files tutorial.
Old answer: FileOutputStream.write(byte[]) would be the most straight forward. What is the data you want to write?
The tutorials for Java IO system may be of some use to you.
Use crontab to add job
crontab -e
And job should be in this format:
00 19 * * 1,3,5 /home/user/somejob.sh
@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs
sizes so you won't notice, but if you used anything else (e.g. col-sm
, col-md
, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/
.left-side {
background-color: blue;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.something {
height: 100%;
background-color: red;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.row {
background-color: green;
overflow: hidden;
}
None of the above answers worked for me using Hibernate 5.2.10, Jersey 2.25.1 and Jackson 2.8.9. I finally found the answer (sort of, they reference hibernate4module but it works for 5 too) here. None of the Json annotations worked at all with @Transient
. Apparently Jackson2 is 'smart' enough to kindly ignore stuff marked with @Transient
unless you explicitly tell it not to. The key was to add the hibernate5 module (which I was using to deal with other Hibernate annotations) and disable the USE_TRANSIENT_ANNOTATION
feature in my Jersey Application:
ObjectMapper jacksonObjectMapper = new ObjectMapper();
Hibernate5Module jacksonHibernateModule = new Hibernate5Module();
jacksonHibernateModule.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
jacksonObjectMapper.registerModule(jacksonHibernateModule);
Here is the dependency for the Hibernate5Module:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.8.9</version>
</dependency>
As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.
If you are allowed to change the code of the document inside your iframe
and that content is visible only using its parent window, simply add the following CSS in your iframe
:
body {
overflow:hidden;
}
Here a very simple example:
This solution allow you to:
Keep you HTML5 valid as it does not need scrolling="no"
attribute on the iframe
(this attribute in HTML5 has been deprecated).
Works on the majority of browsers using CSS overflow:hidden
No JS or jQuery necessary.
Notes:
To disallow scroll-bars horizontally, use this CSS instead:
overflow-x: hidden;
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
Change HeightConstraint
and WidthConstraint
Without creating IBOutlet
.
Note: Assign height or width constraint in Storyboard or XIB file. after fetching this Constraint using this extension.
You can use this extension to fetch a height and width Constraint:
extension UIView {
var heightConstraint: NSLayoutConstraint? {
get {
return constraints.first(where: {
$0.firstAttribute == .height && $0.relation == .equal
})
}
set { setNeedsLayout() }
}
var widthConstraint: NSLayoutConstraint? {
get {
return constraints.first(where: {
$0.firstAttribute == .width && $0.relation == .equal
})
}
set { setNeedsLayout() }
}
}
You can use:
yourView.heightConstraint?.constant = newValue
With Java 7 or newer you can use Files.move(from, to, CopyOption... options)
.
E.g.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
See the Files documentation for more details
One difference between GUID in SQL Server and UUID in PostgreSQL is letter case; SQL Server outputs upper while PostgreSQL outputs lower.
The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input. - rfc4122#section-3
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
Just use
latch = new CountDownLatch(noThreads)
In each thread
latch.countDown();
and as barrier
latch.await();
Solution using the "case" is universal, but then do not use the indexes.
order by case when MyDate is null then 1 else 0 end, MyDate
In my case, I needed performance.
SELECT smoneCol1,someCol2
FROM someSch.someTab
WHERE someCol2 = 2101 and ( someCol1 IS NULL )
UNION
SELECT smoneCol1,someCol2
FROM someSch.someTab
WHERE someCol2 = 2101 and ( someCol1 IS NOT NULL)
Okay, I am now connecting without the semaphore timeout problem.
If anyone reading ever encounters the same thing, I hope that this procedure works for you; but no promises; hey, it's windows.
In my case this was Windows 7
I got a little hint from This page on eHow; not sure if that might help anyone or not.
So anyway, this was the simple twenty three step procedure that worked for me
Click on start button
Choose Control Panel
From Control Panel, choose Device Manger
From Device Manager, choose Universal Serial Bus Controllers
From Universal Serial Bus Controllers, click the little sideways triangle
I cannot predict what you'll see on your computer, but on mine I get a long drop-down list
Begin the investigation to figure out which one of these members of this list is the culprit...
On each member of the drop-down list, right-click on the name
A list will open, choose Properties
Guesswork time: using the various tabs near the top of the resulting window which opens, make a guess if this is the USB adapter driver which is choking your stuff with semaphore timeouts
Once you have made the proper guess, then close the USB Root Hub Properties window (but leave the Device Manager window open).
Physically disonnect anything and everything from that USB hub.
Unplug it.
Return your mouse pointer to that USB Root Hub in the list which you identified earlier.
Right click again
Choose Uninstall
Let Windows do its thing
Wait a little while
Power Down the whole computer if you have the time; some say this is required. I think I got away without it.
Plug the USB hub back into a USB connector on the PC
If the list in the device manager blinks and does a few flash-bulbs, it's okay.
Plug the BlueTooth connector back into the USB hub
Let windows do its thing some more
Within two minutes, I had a working COM port again, no semaphore timeouts.
Hope it works for anyone else who may be having a similar problem.
First, let's clear up some terminology: "asynchronous" (async
) means that it may yield control back to the calling thread before it starts. In an async
method, those "yield" points are await
expressions.
This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".
To futher confuse the issue, async
is very different than "awaitable"; there are some async
methods whose return types are not awaitable, and many methods returning awaitable types that are not async
.
Enough about what they aren't; here's what they are:
async
keyword allows an asynchronous method (that is, it allows await
expressions). async
methods may return Task
, Task<T>
, or (if you must) void
.Task
and Task<T>
.So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run
:
private Task<int> DoWorkAsync() // No async because the method does not need await
{
return Task.Run(() =>
{
return 1 + 2;
});
}
(But this pattern is a poor approach; see below).
But if your question is "how do I create an async
method that can yield back to its caller instead of blocking", the answer is to declare the method async
and use await
for its "yielding" points:
private async Task<int> GetWebPageHtmlSizeAsync()
{
var client = new HttpClient();
var html = await client.GetAsync("http://www.example.com/");
return html.Length;
}
So, the basic pattern of things is to have async
code depend on "awaitables" in its await
expressions. These "awaitables" can be other async
methods or just regular methods returning awaitables. Regular methods returning Task
/Task<T>
can use Task.Run
to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T>
or one of its shortcuts (TaskFactory.FromAsync
, Task.FromResult
, etc). I don't recommend wrapping an entire method in Task.Run
; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run
:
private int DoWork()
{
return 1 + 2;
}
private void MoreSynchronousProcessing()
{
// Execute it directly (synchronously), since we are also a synchronous method.
var result = DoWork();
...
}
private async Task DoVariousThingsFromTheUIThreadAsync()
{
// I have a bunch of async work to do, and I am executed on the UI thread.
var result = await Task.Run(() => DoWork());
...
}
I have an async
/await
intro on my blog; at the end are some good followup resources. The MSDN docs for async
are unusually good, too.
This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:
df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1
print(df)
You'll get:
x
0 -1
1 2
In contrast, the following leaves df unchanged:
df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1
Give your inputs names it will make it easier
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>
</form>
UPDATE:
If you give your button an id things can be even easier:
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>
Javascript:
var button = document.getElementById("theButton"),
value = button.form.valueId.value;
button.onclick = function() {
foo(value);
}
If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto
Vertical centering is a bit tricker, but possible.
df.domain.value_counts()
>>> df.domain.value_counts()
vk.com 5
twitter.com 2
google.com 1
facebook.com 1
Name: domain, dtype: int64
If you have some params, you can do this.
$results = DB::table('rooms')
->distinct()
->leftJoin('bookings', function($join) use ($param1, $param2)
{
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on('arrival','=',DB::raw("'".$param1."'"));
$join->on('arrival','=',DB::raw("'".$param2."'"));
})
->where('bookings.room_type_id', '=', NULL)
->get();
and then return your query
return $results;
Or you could just use justify-content: flex-end
.main { display: flex; }
.c { justify-content: flex-end; }
You can easily achieve this with the use of jQuery .toggle().
$("#btnDisplay").click(function() {
$("#div1").toggle();
$("#div2").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
First Div
</div>
<div id="div2" style="display: none;">
Second Div
</div>
<button id="btnDisplay">Display</button>
The command is gradle dependencies
, and its output is much improved in Gradle 1.2. (You can already try 1.2-rc-1 today.)
This might be your script-free solution: http://davidwalsh.name/css-transform-rotate
It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.
That means that if you don't care for old IEs (the bane of web designers) you can skip the -ms-
and -moz-
prefixes to economize space.
However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need -webkit-
, and there's a still-big cult following of pre-Next Opera and using -o-
is sensate.
If you write only equal condition just: Select Case columns1 When 0 then 'Value1' when 1 then 'Value2' else 'Unknown' End
If you want to write greater , Less then or equal you must do like this: Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then 'value2' Else 'Unkownvalue' End
From tablename
Thanks Mr.Buntha Khin
Have you looked at your build configuration it should like that if you use maven 3 and JDK 7
<build>
<finalName>SpringApp</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
...
</plugins>
...
</build>
If you want to know if both the strings are equal, you can simply do
print string1 == string2
But if you want to know if they both have the same set of characters and they occur same number of times, you can use collections.Counter
, like this
>>> string1, string2 = "abc def ghi", "def ghi abc"
>>> from collections import Counter
>>> Counter(string1) == Counter(string2)
True
Office 365 use two servers, smtp server and protect extended sever.
First server is smtp.office365.com (property Host of smtp client) and second server is STARTTLS/smtp.office365.com (property TargetName of smtp client). Another thing is must put Usedefaultcredential =false before set networkcredentials.
client.UseDefaultCredentials = False
client.Credentials = New NetworkCredential("[email protected]", "Password")
client.Host = "smtp.office365.com"
client.EnableSsl = true
client.TargetName = "STARTTLS/smtp.office365.com"
client.Port = 587
client.Send(mail)
Kotlin version
val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
I used this function htmlspecialchars for alt attributes in images
I know this question is old and most answers here explains padding really well, but while trying to understand it myself I figured having a "visual" image of what is happening helped.
The processor reads the memory in "chunks" of a definite size (word). Say the processor word is 8 bytes long. It will look at the memory as a big row of 8 bytes building blocks. Every time it needs to get some information from the memory, it will reach one of those blocks and get it.
As seem in the image above, doesn't matter where a Char (1 byte long) is, since it will be inside one of those blocks, requiring the CPU to process only 1 word.
When we deal with data larger than one byte, like a 4 byte int or a 8 byte double, the way they are aligned in the memory makes a difference on how many words will have to be processed by the CPU. If 4-byte chunks are aligned in a way they always fit the inside of a block (memory address being a multiple of 4) only one word will have to be processed. Otherwise a chunk of 4-bytes could have part of itself on one block and part on another, requiring the processor to process 2 words to read this data.
The same applies to a 8-byte double, except now it must be in a memory address multiple of 8 to guarantee it will always be inside a block.
This considers a 8-byte word processor, but the concept applies to other sizes of words.
The padding works by filling the gaps between those data to make sure they are aligned with those blocks, thus improving the performance while reading the memory.
However, as stated on others answers, sometimes the space matters more then performance itself. Maybe you are processing lots of data on a computer that doesn't have much RAM (swap space could be used but it is MUCH slower). You could arrange the variables in the program until the least padding is done (as it was greatly exemplified in some other answers) but if that's not enough you could explicitly disable padding, which is what packing is.
When you use lazy load you need to delete your component's module and routing module from app module. If you don't, it'll try to load them when app started and throws that error.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
AppRoutingModule,
// YourComponentModule,
// YourComponentRoutingModule
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Handy way: Using Browser Printing/Preview
I went into this issue today, too. The cause was kinda silly -- vscode
auto imported something from express-validator
and caused the bug.
Just mentioning this in case anyone has done all the steps to clear cache/ delete modules or what not.
In the absence of jQuery, I would use something like this:
<script>
var divsToHide = document.getElementsByClassName("classname"); //divsToHide is an array
for(var i = 0; i < divsToHide.length; i++){
divsToHide[i].style.visibility = "hidden"; // or
divsToHide[i].style.display = "none"; // depending on what you're doing
}
<script>
This is taken from this SO question: Hide div by class id, however seeing that you're asking for "old-school" JS solution, I believe that getElementsByClassName is only supported by modern browsers
The Host
Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host
header does not match any of the configured virtual hosts.
That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).
Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.
This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.
Although the webserver would know the hostname from Server Name Indication, the Host
header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host
header is still valid (and necessary).
Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host
header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD
RESOURCE
and PROTOCOL VERSION
and at least the Host
header, like this:
GET /someresource.html HTTP/1.1
Host: www.example.com
In the MDN Documentation on the "Host" header they actually phrase it like this:
A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.
As mentioned by Darrel Miller, the complete specs can be found in RFC7230.
In the button's XML set android:includeFontPadding="false"
System.Net.WebUtility
class is
available starting from .NET 4.0
(You don't need System.Web.dll dependency).
When using aggregate functions to filter, you must use a HAVING statement.
SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500
Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is QueryPerformanceCounter
. Google it for more info. Try pushing the following into a class, call it CTimer
say, then you can make an instance somewhere global and just call .StartCounter
and .TimeElapsed
Option Explicit
Private Type LARGE_INTEGER
lowpart As Long
highpart As Long
End Type
Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long
Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double
Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#
Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
Low = LI.lowpart
If Low < 0 Then
Low = Low + TWO_32
End If
LI2Double = LI.highpart * TWO_32 + Low
End Function
Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
QueryPerformanceFrequency PerfFrequency
m_crFrequency = LI2Double(PerfFrequency)
End Sub
Public Sub StartCounter()
QueryPerformanceCounter m_CounterStart
End Sub
Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
QueryPerformanceCounter m_CounterEnd
crStart = LI2Double(m_CounterStart)
crStop = LI2Double(m_CounterEnd)
TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property
use http://www.php.net/manual/en/datetime.add.php like
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('1 days'));
echo date_format($date, 'Y-m-d');
output
2000-01-2
All you need is to split using the one of the special character of Java Ragex Engine,
and that is- WhiteSpace Character
[0-9]
[^0-9]
[ \t\n\x0B\f\r]
[^\s]
[\n\x0B\f\r\x85\u2028\u2029]
[^\v]
[a-zA-Z_0-9]
[^\w]
Here, the key point to remember is that the small leter character \s
represents all types of white spaces including a single space [ ]
, tab characters [ ]
or anything similar.
So, if you'll try will something like this-
String theString = "Java<a space><a tab>Programming"
String []allParts = theString.split("\\s+");
You will get the desired output.
Some Very Useful Links:
Hope, this might help you the best!!!
In addition to kieran's answer, apparently, modern browsers have an Object.keys
function. In this case, you could do this:
Object.keys(jsonArray).length;
More details in this answer on How to list the properties of a javascript object
In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/
Are you specifically trying to rotate the links only? Because doing it on the LI tags seems to work fine.
According to Snook transforms require the elements affected be block. He's also got some code there to make this work for IE using filters, if you care to add it on(though there appears to be some limitation on values).
Happened with me twice when I refractor (Rename with SHIFT + F6) the name of a field in our files and it asks you to change it everywhere and we without paying attention change the name everywhere. For example, if you have a variable name "id" in your Java class and you rename it with SHIFT + F6. If you don't pay attention to the next dialog which will ask you wherever else it is going to change the id and you tick check all it will change all the id in your layout files from the new value.
Just set usesCleartextTraffic
flag in the application tag of AndroidManifest.xml
file.
No need to create config file for Android.
<application
android:usesCleartextTraffic="true"
.
.
.>
getopt()
/getopts()
is a good option. Copied from here:
The simple use of "getopt" is shown in this mini-script:
#!/bin/bash
echo "Before getopt"
for i
do
echo $i
done
args=`getopt abc:d $*`
set -- $args
echo "After getopt"
for i
do
echo "-->$i"
done
What we have said is that any of -a, -b, -c or -d will be allowed, but that -c is followed by an argument (the "c:" says that).
If we call this "g" and try it out:
bash-2.05a$ ./g -abc foo
Before getopt
-abc
foo
After getopt
-->-a
-->-b
-->-c
-->foo
-->--
We start with two arguments, and "getopt" breaks apart the options and puts each in its own argument. It also added "--".
My guess is that this could be more elegantly solved in this way:
m <- matrix(1:25, ncol = 5)
m[c(1, 6, 13, 25)] <- NA
df <- data.frame(m)
library(dplyr)
df %>%
filter_all(any_vars(is.na(.)))
#> X1 X2 X3 X4 X5
#> 1 NA NA 11 16 21
#> 2 3 8 NA 18 23
#> 3 5 10 15 20 NA
Just following the thread, can someone conclude which one is the most efficient way to check if an object exists in S3?
I think head_object might win as it just checks the metadata which is lighter than the actual object itself
This adds #
at the beginning of every line:
:%s/^/#/
And people will stop complaining about your lack of properly commenting scripts.
You could make it more readable and more efficient:
string oldValue = valueFieldValue.ToString();
string newValue = value.ToString();
int index = listofelements.IndexOf(oldValue);
if(index != -1)
listofelements[index] = newValue;
This asks only once for the index. Your approach uses Contains
first which needs to loop all items(in the worst case), then you're using IndexOf
which needs to enumerate the items again .
This is a possible solution for you:
a = [15, 12, 10]
b = sorted(a)
print b # --> b = [10, 12, 15]
c = 13
for i in range(len(b)):
if b[i] > c:
break
d = b[:i] + [c] + b[i:]
print d # --> d = [10, 12, 13, 15]
You can handle it all within the same function as following
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>_x000D_
_x000D_
<option value="5">5 dollars</option>_x000D_
<option value="10">10 dollars</option>_x000D_
_x000D_
</select>
_x000D_
as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
Have you tried Tools > Formula Auditing?
I use this extension, almost same as Varun's, but this one (below) is all-purpose:
extension Array where Element: Equatable {
mutating func delete(element: Iterator.Element) {
self = self.filter{$0 != element }
}
}
The difference is that in C++ your object is on the stack, whereas in Java, your object is in the heap. If A and B are Objects, any time in Java you do:
B = A
A and B point to the same object, so anything you do to A you do to B and vice versa.
Use new HashMap()
if you want two different objects.
And you can use Map.putAll(...)
to copy data between two Maps.
<button type="button">my button</button>
we have to add attribute above in our button element
Another way to replace all instances of a string is to use the new (as of August 2020) String.prototype.replaceAll()
method.
It accepts either a string or RegEx as its first argument, and replaces all matches found with its second parameter, either a string or a function to generate the string.
As far as support goes, at time of writing, this method has adoption in current versions of all major desktop browsers* (even Opera!), except IE. For mobile, iOS SafariiOS 13.7+, Android Chromev85+, and Android Firefoxv79+ are all supported as well.
* This includes Edge/ Chrome v85+, Firefox v77+, Safari 13.1+, and Opera v71+
It'll take time for users to update to supported browser versions, but now that there's wide browser support, time is the only obstacle.
References:
You can test your current browser in the snippet below:
//Example coutesy of MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const regex = /dog/gi;
try {
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
console.log('Your browser is supported!');
} catch (e) {
console.log('Your browser is unsupported! :(');
}
_x000D_
.as-console-wrapper: {
max-height: 100% !important;
}
_x000D_
@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})
script below will open the action view url in a new window
<script type="text/javascript">
$(function (){
$('a.edit').click(function () {
var url = $(this).attr('href');
window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
});
return false;
});
</script>
this will also work
data.groupby(data['date'].dt.year)
echo $WORDS | xargs -n1 echo
This outputs every word, you can process that list as you see fit afterwards.
i know a Class is a bit the overkill
class Foo
{
private $sum = NULL;
public function __construct($array)
{
$this->sum[] = $array;
return $this;
}
public function getSum()
{
$sum = $this->sum;
for($i=0;$i<count($sum);$i++)
{
// get the last array index
$res[$i] = $sum[$i] + $sum[count($sum)-$i];
}
return $res;
}
}
$fo = new Foo($myarray)->getSum();
If you are solely interested in outputting the JSON somewhere in your HTML, you could also use a pipe inside an interpolation. For example:
<p> {{ product | json }} </p>
I am not entirely sure it works for every AngularJS version, but it works perfectly in my Ionic App (which uses Angular 2+).
Based on Daniel Krizian's comment, you can also use the pretty_breaks
function from the scales
library, which is imported automatically:
ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 10))
All you have to do is insert the number of ticks wanted for n
.
A slightly less useful solution (since you have to specify the data variable again), you can use the built-in pretty
function:
ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = pretty(dat$x, n = 10)) +
scale_y_continuous(breaks = pretty(dat$y, n = 10))
This is a diff engine for java developers, but it comes with a demo interface - you might be able to use it: https://community.emc.com/docs/DOC-5042
To set permanently,
vim /etc/sysctl.conf
and add
kernel.threads-max = "value"
You must have use correct signature for input parameter *IN is missing in the below code.
CREATE PROCEDURE my_sqrt(IN input_number INT, OUT out_number FLOAT)
Using ScrollView
is not very difficult. You can just add one to your layout and put whatever you want to scroll inside. ScrollView
only takes one child so if you want to put a few things inside then you should make the first thing be something like a LinearLayout
.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- things to scroll -->
</LinearLayout>
</ScrollView>
If you want to scroll things horizontally, then use a HorizontalScrollView
.
As is talked about in this post, sometimes you want the ScrollView
content to fill the screen. For example, if you had some buttons at the end of a readme. You want the buttons to always be at the end of the text and at bottom of the screen, even if the text doesn't scroll.
If the content scrolls, everything is fine. However, if the content is smaller than the size of the screen, the buttons are not at the bottom.
This can be solved with a combination of using fillViewPort
on the ScrollView
and using a layout weight on the content. Using fillViewPort
makes the ScrollView
fill the parent area. Setting the layout_weight
on one of the views in the LinearLayout
makes that view expand to fill any extra space.
Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"> <--- fillViewport
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textview"
android:layout_height="0dp" <---
android:layout_weight="1" <--- set layout_weight
android:layout_width="match_parent"
android:padding="6dp"
android:text="hello"/>
<LinearLayout
android:layout_height="wrap_content" <--- wrap_content
android:layout_width="match_parent"
android:background="@android:drawable/bottom_bar"
android:gravity="center_vertical">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Accept" />
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Refuse" />
</LinearLayout>
</LinearLayout>
</ScrollView>
The idea for this answer came from a previous answer that is now deleted (link for 10K users). The content of this answer is an update and adaptation of this post.
The top voted answer is right and simplest. However, sometimes you may find that not working for some font, but working for others.(Which problem I just came across when dealing with Chinese.)
Solution is do not use "WRAP_CONTENT" only for your TextView, cause there is no extra space for drawing the line. You may set fixed height to your TextView, or use android:paddingVertical with WRAP_CONTENT.
You can use .map
: http://jsfiddle.net/9ndcL/1/.
// array of text of each td
var texts = $("td").map(function() {
return $(this).text();
});
They are the same when used for output, e.g. with printf
.
However, these are different when used as input specifier e.g. with scanf
, where %d
scans an integer as a signed decimal number, but %i
defaults to decimal but also allows hexadecimal (if preceded by 0x
) and octal (if preceded by 0
).
So 033
would be 27 with %i
but 33 with %d
.
numpy.binary_repr(num, width=None)
Examples from the documentation link above:
>>> np.binary_repr(3) '11' >>> np.binary_repr(-3) '-11' >>> np.binary_repr(3, width=4) '0011'
The two’s complement is returned when the input number is negative and width is specified:
>>> np.binary_repr(-3, width=3) '101' >>> np.binary_repr(-3, width=5) '11101'
Write to a file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
byte[] buffer = "This will be writtent in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos != null)
fos.close();
}
Read from file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null)
fis.close();
}
Note: don't forget to add these two permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Try this in config.js
CKEDITOR.editorConfig = function( config )
{
config.enterMode = CKEDITOR.ENTER_BR;
config.shiftEnterMode = CKEDITOR.ENTER_BR;
};
I had some issues with the MouseDown part of this, but here is some code that might get your started.
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Control VerticalAlignment="Top">
<Control.Template>
<ControlTemplate>
<StackPanel>
<TextBox x:Name="MyText"></TextBox>
<Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
<Border Background="Red">
<TextBlock>Test Popup Content</TextBlock>
</Border>
</Popup>
</StackPanel>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Control.Template>
</Control>
</Grid>
</Window>
Let's get very simple:
SELECT stuff(
(
select ', ' + x from (SELECT 'xxx' x union select 'yyyy') tb
FOR XML PATH('')
)
, 1, 2, '')
Replace this line:
select ', ' + x from (SELECT 'xxx' x union select 'yyyy') tb
With your query.
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}