In My cases, After installing Sql server data tools by Visual Studio 2015 installer, problem has been resolved
If you did a custom installation you need to add Microsoft Sql Server Data Tools. After that you can add Reportviwer to your webform.
This is a simple task. You can follow the following steps.
Create a Class ReportData and add it to the Reports folder. Add the following code to the Class.
public class ReportData
{
public ReportData()
{
this.ReportParameters = new List<Parameter>();
this.DataParameters = new List<Parameter>();
}
public bool IsLocal { get; set; }
public string ReportName { get; set; }
public List<Parameter> ReportParameters { get; set; }
public List<Parameter> DataParameters { get; set; }
}
public class Parameter
{
public string ParameterName { get; set; }
public string Value { get; set; }
}
Add another Class and name it ReportBasePage.cs. Add the following code in this Class.
public class ReportBasePage : System.Web.UI.Page
{
protected ReportData ReportDataObj { get; set; }
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (HttpContext.Current != null)
if (HttpContext.Current.Session["ReportData"] != null)
{
ReportDataObj = HttpContext.Current.Session["ReportData"] as ReportData;
return;
}
ReportDataObj = new ReportData();
CaptureRouteData(Page.Request);
}
private void CaptureRouteData(HttpRequest request)
{
var mode = (request.QueryString["rptmode"] + "").Trim();
ReportDataObj.IsLocal = mode == "local" ? true : false;
ReportDataObj.ReportName = request.QueryString["reportname"] + "";
string dquerystr = request.QueryString["parameters"] + "";
if (!String.IsNullOrEmpty(dquerystr.Trim()))
{
var param1 = dquerystr.Split(',');
foreach (string pm in param1)
{
var rp = new Parameter();
var kd = pm.Split('=');
if (kd[0].Substring(0, 2) == "rp")
{
rp.ParameterName = kd[0].Replace("rp", "");
if (kd.Length > 1) rp.Value = kd[1];
ReportDataObj.ReportParameters.Add(rp);
}
else if (kd[0].Substring(0, 2) == "dp")
{
rp.ParameterName = kd[0].Replace("dp", "");
if (kd.Length > 1) rp.Value = kd[1];
ReportDataObj.DataParameters.Add(rp);
}
}
}
}
}
Add ScriptManager to the ReportView.aspx page. Now add a Report Viewer to the page. In report viewer set the property AsyncRendering="false". The code is given below.
<rsweb:ReportViewer ID="ReportViewerRSFReports" runat="server" AsyncRendering="false"
Width="1271px" Height="1000px" >
</rsweb:ReportViewer>
Add two NameSpace in ReportView.aspx.cs
using Microsoft.Reporting.WebForms;
using System.IO;
Change the System.Web.UI.Page to ReportBasePage. Just replace your code using the following.
public partial class ReportView : ReportBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RenderReportModels(this.ReportDataObj);
}
}
private void RenderReportModels(ReportData reportData)
{
// This is the Data Access Layer from which a method is called to fill data to the list.
RASolarERPData dal = new RASolarERPData();
List<ClosingInventoryValuation> objClosingInventory = new List<ClosingInventoryValuation>();
// Reset report properties.
ReportViewerRSFReports.Height = Unit.Parse("100%");
ReportViewerRSFReports.Width = Unit.Parse("100%");
ReportViewerRSFReports.CssClass = "table";
// Clear out any previous datasources.
this.ReportViewerRSFReports.LocalReport.DataSources.Clear();
// Set report mode for local processing.
ReportViewerRSFReports.ProcessingMode = ProcessingMode.Local;
// Validate report source.
var rptPath = Server.MapPath(@"./Report/" + reportData.ReportName +".rdlc");
//@"E:\RSFERP_SourceCode\RASolarERP\RASolarERP\Reports\Report\" + reportData.ReportName + ".rdlc";
//Server.MapPath(@"./Report/ClosingInventory.rdlc");
if (!File.Exists(rptPath))
return;
// Set report path.
this.ReportViewerRSFReports.LocalReport.ReportPath = rptPath;
// Set report parameters.
var rpPms = ReportViewerRSFReports.LocalReport.GetParameters();
foreach (var rpm in rpPms)
{
var p = reportData.ReportParameters.SingleOrDefault(o => o.ParameterName.ToLower() == rpm.Name.ToLower());
if (p != null)
{
ReportParameter rp = new ReportParameter(rpm.Name, p.Value);
ReportViewerRSFReports.LocalReport.SetParameters(rp);
}
}
//Set data paramater for report SP execution
objClosingInventory = dal.ClosingInventoryReport(this.ReportDataObj.DataParameters[0].Value);
// Load the dataSource.
var dsmems = ReportViewerRSFReports.LocalReport.GetDataSourceNames();
ReportViewerRSFReports.LocalReport.DataSources.Add(new ReportDataSource(dsmems[0], objClosingInventory));
// Refresh the ReportViewer.
ReportViewerRSFReports.LocalReport.Refresh();
}
}
Add a Folder to the Reports Folder and name it Report. Now add a RDLC report to the Reports/Report folder and name it ClosingInventory.rdlc.
Now add a Controller and name it ReportController. In the controller add the following action method.
public ActionResult ReportViewer()
{
ViewData["reportUrl"] = "../Reports/View/local/ClosingInventory/";
return View();
}
Add a view page click on the ReportViewer Controller. Name the view page ReportViewer.cshtml. Add the following code to the view page.
@using (Html.BeginForm("Login"))
{
@Html.DropDownList("ddlYearMonthFormat", new SelectList(ViewBag.YearMonthFormat, "YearMonthValue",
"YearMonthName"), new { @class = "DropDown" })
Stock In Transit: @Html.TextBox("txtStockInTransit", "", new { @class = "LogInTextBox" })
<input type="submit" onclick="return ReportValidationCheck();" name="ShowReport"
value="Show Report" />
}
Add an Iframe. Set the property of the Iframe as follows
frameborder="0" width="1000"; height="1000"; style="overflow:hidden;"
scrolling="no"
Add Following JavaScript to the viewer.
function ReportValidationCheck() {
var url = $('#hdUrl').val();
var yearmonth = $('#ddlYearMonthFormat').val();
var stockInTransit = $('#txtStockInTransit').val()
if (stockInTransit == "") {
stockInTransit = 0;
}
if (yearmonth == "0") {
alert("Please Select Month Correctly.");
}
else {
//url = url + "dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
url = "../Reports/ReportView.aspx?rptmode=local&reportname=ClosingInventory¶meters=dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
var myframe = document.getElementById("ifrmReportViewer");
if (myframe !== null) {
if (myframe.src) {
myframe.src = url;
}
else if (myframe.contentWindow !== null && myframe.contentWindow.location !== null) {
myframe.contentWindow.location = url;
}
else { myframe.setAttribute('src', url); }
}
}
return false;
}
Web.config file add the following key to the appSettings section
add key="UnobtrusiveJavaScriptEnabled" value="true"
In system.web handlers Section add the following key
add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Change your data source to your own. This solution is very simple and I think every one will enjoy it.
The below code work fine with me of sure thanks for the above comments. You can add report viewer and change the visible=false and use the below code on submit button:
protected void Button1_Click(object sender, EventArgs e)
{
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string HIJRA_TODAY = "01/10/1435";
ReportParameter[] param = new ReportParameter[3];
param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);
byte[] bytes = ReportViewer1.LocalReport.Render(
"PDF",
null,
out mimeType,
out encoding,
out extension,
out streamIds,
out warnings);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader(
"content-disposition",
"attachment; filename= filename" + "." + extension);
Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
}
FYI - none of the above worked for me in 2012 SP1...simple solution was to embed credentials in the shared data source and then tell Safari to trust the SSRS server site. Then it worked great! Took days chasing down supposed solutions like above only to find out integrated security won't work reliably on Safari - you have to mess with the keychain on the mac and then still wouldn't work reliably.
This link gave me a clue that I didn't install a required update (my problemed concerned version nr, v11.0.0.0)
ReportViewer 2012 Update 'Gotcha' to be aware of
I installed the update SQLServer2008R2SP2
I downloaded ReportViewer.msi, which required to have installed Microsoft® System CLR Types for Microsoft® SQL Server® 2012 (look halfway down the page for installer)
In the GAC was now available WebForms v11.0.0.0 (C:\Windows\assembly\Microsoft.ReportViewer.WebForms
v11.0.0.0
as well as Microsoft.ReportViewer.Common
v11.0.0.0
)
Found a Fix:
First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).
If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.
KB954606 - Security Update for SQL Server SP2
ReportViewer 2005 SP1
http://www.microsoft.com/downloads/details.aspx?familyid=82833F27-081D-4B72-83EF-2836360A904D
Download and install the following update:
KB954607 - Security Update for SQL Server SP2
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
Something to add to this (which I would've added as a comment but the time of writing this post I'd not yet enough reputation)
Having multiple inits in the same package I've not yet found any guaranteed way to know what order in which they will be run. For example I have:
package config
- config.go
- router.go
Both config.go
and router.go
contain init()
functions, but when running router.go
's function ran first (which caused my app to panic).
If you're in a situation where you have multiple files, each with its own init()
function be very aware that you aren't guaranteed to get one before the other. It is better to use a variable assignment as OneToOne shows in his example. Best part is: This variable declaration will happen before ALL init()
functions in the package.
config.go:
var ConfigSuccess = configureApplication()
func init() {
doSomething()
}
func configureApplication() bool {
l4g.Info("Configuring application...")
if valid := loadCommandLineFlags(); !valid {
l4g.Critical("Failed to load Command Line Flags")
return false
}
return true
}
router.go:
func init() {
var (
rwd string
tmp string
ok bool
)
if metapath, ok := Config["fs"]["metapath"].(string); ok {
var err error
Conn, err = services.NewConnection(metapath + "/metadata.db")
if err != nil {
panic(err)
}
}
}
regardless of whether var ConfigSuccess = configureApplication()
exists in router.go
or config.go
, it will be run before EITHER init()
is run.
The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.
For Ubuntu use
apt-get install openjdk-7-jdk
to get Java 7 as default. You may have to uninstall openjdk-6 first.
You have to switch it!
switch (true) {
case ( (pageid === "listing-page") || (pageid === ("home-page") ):
alert("hello");
break;
case (pageid === "details-page"):
alert("goodbye");
break;
}
It depends on the context.
final
class or method, the C# equivalent is sealed
.final
field, the C# equivalent is readonly
.final
local variable or method parameter, there's no direct C# equivalent.If you have many fields in select statement and you want latest value for all of those fields through optimized code:
select * from
(select * from table_name
order by id,rev desc) temp
group by id
In my case for exact same error, I was also not the only developer.
So I went to commit & push my changes at same time, seen at bottom of the Commit
dialog popup:
...but I made the huge mistake of forgetting to hit the Fetch
button to see if I have latest, which I did not.
The commit successfully executed, however not the push, but instead gives the same mentioned error; ...even though other developers didn't alter same files as me, I cannot pull latest as same error is presented.
Most of the time I prefer sticking with Sourcetree's GUI (Graphical User Interface). This solution might not be ideal, however this is what got things going again for me without worrying that I may lose my changes or compromise more recent updates from other developers.
Right-click on the commit right before yours to undo your locally committed changes and select Reset current branch to this commit
like so:
Once all the loading spinners disappear and Sourcetree is done loading the previous commit, at the top-left of window, click on Pull
button...
...then a dialog popup will appear, and click the OK
button at bottom-right:
After pulling latest, if you do not get any errors, skip to STEP 4 (next step below). Otherwise if you discover any merge conflicts at this point, like I did with my Web.config
file:
...then click on the Stash
button at the top, a dialog popup will appear and you will need to write a Descriptive-name-of-your-changes, then click the OK
button:
...once Sourcetree is done stashing your altered file(s), repeat actions in STEP 2 (previous step above), and then your local files will have latest changes. Now your changes can be reapplied by opening your STASHES
seen at bottom of Sourcetree left column, use the arrow to expand your stashes, then right-click to choose Apply Stash 'Descriptive-name-of-your-changes'
, and after select OK
button in dialog popup that appears:
IF you have any Merge Conflict(s) right now, go to your preferred text-editor, like Visual Studio Code, and in the affected files select the Accept Incoming Change
link, then save:
Then back to Sourcetree, click on the Commit
button at top:
then right-click on the conflicted file(s), and under Resolve Conflicts
select the Mark Resolved
option:
Finally!!! We are now able to commit our file(s), also checkmark the Push changes immediately to origin
option before clicking the Commit
button:
P.S. while writing this, a commit was submitted by another developer right before I got to commit, so had to pretty much repeat steps.
Another way is to use np.place
which does in-place replacement and works with multidimentional arrays:
import numpy as np
# create 2x3 array with numbers 0..5
arr = np.arange(6).reshape(2, 3)
# replace 0 with -10
np.place(arr, arr == 0, -10)
To solve the problem, double-click the "MIME Types" configuration option while having IIS root node selected in the left panel and click "Add..." link in the Actions panel on the right. This will bring up the following dialog. Add .woff file extension and specify "application/x-font-woff" as the corresponding MIME type:
Follow same for woff2 with application/x-font-woff2
Following code works..
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(0);
}
});
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
day = selectedDay;
month = selectedMonth;
year = selectedYear;
datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
You may obtain the stream key via the API: https://github.com/justintv/twitch-api
My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):
// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
// Replace 8000, below, with the correct size of the field
cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
cmd.ExecuteNonQuery();
}
Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with
What are you using when operate with CLOB?
In all events you can do it with PL/SQL
DECLARE
str varchar2(32767);
BEGIN
str := 'Very-very-...-very-very-very-very-very-very long string value';
update t1 set col1 = str;
END;
/
I'm using moment.js library for date-time manipulations. Sample code to add one month:
var startDate = new Date(...);
var endDateMoment = moment(startDate); // moment(...) can also be used to parse dates in string format
endDateMoment.add(1, 'months');
During the installation if you think it has hung (notably during the "Android SDK Setup"), browse to your %temp% directory and order by "Date modified" (descending), there should be a bunch of log files created by the installer.
The one for the "Android SDK Setup" will be named "AndroidSDK_SI.log" (or similar).
Open the file and got to the end of it (Ctrl+End), this should indicate the progress of the current file that is being downloaded.
i.e: "(80%, 349 KiB/s, 99 seconds left)"
Reopening the file, again going to the end, you should see further indication that the download has progressed (or you could just track the modified timestamp of the file [in minutes]).
i.e: "(99%, 351 KiB/s, 1 seconds left)"
Unfortunately, the installer doesn't indicate this progress (it's running in a separate "Java.exe" process, used by the Android SDK).
This seems like a rather long-winded way to check what's happening but does give an indication that the installer hasn't hung and is doing something, albeit very slowly.
,Another aproach using common table expression:
with firstOnly as (
select Orders.OrderNumber, LineItems.Quantity, LineItems.Description, ROW_NUMBER() over (partiton by Orders.OrderID order by Orders.OrderID) lp
FROM Orders
join LineItems on Orders.OrderID = LineItems.OrderID
) select *
from firstOnly
where lp = 1
or, in the end maybe you would like to show all rows joined?
comma separated version here:
select *
from Orders o
cross apply (
select CAST((select l.Description + ','
from LineItems l
where l.OrderID = s.OrderID
for xml path('')) as nvarchar(max)) l
) lines
Try using absolute positioning, rather than relative positioning
this should get you close - you can adjust by tweaking margins or top/left positions
#play_button {
position:absolute;
transition: .5s ease;
top: 50%;
left: 50%;
}
If you want they to be paragraph, then use it.
<p><label for="id1">label1:</label> <input type="text" id="id1"/></p>
<p><label for="id2">label2:</label> <input type="text" id="id2"/></p>
Both <label>
and <input>
are paragraph and flow content so you can insert as paragraph elements and as block elements.
Create a UNIQUE
constraint on your subs_email
column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE
:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
Try this:
<?php
$servername = "localhost";
$database = "database";
$username = "user";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
Some of it is native, the rest is available through libraries.
For example Datejs is a good international date library.
For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).
Here is my solution for mac users I think it work for window also:
First go to your Android Studio toolbar
Build > Make Project (while you guys are online let it to download the files) and then
Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then
Run your app that is done it will launch your emulator and configure it then run it!
That is it!!! Happy Coding guys!!!!!!!
I thought it would be valuable to summarize and compare the given answers.
(easier/shorter/memorable option)
[Environment]::UserName
-- @ThomasBratt$env:username
-- @Eoinwhoami
-- @galaktor(more dependable option)
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
-- @MarkSeemann(rather than the name of the user running the PowerShell instance)
$(Get-WMIObject -class Win32_ComputerSystem | select username).username
-- @TwonOfAn on this other forum@Kevin Panko's comment on @Mark Seemann's answer deals with choosing one of the categories over the other:
[The Windows access token approach] is the most secure answer, because $env:USERNAME can be altered by the user, but this will not be fooled by doing that.
In short, the environment variable option is more succinct, and the Windows access token option is more dependable.
I've had to use @Mark Seemann's Windows access token approach in a PowerShell script that I was running from a C# application with impersonation.
The C# application is run with my user account, and it runs the PowerShell script as a service account. Because of a limitation of the way I'm running the PowerShell script from C#, the PowerShell instance uses my user account's environment variables, even though it is run as the service account user.
In this setup, the environment variable options return my account name, and the Windows access token option returns the service account name (which is what I wanted), and the logged in user option returns my account name.
Also, if you want to compare the options yourself, here is a script you can use to run a script as another user. You need to use the Get-Credential cmdlet to get a credential object, and then run this script with the script to run as another user as argument 1, and the credential object as argument 2.
Usage:
$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $cred
Contents of Run-AsUser.ps1 script:
param(
[Parameter(Mandatory=$true)]
[string]$script,
[Parameter(Mandatory=$true)]
[System.Management.Automation.PsCredential]$cred
)
Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"
Extrapolating from Rolando's answer above, it is these that are blocking your query:
---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 10.64.89.143 viget
If you need to execute your query and can not wait for the others to run, kill them off using the MySQL thread id:
kill 5341773 <replace with your thread id>
(from within mysql, not the shell, obviously)
You have to find the thread IDs from the:
show engine innodb status\G
command, and figure out which one is the one that is blocking the database.
MySQL server 5.7 was already installed by default on my new Linux Mint 19.
But, what's the MySQL root
password? It turns out that:
The default installation uses auth_socket
for authentication, in lieu of passwords!
It allows a password-free login, provided that one is logged into the Linux system with the same user name. To login as the MySQL root user
, one can use sudo:
sudo mysql --user=root
But how to then change the root password? To illustrate what's going on, I created a new user "me", with full privileges, with:
mysql> CREATE USER 'me'@'localhost' IDENTIFIED BY 'my_new_password';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'me'@'localhost' WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES;
Comparing "me" with "root":
mysql> SELECT user, plugin, HEX(authentication_string) FROM mysql.user WHERE user = 'me' or user = 'root';
+------+-----------------------+----------------------------------------------------------------------------+
| user | plugin | HEX(authentication_string) |
+------+-----------------------+----------------------------------------------------------------------------+
| root | auth_socket | |
| me | mysql_native_password | 2A393846353030304545453239394634323734333139354241344642413245373537313... |
+------+-----------------------+----------------------------------------------------------------------------+
Because it's using auth_socket, the root password cannot be changed: the SET PASSWORD
command fails, and mysql_secure_installation
desn't attain anything...
==> To zap this alternate authentication mode and return the MySQL root
user to using passwords:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'SOME_NEW_ROOT_PASSWORD';
I just posted a Notepad++ plugin to convert tabs to spaces. Yes, it converts tabs in the middle of a line. Yes, it takes into account other characters within the tabbed field. Check it out.
Another approach is you can represent each row as a string, i.e. mapping the 2D array into an 1D array. Then, all you need to do is unpack and repack the row's string whenever you make an edit:
# Init a 4x5 matrix
a=("00 01 02 03 04" "10 11 12 13 14" "20 21 22 23 24" "30 31 32 33 34")
aset() {
row=$1
col=$2
value=$3
IFS=' ' read -r -a tmp <<< "${a[$row]}"
tmp[$col]=$value
a[$row]="${tmp[@]}"
}
# Set a[2][3] = 9999
aset 2 3 9999
# Show result
for r in "${a[@]}"; do
echo $r
done
Outputs:
00 01 02 03 04
10 11 12 13 14
20 21 22 9999 24
30 31 32 33 34
You can install the package gcolor2
for this:
sudo apt-get install gcolor2
Then:
Applications -> Graphics -> GColor2
Johannes Sixt from the [email protected] mailing list suggested using following command line arguments:
git apply --ignore-space-change --ignore-whitespace mychanges.patch
This solved my problem.
Here is from pandas docs on advanced indexing:
The section will explain exactly what you need! Turns out df.loc
(as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.
df.loc[selection criteria, columns I want] = value
So Bren's answer is saying 'find me all the places where df.A == 0
, select column B
and set it to np.nan
'
Imagine the string could be reversed. Then it is really easy. Instead of working on the string:
"My little cat" (1)
you work with
"tac elttil yM" (2)
With =LEFT(A1;FIND(" ";A1)-1)
in A2 you get "My"
with (1) and "tac"
with (2), which is reversed "cat"
, the last word in (1).
There are a few VBAs around to reverse a string. I prefer the public VBA function ReverseString
.
Install the above as described. Then with your string in A1, e.g., "My little cat"
and this function in A2:
=ReverseString(LEFT(ReverseString(A1);IF(ISERROR(FIND(" ";A1));
LEN(A1);(FIND(" ";ReverseString(A1))-1))))
you'll see "cat"
in A2.
The method above assumes that words are separated by blanks. The IF
clause is for cells containing single words = no blanks in cell. Note: TRIM
and CLEAN
the original string are useful as well. In principle it reverses the whole string from A1 and simply finds the first blank in the reversed string which is next to the last (reversed) word (i.e., "tac "
). LEFT
picks this word and another string reversal reconstitutes the original order of the word (" cat"
). The -1
at the end of the FIND
statement removes the blank.
The idea is that it is easy to extract the first(!) word in a string with LEFT
and FIND
ing the first blank. However, for the last(!) word the RIGHT
function is the wrong choice when you try to do that because unfortunately FIND does not have a flag for the direction you want to analyse your string.
Therefore the whole string is simply reversed. LEFT
and FIND
work as normal but the extracted string is reversed. But his is no big deal once you know how to reverse a string. The first ReverseString
statement in the formula does this job.
I believe you need to put the libeay32.dll and ssleay32.dll files in the systems folder
I tried the above for a Float64Array and it just did not work.
I ended up realising that really the data needed to be read 'INTO' the view in correct chunks. This means reading 8 bytes at a time from the source Buffer.
Anyway this is what I ended up with...
var buff = new Buffer("40100000000000004014000000000000", "hex");
var ab = new ArrayBuffer(buff.length);
var view = new Float64Array(ab);
var viewIndex = 0;
for (var bufferIndex=0;bufferIndex<buff.length;bufferIndex=bufferIndex+8) {
view[viewIndex] = buff.readDoubleLE(bufferIndex);
viewIndex++;
}
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
To get the namespace in its namespace format, e.g. {myNameSpace}
, you can do the following:
root = tree.getroot()
ns = re.match(r'{.*}', root.tag).group(0)
This way, you can use it later on in your code to find nodes, e.g using string interpolation (Python 3).
link = root.find(f"{ns}link")
The most direct way is sum(numbers == x)
.
numbers == x
creates a logical vector which is TRUE at every location that x occurs, and when sum
ing, the logical vector is coerced to numeric which converts TRUE to 1 and FALSE to 0.
However, note that for floating point numbers it's better to use something like: sum(abs(numbers - x) < 1e-6)
.
The supplied answers didn't work for me.
I had an empty repo on GitHub with only the LICENSE file and a single commit locally. What worked was:
$ git fetch
$ git merge --allow-unrelated-histories
Merge made by the 'recursive' strategy.
LICENSE | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
create mode 100644 LICENSE
Also before merge
you may want to:
$ git branch --set-upstream-to origin/master
Branch 'master' set up to track remote branch 'master' from 'origin'.
Use a custom Listview.
You can also customize how row looks by having a custom background. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#0095FF"> //background color
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="@android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
MainActivity
Define populateString() in MainActivity
public class MainActivity extends Activity {
String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data_array = populateString();
ListView ll = (ListView) findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter();
ll.setAdapter(cus);
}
class CustomAdapter extends BaseAdapter
{
LayoutInflater mInflater;
public CustomAdapter()
{
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data_array.length;//listview item count.
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder vh;
vh= new ViewHolder();
if(convertView==null )
{
convertView=mInflater.inflate(R.layout.row, parent,false);
//inflate custom layour
vh.tv2= (TextView)convertView.findViewById(R.id.textView2);
}
else
{
convertView.setTag(vh);
}
//vh.tv2.setText("Position = "+position);
vh.tv2.setText(data_array[position]);
//set text of second textview based on position
return convertView;
}
class ViewHolder
{
TextView tv1,tv2;
}
}
}
row.xml. Custom layout for each row.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Header" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TextView" />
</LinearLayout>
Inflate a custom layout. Use a view holder for smooth scrolling and performance.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about listview performance by android developers.
I faced a similar problem, here's how I solved in my case. I verify if the task
already is RUNNING
or FINISHED
because an task can run only once. Below you will see a partial and adapted code from my solution.
public class MyActivity... {
private MyTask task;
@Override
protected void onCreate(Bundle savedInstanceState) {
// your code
task = new MyTask();
setList();
}
private void setList() {
if (task != null)
if (task.getStatus().equals(AsyncTask.Status.RUNNING)){
task.cancel(true);
task = new MyTask();
task.execute();
} else if (task.getStatus().equals(AsyncTask.Status.FINISHED)) {
task = new MyTask();
task.execute();
} else
task.execute();
}
class MyTask extends AsyncTask<Void, Item, Void>{
List<Item> Itens;
@Override
protected void onPreExecute() {
//your code
list.setVisibility(View.GONE);
adapterItem= new MyListAdapter(MyActivity.this, R.layout.item, new ArrayList<Item>());
list.setAdapter(adapterItem);
adapterItem.notifyDataSetChanged();
}
@Override
protected Void doInBackground(Void... params) {
Itens = getItens();
for (Item item : Itens) {
publishProgress(item );
}
return null;
}
@Override
protected void onProgressUpdate(Item ... item ) {
adapterItem.add(item[0]);
}
@Override
protected void onPostExecute(Void result) {
//your code
adapterItem.notifyDataSetChanged();
list.setVisibility(View.VISIBLE);
}
}
}
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
The solution proposed in release notes for 2.1 doesn't work out-of-the-box. They forgot to mention that there is code:
internal string ResolveInstallPath()
{
if (!string.IsNullOrEmpty(this.OutputDirectory))
{
return this.OutputDirectory;
}
ISettings settings = this._configSettings;
...
}
which prevents it from working. To fix this you need to modify your NuGet.targets file and remove 'OutputDirectory' parameter:
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(RequireConsentSwitch)</RestoreCommand>
So now, if you add 'repositoryPath' config somewhere in NuGet.config (see the release notes for a description of valid places to put the config files), it will restore all packages into single location, but... Your .csproj still contains hints to assemblies written as relative paths...
I still don't understand why they went hard way instead of changing PackageManager so it would add hint paths relative to PackagesDir. That's the way I do manually to have different package locations locally (on my desktop) and on build agent.
<Reference Include="Autofac.Configuration, Version=2.6.3.862, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>$(PackagesDir)\Autofac.2.6.3.862\lib\NET40\Autofac.Configuration.dll</HintPath>
</Reference>
For Windows Server® 2008, Windows 7, Windows Server 2003, Windows Vista®, or Windows XP run "control userpasswords2"
Click the Start button, then click Run (Windows XP, Server 2003 or below)
Type control userpasswords2 and press Enter on your keyboard.
Note: For Windows 7 and Windows Vista, this command will not run by typing it in the Serach box on the Start Menu - it must be run using the Run option. To add the Run command to your Start menu, right-click on it and choose the option to customize it, then go to the Advanced options. Check to option to add the Run command.
You will see a window of user details!
select columns
from table
where (
column like 'a%'
or column like 'b%' )
order by column asc
In case you have multiple images and you want to loop though them and show them 1 by 1 along with titles - this is what you can do. No need to explicitly define ax1, ax2, etc.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, figsize=(6, 8))
for i in range(len(ax)):
for j in range(len(ax[i])):
## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
ax[i,j].set_title('Title-' + str(i) + str(j))
Ultimately no. You can query for listings with a search string from an RSS feed such as this:
http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString
As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.
Craigslist Automated Posting API?
Write a note to craigslist asking them to open their API,
For td elements line-height will successfully allow you to resize the border-height as SPrince mentioned.
For other elements such as list items, you can control the border height with line-height and the height of the actual element with margin-top and margin-bottom.
Here is a working example of both: http://jsfiddle.net/byronj/gLcqu6mg/
An example with list items:
li {
list-style: none;
padding: 0 10px;
display: inline-block;
border-right: 1px solid #000;
line-height: 5px;
margin: 20px 0;
}
<ul>
<li>cats</li>
<li>dogs</li>
<li>birds</li>
<li>swine!</li>
</ul>
I don't think you can do that directly. You could create a class containing both your object
and double
and put an instance of it in the dictionary though.
class Pair
{
object obj;
double dbl;
}
Dictionary<int, Pair> = new Dictionary<int, Pair>();
This strategy physically copies the rows around twice which can take a much longer time if the table you are copying is very large.
You could save out your data, drop and rebuild the table with the auto-increment and primary key, then load the data back in.
I'll walk you through with an example:
Step 1, create table foobar (without primary key or auto-increment):
CREATE TABLE foobar(
id int NOT NULL,
name nchar(100) NOT NULL,
)
Step 2, insert some rows
insert into foobar values(1, 'one');
insert into foobar values(2, 'two');
insert into foobar values(3, 'three');
Step 3, copy out foobar data into a temp table:
select * into temp_foobar from foobar
Step 4, drop table foobar:
drop table foobar;
Step 5, recreate your table with the primary key and auto-increment properties:
CREATE TABLE foobar(
id int primary key IDENTITY(1, 1) NOT NULL,
name nchar(100) NOT NULL,
)
Step 6, insert your data from temp table back into foobar
SET IDENTITY_INSERT temp_foobar ON
INSERT into foobar (id, name) select id, name from temp_foobar;
Step 7, drop your temp table, and check to see if it worked:
drop table temp_foobar;
select * from foobar;
You should get this, and when you inspect the foobar table, the id column is auto-increment of 1 and id is a primary key:
1 one
2 two
3 three
I faced the same problem when connecting to EC2, the issue was with Security Group, I solved by adding the allowed IPs at port 5432
'default' => env('DB_CONNECTION', 'mysql'),
add this in your code
Try checking his post. It shows how to implement transitions between web pages using AngularJS's ngRoute and ngAnimate: How to Make iPhone-Style Web Page Transitions Using AngularJS & CSS
If you hit = and expect to see line numbers, but only see byte counts, then line numbers are turned off. Hit -n to turn them on, and make sure $LESS
doesn't include 'n'.
Turning off line numbers by default (for example, setting LESS=n
) speeds up searches in very large files. It is handy if you frequently search through big files, but don't usually care which line you're on.
I typically run with LESS=RSXin
(escape codes enabled, long lines chopped, don't clear the screen on exit, ignore case on all lower case searches, and no line number counting by default) and only use -n or -S from inside less
as needed.
I have encountered this pattern a few times, I found that the easiest way is to define an inner class with JaxB annotations. (anyways, you'll probably want to define the root tag name)
so your code would look something like this
@GET
@Path("/test2")
public Object test2(){
MyResourceWrapper wrapper = new MyResourceWrapper();
wrapper .add("a");
wrapper .add("b");
return wrapper ;
}
@XmlRootElement(name="MyResource")
private static class MyResourceWrapper {
@XmlElement(name="Item")
List<String> list=new ArrayList<String>();
MyResourceWrapper (){}
public void add(String s){ list.add(s);}
}
if you work with javax.rs (jax-rs) I'd return Response object with the wrapper set as its entity
So, save yourself some hours that I didn't and try this if it seems not to work:
<additionalJOption>-Xdoclint:none</additionalJOption>
The tag is changed for newer versions.
Just to correct mingos' answer:
If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.
To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.
Example:
Instead of:
document.cookie = "cookie_name=cookie_value; 0; path=/";
Just write:
document.cookie = "cookie_name=cookie_value; path=/";
You can use:
str.replace(/text/g, "replaced text");
Your compiler just tried to compile the file named foo.cc
. Upon hitting line number line
, the compiler finds:
#include "bar"
or
#include <bar>
The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar
. For an explanation of the difference between the versions of the include statement look here.
g++
has an option -I
. It lets you add include search paths to the command line. Imagine that your file bar
is in a folder named frobnicate
, relative to foo.cc
(assume you are compiling from the directory where foo.cc
is located):
g++ -Ifrobnicate foo.cc
You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I
that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.
Now imagine you have multiple version of bar
in different folders, given:
// A/bar
#include<string>
std::string which() { return "A/bar"; }
// B/bar
#include<string>
std::string which() { return "B/bar"; }
// C/bar
#include<string>
std::string which() { return "C/bar"; }
// foo.cc
#include "bar"
#include <iostream>
int main () {
std::cout << which() << std::endl;
}
The priority with #include "bar"
is leftmost:
$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar
As you see, when the compiler started looking through A/
, B/
and C/
, it stopped at the first or leftmost hit.
This is true of both forms, include <>
and incude ""
.
#include <bar>
and #include "bar"
Usually, the #include <xxx>
makes it look into system folders first, the #include "xxx"
makes it look into the current or custom folders first.
E.g.:
Imagine you have the following files in your project folder:
list
main.cc
with main.cc
:
#include "list"
....
For this, your compiler will #include
the file list
in your project folder, because it currently compiles main.cc
and there is that file list
in the current folder.
But with main.cc
:
#include <list>
....
and then g++ main.cc
, your compiler will look into the system folders first, and because <list>
is a standard header, it will #include
the file named list
that comes with your C++ platform as part of the standard library.
This is all a bit simplified, but should give you the basic idea.
<>
/""
-priorities and -I
According to the gcc-documentation, the priority for include <>
is, on a "normal Unix system", as follows:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].
The documentation also states:
You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.
To continue our #include<list> / #include"list"
example (same code):
g++ -I. main.cc
and
#include<list>
int main () { std::list<int> l; }
and indeed, the -I.
prioritizes the folder .
over the system includes and we get a compiler error.
I don't know about targeting iOS as a whole, but to target iOS Safari specifically:
@supports (-webkit-touch-callout: none) {
/* CSS specific to iOS devices */
}
@supports not (-webkit-touch-callout: none) {
/* CSS for other than iOS devices */
}
Apparently as of iOS 13 -webkit-overflow-scrolling
no longer responds to @supports
, but -webkit-touch-callout
still does. Of course that could change in the future...
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
Example:
>>> a = 'some var'
>>> namestr(a, globals())
['a']
As @rbright already pointed out whatever you do there are probably better ways to do it.
I know this is a Java question, but if you're using Kotlin you can do this quite nicely:
val uri = request.run {
if (queryString.isNullOrBlank()) requestURI else "$requestURI?$queryString"
}
I have added few lines inside package.json:
"scripts": {
...
"clean": "rmdir /s /q node_modules",
"reinstall": "npm run clean && npm install",
"rebuild": "npm run clean && npm install && rmdir /s /q dist && npm run build --prod",
...
}
If you want to clean
only you can use this rimraf node_modules
or rm -rf node_modules
.
It works fine
Remember that union will merge results (SQL Server to be sure)(feature or bug?)
select 1 as id, 3 as value
union
select 1 as id, 3 as value
id,value
1,3
select * from (select 1 as id, 3 as value) t1 inner join (select 1 as id, 3 as value) t2 on t1.id = t2.id
id,value,id,value
1,3,1,3
This is very easy to do with geography type in SQL Server 2008.
SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))
-- computes distance in meters using eliptical model, accurate to the mm
4326 is SRID for WGS84 elipsoidal Earth model
I had a similar use case during testing hibernate event listeners which are only called on commit.
The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW
. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.
Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.
Try to use the fleqn
document class option.
\documentclass[fleqn]{article}
(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)
No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:
using System;
class Program {
static void Main(string[] args) {
System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
throw new Exception("Kaboom");
}
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
Console.WriteLine(e.ExceptionObject.ToString());
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
Environment.Exit(1);
}
}
Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.
awk is very cool, but why not keep it simple?
num=$(echo $var | grep -o "," | wc -l)
You asked of Function but there is an easier way too. When you will upload the image, copy it's URL which is at the top right part of the window (View Screenshot) and paste it in the src='[link you copied]'
. Hope this will help if someone is looking for similar problem.
The shift can be implement with data types (char, int and long int). The float and double data connot be shifted.
value= value >> steps // Right shift, signed data.
value= value << steps // Left shift, signed data.
Real answers:
http://cutycapt.sourceforge.net/
http://iecapt.sourceforge.net/
http://www.websitescreenshots.com/
http://khtml2png.sourceforge.net/
https://htmlcsstoimage.com/ (Uses Google Chrome)
https://gofullpage.com/ - Full Page Screen Capture (Chrome extension) - see this superuser answer for more info
(Don't know of one to use Mozilla's renderer, though.)
You shouldn't use the keypress
event, but the keyup
or keydown
event because the keypress
event is intended for real (printable) characters. keydown
is handled at a lower level so it will capture all nonprinting keys like delete and enter.
Run the following commands in CMD
choco install powershell
choco upgrade powershell
Based on Blorgbeard's solution.
foreach (var sqlBatch in commandText.Split(new[] { "GO" }, StringSplitOptions.RemoveEmptyEntries))
{
sqlCommand.CommandText = sqlBatch;
sqlCommand.ExecuteNonQuery();
}
To hide the prompt set xls.DisplayAlerts = False
ConflictResolution
is not a true
or false
property, it should be xlLocalSessionChanges
Note that this has nothing to do with displaying the Overwrite prompt though!
Set xls = CreateObject("Excel.Application")
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"
wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
wb.Close (True)
One of the way is Using below sql queries
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
If you want to just toggle visibility and still keep the input in DOM:
<input class="txt" type="password" [(ngModel)]="input_pw"
[style.visibility]="isHidden? 'hidden': 'visible'">
The other way around is as per answer by rrd, which is to use HTML hidden attribute. In an HTML element if hidden
attribute is set to true
browsers are supposed to hide the element from display, but the problem is that this behavior is overridden if the element has an explicit display
style mentioned.
.hasDisplay {_x000D_
display: block;_x000D_
}
_x000D_
<input class="hasDisplay" hidden value="shown" />_x000D_
<input hidden value="not shown">
_x000D_
To overcome this you can opt to use an explicit css for [hidden]
that overrides the display;
[hidden] {
display: none !important;
}
Yet another way is to have a is-hidden
class and do:
<input [class.is-hidden]="isHidden"/>
.is-hidden {
display: none;
}
If you use display: none
the element will be skipped from the static flow and no space will be allocated for the element, if you use visibility: hidden
it will be included in the flow and a space will be allocated but it will be blank space.
The important thing is to use one way across an application rather than mixing different ways thereby making the code less maintainable.
If you want to remove it from DOM
<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">
Windows 8 running the x64 SDK.
For whatever reason Android Studio wouldn't detect it no matter what I put in manually or searched using the browse option.
Pressing back would not work.
Reporting the error would not work.
Adding JAVA_HOME or other suggestions to the C:... would not work.
It was only beginning the installation of Android Studio again after running the java file that it worked.
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Hope it helps.
To extend on this question (& answer by @user2700065) for a slightly different cases, if anyone does not want to extract every frame but wants to extract frame every one second. So a 1-minute video will give 60 frames(images).
import sys
import argparse
import cv2
print(cv2.__version__)
def extractImages(pathIn, pathOut):
count = 0
vidcap = cv2.VideoCapture(pathIn)
success,image = vidcap.read()
success = True
while success:
vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000)) # added this line
success,image = vidcap.read()
print ('Read a new frame: ', success)
cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image) # save frame as JPEG file
count = count + 1
if __name__=="__main__":
a = argparse.ArgumentParser()
a.add_argument("--pathIn", help="path to video")
a.add_argument("--pathOut", help="path to images")
args = a.parse_args()
print(args)
extractImages(args.pathIn, args.pathOut)
Mocking is generating pseudo-objects that simulate real objects behaviour for tests
If you're looking for ES6 OOP implementation of Stack and Queue data-structure with some basic operations (based on linked lists) then it may look like this:
Queue.js
import LinkedList from '../linked-list/LinkedList';
export default class Queue {
constructor() {
this.linkedList = new LinkedList();
}
isEmpty() {
return !this.linkedList.tail;
}
peek() {
if (!this.linkedList.head) {
return null;
}
return this.linkedList.head.value;
}
enqueue(value) {
this.linkedList.append(value);
}
dequeue() {
const removedHead = this.linkedList.deleteHead();
return removedHead ? removedHead.value : null;
}
toString(callback) {
return this.linkedList.toString(callback);
}
}
Stack.js
import LinkedList from '../linked-list/LinkedList';
export default class Stack {
constructor() {
this.linkedList = new LinkedList();
}
/**
* @return {boolean}
*/
isEmpty() {
return !this.linkedList.tail;
}
/**
* @return {*}
*/
peek() {
if (!this.linkedList.tail) {
return null;
}
return this.linkedList.tail.value;
}
/**
* @param {*} value
*/
push(value) {
this.linkedList.append(value);
}
/**
* @return {*}
*/
pop() {
const removedTail = this.linkedList.deleteTail();
return removedTail ? removedTail.value : null;
}
/**
* @return {*[]}
*/
toArray() {
return this.linkedList
.toArray()
.map(linkedListNode => linkedListNode.value)
.reverse();
}
/**
* @param {function} [callback]
* @return {string}
*/
toString(callback) {
return this.linkedList.toString(callback);
}
}
And LinkedList implementation that is used for Stack and Queue in examples above may be found on GitHub here.
This is fixed in Android 4.2 and also in the support library's source.[*]
For details of the cause (and work-arounds) refer to the the Google bug report: http://code.google.com/p/android/issues/detail?id=19917
If you're using the support library then you shouldn't have to worry about this bug (for long)[*]. However, if you're using the API directly (i.e. Not using the support library's FragmentManager) and targeting an API below Android 4.2 then you will need to try one of the work-arounds.
[*] At the time of writing the Android SDK Manager is still distributing an old version that exhibits this bug.
Edit I'm going to add some clarification here because I've obviously somehow confused whoever down-voted this answer.
There are several different (but related) circumstances that can cause this exception to be thrown. My answer above is referring to the specific instance discussed in the question i.e. a bug in Android which has subsequently been fixed. If you're getting this exception for another reason it's because you're adding/removing fragments when you shouldn't be (after fragment states have been saved). If you're in such a situation then perhaps "Nested Fragments - IllegalStateException “Can not perform this action after onSaveInstanceState”" can be of use to you.
I think the best way to solve this is to follow the error advice, hence looking for server logs. To enable logs I added
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\logs\TracesServ_ce.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
Then you go to c:\logs\TracesServ_ce.svclog open it with microsoft service trace viewer. And see what the problem really is.
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
ls
from coreutils
performs a locale-aware sort by default, and thus may produce surprising results in some cases (for instance, %foo
will sort between bar
and quux
in LANG=en_US
). If you want an ASCIIbetical sort, use
LANG=C ls
... since dates naturally have time-zone information, which can span regions with different day light savings adjustments
Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24
, so the typical calculation will fail.
You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.
Now, the solution can be written as,
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
// test it
const a = new Date("2017-01-01"),
b = new Date("2017-07-25"),
difference = dateDiffInDays(a, b);
This works because UTC time never observes DST. See Does UTC observe daylight saving time?
p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.
You may also want to cut the data frame into an arbitrary number of smaller dataframes. Here, we cut into two dataframes.
x = data.frame(num = 1:26, let = letters, LET = LETTERS)
set.seed(10)
split(x, sample(rep(1:2, 13)))
gives
$`1`
num let LET
3 3 c C
6 6 f F
10 10 j J
12 12 l L
14 14 n N
15 15 o O
17 17 q Q
18 18 r R
20 20 t T
21 21 u U
22 22 v V
23 23 w W
26 26 z Z
$`2`
num let LET
1 1 a A
2 2 b B
4 4 d D
5 5 e E
7 7 g G
8 8 h H
9 9 i I
11 11 k K
13 13 m M
16 16 p P
19 19 s S
24 24 x X
25 25 y Y
You can also split a data frame based upon an existing column. For example, to create three data frames based on the cyl
column in mtcars
:
split(mtcars,mtcars$cyl)
This can also occur when the path ends in a '' followed by the closing quotation mark. e.g. The following line is passed as one of the arguments and this is not right:
"c:\users\abc\"
instead pass that argument as shown below so that the last backslash is escaped instead of escaping the quotation mark.
"c:\users\abc\\"
@Tom, thank you very much for pointing out this solution. It works great for me.
I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this
library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]
var newTH = document.createElement('th');
newTH.onclick = function() {
//Your code here
}
Generically, do
/while
is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while
or even a for
loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:
do {
char c = read_input();
process_input(c);
} while (c != 'Q');
I don't know how it was never made officially, but I've added my own json
method to console
object for easier printing stringified logs:
Observing Objects (non-primitives) in javascript is a bit like quantum mechanics..what you "measure" might not be the real state, which already have changed.
console.json = console.json || function(argument){_x000D_
for(var arg=0; arg < arguments.length; ++arg)_x000D_
console.log( JSON.stringify(arguments[arg], null, 4) )_x000D_
}_x000D_
_x000D_
// use example_x000D_
console.json( [1,'a', null, {a:1}], {a:[1,2]} )
_x000D_
Many times it is needed to view a stringified version of an Object because printing it as-is (raw Object) will print a "live" version of the object which gets mutated as the program progresses, and will not mirror the state of the object at the logged point-of-time, for example:
var foo = {a:1, b:[1,2,3]}
// lets peek under the hood
console.log(foo)
// program keeps doing things which affect the observed object
foo.a = 2
foo.b = null
JVM specification doesn't say anything specific about garbage collection. Due to this, vendors are free to implement GC in their way.
So this vagueness causes uncertainty in garbage collection behavior. You should check your JVM details to know about the garbage collection approaches/algorithms. Also there are options to customize behavior as well.
You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)
That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:
int main()
{
for(;;)
{
printf ("%ld\n", time(NULL));
printf ("%f\n", time(NULL));
sleep(1);
}
return 0;
}
The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.
In ES6/ES2015 or later you can do this way:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
Prior to ES6/ES2015
objs.sort(function(a, b) {
return a.last_nom.localeCompare(b.last_nom)
});
The most effective way:
if (array.indexOf(element) > -1) {
alert('Bingooo')
}
For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 Now Just go Project under Project settings and select the project SDK.
It's very similar to
char array[] = {'O', 'n', 'e', ' ', /*etc*/ ' ', 'm', 'u', 's', 'i', 'c', '\0'};
but gives you read-only memory.
For a discussion of the difference between a char[]
and a char *
, see comp.lang.c FAQ 1.32.
This article has a good discussion on this issue. You can use
SELECT *
FROM Y
INNER JOIN X ON EXISTS(SELECT X.QID
INTERSECT
SELECT y.QID);
If you are using an array (and purely an array), the lookup of "contains" is O(N)
, because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N)
with the overhead of the sort.
If this is something that is invoked repeatedly, place it in a function:
private boolean inArray(int[] array, int value)
{
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
return true;
}
}
return false;
}
The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:
var tomorrow = new Date(today.getTime()+1000*60*60*24);
So you need a natural sort ?
If so, than maybe this script by Brian Huisman based on David koelle's work would be what you need.
It seems like Brian Huisman's solution is now directly hosted on David Koelle's blog:
Concurrency and Parallelism Source
In a multithreaded process on a single processor, the processor can switch execution resources between threads, resulting in concurrent execution.
In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run on a separate processor at the same time, resulting in parallel execution.
When the process has fewer or as many threads as there are processors, the threads support system in conjunction with the operating environment ensure that each thread runs on a different processor.
For example, in a matrix multiplication that has the same number of threads and processors, each thread (and each processor) computes a row of the result.
Try using batch file
php -S localhost:8000
.bat
extension, server.bat
server.bat
file your server is ready on http://localhost:8000
if you got error php not recognize any internal or external command
then goto environment variable and edit path to php.exe
"C:\wamp\bin\php\php5.4.3"
Here's a handy open source library I made earlier that uses jQuery: https://bitbucket.org/warwick/searchablelist/src/master/ And here is a working copy on my VPS: http://developersfound.com/SearchableList/ The library is highly customisable with overridable behavours and can have seperate designs on the same web page Hope this helps
May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....
Even though the original question seems to be from 2015, this 'bug' seems to affect users installing pip-10.0.0
as well.
The workaround is not to modify pip
, however to change the way pip is called. Instead of calling /usr/bin/pip
call pip
via Python itself. For example, instead of the below:
pip install <package>
If from Python version 2 (or default Python binary is called python
) do :
python -m pip install <package>
or if from Python version 3:
python3 -m pip install <package>
our project surely is configured as "library" thats why you get the message : "Android library projects cannot be launched."
right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.
If you must work with only standard JDK classes you can use this:
/**
* Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
* <code>toTimeZone</code>. Since java.util.Date has does not really store time zome
* information, this actually converts the date to the date that it would be in the
* other time zone.
* @param date
* @param fromTimeZone
* @param toTimeZone
* @return
*/
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);
return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}
/**
* Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
* additional offset due to the time zone being in daylight savings time as of
* the given <code>date</code>.
* @param date
* @param timeZone
* @return
*/
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
long timeZoneDSTOffset = 0;
if(timeZone.inDaylightTime(date))
{
timeZoneDSTOffset = timeZone.getDSTSavings();
}
return timeZone.getRawOffset() + timeZoneDSTOffset;
}
Credit goes to this post.
The orderBy
filter performs a stable sorting as of Angular 1.4.5. (See the GitHub pull request https://github.com/angular/angular.js/pull/12408.)
So it is sufficient to use a constant predicate and reverse
set to true
:
<div ng-repeat="friend in friends | orderBy:0:true">{{friend.name}}</div>
To change DatePicker
colors (calendar mode) at application level define below properties.
<style name="MyAppTheme" parent="Theme.AppCompat.Light">
<item name="colorAccent">#ff6d00</item>
<item name="colorControlActivated">#33691e</item>
<item name="android:selectableItemBackgroundBorderless">@color/colorPrimaryDark</item>
<item name="colorControlHighlight">#d50000</item>
</style>
See http://www.zoftino.com/android-datepicker-example for other DatePicker
custom styles
You can create a utility class to check if the class represents any Collection, Map or Array
public static boolean isCollection(Class<?> rawPropertyType) {
return Collection.class.isAssignableFrom(rawPropertyType) ||
Map.class.isAssignableFrom(rawPropertyType) ||
rawPropertyType.isArray();
}
this in your callback function refers to the clicked element.
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS
<style type="text/css">
#nav-ask{ display:none; }
</style>
or if you already have a "hideMe" CSS Class:
<script type="text/javascript">
if(document.getElementById && document.createTextNode)
{
if(document.getElementById('nav-ask'))
{
document.getElementById('nav-ask').className='hideMe';
}
}
</script>
Primitive data types (such as byte) don't have methods in java, but you can directly do:
int i=rno[0];
What worked for me... It seems if you install (or a dependent package installs) Microsoft.CodeDom.Providers.DotNetCompilerPlatform
NuGet package it makes some web.config
transforms that allow you to use C#7.x features in ASP.NET Razor pages. Whilst I found these worked fine on my local machine they didn't work on our server (even when the compiler was in the /bin/ folder).
The solution was to locate the element below and remove completely from web.config
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. So bar::getA
doesn't have any specific instance of foo
whose a
it can be returning. I'm guessing that what you want is something like:
class bar {
private:
foo * const owner;
public:
bar(foo & owner) : owner(&owner) { }
int getA() {return owner->a;}
};
But even for this you may have to make some changes, because in versions of C++ before C++11, unlike (again, say) Java, a nested class has no special access to its enclosing class, so it can't see the protected
member a
. This will depend on your compiler version. (Hat-tip to Ken Wayne VanderLinde for pointing out that C++11 has changed this.)
In one reusable piece of code I use the directive <%@include file="reuse.html"%>
and in the second I use the standard action <jsp:include page="reuse.html" />
.
Let the code in the reusable file be:
<html>
<head>
<title>reusable</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<img src="candle.gif" height="100" width="50"/> <br />
<p><b>As the candle burns,so do I</b></p>
</body>
After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet
of the two JSP files, you will see the difference.
Here is what you will see when you use the directive:
out.write("<html>\r\n");
out.write(" <head>\r\n");
out.write(" <title>reusable</title>\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write(" </head>\r\n");
out.write(" <body>\r\n");
out.write(" <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write(" <p><b>As the candle burns,so do I</b></p>\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
And this is what you will see for the used standard action in the second JSP file :
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);
So now you know that the include directive inserts the source of reuse.html
at translation time, but the action tag inserts the response of reuse.html
at runtime.
If you think about it, there is an extra performance hit with every action tag (<jsp:include>
). It means you can guarantee you will always have the latest content, but it increases performance cost.
A "release" is the final build for a version which does not change.
A "snapshot" is a build which can be replaced by another build which has the same name. It implies that the build could change at any time and is still under active development.
You have different artifacts for different builds based on the same code. E.g. you might have one with debugging and one without. One for Java 5.0 and one for Java 6. Generally its simpler to have one build which does everything you need. ;)
There is no colspan in css as far as I know, but there will be column-span
for multi column layout in the near future, but since it is only a draft in CSS3, you can check it in here. Anyway you can do a workaround using div
and span
with table-like display like this.
This would be the HTML:
<div class="table">
<div class="row">
<span class="cell red first"></span>
<span class="cell blue fill"></span>
<span class="cell green last"></span>
</div>
</div>
<div class="table">
<div class="row">
<span class="cell black"></span>
</div>
</div>
And this would be the css:
/* this is to reproduce table-like structure
for the sake of table-less layout. */
.table { display:table; table-layout:fixed; width:100px; }
.row { display:table-row; height:10px; }
.cell { display:table-cell; }
/* this is where the colspan tricks works. */
span { width:100%; }
/* below is for visual recognition test purposes only. */
.red { background:red; }
.blue { background:blue; }
.green { background:green; }
.black { background:black; }
/* this is the benefit of using table display, it is able
to set the width of it's child object to fill the rest of
the parent width as in table */
.first { width: 20px; }
.last { width: 30px; }
.fill { width: 100%; }
The only reason to use this trick is to gain the benefit of table-layout
behaviour, I use it alot if only setting div and span width to certain percentage didn't fullfil our design requirement.
But if you don't need to benefit from the table-layout
behaviour, then durilai's answer would suit you enough.
You can turn autocommit ON by setting implicit_transactions OFF:
SET IMPLICIT_TRANSACTIONS OFF
When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.
Maybe an example is clearer. This will write a change to the database:
SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION
This will not write a change to the database:
SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION
The following example will update a row, and then complain that there's no transaction to commit:
SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION
Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.
I would simply do this, which literally follows what your desired logic was:
df.groupby(['org']).mean().groupby(['cluster']).mean()
Cordova Apps
:We need to place the google-services.json
file in app root
(I believe; when working with Cordova apps, we are not to get into other folders/files such as Gradle, Java files, platforms, etc; instead only work with them VIA the config.xml
and www
folder) and refer it in the config.xml
like so:
<platform name="android">
<!-- Add this line -->
<resource-file src="google-services.json" target="app/google-services.json" />
</platform>
Firebase App packagename
is same as the id
attribute in <widget id="<packagename>" ... >
are same.For ex:
<!-- config.xml of Cordova App -->
<widget id="com.appFactory.torchapp" ...>
<!--google-serivces.json from generated from Firebase console.-->
{
...
packagename: "com.appFactory.torchapp",
...
}
Good Luck...
This give you the date like in a social network : ["today","yesterday","dayoftheweek",etc..]
void main() {
DateTime now = new DateTime(2018,6,26);
print(date(now));
}
String date(DateTime tm) {
DateTime today = new DateTime.now();
Duration oneDay = new Duration(days: 1);
Duration twoDay = new Duration(days: 2);
Duration oneWeek = new Duration(days: 7);
String month;
switch (tm.month) {
case 1:
month = "january";
break;
case 2:
month = "february";
break;
case 3:
month = "march";
break;
case 4:
month = "april";
break;
case 5:
month = "may";
break;
case 6:
month = "june";
break;
case 7:
month = "july";
break;
case 8:
month = "august";
break;
case 9:
month = "september";
break;
case 10:
month = "october";
break;
case 11:
month = "november";
break;
case 12:
month = "december";
break;
}
Duration difference = today.difference(tm);
if (difference.compareTo(oneDay) < 1) {
return "today";
} else if (difference.compareTo(twoDay) < 1) {
return "yesterday";
} else if (difference.compareTo(oneWeek) < 1) {
switch (tm.weekday) {
case 1:
return "monday";
case 2:
return "tuesday";
case 3:
return "wednesday";
case 4:
return "thursday";
case 5:
return "friday";
case 6:
return "saturday";
case 7:
return "sunday";
}
} else if (tm.year == today.year) {
return '${tm.day} $month';
} else {
return '${tm.day} $month ${tm.year}';
}
}
Exercise 16 from Zed Shaw's book? You can use escape characters as follows:
paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
Using data.frame
instead of cbind
should be helpful
x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
col1 col2 col3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
sapply(x, class) # looking into x to see the class of each element
col1 col2 col3
"numeric" "factor" "factor"
As you can see elements from col1 are numeric
as you wish.
data.frame
can have variables of different class
: numeric
, factor
and character
but matrix
doesn't, once you put a character
element into a matrix all the other will become into this class no matter what clase they were before.
You want the argument unpacking operator *.
I came across this problem recently, and I found it helpful to explore the new documentation by Google on debugging Analytics. It didn't actually care about sending tracking info to Google Analytics, I just wanted to ensure that the events were firing correctly, and the debugging tools gave me the info I needed. YMMV, I realize doesn't exactly answer the question.
This is a tow way Concurrent dictionary I think this will help you:
public class HashMapDictionary<T1, T2> : System.Collections.IEnumerable
{
private System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>> _keyValue = new System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>>();
private System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>> _valueKey = new System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>>();
public ICollection<T1> Keys
{
get
{
return _keyValue.Keys;
}
}
public ICollection<T2> Values
{
get
{
return _valueKey.Keys;
}
}
public int Count
{
get
{
return _keyValue.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public List<T2> this[T1 index]
{
get { return _keyValue[index]; }
set { _keyValue[index] = value; }
}
public List<T1> this[T2 index]
{
get { return _valueKey[index]; }
set { _valueKey[index] = value; }
}
public void Add(T1 key, T2 value)
{
lock (this)
{
if (!_keyValue.TryGetValue(key, out List<T2> result))
_keyValue.TryAdd(key, new List<T2>() { value });
else if (!result.Contains(value))
result.Add(value);
if (!_valueKey.TryGetValue(value, out List<T1> result2))
_valueKey.TryAdd(value, new List<T1>() { key });
else if (!result2.Contains(key))
result2.Add(key);
}
}
public bool TryGetValues(T1 key, out List<T2> value)
{
return _keyValue.TryGetValue(key, out value);
}
public bool TryGetKeys(T2 value, out List<T1> key)
{
return _valueKey.TryGetValue(value, out key);
}
public bool ContainsKey(T1 key)
{
return _keyValue.ContainsKey(key);
}
public bool ContainsValue(T2 value)
{
return _valueKey.ContainsKey(value);
}
public void Remove(T1 key)
{
lock (this)
{
if (_keyValue.TryRemove(key, out List<T2> values))
{
foreach (var item in values)
{
var remove2 = _valueKey.TryRemove(item, out List<T1> keys);
}
}
}
}
public void Remove(T2 value)
{
lock (this)
{
if (_valueKey.TryRemove(value, out List<T1> keys))
{
foreach (var item in keys)
{
var remove2 = _keyValue.TryRemove(item, out List<T2> values);
}
}
}
}
public void Clear()
{
_keyValue.Clear();
_valueKey.Clear();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _keyValue.GetEnumerator();
}
}
examples:
public class TestA
{
public int MyProperty { get; set; }
}
public class TestB
{
public int MyProperty { get; set; }
}
HashMapDictionary<TestA, TestB> hashMapDictionary = new HashMapDictionary<TestA, TestB>();
var a = new TestA() { MyProperty = 9999 };
var b = new TestB() { MyProperty = 60 };
var b2 = new TestB() { MyProperty = 5 };
hashMapDictionary.Add(a, b);
hashMapDictionary.Add(a, b2);
hashMapDictionary.TryGetValues(a, out List<TestB> result);
foreach (var item in result)
{
//do something
}
Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:
public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
}
This will list only modified files:
svn status -u | grep M
Just change your line of code to
<a href="~/Required/[email protected]">Edit</a>
from where you are calling this function that will pass corect id
<form onsubmit="return false;">
...
</form>
Django = 2.2
urlpatterns = [
re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]
Since it was a successful comment, I am adding it as an answer:
with files:
find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
Easy solution in Python3+:
import time
todaysdate = time.strftime("%d/%m/%Y")
#with '.' isntead of '/'
todaysdate = time.strftime("%d.%m.%Y")
Another observation:
merge()
will only care about an auto-generated id(tested on IDENTITY
and SEQUENCE
) when a record with such an id already exists in your table. In that case merge()
will try to update the record.
If, however, an id is absent or is not matching any existing records, merge()
will completely ignore it and ask a db to allocate a new one. This is sometimes a source of a lot of bugs. Do not use merge()
to force an id for a new record.
persist()
on the other hand will never let you even pass an id to it. It will fail immediately. In my case, it's:
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist
hibernate-jpa javadoc has a hint:
Throws: javax.persistence.EntityExistsException - if the entity already exists. (If the entity already exists, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.)
simple way to do maxlength for textarea in html4 is:
<textarea cols="60" rows="5" onkeypress="if (this.value.length > 100) { return false; }"></textarea>
Change the "100" to however many characters you want
You can create a jQuery object from a JSON object:
$.getJSON(url, data, function(json) {
$(json).each(function() {
/* YOUR CODE HERE */
});
});
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
select * from yourtable where created < now() and created > '2011-04-25 04:00:00'
Add this style to your span:
position:relative;
top: 10px;
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
I also wouldn't call two many (is_a?
and kind_of?
are aliases of the same method), but if you want to see more possibilities, turn your attention to #class
method:
A = Class.new
B = Class.new A
a, b = A.new, B.new
b.class < A # true - means that b.class is a subclass of A
a.class < B # false - means that a.class is not a subclass of A
# Another possibility: Use #ancestors
b.class.ancestors.include? A # true - means that b.class has A among its ancestors
a.class.ancestors.include? B # false - means that B is not an ancestor of a.class
[explanations in my “main answer”]
line 7. section around the whole website? Or only a div?
Neither. For styling: use the <body>
, it’s already there. For sectioning/semantics: as detailed in my example HTML its effect is contrary to usefulness. Extra wrappers to already wrapped content is no improvement, but noise.
line 8. Each section start with a header?
No, it is the author’s choice where to put content typically summarized as “header”. And if that header-content is clearly recognizable without extra marking, it may perfectly stay without <header>
. This is also the author’s choice.
line 23. Is this div right? or must this be a section?
The <div>
is probably wrong. It depends on the intentions: is it for styling only it could be right. If it’s for semantic purposes it is wrong: it should be an <article>
instead as shown in my other answer. <article>
is also right if it is for both styling and sectioning combined.
<section>
looks wrong here, as there are no similar sections before or after this one, like chapters in a book. (This is the purpose of <section>
).
line 24. Split left/right column with a div.
No. Why?
line 25. Right place for the article tag?
Yes, makes sense.
line 26. Is it required to put your h1-tag in the header-tag?
No. A lone <h*>
element probably never needs to go in a <header>
(but it can if you want to) as it is already clear that it’s the heading of what is about to come. – It would make sense if that <header>
also encompassed a tagline (marked with <p>
), for example.
line 43. The content is not related to the main article, so I decided this is a section and not an aside.
It is a misunderstanding that an <aside>
has to be “tangentially related” to the content around. The point is: use an <aside>
if the content is only “tangentially related” or not at all!
Nevertheless, apart from <aside>
being a decent choice, <article>
might still be better than a <section>
as “hot items” and “new items” are not to be read like two chapters in a book. You can perfectly go for one of them and not the other like an alternative sorting of something, not like two parts of a whole.
line 44. H2 without header
Is great.
line 53. section without header
Well, there is no <header>
, but the <h2>
-heading leaves pretty clear which part in this section is the header.
line 63. Div with all (non-related) news items
<article>
or <aside>
might be better.
line 64. header with h2
Discussed already.
line 65. Hmm, div or section? Or remove this div and only use the article-tag
Exactly! Remove the <div>
.
line 105. Footer :-)
Very reasonable.
I found the existing answers confusing.
Personally, I just want to have something which looks and works like C.
This snippet works many times a day in production:
snapshotEvents=true
if ($snapshotEvents)
then
# Do stuff if true
fi
and to keep everyone happy, I tested:
snapshotEvents=false
if !($snapshotEvents)
then
# Do stuff if false
fi
Which also worked fine.
The $snapshotEvents
evaluates the contents of value of the variable. So you need the $
.
You don't really need the parentheses, I just find them helpful.
Tested on: GNU Bash, version 4.1.11(2)-release
Bash Guide for Beginners, Machtelt Garrels, v1.11, 2008
Double check if you are not able to use keys.
Otherwise use expect:
#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact
After lots of search finally this worked for me . I hope it helps.
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
return RedirectToAction("Index", "Home");
}
<li class="page-scroll">@Html.ActionLink("Log off", "LogOff", "Account")</li>
From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:
JSONArray jsonArray=new JSONArray(jsonObject);
JSONArray has constructor to accept object.
As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.
Another possibility is to use mobile-detect.js. Try the demo.
<script src="mobile-detect.js"></script>
<script>
var md = new MobileDetect(window.navigator.userAgent);
// ... see below
</script>
var MobileDetect = require('mobile-detect'),
md = new MobileDetect(req.headers['user-agent']);
// ... see below
var md = new MobileDetect(
'Mozilla/5.0 (Linux; U; Android 4.0.3; en-in; SonyEricssonMT11i' +
' Build/4.1.A.0.562) AppleWebKit/534.30 (KHTML, like Gecko)' +
' Version/4.0 Mobile Safari/534.30');
// more typically we would instantiate with 'window.navigator.userAgent'
// as user-agent; this string literal is only for better understanding
console.log( md.mobile() ); // 'Sony'
console.log( md.phone() ); // 'Sony'
console.log( md.tablet() ); // null
console.log( md.userAgent() ); // 'Safari'
console.log( md.os() ); // 'AndroidOS'
console.log( md.is('iPhone') ); // false
console.log( md.is('bot') ); // false
console.log( md.version('Webkit') ); // 534.3
console.log( md.versionStr('Build') ); // '4.1.A.0.562'
console.log( md.match('playstation|xbox') ); // false
Here's a SCSS version of @Patrick's mixin.
$mqIterations: 19;
@mixin fontResize($iterations)
{
$i: 1;
@while $i <= $iterations
{
@media all and (min-width: 100px * $i) {
body { font-size:0.2em * $i; }
}
$i: $i + 1;
}
}
@include fontResize($mqIterations);
Use http://facebook.github.io/stetho/ library to access your app's local storage with chrome inspect tools. You can find sharedPreference file under Local storage -> < your app's package name >
Use the setAttribute
method:
document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");
But you really should be using data followed with a dash and with its property, like:
<li ... data-icon="base.gif" ...>
And to do it in JS use the dataset
property:
document.getElementById('item1').dataset.icon = "base.gif";
Switch case is every help full instead of if else statement :
switch ($("[id*=btnSave]").val()) {
case 'Search':
saveFlight();
break;
case 'Update':
break;
case 'Delete':
break;
default:
break;
}
Adding another better version of same code (accepted answer) with JavaScript 1.6 indexOf function. Do not need to loop thru whole array every time you are checking the duplicate.
var arr = []
while(arr.length < 8){
var randomnumber=Math.ceil(Math.random()*100)
var found=false;
if(arr.indexOf(randomnumber) > -1){found=true;}
if(!found)arr[arr.length]=randomnumber;
}
Older version of Javascript can still use the version at top
PS: Tried suggesting an update to the wiki but it was rejected. I still think it may be useful for others.
Adding to bobble bubble's answer, there are other regex flavors where recursive constructs are supported.
Lua
Use %b()
(%b{}
/ %b[]
for curly braces / square brackets):
for s in string.gmatch("Extract (a(b)c) and ((d)f(g))", "%b()") do print(s) end
(see demo)Raku (former Perl6):
Non-overlapping multiple balanced parentheses matches:
my regex paren_any { '(' ~ ')' [ <-[()]>+ || <&paren_any> ]* }
say "Extract (a(b)c) and ((d)f(g))" ~~ m:g/<&paren_any>/;
# => (?(a(b)c)? ?((d)f(g))?)
Overlapping multiple balanced parentheses matches:
say "Extract (a(b)c) and ((d)f(g))" ~~ m:ov:g/<&paren_any>/;
# => (?(a(b)c)? ?(b)? ?((d)f(g))? ?(d)? ?(g)?)
See demo.
Python re
non-regex solution
See poke's answer for How to get an expression between balanced parentheses.
Java customizable non-regex solution
Here is a customizable solution allowing single character literal delimiters in Java:
public static List<String> getBalancedSubstrings(String s, Character markStart,
Character markEnd, Boolean includeMarkers)
{
List<String> subTreeList = new ArrayList<String>();
int level = 0;
int lastOpenDelimiter = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == markStart) {
level++;
if (level == 1) {
lastOpenDelimiter = (includeMarkers ? i : i + 1);
}
}
else if (c == markEnd) {
if (level == 1) {
subTreeList.add(s.substring(lastOpenDelimiter, (includeMarkers ? i + 1 : i)));
}
if (level > 0) level--;
}
}
return subTreeList;
}
}
Sample usage:
String s = "some text(text here(possible text)text(possible text(more text)))end text";
List<String> balanced = getBalancedSubstrings(s, '(', ')', true);
System.out.println("Balanced substrings:\n" + balanced);
// => [(text here(possible text)text(possible text(more text)))]
Kept everything same and just added a blank test file at the root folder .. Solved it
Here are the findings, this problem really bugged me for a while. My folder structure was
mathapp/
- server.py
- configuration.py
- __init__.py
- static/
- home.html
tests/
- functional
- test_errors.py
- unit
- test_add.py
and pytest would complain with the ModuleNotFoundError and gives the HINT - make sure your test modules/packages have valid Python names.
I introduced a mock test file at the same level as mathsapp and tests directory. The file contained nothing. Now pytest does not complain.
Result without the file
$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error
=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
from mathapp.service import sum
E ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================
Results with the file
$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items
tests\functional\test_func.py . [ 50%]
tests\unit\test_unit.py . [100%]
============================== 2 passed in 0.11s ==============================
I think you are a bit confused on the purpose of custom data attributes. From the w3 spec
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
By itself an attribute of data-toggle=value
is basically a key-value pair, in which the key is "data-toggle" and the value is "value".
In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.
Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".
Button Toggle
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
}
if (changed) this.$element.toggleClass('active')
}
The context that the code provides shows that Bootstrap is using the data-toggle
attribute as a custom query selector to process the particular element.
From what I see these are the data-toggle options:
You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle
attribute toggles the element to active or not.
Sorry if I've missed the point, but wouldn't the following do what you want on it's own?
SELECT distinct idCustomer FROM reservations
WHERE DATEPART(hour, insertDate) >= 2
You need to add the column with a default of null
, then alter the column to have default now()
.
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP;
ALTER TABLE mytable ALTER COLUMN created_at SET DEFAULT now();
Once you get the macports version of gdb
installed you will need to disable SIP in order to make the proper edits to /System/Library/LaunchDaemons/com.apple.taskgated.plist
. To disable SIP, you need to restart in recovery mode and execute the following command:
csrutil disable
Then restart. Then you will need to edit the bottom part of com.apple.taskgated.plist
like this:
<array>
<string>/usr/libexec/taskgated</string>
<string>-sp</string>
</array>
Then you will have to restart to have the changes take effect. Then you should reenable SIP. The gdb
command for the macports install is actually ggdb
. You will need to code sign ggdb
following the instructions here:
https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html
The only way I have been able to get the code signing to work is by running ggdb
with sudo
. Good luck!
This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version
to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.
Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.
Similar to the answer before there there is
location.host
The location global has more fun facts about the current url as well. ( protocol, host, port, pathname, search, hash )
XDebug is not stable and it's not always available for particular php version. For example on some servers I still run php-5.1.6, -- it's what comes with RedHat RHEL5 (and btw still receives updates for all important issues), and recent XDebug does not even compile with this php. So I ended up with switching to DBG debugger Its php benchmarking provides timing for functions, methods, modules and even lines.
See Semantic Designs' CloneDR, a "clone detection" tool that finds copy/paste/edited code.
It will find exact and near miss code fragments, in spite of white space, comments and even variable renamings. A sample detection report for PHP can be found at the website. (I'm the author.)
Hopefully this may help, and hopefully I'll get to try this during the week.
See this answer re how a dyslexic colleague made life easier for themselves with a common header file full of things like #define fasle false
.
How about disabled=disabled
:
<input id="price_from" value="price from " disabled="disabled">????????????
Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.
If you know for sure that there's always going to be exactly one key in the object, then you can use Object.keys
:
theTypeIs = Object.keys(myVar)[0];
Currently there is no production ready HTML5 only solution for recording video over the web. The current available solutions are as follows:
HTML Media Capture
Works on mobile devices and uses the OS' video capture app to capture video and upload/POST it to a web server. You will get .mov files on iOS (these are unplayable on Android I've tried) and .mp4 and .3gp on Android. At least the codecs will be the same: H.264 for video and AAC for audio in 99% of the devices.
Image courtesy of https://addpipe.com/blog/the-new-video-recording-prompt-for-media-capture-in-ios9/
Flash and a media server on desktop.
Video recording in Flash works like this: audio and video data is captured from the webcam and microphone, it's encoded using Sorenson Spark or H.264 (video) and Nellymoser Asao or Speex (audio) then it's streamed (rtmp) to a media server (Red5, AMS, Wowza) where it is saved in .flv or .f4v files.
The MediaStream Recording proposal
The MediaStream Recording is a proposal by the the Media Capture Task Force (a joint task force between the WebRTC and Device APIs working groups) for a JS API who's purpose is to make basic video recording in the browser very simple.
Not supported by major browsers. When it'll get implemented (if it will) you will most probably end up with different filetypes (at least .ogg and .webm) and audio/video codecs depending on the browser.
Commercial solutions
There are a few saas and software solutions out there that will handle some or all of the above including addpipe.com, HDFVR, Nimbb and Cameratag.
Further reading:
As an alternative, you can install 7.1 version of mcrypt
and create a symbolic link to it:
Install php7.1-mcrypt:
sudo apt install php7.1-mcrypt
Create a symbolic link:
sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available
After enabling mcrypt
by sudo phpenmod mcrypt
, it gets available.
Shortest and quickest way to remove all the selection, is by passing empty string in jQuery .val() function :
$("#my_select").val('')
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2
will return
password : [pwd1, pwd2]
(length = 2)
username : [james, smith]
(length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
opt
is new for ruby 1.9. The various options are documented in IO.new
: www.ruby-doc.org/core/IO.html
Here is an example on how to use the onClickListener in Kotlin
button1.setOnClickListener(object : View.OnClickListener{
override fun onClick(v: View?) {
//Your code here
}})
Don't set the style object itself, set the background color property of the style object that is a property of the element.
And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.
And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized
How about some simple testing? Used the code below:
long start = System.currentTimeMillis();
String a = "a";
String b = "b";
for (int i = 0; i < 10000000; i++) { //ten million times
String c = a.concat(b);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
"a + b"
version executed in 2500ms.a.concat(b)
executed in 1200ms.Tested several times. The concat()
version execution took half of the time on average.
This result surprised me because the concat()
method always creates a new string (it returns a "new String(result)
". It's well known that:
String a = new String("a") // more than 20 times slower than String a = "a"
Why wasn't the compiler capable of optimize the string creation in "a + b" code, knowing the it always resulted in the same string? It could avoid a new string creation. If you don't believe the statement above, test for your self.
Because recursion is always the answer.
function getPosition(input, search, nth, curr, cnt) {
curr = curr || 0;
cnt = cnt || 0;
var index = input.indexOf(search);
if (curr === nth) {
if (~index) {
return cnt;
}
else {
return -1;
}
}
else {
if (~index) {
return getPosition(input.slice(index + search.length),
search,
nth,
++curr,
cnt + index + search.length);
}
else {
return -1;
}
}
}
The official Microsoft answer on how to do this is in KB article 318785.
I find the accepted answer, and all the others strange, since they pass self
to an abstract class. An abstract class is not instantiated so can't have a self
.
So try this, it works.
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def foo():
"""An abstract method. No need to write pass"""
class Derived(Abstract):
def foo(self):
print('Hooray!')
FOO = Derived()
FOO.foo()
Apache StringUtils addresses this problem too.
Failings of the other options:
Granted StringUtils is another library to drag around, but it works very well and saves loads of time and hassle checking for nulls or gracefully handling NPEs.
(DateTime)MyReader["ColumnName"];
OR
Convert.ToDateTime(MyReader["ColumnName"]);
FYI dataTables requires a well formed table. It must contain <thead>
and <tbody>
tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.
The following will throw error (no <thead>
and <tbody>
tags)
<table id="sample-table">
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
<tr>
<td>data-1</td>
<td>data-2</td>
</tr>
</table>
The following will also throw an error (unequal number of columns)
<table id="sample-table">
<thead>
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>
For more info read more here
All the answers here suggest to use ipairs but beware, it does not work all the time.
t = {[2] = 44, [4]=77, [6]=88}
--This for loop prints the table
for key,value in next,t,nil do
print(key,value)
end
--This one does not print the table
for key,value in ipairs(t) do
print(key,value)
end
Width 100% : It will make content with 100%. margin, border, padding will be added to this width and element will overflow if any of these added.
Width auto : It will fit the element in available space including margin, border and padding. space remaining after adjusting margin + padding + border will be available width/ height.
Width 100% + box-sizing: border box : It will also fits the element in available space including border, padding (margin will make it overflow the container).
Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.
What replaceFirst()
does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.
What you want to do is convert the string to an array using the String
class' charAt()
method, and then use Character.toUpperCase()
to change the character to upper case (obviously). Your code would look like this:
char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);
Or, if you feel comfortable with more complex, one-lined java code:
betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);
Both of these do the same thing, which is converting the first character of userIdea
to an upper case character.
James Curran's answer was the most concise in my opinion, but the output wasn't correct. For SQL Server the simplest statement is as follows:
SELECT
[score range] = CAST((Score/10)*10 AS VARCHAR) + ' - ' + CAST((Score/10)*10+9 AS VARCHAR),
[number of occurrences] = COUNT(*)
FROM #Scores
GROUP BY Score/10
ORDER BY Score/10
This assumes a #Scores temporary table I used to test it, I just populated 100 rows with random number between 0 and 99.
As it turns out, my suspicions were right. The audience aud
claim in a JWT is meant to refer to the Resource Servers that should accept the token.
As this post simply puts it:
The audience of a token is the intended recipient of the token.
The audience value is a string -- typically, the base address of the resource being accessed, such as
https://contoso.com
.
The client_id
in OAuth refers to the client application that will be requesting resources from the Resource Server.
The Client app (e.g. your iOS app) will request a JWT from your Authentication Server. In doing so, it passes it's client_id
and client_secret
along with any user credentials that may be required. The Authorization Server validates the client using the client_id
and client_secret
and returns a JWT.
The JWT will contain an aud
claim that specifies which Resource Servers the JWT is valid for. If the aud
contains www.myfunwebapp.com
, but the client app tries to use the JWT on www.supersecretwebapp.com
, then access will be denied because that Resource Server will see that the JWT was not meant for it.
Use align-items: flex-start
on the container, or align-self: flex-start
on the flex items.
No need for display: inline-flex
.
An initial setting of a flex container is align-items: stretch
. This means that flex items will expand to cover the full length of the container along the cross axis.
The align-self
property does the same thing as align-items
, except that align-self
applies to flex items while align-items
applies to the flex container.
By default, align-self
inherits the value of align-items
.
Since your container is flex-direction: column
, the cross axis is horizontal, and align-items: stretch
is expanding the child element's width as much as it can.
You can override the default with align-items: flex-start
on the container (which is inherited by all flex items) or align-self: flex-start
on the item (which is confined to the single item).
Learn more about flex alignment along the cross axis here:
Learn more about flex alignment along the main axis here:
If you need to fetch an object's property dynamically, use the getattr() function: getattr(user, "fullName")
- or to elaborate:
user = User()
property = "fullName"
name = getattr(user, property)
Otherwise just use user.fullName
.
echo -e "open <ftp.hostname>\nuser <username> <password>\nbinary\nmkdir New_Folder\nquit"|ftp -nv
As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.
To answer your specific questions: