Your model is null
because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}
is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:
<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />
However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:
<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:
EditorTemplates
folder inside your view's current folder (e.g. if your view is Home\Index.cshtml
, create the folder Home\EditorTemplates
).PlanCompareViewModel.cshtml
.Now, everything you have in your partial view wants to go in that template:
@model PlanCompareViewModel
<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/>
</div>
Finally, your parent view is simplified to this:
@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
@Html.EditorForModel()
</div>
}
DisplayTemplates
and EditorTemplates
are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.
Self-referencing as example
public class Employee {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int ManagerId { get; set; }
public virtual Employee Manager { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public Employee() {
Employees = new HashSet<Employee>();
}
}
HasMany(e => e.Employees)
.WithRequired(e => e.Manager)
.HasForeignKey(e => e.ManagerId)
.WillCascadeOnDelete(false);
Another cause of this could be if you don't use the default variable name for the "id" which is actually: id.
Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...
Consider following example, suppose we have DataTable like below.
DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));
Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.
Area | Quantity | Breath | Length | Price = Quantity * breath *Length
Than we have to fire following query which will give us exact result as we want.
var data = ObjDt.AsEnumerable().Select
(r => new
{
Area = r.Field<string>("Area"),
Que = r.Field<int>("Quantity"),
Breath = r.Field<decimal>("Breath"),
Length = r.Field<decimal>("Length"),
totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
}).ToList();
We just have to assign this data variable as Data Source.
By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…
Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.
var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();
Here is just another option you couold apply for ASP NET MVC.
Normally you shoud use BaseController
class for each Controller
class.
So inside of it's constructor method do following.
public class BaseController : Controller
{
public BaseController()
{
// get the previous url and store it with view model
ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
}
}
And now in ANY view you can do like
<button class="btn btn-success mr-auto" onclick=" window.location.href = '@ViewBag.PreviousUrl'; " style="width:2.5em;"><i class="fa fa-angle-left"></i></button>
Enjoy!
IEquatable<T>
can be a much easier way to do this with modern frameworks.
You get a nice simple bool Equals(T other)
function and there's no messing around with casting or creating a separate class.
public class Person : IEquatable<Person>
{
public Person(string name, string hometown)
{
this.Name = name;
this.Hometown = hometown;
}
public string Name { get; set; }
public string Hometown { get; set; }
// can't get much simpler than this!
public bool Equals(Person other)
{
return this.Name == other.Name && this.Hometown == other.Hometown;
}
public override int GetHashCode()
{
return Name.GetHashCode(); // see other links for hashcode guidance
}
}
Note you DO have to implement GetHashCode
if using this in a dictionary or with something like Distinct
.
PS. I don't think any custom Equals methods work with entity framework directly on the database side (I think you know this because you do AsEnumerable) but this is a much simpler method to do a simple Equals for the general case.
If things don't seem to be working (such as duplicate key errors when doing ToDictionary) put a breakpoint inside Equals to make sure it's being hit and make sure you have GetHashCode
defined (with override keyword).
Most likely this issue happens because of "lazy loading" feature of Entity Framework. Usually, unless explicitly required during initial fetch, all joined data (anything that stored in other database tables) is fetched only when required. In many cases that is a good thing, since it prevents from fetching unnecessary data and thus improve query performance (no joins) and saves bandwidth.
In the situation described in the question, initial fetch is performed, and during "select" phase missing lazy loading data is requested, additional queries are issued and then EF is complaining about "open DataReader".
Workaround proposed in the accepted answer will allow execution of these queries, and indeed the whole request will succeed.
However, if you will examine requests sent to the database, you will notice multiple requests - additional request for each missing (lazy loaded) data. This might be a performance killer.
A better approach is to tell to EF to preload all needed lazy loaded data during the initial query. This can be done using "Include" statement:
using System.Data.Entity;
query = query.Include(a => a.LazyLoadedProperty);
This way, all needed joins will be performed and all needed data will be returned as a single query. The issue described in the question will be solved.
Simple excel file create in mvc 4
public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }
I wrote an article on this subject over here. I think it could help you.
Typically it's doing something like that:
static void Main(string[] args)
{
// Convert from a DataTable source to an IEnumerable.
var usersSourceDataTable = CreateMockUserDataTable();
var usersConvertedList = usersSourceDataTable.ToEnumerable<User>();
// Convert from an IEnumerable source to a DataTable.
var usersSourceList = CreateMockUserList();
var usersConvertedDataTable = usersSourceList.ToDataTable<User>();
}
Without using a lambda function and for valid inputs only, I think it's clearer to do this:
Array.ConvertAll<string, int>(value.Split(','), Convert.ToInt32);
@Jon: Jon, are you saying using multiple where clauses e.g.
var query = from r in tempData.AsEnumerable()
where r.Field<string>("UserName") != "XXXX"
where r.Field<string>("UserName") != "YYYY"
select r;
is more restictive than using
var query = from r in tempData.AsEnumerable()
where r.Field<string>("UserName") != "XXXX" && r.Field<string>("UserName") != "YYYY"
select r;
I think they are equivalent as far as the result goes.
However, I haven't tested, if using multiple where in the first example cause in 2 subqueries, i.e. .Where(r=>r.UserName!="XXXX").Where(r=>r.UserName!="YYYY)
or the LINQ translator is smart enought to execute .Where(r=>r.UserName!="XXXX" && r.UsernName!="YYYY")
Use the following to evaluate an expression (constant 0 evaluates to false).
#if 0
...
#endif
To refine the answer from Zed, and to answer your comment:
INSERT INTO dues_storage
SELECT d.*, CURRENT_DATE()
FROM dues d
WHERE id = 5;
See T.J. Crowder's comment
You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat
I say this because captions are usually applied to floats.
Straight ahead equations (those written with $ ... $
, $$ ... $$
, begin{equation}...
) are in-line objects that do not support \caption
.
This can be done using the following snippet just before \begin{document}
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}
\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
\let\ORIGINALcaption\caption
\def\caption{%
\addtocounter{equation}{-1}%
\ORIGINALcaption
}%
\ORGeqfloat
}
and when adding an equation use something like
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.
Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)
Update: My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is not implemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.
You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog post for example (last example there).
string filePath = HttpContext.Current.Server.MapPath("~/folderName/filename.extension");
OR
string filePath = HttpContext.Server.MapPath("~/folderName/filename.extension");
Update: Incredibly frustrating, but the Google redirect of the maven.google.com
repo seems to mess with loading the resources. If you instead set your repository to
maven { url 'https://dl.google.com/dl/android/maven2' }
the files will resolve. You can prove this out by attempting to get the fully qualified resource at https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.0-alpha1/gradle-3.0.0-alpha1.pom
3.0.0 Alpha
This is because currently the gradle:3.0.0-alpha1
is only being served via the new 'https://maven.google.com'
repository, but the site currently 404s at that location otherwise, being a public directory, you'd see a tree listing of all the files available by simply navigating to that location in your browser. When they resolve their outage, your CI build should pass immediately.
I just installed Visual Studio Code v1.25.1. on a Windows 7 Professional SP1 machine. I wanted to understand workspaces in detail, so I spent a few hours figuring out how they work in this version of Visual Studio Code. I thought the results of my research might be of interest to the community.
First, workspaces are referred to by Microsoft in the Visual Studio Code documentation as "multi-root workspaces." In plain English that means "a multi-folder (A.K.A "root") work environment." A Visual Studio Code workspace is simply a collection of folders - any collection you desire, in any order you wish. The typical collection of folders constitutes a software development project. However, a folder collection could be used for anything else for which software code is being developed.
The mechanics behind how Visual Studio Code handles workspaces is a bit complicated. I think the quickest way to convey what I learned is by giving you a set of instructions that you can use to see how workspaces work on your computer. I am assuming that you are starting with a fresh install of Visual Studio Code v1.25.1. If you are using a production version of Visual Studio Code I don't recommend that you follow my instructions because you may lose some or all of your existing Visual Studio Code configuration! If you already have a test version of Visual Studio Code v1.25.1 installed, **and you are willing to lose any configuration that already exists, the following must be done to revert your Visual Studio Code to a fresh installation state:
Delete the following folder (if it exists):
C:\Users\%username%\AppData\Roaming\Code\Workspaces (where "%username%" is the name of the currently logged-on user)
You will be adding folders to Visual Studio Code to create a new workspace. If any of the folders you intend to use to create this new workspace have previously been used with Visual Studio Code, please delete the ".vscode" subfolder (if it exists) within each of the folders that will be used to create the new workspace.
Launch Visual Studio Code. If the Welcome page is displayed, close it. Do the same for the Panel (a horizontal pane) if it is displayed. If you received a message that Git isn't installed click "Remind me later." If displayed, also close the "Untitled" code page that was launched as the default code page. If the Explorer pane is not displayed click "View" on the main menu then click "Explorer" to display the Explorer pane. Inside the Explorer pane you should see three (3) View headers - Open Editors, No Folder Opened, and Outline (located at the very bottom of the Explorer pane). Make sure that, at a minimum, the open editors and no folder opened view headers are displayed.
Visual Studio Code displays a button that reads "Open Folder." Click this button and select a folder of your choice. Visual Studio Code will refresh and the name of your selected folder will have replaced the "No Folder Opened" View name. Any folders and files that exist within your selected folder will be displayed beneath the View name.
Now open the Visual Studio Code Preferences Settings file. There are many ways to do this. I'll use the easiest to remember which is menu File → Preferences → Settings. The Settings file is displayed in two columns. The left column is a read-only listing of the default values for every Visual Studio Code feature. The right column is used to list the three (3) types of user settings. At this point in your test only two user settings will be listed - User Settings and Workspace Settings. The User Settings is displayed by default. This displays the contents of your User Settings .json file. To find out where this file is located, simply hover your mouse over the "User Settings" listing that appears under the OPEN EDITORS View in Explorer. This listing in the OPEN EDITORS View is automatically selected when the "User Settings" option in the right column is selected. The path should be:
C:\Users\%username%\AppData\Roaming\Code\User\settings.json
This settings.json file is where the User Settings for Visual Studio Code are stored.
Now click the Workspace Settings option in the right column of the Preferences listing. When you do this, a subfolder named ".vscode" is automatically created in the folder you added to Explore a few steps ago. Look at the listing of your folder in Explorer to confirm that the .vscode subfolder has been added. Inside the new .vscode subfolder is another settings.json file. This file contains the workspace settings for the folder you added to Explorer a few steps ago.
At this point you have a single folder whose User Settings are stored at:
C:\Users\%username%\AppData\Roaming\Code\User\settings.json
and whose Workspace Settings are stored at:
C:\TheLocationOfYourFolder\settings.json
This is the configuration when a single folder is added to a new installation of Visual Studio Code. Things get messy when we add a second (or greater) folder. That's because we are changing Visual Studio Code's User Settings and Workspace Settings to accommodate multiple folders. In a single-folder environment only two settings.json files are needed as listed above. But in a multi-folder environment a .vscode subfolder is created in each folder added to Explorer and a new file, "workspaces.json," is created to manage the multi-folder environment. The new "workspaces.json" file is created at:
c:\Users\%username%\AppData\Roaming\Code\Workspaces\%workspace_id%\workspaces.json
The "%workspaces_id%" is a folder with a unique all-number name.
In the Preferences right column there now appears three user setting options - User Settings, Workspace Settings, and Folder Settings. The function of User Settings remains the same as for a single-folder environment. However, the settings file behind the Workspace Settings has been changed from the settings.json file in the single folder's .vscode subfolder to the workspaces.json file located at the workspaces.json file path shown above. The settings.json file located in each folder's .vscode subfolder is now controlled by a third user setting, Folder Options. This is a drop-down selection list that allows for the management of each folder's settings.json file located in each folder's .vscode subfolder. Please note: the .vscode subfolder will not be created in newly-added explorer folders until the newly-added folder has been selected at least once in the folder options user setting.
Notice that the Explorer single folder name has bee changed to "UNTITLED (WORKSPACE)." This indicates the following:
The full functionality of Visual Studio Code workspaces is only realized when a workspace is saved as a file that can be reloaded as needed. This provides the capability to create unique multi-folder workspaces (e.g., projects) and save them as files for later use! To do this select menu File → Save Workspace As from the main menu and save the current workspace configuration as a unique workspace file. If you need to create a workspace "from scratch," first save your current workspace configuration (if needed) then right-click each Explorer folder name and click "Remove Folder from Workspace." When all folders have been removed from the workspace, add the folders you require for your new workspace. When you finish adding new folders, simply save the new workspace as a new workspace file.
An important note - Visual Studio Code doesn't "revert" to single-folder mode when only one folder remains in Explorer or when all folders have been removed from Explorer when creating a new workspace "from scratch." The multi-folder workspace configuration that utilizes three user preferences remains in effect. This means that unless you follow the instructions at the beginning of this post, Visual Studio Code can never be returned to a single-folder mode of operation - it will always remain in multi-folder workspace mode.
I have written this code in vb and its is working fine to check weather a file is exists or not for fileupload control. try it
FOR VB CODE ============
If FileUpload1.HasFile = True Then
Dim FileExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
If FileExtension.ToLower <> ".jpg" Then
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "Please select .jpg image file to upload"
Else
Dim FileSize As Integer = FileUpload1.PostedFile.ContentLength
If FileSize > 1048576 Then
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File size (1MB) exceeded"
Else
Dim FileName As String = System.IO.Path.GetFileName(FileUpload1.FileName)
Dim ServerFileName As String = Server.MapPath("~/Images/Folder1/" + FileName)
If System.IO.File.Exists(ServerFileName) = False Then
FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File : " + FileName.ToString() + " already exsist"
End If
End If
End If
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "Please select a file to upload"
End If
FOR C# CODE ======================
if (FileUpload1.HasFile == true) {
string FileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (FileExtension.ToLower != ".jpg") {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select .jpg image file to upload";
} else {
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize > 1048576) {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File size (1MB) exceeded";
} else {
string FileName = System.IO.Path.GetFileName(FileUpload1.FileName);
string ServerFileName = Server.MapPath("~/Images/Folder1/" + FileName);
if (System.IO.File.Exists(ServerFileName) == false) {
FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully";
} else {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File : " + FileName.ToString() + " already exsist";
}
}
}
} else {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select a file to upload";
}
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
for (NSString *key in [defaultsDictionary allKeys]) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
In case if you are developing your own framework:
WHY is this happening?
If any of the public header files you have mentioned in your module.modulemap have import statements that are not mentioned in modulemap, this will give you the error. Since it tries to import some header that is not declared as modular (in module.modulemap), it breaks the modularity of the framework.
HOW can I fix it?
Just include the header that gave the error to your module.modulemap and build again!
WHY NOT just set allow non-modular to YES?
Because it's not really a solution here, with that you tell your project "this framework was supposed to be modular but it's not. Use it somehow, I don't care." This doesn't fix your library's modularity problem.
For more information check this archived blog post or refer to clang docs.
Your friend's PC is missing the runtime support DLLs for your program:
The "escape hatch" operation that lets you do weird things that are not otherwise supported by streams is to ask for an Iterator
:
Iterator<T> it = users.stream().filter((user) -> user.getId() < 0).iterator();
if (!it.hasNext())
throw new NoSuchElementException();
else {
result = it.next();
if (it.hasNext())
throw new TooManyElementsException();
}
Guava has a convenience method to take an Iterator
and get the only element, throwing if there are zero or multiple elements, which could replace the bottom n-1 lines here.
try this:
declare @foo varchar(7),
@oldFoo varchar(7)
set @foo = '138'
set @oldFoo = '0' + @foo
.input:focus {
outline: none !important;
border:1px solid red;
box-shadow: 0 0 10px #719ECE;
}
In case this is happening to you on a server build (AppCenter) and yo uaer using CocoaPods ensure that your Podfile is checked in.
AppCenter only runs the "pod install" command if it finds a Pofile and it DOES NOT find the PODS folder on the files.
I had the folder checked-in, but because git automatically ignores .pch files (check you .gitignore to veryfy this), my .pch weren'nt being checked in.
I sorted my issue by forcing the .pch files to check it, but Deleting the PODS folder should work too, since Appcenter will run the pod install command in that case.
Hoppefully this helps somebody.
Just listen to what the warning is telling you:
Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.
For your example type(if you have more than one feature/column):
temp = temp.reshape(1,-1)
For one feature/column:
temp = temp.reshape(-1,1)
Tongue-in-cheek obviously:
var harshNum = 108;
"".split.call(harshNum,"").join("");
Or in ES6 you could simply use template strings:
var harshNum = 108;
`${harshNum}`;
In clean Ubuntu 16.04 LTS, MariaDB root login for localhost changed from password style to sudo login style...
so, just do
sudo mysql -u root
since we want to login with password, create another user 'user'
in MariaDB console... (you get in MariaDB console with 'sudo mysql -u root')
use mysql
CREATE USER 'user'@'localhost' IDENTIFIED BY 'yourpassword';
\q
then in bash shell prompt,
mysql-workbench
and you can login with 'user' with 'yourpassword' on localhost
Here is my way of validating a form with a disabled button. Check out the snippet below:
var inp = document.getElementsByTagName("input");_x000D_
var btn = document.getElementById("btn");_x000D_
// Disable the button dynamically using javascript_x000D_
btn.disabled = "disabled";_x000D_
_x000D_
function checkForm() {_x000D_
for (var i = 0; i < inp.length; i++) {_x000D_
if (inp[i].checkValidity() == false) {_x000D_
btn.disabled = "disabled";_x000D_
} else {_x000D_
btn.disabled = false;_x000D_
}_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8"/>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>_x000D_
<title>JavaScript</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<h1>Javascript form validation</h1>_x000D_
<p>Javascript constraint form validation example:</p>_x000D_
_x000D_
<form onkeyup="checkForm()" autocomplete="off" novalidate>_x000D_
<input type="text" name="fname" placeholder="First Name" required><br><br>_x000D_
<input type="text" name="lname" placeholder="Last Name" required><br><br>_x000D_
<button type="submit" id="btn">Submit</button>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Example explained:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
for (var i = 0; i < inp.length; i++) {
// Code
}
checkValidity()
method to check if the input elements
(with a required
attribute) are valid or not (Code is inserted inside the
for loop). If it is invalid, then the button will remain disabled, else the
attribute is removed.
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
Got this helpful link that states the difference, as John Zwinck has stated and a drawback of git stash pop
.
For instance, say your stashed changes conflict with other changes that you’ve made since you first created the stash. Both pop and apply will helpfully trigger merge conflict resolution mode, allowing you to nicely resolve such conflicts… and neither will get rid of the stash, even though perhaps you’re expecting pop too. Since a lot of people expect stashes to just be a simple stack, this often leads to them popping the same stash accidentally later because they thought it was gone.
Link: http://codingkilledthecat.wordpress.com/2012/04/27/git-stash-pop-considered-harmful/
I would suggest taking a look JetBrains AppCode IDE. It has a Reformat Code command. I have come from a C# background and used Visual Studio with Jetbrains Resharper plugin, so learning AppCode has been a pleasure because many of the features in Resharper also exist in AppCode!
Theres too many features to list here but could well be worth checking out
had the same problem.run command 'python manage.py migrate' as root. works fine with root access (sudo python manage.py migrate )
Can also be called as
@Html.Partial("_PartialView", (ModelClass)View.Data)
along with these two variants, there is also jade.renderFile
which generates html that need not be passed to the client.
usage-
var jade = require('jade');
exports.getJson = getJson;
function getJson(req, res) {
var html = jade.renderFile('views/test.jade', {some:'json'});
res.send({message: 'i sent json'});
}
getJson()
is available as a route in app.js.
I had to update the proxy settings under Plugins -> Plugin Manager -> Show Plugin Manager -> Settings to see any PlugIns in the "Available" list.
After that, installing "XML Tools" was easy and did the requested job as described above.
Use the following command to kill and restart node server from batch file
@echo off
cd "D:\sam\Projects\Node"
taskkill /IM node.exe -F
start /min cmd /C "node index.js"
goto :EOF
include your Member Class to your jsp :
<%@ page import="pageNumber.*, java.util.*, java.io.*,yourMemberPackage.Member" %>
Add iframe: { scrolling : 'no' } as option
example
$.fancybox({
href: 'yourUrl.html',
width: 800,
height: 415,
autoSize: false,
type : 'iframe',
iframe: {
scrolling : 'no',
preload : true
}});
Here's some reusable css that will preserve the height of each element without using position: absolute
:
.stack {
display: grid;
}
.stack > * {
grid-row: 1;
grid-column: 1;
}
The first element in your stack
is the background, and the second is the foreground.
Not a solution to this issue, but if you're experiencing the above error with Ektron eSync, it could be that your database has run out of disk space.
Edit: In fact this isn't entirely an Ektron eSync only issue. This could happen on any service that querying a full database.
Edit: Out of disk space, or blocking access to a directory that you need will cause this issue.
Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.
echo <<<MYTAG
<tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;
How about this way?
['Cat', 'Dog', 'Bird'].index('Dog')
Two options here:
Replace ifPresent
with map
and use Function
instead of Consumer
private String getStringIfObjectIsPresent(Optional<Object> object) {
return object
.map(obj -> {
String result = "result";
//some logic with result and return it
return result;
})
.orElseThrow(MyCustomException::new);
}
Use isPresent
:
private String getStringIfObjectIsPresent(Optional<Object> object) {
if (object.isPresent()) {
String result = "result";
//some logic with result and return it
return result;
} else {
throw new MyCustomException();
}
}
In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.
using(OracleCommand cmd = con.CreateCommand()) {
...
cmd.BindByName = true;
...
}
I had same issue before, here is my class which solved color conversions Use it and enjoy :
Here U go, Use my Class to Multi Color Conversion
using System;
using System.Windows.Media;
using SDColor = System.Drawing.Color;
using SWMColor = System.Windows.Media.Color;
using SWMBrush = System.Windows.Media.Brush;
//Developed by ???? ????? ?????
namespace APREndUser.CodeAssist
{
public static class ColorHelper
{
public static SWMColor ToSWMColor(SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B);
public static SDColor ToSDColor(SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B);
public static SWMBrush ToSWMBrush(SDColor color) => (SolidColorBrush)(new BrushConverter().ConvertFrom(ToHexColor(color)));
public static string ToHexColor(SDColor c) => "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
public static string ToRGBColor(SDColor c) => "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
public static Tuple<SDColor, SDColor> GetColorFromRYGGradient(double percentage)
{
var red = (percentage > 50 ? 1 - 2 * (percentage - 50) / 100.0 : 1.0) * 255;
var green = (percentage > 50 ? 1.0 : 2 * percentage / 100.0) * 255;
var blue = 0.0;
SDColor result1 = SDColor.FromArgb((int)red, (int)green, (int)blue);
SDColor result2 = SDColor.FromArgb((int)green, (int)red, (int)blue);
return new Tuple<SDColor, SDColor>(result1, result2);
}
}
}
Use fabs() instead of abs(), it's the same but for floats instead of integers.
Spaces are horrible in filenames or directory names.
The correct syntax for this is to include every directory name that includes spaces, in double quotes
cmd /c C:\"Program Files"\"Microsoft Visual Studio 9.0"\Common7\IDE\devenv.com mysolution.sln /build "release|win32"
from ctypes import *
pthread = cdll.LoadLibrary("libpthread-2.15.so")
pthread.pthread_cancel(c_ulong(t.ident))
t is your Thread
object.
Read the python source (Modules/threadmodule.c
and Python/thread_pthread.h
) you can see the Thread.ident
is an pthread_t
type, so you can do anything pthread
can do in python use libpthread
.
If your query consists only of the $where
operator, you can pass in just the JavaScript expression:
db.T.find("this.Grade1 > this.Grade2");
For greater performance, run an aggregate operation that has a $redact
pipeline to filter the documents which satisfy the given condition.
The $redact
pipeline incorporates the functionality of $project
and $match
to implement field level redaction where it will return all documents matching the condition using $$KEEP
and removes from the pipeline results those that don't match using the $$PRUNE
variable.
Running the following aggregate operation filter the documents more efficiently than using $where
for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where
, which can slow down the query:
db.T.aggregate([
{
"$redact": {
"$cond": [
{ "$gt": [ "$Grade1", "$Grade2" ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
which is a more simplified version of incorporating the two pipelines $project
and $match
:
db.T.aggregate([
{
"$project": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
"Grade1": 1,
"Grade2": 1,
"OtherFields": 1,
...
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
With MongoDB 3.4 and newer:
db.T.aggregate([
{
"$addFields": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
You can do like this also:
HTML:
<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ' onmouseover="somefunction();"></a>
In javascript:
function somefunction()
{
//Do somethisg.
}
?
From docs and example it is not clear that classpath manipulation is not allowed.
<configuration>
<compilerArgs>
<arg>classpath=${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)
-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.
Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?
<properties>
<cpfile>cp.txt</cpfile>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>build-classpath</id>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
<configuration>
<outputFile>${cpfile}</outputFile>
</configuration>
</execution>
</executions>
</plugin>
Read file (Read a file into a Maven property)
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
def file = new File(project.properties.cpfile)
project.properties.cp = file.getText()
</source>
</configuration>
</execution>
</executions>
</plugin>
and finally
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<compilerArgs>
<arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
</plugin>
This worked for me. Each month on X axis
str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)
From the Design Patterns theory; "encapsulate what varies". By defining a 'getter' there is good adherence to the above principle. So, if the implementation-representation of the member changes in future, the member can be 'massaged' before returning from the 'getter'; implying no code refactoring at the client side where the 'getter' call is made.
Regards,
If the performance hit of the default constructor isn't an issue, the please, for the love of god, go with the more readable version.
:)
If your button was made with Interface Builder, and you're changing the title in code, you can do this:
[self.button setTitle:@"Button Title" forState:UIControlStateNormal];
[self.button sizeToFit];
You can (should) use CROSS JOIN
. Following query will be equivalent to yours:
SELECT
table1.columnA
, table2.columnA
FROM table1
CROSS JOIN table2
WHERE table1.columnA = 'Some value'
or you can even use INNER JOIN with some always true conditon:
FROM table1
INNER JOIN table2 ON 1=1
You can also create a soft link to your script in one of the directories (/usr/local/bin
for example) in the super user PATH. It'll then be available to the sudo.
chmod +x foo.sh
sudo ln -s path-to-foo.sh /usr/local/bin/foo
Have a look at this answer to have an idea of which directory to put soft link in.
Issue: The Jet OLE DB provider reads a registry key to determine how many rows are to be read to guess the type of the source column. By default, the value for this key is 8. Hence, the provider scans the first 8 rows of the source data to determine the data types for the columns. If any field looks like text and the length of data is more than 255 characters, the column is typed as a memo field. So, if there is no data with a length greater than 255 characters in the first 8 rows of the source, Jet cannot accurately determine the nature of the data type. As the first 8 row length of data in the exported sheet is less than 255 its considering the source length as VARCHAR(255) and unable to read data from the column having more length.
Fix: The solution is just to sort the comment column in descending order. In 2012 onwards we can update the values in Advance tab in the Import wizard.
An easy way to change to a different codec, is by using encode() or decode(). In your case, you want to convert to ASCII and ignore all symbols that are not supported. For example, the Swedish letter å is not an ASCII character:
>>>s = u'Good bye in Swedish is Hej d\xe5'
>>>s = s.encode('ascii',errors='ignore')
>>>print s
Good bye in Swedish is Hej d
Edit:
Python3: str -> bytes -> str
>>>"Hej då".encode("ascii", errors="ignore").decode()
'hej d'
Python2: unicode -> str -> unicode
>>> u"hej då".encode("ascii", errors="ignore").decode()
u'hej d'
Python2: str -> unicode -> str (decode and encode in reverse order)
>>> "hej d\xe5".decode("ascii", errors="ignore").encode()
'hej d'
You need to convert your image to a numpy array this way:
import numpy
import PIL
img = PIL.Image.open("foo.jpg").convert("L")
imgarr = numpy.array(img)
What about just using the UniqueID of the processor?
Modify your web.config to display the server error details:
<system.web>
<customErrors mode="Off" />
</system.web>
You may also need to remove/comment out the follow httpErrors section
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404" />
<error statusCode="404" path="/Error/Error404" responseMode="ExecuteURL" />
<remove statusCode="500" />
<error statusCode="500" path="/Error/Error500" responseMode="ExecuteURL" />
<remove statusCode="403" />
<error statusCode="403" path="/Error/Error403" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
From my experience if you directly have a server error, this may be caused from an assembly version mismatch.
Check what is declared in the web.config and the actual ddl in the bin folder's project.
You will find the tomcat-users.xml in \Users\<Name>\AppData\Roaming\Netbeans\
. It exists at least twice on your machine, depending on the number of Tomcat installations you have.
Out of curiosity, why don't you just use the url for the said folder?
Assuming that the folder never changes location, that would be the easiest way to do it.
Here's how:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
Here is the example in which you can easily find the way to use Post,GET method and use the same way to add other curd operations as well..
#libraries to include
import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')<br>
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
def question():
# request.args is to get urls arguments
if request.method == 'GET':
start = request.args.get('start', default=0, type=int)
limit_url = request.args.get('limit', default=20, type=int)
questions = mongo.db.questions.find().limit(limit_url).skip(start);
data = [doc for doc in questions]
return jsonify(isError= False,
message= "Success",
statusCode= 200,
data= data), 200
# request.form to get form parameter
if request.method == 'POST':
average_time = request.form.get('average_time')
choices = request.form.get('choices')
created_by = request.form.get('created_by')
difficulty_level = request.form.get('difficulty_level')
question = request.form.get('question')
topics = request.form.get('topics')
##Do something like insert in DB or Render somewhere etc. it's up to you....... :)
SELECT
campo1,
campo2,
campo3,
campo4
FROM tabela1
WHERE CONCAT(campo1,campo2,campo3,IF(campo4 IS NULL,'',campo4))
NOT IN
(SELECT CONCAT(campo1,campo2,campo3,IF(campo4 IS NULL,'',campo4))
FROM tabela2);
import datetime
def daterange(start, stop, step_days=1):
current = start
step = datetime.timedelta(step_days)
if step_days > 0:
while current < stop:
yield current
current += step
elif step_days < 0:
while current > stop:
yield current
current += step
else:
raise ValueError("daterange() step_days argument must not be zero")
if __name__ == "__main__":
from pprint import pprint as pp
lo = datetime.date(2008, 12, 27)
hi = datetime.date(2009, 1, 5)
pp(list(daterange(lo, hi)))
pp(list(daterange(hi, lo, -1)))
pp(list(daterange(lo, hi, 7)))
pp(list(daterange(hi, lo, -7)))
assert not list(daterange(lo, hi, -1))
assert not list(daterange(hi, lo))
assert not list(daterange(lo, hi, -7))
assert not list(daterange(hi, lo, 7))
I looked into the answer from Máta whose name hints at encoding qualifications and experience. The VBA docs say CreateTextFile(filename, [overwrite [, unicode]])
creates a file "as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it's created as an ASCII file. If omitted, an ASCII file is assumed." It's fine that a file stores unicode characters, but in what encoding? Unencoded unicode can't be represented in a file.
The VBA doc page for OpenTextFile(filename[, iomode[, create[, format]]])
offers a third option for the format:
Máta passes -1 for this argument.
Judging from VB.NET documentation (not VBA but I think reflects realities about how underlying Windows OS represents unicode strings and echoes up into MS Office, I don't know) the system default is an encoding using 1 byte/unicode character using an ANSI code page for the locale. UnicodeEncoding
is UTF-16. The docs also describe UTF-8 is also a "Unicode encoding," which makes sense to me. But I don't yet know how to specify UTF-8 for VBA output nor be confident that the data I write to disk with the OpenTextFile(,,,1) is UTF-16 encoded. Tamalek's post is helpful.
You should consider using an angular plug-in to handle the heavy lifting for you, unless you particularly enjoy typing hundreds of lines of knarly error prone ion-grid code. Simon Grimm has a cracking step by step tutorial that anyone can follow: https://devdactic.com/ionic-datatable-ngx-datatable/. This shows how to use ngx-datatable. But there are many other options (ng2-table is good).
The dead simple example goes like this:
<ion-content>
<ngx-datatable class="fullscreen" [ngClass]="tablestyle" [rows]="rows" [columnMode]="'force'" [sortType]="'multi'" [reorderable]="false">
<ngx-datatable-column name="Name"></ngx-datatable-column>
<ngx-datatable-column name="Gender"></ngx-datatable-column>
<ngx-datatable-column name="Age"></ngx-datatable-column>
</ngx-datatable>
</ion-content>
And the ts:
rows = [
{
"name": "Ethel Price",
"gender": "female",
"age": 22
},
{
"name": "Claudine Neal",
"gender": "female",
"age": 55
},
{
"name": "Beryl Rice",
"gender": "female",
"age": 67
},
{
"name": "Simon Grimm",
"gender": "male",
"age": 28
}
];
Since the original poster expressed their frustration of how difficult it is to achieve this with ion-grid, I think the correct answer should not be constrained by this as a prerequisite. You would be nuts to roll your own, given how good this is!
Form nesting can be achieved with new HTML5 input element's form attribute. Although we don't nest forms structurally, inputs are evaluated as they are in their own form. In my tests, 3 major browsers support this except IE(IE11). Form nesting limitation was a big obstacle for HTML UI design.
Here is a sample code, when you click Save button you should see "2 3 success" (Original http://www.impressivewebs.com/html5-form-attribute/):
<form id="saveForm" action="/post/dispatch/save" method="post"></form>
<form id="deleteForm" action="/post/dispatch/delete" method="post"></form>
<div id="toolbar">
<input type="text" name="foo" form="saveForm" />
<input type="hidden" value="some_id" form="deleteForm" />
<input type="text" name="foo2" id="foo2" form="saveForm" value="success" />
<input type="submit" name="save" value="Save" form="saveForm" onclick="alert(document.getElementById('deleteForm').elements.length + ' ' + document.getElementById('saveForm').elements.length + ' ' + document.getElementById('saveForm').elements['foo2'].value);return false;" />
<input type="submit" name="delete" value="Delete" form="deleteForm" />
<a href="/home/index">Cancel</a>
</div>
You can use pywinrm
library instead which is cross-platform compatible.
Here is a simple code example:
#!/usr/bin/env python
import winrm
# Create winrm connection.
sess = winrm.Session('https://10.0.0.1', auth=('username', 'password'), transport='kerberos')
result = sess.run_cmd('ipconfig', ['/all'])
Install library via: pip install pywinrm requests_kerberos
.
Here is another example from this page to run Powershell script on a remote host:
import winrm
ps_script = """$strComputer = $Host
Clear
$RAM = WmiObject Win32_ComputerSystem
$MB = 1048576
"Installed Memory: " + [int]($RAM.TotalPhysicalMemory /$MB) + " MB" """
s = winrm.Session('windows-host.example.com', auth=('john.smith', 'secret'))
r = s.run_ps(ps_script)
>>> r.status_code
0
>>> r.std_out
Installed Memory: 3840 MB
>>> r.std_err
In my experience the pythonw.exe is faster at least with using pygame.
I used Selva's solution but had two kinds of issues:
I fixed these two issues. You can find the solution (within my own project package) at
I had the same issue when i reference the Class library into my MVC web application,
the issue was the nuget package version number mismatch between two projects.
ex: my class library had log4net of 1.2.3 but my webapp had 1.2.6
fix: just make sure both the project have the same version number referenced.
You can add a callback function to your list of get_category(...) parameters.
Ex:
get_categories(number, callback){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
callback();
}, error => {
}
);
}
And then you can just call get_category(...) like this:
this.get_category(1, name_of_function);
I'm no expert in Typescript, but I think the main problem is the way of accessing data. Seeing how you described your Images
interface, you can define any key as a String.
When accessing a property, the "dot" syntax (images.main
) supposes, I think, that it already exists. I had such problems without Typescript, in "vanilla" Javascript, where I tried to access data as:
return json.property[0].index
where index was a variable. But it interpreted index
, resulting in a:
cannot find property "index" of json.property[0]
And I had to find a workaround using your syntax:
return json.property[0][index]
It may be your only option there. But, once again, I'm no Typescript expert, if anyone knows a better solution / explaination about what happens, feel free to correct me.
Here is what I used for TSQL which took care of the problem that my table name could contain the schema name and possibly the database name:
DECLARE @THETABLE varchar(100);
SET @THETABLE = 'theschema.thetable';
select i.*
from sys.indexes i
where i.object_id = OBJECT_ID(@THETABLE)
and i.name is not NULL;
The use case for this is that I wanted the list of indexes for a named table so I could write a procedure that would dynamically compress all indexes on a table.
First of all, don’t fix it this way
if ( ! $scope.$$phase) {
$scope.$apply();
}
It does not make sense because $phase is just a boolean flag for the $digest cycle, so your $apply() sometimes won’t run. And remember it’s a bad practice.
Instead, use $timeout
$timeout(function(){
// Any code in here will automatically have an $scope.apply() run afterwards
$scope.myvar = newValue;
// And it just works!
});
If you are using underscore or lodash, you can use defer():
_.defer(function(){
$scope.$apply();
});
You can use double splat operator which is available since Ruby 2.0:
h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}
Server.UrlDecode(xxxxxxxx)
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
You can give opacity value as
div {opacity: 0.4;}
For IE
, you can specify as
div { filter:alpha(opacity=10));}
Lower the value - Higher the transparency.
You can use int
and set the base to 2
(for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int
like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a demonstration:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>
Try this :
void removeChar(char *str, char garbage) {
char *src, *dst;
for (src = dst = str; *src != '\0'; src++) {
*dst = *src;
if (*dst != garbage) dst++;
}
*dst = '\0';
}
Test program:
int main(void) {
char* str = malloc(strlen("abcdef")+1);
strcpy(str, "abcdef");
removeChar(str, 'b');
printf("%s", str);
free(str);
return 0;
}
Result:
>>acdef
EOF
is a constant in C. You are not checking the actual file for EOF. You need to do something like this
while(!feof(stdin))
Here is the documentation to feof. You can also check the return value of scanf. It returns the number of successfully converted items, or EOF
if it reaches the end of the file.
Verify the following steps.
Those things should fix the problem
Make sure you have the projects targeting the same framework version. Most of the times the reason would be that current project ( where you are adding reference of another project ) points to a different .net framework version than the rest ones.
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
You are correct in that static files are copied to the application at link-time, and that shared files are just verified at link time and loaded at runtime.
The dlopen call is not only for shared objects, if the application wishes to do so at runtime on its behalf, otherwise the shared objects are loaded automatically when the application starts. DLLS and .so are the same thing. the dlopen exists to add even more fine-grained dynamic loading abilities for processes. You dont have to use dlopen yourself to open/use the DLLs, that happens too at application startup.
It is worth pointing out that if you use json_decode(file_get_contents("php://input"))
(as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params)
above may result in subtle errors, as json_last_error()
does not change when null
or a blank string is passed, as shown here:
http://ideone.com/va3u8U
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'
IDENTIFIED BY 'YOUR_PASS'
WITH GRANT OPTION;
FLUSH PRIVILEGES;
*.* = DB.TABLE
you can restrict user to specific database and specific table.
'root'@'%'
you can change root with any user you created and % is to allow all IP. You can restrict it by changing %.168.1.1 etc too.
If that doesn't resolve, then also modify my.cnf or my.ini and comment these lines
bind-address = 127.0.0.1
to #bind-address = 127.0.0.1
and
skip-networking
to #skip-networking
Raspberry Pi, I found bind-address configuration under \etc\mysql\mariadb.conf.d\50-server.cnf
You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.
Usually I do the juggling-check as Fenton already discussed. To make it more readable, you can use isNil from ramda.
import * as isNil from 'ramda/src/isNil';
totalAmount = isNil(totalAmount ) ? 0 : totalAmount ;
import java.util.Scanner;
class my{
public static void main(String args[])
{
Scanner x=new Scanner(System.in);
double a,b,c=0,d;
d=1;
d=d/10;
int e,z=0;
System.out.print("Enter no:");
a=x.nextInt();
for(b=1;b<=a/2;b++)
{
if(b*b==a)
{
c=b;
break;
}
else
{
if(b*b>a)
break;
}
}
b--;
if(c==0)
{
for(e=1;e<=15;e++)
{
while(b*b<=a && z==0)
{
if(b*b==a){c=b;z=1;}
else
{
b=b+d; //*d==0.1 first time*//
if(b*b>=a){z=1;b=b-d;}
}
}
d=d/10;
z=0;
}
c=b;
}
System.out.println("Squre root="+c);
}
}
In case you are just a beginner and want to split a string into an array of letters but didn't know the right terminology for that is a char[];
String myString = "My String";
char[] characters = myString.ToCharArray();
If this is not what you were looking for, sorry for wasting your time :P
A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:
Derived d;
Base& rb = d;
// if Base::f() is virtual and Derived overrides it, Derived::f() will be called
rb.f();
A pure virtual function is a virtual function whose declaration ends in =0
:
class Base {
// ...
virtual void f() = 0;
// ...
A pure virtual function implicitly makes the class it is defined for abstract (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.
An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation. (What that's good for is debatable.)
Note that C++11 brought a new use for the delete
and default
keywords which looks similar to the syntax of pure virtual functions:
my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;
See this question and this one for more info on this use of delete
and default
.
In C++11 you can use std::to_string
:
#include <string>
std::string s = std::to_string(5);
If you're working with prior to C++11, you could use C++ streams:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
There is a way to increase character using ascii_letters
from string
package which ascii_letters
is a string that contains all English alphabet, uppercase and lowercase:
>>> from string import ascii_letters
>>> ascii_letters[ascii_letters.index('a') + 1]
'b'
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Also it can be done manually;
>>> letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> letters[letters.index('c') + 1]
'd'
You need to generate a font first. You must use the MakeFont
utility included within the FPDF package. I used on Linux this a bit extended script from the demo:
<?php
// Generation of font definition file for tutorial 7
require('../makefont/makefont.php');
$dir = opendir('/usr/share/fonts/truetype/ttf-dejavu/');
while (($relativeName = readdir($dir)) !== false) {
if ($relativeName == '..' || $relativeName == '.')
continue;
MakeFont("/usr/share/fonts/truetype/ttf-dejavu/$relativeName",'ISO-8859-2');
}
?>
Then I copied generated files to the font
directory of my web and used this:
$pdf->Cell(80,70, iconv('UTF-8', 'ISO-8859-2', 'Bunka jedna'),1);
(I was working on a table.) That worked for my language (Bunka jedna is czech for Cell one). Czech language belongs to central european languages, also ISO-8859-2. Regrettably the user of FPDF is forced to lost advantages of UTF-8 encoding. You cannot get this in your PDF:
Mestecko Fruens Bøge
Danish letter ø
becomes r
in ISO-8859-2.
Suggestion of solution: You need to get a Greek font, generate the font using proper encoding (ISO-8859-7) and use iconv
with the same target encoding as the one the font has been generated with.
It's all about the ease of use/steps required to do something.
If I'm developing a single project on my PC/laptop, git is better, because it is far easier to set up and use. You don't need a server, and you don't need to keep typing repository URL's in when you do merges.
If it were just 2 people, I'd say git is also easier, because you can just push and pull from eachother.
Once you get beyond that though, I'd go for subversion, because at that point you need to set up a 'dedicated' server or location.
You can do this just as well with git as with SVN, but the benefits of git get outweighed by the need to do additional steps to synch with a central server. In SVN you just commit. In git you have to git commit, then git push. The additional step gets annoying simply because you end up doing it so much.
SVN also has the benefit of better GUI tools, however the git ecosystem seems to be catching up quickly, so I wouldn't worry about this in the long term.
VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.
Dim val1 As Integer, val2 As Integer, i As Integer
For i = 1 To 333
Sheets("Feuil2").Activate
ActiveSheet.Cells(i, 1).Select
val1 = Cells(i, 1).Value
val2 = Cells(i, 2).Value
Sheets("Classeur2.csv").Select
Cells(val1, val2).Select
ActiveCell.FormulaR1C1 = "1"
Next i
For deleting the remote branch:
git push origin --delete <your_branch>
For deleting the local branch, you have three ways:
1: git branch -D <branch_name>
2: git branch --delete --force <branch_name> # Same as -D
3: git branch --delete <branch_name> # Error on unmerge
Explain: OK, just explain what's going on here!
Simply do git push origin --delete
to delete your remote branch only, add the name of the branch at the end and this will delete and push it to remote at the same time...
Also, git branch -D
, which simply delete the local branch only!...
-D
stands for --delete --force
which will delete the branch even it's not merged (force delete), but you can also use -d
which stands for --delete
which throw an error respective of the branch merge status...
I also create the image below to show the steps:
Not to be vague or anything but I think the type of 'file' you will be storing is one of the biggest determining factors. If you essentially talking about a large text field which could be stored as file my preference would be for db storage.
For the sake of completeness:
macOS High Sierra, Jenkins 2.x, installation via Homebrew
~/.jenkins/jobs/{project_name}/config.xml
Complete overview about jenkins home: https://wiki.jenkins.io/display/JENKINS/Administering+Jenkins
inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,
android:screenOrientation="landscape"
for landscape orientation and for portrait add the following code,
android:screenOrientation="portrait"
The best i can do for both iOS7 and less is:
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rect = CGRectInset(bounds, 0, 6); //TODO: can be improved by comparing font size versus bounds.size.height
return rect;
}
- (void)drawPlaceholderInRect:(CGRect)rect {
UIColor *color =RGBColor(65, 65, 65);
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
[self.placeholder drawInRect:rect withAttributes:@{NSFontAttributeName:self.font, UITextAttributeTextColor:color}];
} else {
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font];
}
}
Sorted arrays are processed faster than an unsorted array, due to a phenomena called branch prediction.
The branch predictor is a digital circuit (in computer architecture) trying to predict which way a branch will go, improving the flow in the instruction pipeline. The circuit/computer predicts the next step and executes it.
Making a wrong prediction leads to going back to the previous step, and executing with another prediction. Assuming the prediction is correct, the code will continue to the next step. A wrong prediction results in repeating the same step, until a correct prediction occurs.
The answer to your question is very simple.
In an unsorted array, the computer makes multiple predictions, leading to an increased chance of errors. Whereas, in a sorted array, the computer makes fewer predictions, reducing the chance of errors. Making more predictions requires more time.
Sorted Array: Straight Road
____________________________________________________________________________________
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
Unsorted Array: Curved Road
______ ________
| |__|
Branch prediction: Guessing/predicting which road is straight and following it without checking
___________________________________________ Straight road
|_________________________________________|Longer road
Although both the roads reach the same destination, the straight road is shorter, and the other is longer. If then you choose the other by mistake, there is no turning back, and so you will waste some extra time if you choose the longer road. This is similar to what happens in the computer, and I hope this helped you understand better.
Also I want to cite @Simon_Weaver from the comments:
It doesn’t make fewer predictions - it makes fewer incorrect predictions. It still has to predict for each time through the loop...
The variables you need are explained here in the jenkins wiki: https://wiki.jenkins.io/display/JENKINS/Features+controlled+by+system+properties
The default variable ITEM_ROOTDIR points to a directory inside the jenkins installation. As you already found out you need:
You need to achieve this through config.xml nowerdays. Citing from the wiki page linked above:
This used to be a UI setting, but was removed in 2.119 as it did not support migration of existing build records and could lead to build-related errors until restart.
&& and || were on the list of things to implement (still are) but did not pop up as the next most useful thing to add. The reason is that we have -AND and -OR. If you think it is important, please file a suggestion on Connect and we'll consider it for V3.
How about using
ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(myString)
In this context, there are loads to textual materials everywhere. I just wanted to post a diagrammatic representation that really helped me to grasp the concept.
When fast and slow meet at point p,
Distance travelled by fast = a+b+c+b = a+2b+c
Distance travelled by slow = a+b
Since the fast is 2 times faster than the slow. So a+2b+c = 2(a+b), then we get a=c.
So when another slow pointer runs again from head to q, at the same time, fast pointer will run from p to q, so they meet at the point q together.
public ListNode detectCycle(ListNode head) {
if(head == null || head.next==null)
return null;
ListNode slow = head;
ListNode fast = head;
while (fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
/*
if the 2 pointers meet, then the
dist from the meeting pt to start of loop
equals
dist from head to start of loop
*/
if (fast == slow){ //loop found
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
yield
basically makes an IEnumerable<T>
method behave similarly to a cooperatively (as opposed to preemptively) scheduled thread.
yield return
is like a thread calling a "schedule" or "sleep" function to give up control of the CPU. Just like a thread, the IEnumerable<T>
method regains controls at the point immediately afterward, with all local variables having the same values as they had before control was given up.
yield break
is like a thread reaching the end of its function and terminating.
People talk about a "state machine", but a state machine is all a "thread" really is. A thread has some state (I.e. values of local variables), and each time it is scheduled it takes some action(s) in order to reach a new state. The key point about yield
is that, unlike the operating system threads we're used to, the code that uses it is frozen in time until the iteration is manually advanced or terminated.
You have to be specific about the columns you are selecting. If your user
table had four columns id, name, username, opted_in
you must select exactly those four columns from the query. The syntax looks like:
INSERT INTO user (id, name, username, opted_in)
SELECT id, name, username, opted_in
FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id
However, there does not appear to be any reason to join against user_permission
here, since none of the columns from that table would be inserted into user
. In fact, this INSERT
seems bound to fail with primary key uniqueness violations.
MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT
statements in your code, using the last insert id from the first query, or create an AFTER INSERT
trigger on the primary table.
INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)
Or using a trigger:
CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END
In Place of using this
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
You can also use
MsgBox(json.SelectToken("Venue.ID"))
When root permissions are required for the destination file, use |sudo tee
instead of >
:
cat << 'EOF' |sudo tee /tmp/yourprotectedfilehere
The variable $FOO will *not* be interpreted.
EOF
cat << "EOF" |sudo tee /tmp/yourprotectedfilehere
The variable $FOO *will* be interpreted.
EOF
Input String
[
{
"userName": "sandeep",
"age": 30
},
{
"userName": "vivan",
"age": 5
}
]
Simple Way to Convert String to JSON
public class Test
{
public static void main(String[] args) throws JSONException
{
String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] ";
JSONArray jsonArr = new JSONArray(data);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
}
}
}
Output
{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}
http://www.kernel.org/pub/software/scm/git/docs/git-revert.html
using git revert <commit>
will create a new commit that reverts the one you dont want to have.
You can specify a list of commits to revert.
An alternative: http://git-scm.com/docs/git-reset
git reset
will reset your copy to the commit you want.
Go to the Config button (up right) and select the Autostart for Apache.
If you just want your query data dumped into excel I have to do this frequently and using an html table is a very simple method. I use mysqli for db queries and the following code for exports to excel:
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo '<table border="1">';
//make the column headers what you want in whatever order you want
echo '<tr><th>Field Name 1</th><th>Field Name 2</th><th>Field Name 3</th></tr>';
//loop the query data to the table in same order as the headers
while ($row = mysqli_fetch_assoc($result)){
echo "<tr><td>".$row['field1']."</td><td>".$row['field2']."</td><td>".$row['field3']."</td></tr>";
}
echo '</table>';
I finally solved this problem, at least with Safari, by putting "pointer-events: auto" before "disabled". The reverse order didn't work.
Simply put, "Non-identifying" relationships between Entities is part of ER-Model and is available in Microsoft Visio when designing ER-Diagram. This is required to enforce cardinality between Entities of type " zero or more than zero", or "zero or one". Note this "zero" in cardinality instead of "one" in "one to many".
Now, example of non-identifying relationship where cardinality may be "zero" (non-identifying) is when we say a record / object in one entity-A "may" or "may not" have a value as a reference to the record/s in another Entity-B.
As, there is a possibility for one record of entity-A to identify itself to the records of other Entity-B, therefore there should be a column in Entity-B to have the identity-value of the record of Entity-B. This column may be "Null" if no record in Entity-A identifies the record/s (or, object/s) in Entity-B.
In Object Oriented (real-world) Paradigm, there are situations when an object of Class-B does not necessarily depends (strongly coupled) on object of class-A for its existence, which means Class-B is loosely-coupled with Class-A such that Class-A may "Contain" (Containment) an object of Class-A, as opposed to the concept of object of Class-B must have (Composition) an object of Class-A, for its (object of class-B) creation.
From SQL Query point of view, you can query all records in entity-B which are "not null" for foreign-key reserved for Entity-B. This will bring all records having certain corresponding value for rows in Entity-A alternatively all records with Null value will be the records which do not have any record in Entity-A in Entity-B.
in case you are interested in reading some data from a .txt
file and only extract few columns of that file into a new .txt
file with a customized header, the following code might be useful:
# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")
# assign the name for the output file:
seqName <- "seq1_data.txt"
#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx <- civit_cam$q.x.rad.
qy <- civit_cam$q.y.rad.
qz <- civit_cam$q.z.rad.
qw <- civit_cam$q.w
# From GPS:
gpsT <- civit_gps$X.gpsTime.sec.
latitude <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude <- civit_gps$H.Ell.m.
heading <- civit_gps$Heading.deg.
pitch <- civit_gps$pitch.deg.
roll <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]
#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
c(frame_idx),
c(qx),
c(qy),
c(qz),
c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")
Of course, you should modify this sample script based on your own application.
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
You just need to append your command after start in the string that you are passing.
String command = "cmd.exe /c start "+"*your command*";
Process child = Runtime.getRuntime().exec(command);
Use
Console.WriteLine(String.Format(" {0:G17}", i));
That will give you all the 17 digits it have. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. {0:R} will not always give you 17 digits, it will give 15 if the number can be represented with that precision.
which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision. There isn't any thing you can to do to make the the double return more digits that is the way it's implemented. If you don't like it do a new double class yourself...
.NET's double cant store any more digits than 17 so you cant see 6.89999999999999946709 in the debugger you would see 6.8999999999999995. Please provide an image to prove us wrong.
from ..gen_py.lib import MyService
or
from main.gen_py.lib import MyService
Make sure you have a (at least empty) __init__.py
file on each directory.
I don't think it's necessary to use semi-quotes around the variables, try:
curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"
%2f
is the escape code for a /
.
http://www.december.com/html/spec/esccodes.html
Also, do you need to specify a port? ( just checking :) )
Another approach to sort HTML table. (based on W3.JS HTML Sort)
var collection = [{_x000D_
"Country": "France",_x000D_
"Date": "2001-01-01",_x000D_
"Size": "25",_x000D_
}, {_x000D_
"Country": "spain",_x000D_
"Date": "2005-05-05",_x000D_
"Size": "",_x000D_
}, {_x000D_
"Country": "Lebanon",_x000D_
"Date": "2002-02-02",_x000D_
"Size": "-17",_x000D_
}, {_x000D_
"Country": "Argentina",_x000D_
"Date": "2005-04-04",_x000D_
"Size": "100",_x000D_
}, {_x000D_
"Country": "USA",_x000D_
"Date": "",_x000D_
"Size": "-6",_x000D_
}]_x000D_
_x000D_
for (var j = 0; j < 3; j++) {_x000D_
$("#myTable th:eq(" + j + ")").addClass("control-label clickable");_x000D_
$("#myTable th:eq(" + j + ")").attr('onClick', "w3.sortHTML('#myTable', '.item', 'td:nth-child(" + (j + 1) + ")')");_x000D_
}_x000D_
_x000D_
$tbody = $("#myTable").append('<tbody></tbody>');_x000D_
_x000D_
for (var i = 0; i < collection.length; i++) {_x000D_
$tbody = $tbody.append('<tr class="item"><td>' + collection[i]["Country"] + '</td><td>' + collection[i]["Date"] + '</td><td>' + collection[i]["Size"] + '</td></tr>');_x000D_
}
_x000D_
.control-label:after {_x000D_
content: "*";_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.clickable {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="myTable" class="w3-table-all">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Country</th>_x000D_
<th>Date</th>_x000D_
<th>Size</th>_x000D_
</tr>_x000D_
</thead>_x000D_
</table>
_x000D_
I had the same issue. I found that I forgot to add selenium-2.53.0/selenium-java-2.53.0-srcs.jar file to my project's Reference library.
You can use Visual Paradigm for UML. This might not be the best paid (it's US$699) product, just as an option if anyone would like to try. It can create class diagram from PHP and vice versa, and not only PHP, there's a bunch of language you can choose such as C#, C++, Ruby, Java, VB.NET, Python, Objective C, Perl, etc. There's also a trial you can check on.
This script is ok except for this case that of course, I've met :
INSERT INTO "requestcomparison_stopword" VALUES(149,'f'); INSERT INTO "requestcomparison_stopword" VALUES(420,'t');
The script should give this output :
INSERT INTO requestcomparison_stopword VALUES(149,'f'); INSERT INTO requestcomparison_stopword VALUES(420,'t');
But gives instead that output :
INSERT INTO requestcomparison_stopword VALUES(1490; INSERT INTO requestcomparison_stopword VALUES(4201;
with some strange non-ascii characters around the last 0 and 1.
This didn't show up anymore when I commented the following lines of the code (43-46) but others problems appeared:
line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
line = line.replace('THIS_IS_FALSE', '0')
This is just a special case, when we want to add a value being 'f' or 't' but I'm not really comfortable with regular expressions, I just wanted to spot this case to be corrected by someone.
Anyway thanks a lot for that handy script !!!
The first thing you need to do is read the HTTP spec which will explain what you can expect to receive over the wire. The data returned inside the content will be the "rendered" web page, not the source. The source could be a JSP, a servlet, a CGI script, in short, just about anything, and you have no access to that. You only get the HTML that the server sent you. In the case of a static HTML page, then yes, you will be seeing the "source". But for anything else you see the generated HTML, not the source.
When you say modify the page and return the modified page
what do you mean?
write.csv(t, "t.csv", row.names=FALSE)
From ?write.csv
:
row.names: either a logical value indicating whether the row names of
‘x’ are to be written along with ‘x’, or a character vector
of row names to be written.
Neither of the above solutions worked for me on Visual Studio Community 2017 v15.7.1. Somehow, there was no "Go Online" option in the context menu. I tried registry edit as suggested here, but that only displayed me error that it could not find the binding. What worked for me is rebinding solution to the server from Change Source Control menu.
Go to File->Source Control->Advanced->Change Source Control
and make sure that your solution is binded to your source control. If not (like mine) then click on bind button, it will automatically search online TFS server and rebind your solution to it.
I don't know if this will be of any help to you, but I have written a couple of articles which introduce the basics.
The next article is 95% complete, I just have to write up explanations of the last few parts of the code I have written. If you are interested then I will try to remember to post here when I publish it.
I had the same issue. In my case I was using a web service which was build using AnyCPU settings. Since the WCF was using 32 bit Oracle data access components therefore it was raising the same error when I tried to call it from a console client. So when I compiled the WCF service using the x86 based setting the client was able to successfully get data from the web service.
If you compile as "Any CPU" and run on an x64 platform, then you won't be able to load 32-bit dlls (which in our case were the Oracle Data Access components), because our app wasn't started in WOW64 (Windows32 on Windows 64). So in order to allow the 32 bit dependency of Oracle Data Access components I compilee the web service with Platform target of x86 and that solved it for me
As an alternative if you have 64bit ODAC drivers installed on the machine that also caused the problem to go away.
You can use the BS Typeahead fork which supports ajax calls. Then you will be able to write:
$('.typeahead').typeahead({
source: function (typeahead, query) {
return $.get('/typeahead', { query: query }, function (data) {
return typeahead.process(data);
});
}
});
my solution only works for the next cases: if you are mistaking a multidimensaional array into a single one
$json = file_get_contents('url_json'); //get the json
$objhigher=json_decode($json); //converts to an object
$objlower = $objhigher[0]; // if the json response its multidimensional this lowers it
echo "<pre>"; //box for code
print_r($objlower); //prints the object with all key and values
echo $objlower->access_token; //prints the variable
i know that the answer was has already been answered but for those who came here looking for something i hope this can help you
Seems like you've shadowed the builtin name list
pointing at a class by the same name pointing at its instance. Here is an example:
>>> example = list('easyhoss') # here `list` refers to the builtin class
>>> list = list('abc') # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss') # here `list` refers to the instance
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:
Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest namespaces. As I've already mentioned, namespaces are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace. In fact it's just a local namespace with respect to that particular module.
Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError
. Builtin functions and classes reside in a special high-order namespace __builtins__
. If you declare a variable named list
in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__
). Similarly, suppose you create a variable var
inside a function in your module, and another variable var
in the module. Then, if you reference var
inside the function, you will never get the global var
, because there is a var
in the local namespace - the interpreter has no need to search it elsewhere.
Here is a simple illustration.
>>> example = list("abc") # Works fine
>>>
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>>
>>> example = list("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>>
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name.
>>> example = list("abc") # It works.
So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.
You might as well be wondering what is a "callable", in which case you can read this post. list
, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list
instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).
If you want to know more about builtins, please read the answer by Christian Dean.
P.S. When you start an interactive Python session, you create a temporary module.
I was having this issue when loading a cached redux state. If I just load the cached state, I'd run into errors for new app version with an updated state structure.
It was already mentioned, that lodash offers the merge
function, which I used:
const currentInitialState = configureState().getState();
const mergedState = _.merge({}, currentInitialState, cachedState);
const store = configureState(mergedState);
ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused
When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.
The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.
Here is another quick approach without using additional panel.
JFrame f = new JFrame("stackoverflow") {
private Image backgroundImage = ImageIO.read(new File("background.jpg"));
public void paint( Graphics g ) {
super.paint(g);
g.drawImage(backgroundImage, 0, 0, null);
}
};
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
This solution has really helped me :
By using below two methods we can clear data programatically
public void clearApplicationData() {
File cacheDirectory = getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
if (applicationDirectory.exists()) {
String[] fileNames = applicationDirectory.list();
for (String fileName : fileNames) {
if (!fileName.equals("lib")) {
deleteFile(new File(applicationDirectory, fileName));
}
}
}
}
public static boolean deleteFile(File file) {
boolean deletedAll = true;
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
}
} else {
deletedAll = file.delete();
}
}
return deletedAll;
}
Just iterate over the transposed of your array:
for column in array.T:
some_function(column)
Normally you want to perform this check atomically with using the result, so stat()
is useless. Instead, open()
the file read-only first and use fstat()
. If it's a directory, you can then use fdopendir()
to read it. Or you can try opening it for writing to begin with, and the open will fail if it's a directory. Some systems (POSIX 2008, Linux) also have an O_DIRECTORY
extension to open
which makes the call fail if the name is not a directory.
Your method with opendir()
is also good if you want a directory, but you should not close it afterwards; you should go ahead and use it.
To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.
This means that if you generate a 200x200
image for xhdpi
devices, you should generate the same resource in 150x150
for hdpi
, 100x100
for mdpi
, and 75x75
for ldpi
devices.
Then, place the files in the appropriate drawable resource directory:
MyProject/
res/
drawable-xhdpi/
awesomeimage.png
drawable-hdpi/
awesomeimage.png
drawable-mdpi/
awesomeimage.png
drawable-ldpi/
awesomeimage.png
Any time you reference @drawable/awesomeimage
, the system selects the appropriate bitmap based on the screen's density.
I ended up using BackgroundWorker, it is definitely asynchronous unlike some of the above solutions, it handles returning to the GUI thread for you, and it is very easy to understand.
It is also very easy to handle exceptions, as they end up in the RunWorkerCompleted method, but make sure you read this: Unhandled exceptions in BackgroundWorker
I used WebClient but obviously you could use HttpWebRequest.GetResponse if you wanted.
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) => {
args.Result = new WebClient().DownloadString(settings.test_url);
};
worker.RunWorkerCompleted += (sender, e) => {
if (e.Error != null) {
connectivityLabel.Text = "Error: " + e.Error.Message;
} else {
connectivityLabel.Text = "Connectivity OK";
Log.d("result:" + e.Result);
}
};
connectivityLabel.Text = "Testing Connectivity";
worker.RunWorkerAsync();
If the file is really an old .xls, this works for me on python3 just using base open() and pandas:
df = pandas.read_csv(open(f, encoding = 'UTF-8'), sep='\t')
Note that the file I'm using is tab delimited. less or a text editor should be able to read .xls so that you can sniff out the delimiter.
I did not have a lot of luck with xlrd because of – I think – UTF-8 issues.
For me (also XAMPP on Windows 7), this is what worked:
<Directory "C:\projects\myfolder\htdocs">`
AllowOverride All
Require all granted
Options Indexes FollowSymLinks
</Directory>`
It is this line that would cause the 403:
Order allow,deny
In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).
Modernizr.js will remove the no-js
class.
This allows you to make CSS rules for .no-js something
to apply them only if Javascript is disabled.
Hadley Wickham
dplyr
packages is always a saver in case of data wrangling.
To add the desired division as a third variable I would use mutate()
d <- mutate(d, new = min / count2.freq)
Try it:
document.querySelector("input").addEventListener("keyup", function () {
this.value = this.value.replace(/\D/, "")
});
Step 1: Install update http://httpjunkie.com/2013/340/develop-mvc-5-with-asp-net-identity-in-visual-studio-2012/.
OK, so that gets you to be able to start from a blank ASP.NET MVC project, but a lot of people want the FULL INTERNET APPLICATION as shipped with Visual Studio 2013.
So I have a step 2: http://httpjunkie.com/2013/340/develop-mvc-5-with-asp-net-identity-in-visual-studio-2012/
If you follow that tutorial on my website I follow it up with a full install of Foundation 5 and a cool Hybrid OffCanvas/Top-Bar navigation.
public mySentences:Array<any> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
OR
public mySentences:Array<object> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
There aren't a lot of them because they would be in competition with JFreeChart, and it's awesome. You can get documentation and examples by downloading the developer's guide. There are also tons of free online tutorials if you search for them.
The below nodejs code scrapes popular Images from an Instagram Page. The function 'ScrapeInstagramPage' takes care of post ageing effect.
var request = require('parse5');
var request = require('request');
var rp = require('request-promise');
var $ = require('cheerio'); // Basically jQuery for node.js
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
function ScrapeInstagramPage (args) {
dout("ScrapeInstagramPage for username -> " + args.username);
var query_url = 'https://www.instagram.com/' + args.username + '/';
var cookieString = '';
var options = {
url: query_url,
method: 'GET',
headers: {
'x-requested-with' : 'XMLHttpRequest',
'accept-language' : 'en-US,en;q=0.8,pt;q=0.6,hi;q=0.4',
'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'referer' : 'https://www.instagram.com/dress_blouse_designer/',
'Cookie' : cookieString,
'Accept' : '*/*',
'Connection' : 'keep-alive',
'authority' : 'www.instagram.com'
}
};
function dout (msg) {
if (args.debug) {
console.log(msg);
}
}
function autoParse(body, response, resolveWithFullResponse) {
// FIXME: The content type string could contain additional values like the charset.
// Consider using the `content-type` library for a robust comparison.
if (response.headers['content-type'] === 'application/json') {
return JSON.parse(body);
} else if (response.headers['content-type'] === 'text/html') {
return $.load(body);
} else {
return body;
}
}
options.transform = autoParse;
rp(options)
.then(function (autoParsedBody) {
if (args.debug) {
console.log("Responce of 'Get first user page': ");
console.log(autoParsedBody);
console.log("Creating JSDOM from above Responce...");
}
const dom = new JSDOM(autoParsedBody.html(), { runScripts: "dangerously" });
if (args.debug) console.log(dom.window._sharedData); // full data doc form instagram for a page
var user = dom.window._sharedData.entry_data.ProfilePage[0].user;
if (args.debug) {
console.log(user); // page user
console.log(user.id); // user ID
console.log(user.full_name); // user full_name
console.log(user.username); // user username
console.log(user.followed_by.count); // user followed_by
console.log(user.profile_pic_url_hd); // user profile pic
console.log(autoParsedBody.html());
}
if (user.is_private) {
dout ("User account is PRIVATE");
} else {
dout ("User account is public");
GetPostsFromUser(user.id, 5000, undefined);
}
})
.catch(function (err) {
console.log( "ERROR: " + err );
});
var pop_posts = [];
function GetPostsFromUser (user_id, first, end_cursor) {
var end_cursor_str = "";
if (end_cursor != undefined) {
end_cursor_str = '&after=' + end_cursor;
}
options.url = 'https://www.instagram.com/graphql/query/?query_id=17880160963012870&id='
+ user_id + '&first=' + first + end_cursor_str;
rp(options)
.then(function (autoParsedBody) {
if (autoParsedBody.status === "ok") {
if (args.debug) console.log(autoParsedBody.data);
var posts = autoParsedBody.data.user.edge_owner_to_timeline_media;
// POSTS processing
if (posts.edges.length > 0) {
//console.log(posts.edges);
pop_posts = pop_posts.concat
(posts.edges.map(function(e) {
var d = new Date();
var now_seconds = d.getTime() / 1000;
var seconds_since_post = now_seconds - e.node.taken_at_timestamp;
//console.log("seconds_since_post: " + seconds_since_post);
var ageing = 10; // valuses (1-10]; big value means no ageing
var days_since_post = Math.floor(seconds_since_post/(24*60*60));
var df = (Math.log(ageing+days_since_post) / (Math.log(ageing)));
var likes_per_day = (e.node.edge_liked_by.count / df);
// console.log("likes: " + e.node.edge_liked_by.count);
//console.log("df: " + df);
//console.log("likes_per_day: " + likes_per_day);
//return (likes_per_day > 10 * 1000);
var obj = {};
obj.url = e.node.display_url;
obj.likes_per_day = likes_per_day;
obj.days_since_post = days_since_post;
obj.total_likes = e.node.edge_liked_by.count;
return obj;
}
));
pop_posts.sort(function (b,a) {
if (a.likes_per_day < b.likes_per_day)
return -1;
if (a.likes_per_day > b.likes_per_day)
return 1;
return 0;
});
//console.log(pop_posts);
pop_posts.forEach(function (obj) {
console.log(obj.url);
});
}
if (posts.page_info.has_next_page) {
GetPostsFromUser(user_id, first, posts.page_info.end_cursor);
}
} else {
console.log( "ERROR: Posts AJAX call not returned good..." );
}
})
.catch(function (err) {
console.log( "ERROR: " + err );
});
}
}
ScrapeInstagramPage ({username : "dress_blouse_designer", debug : false});
Try it here
Example: For given a URL 'https://www.instagram.com/dress_blouse_designer/' one may call function
ScrapeInstagramPage ({username : "dress_blouse_designer", debug : false});
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
Using one while loop:
In [1]: start = 1
...:
...: while True:
...: if start != 1:
...: do_run = raw_input('Restart? y/n:')
...: if do_run == 'y':
...: pass
...: elif do_run == 'n':
...: break
...: else:
...: print 'Invalid input'
...: continue
...:
...: print 'Doing stuff!!!'
...:
...: if start == 1:
...: start = 0
...:
Doing stuff!!!
Restart? y/n:y
Doing stuff!!!
Restart? y/n:f
Invalid input
Restart? y/n:n
In [2]:
Referred link has correct answer, but there are written some libraries to make your work easy.
So don't write all code again, just use any of these library and get your work done in little time.
Assuming you merely want to know the size of an array whose type you know (int) but whose size, obviously, you don't know, it is suitable to verify whether the array is empty, otherwise you will end up with a division by zero (causing a Float point exception
).
int array_size(int array[]) {
if(sizeof(array) == 0) {
return 0;
}
return sizeof(array)/sizeof(array[0]);
}
The list of encodings that node supports natively is rather short:
If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:
Use iconv-lite to recode files:
var iconvlite = require('iconv-lite');
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
return iconvlite.decode(content, encoding);
}
Alternatively, use iconv:
var Iconv = require('iconv').Iconv;
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
var iconv = new Iconv(encoding, 'UTF-8');
var buffer = iconv.convert(content);
return buffer.toString('utf8');
}
Another important module that needs reconfiguring before PUT and DELETE will work is the options verb
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="OPTIONSVerbHandler" />
<remove name="WebDAV" />
<add name="OPTIONSVerbHandler" path="*" verb="*" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="Script" />
</handlers>
Also see this post: https://stackoverflow.com/a/22018750/9376681
Why parentheses?
Here is the quote from the book programming in scala.
Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.
Here are a few examples how to pull certain element (first elem in this case) using functional programming style.
// Create a multdimension Array
scala> val a = Array.ofDim[String](2, 3)
a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
scala> a(0) = Array("1","2","3")
scala> a(1) = Array("4", "5", "6")
scala> a
Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))
// 1. paratheses
scala> a.map(_(0))
Array[String] = Array(1, 4)
// 2. apply
scala> a.map(_.apply(0))
Array[String] = Array(1, 4)
// 3. function literal
scala> a.map(a => a(0))
Array[String] = Array(1, 4)
// 4. lift
scala> a.map(_.lift(0))
Array[Option[String]] = Array(Some(1), Some(4))
// 5. head or last
scala> a.map(_.head)
Array[String] = Array(1, 4)
I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)
see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm
You can move from one scene to another programmatically using below code :
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let objSomeViewController = storyBoard.instantiateViewControllerWithIdentifier(“storyboardID”) as! SomeViewController
// If you want to push to new ViewController then use this
self.navigationController?.pushViewController(objSomeViewController, animated: true)
// ---- OR ----
// If you want to present the new ViewController then use this
self.presentViewController(objSomeViewController, animated:true, completion:nil)
Here storyBoardID is value that you set to scene using Interface Builder. This is shown below :
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
How about placing a touchable component around/beside the TextInput
?
var INPUTREF = 'MyTextInput';
class TestKb extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={{ flex: 1, flexDirection: 'column', backgroundColor: 'blue' }}>
<View>
<TextInput ref={'MyTextInput'}
style={{
height: 40,
borderWidth: 1,
backgroundColor: 'grey'
}} ></TextInput>
</View>
<TouchableWithoutFeedback onPress={() => this.refs[INPUTREF].blur()}>
<View
style={{
flex: 1,
flexDirection: 'column',
backgroundColor: 'green'
}}
/>
</TouchableWithoutFeedback>
</View>
)
}
}
In addition with skaffman answer, simple if-else you can use ternary operator like this
<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>
The SQLiteAssetHelper
library makes this task really simple.
It's easy to add as a gradle dependency (but a Jar is also available for Ant/Eclipse), and together with the documentation it can be found at:
https://github.com/jgilfelt/android-sqlite-asset-helper
Note: This project is no longer maintained as stated on above Github link.
As explained in documentation:
Add the dependency to your module's gradle build file:
dependencies {
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
}
Copy the database into the assets directory, in a subdirectory called assets/databases
. For instance:
assets/databases/my_database.db
(Optionally, you may compress the database in a zip file such as assets/databases/my_database.zip
. This isn't needed, since the APK is compressed as a whole already.)
Create a class, for example:
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "my_database.db";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
The easiest and cleanest way, without any hacks, is to just to indent the ul
(or ol
), like so:
ol {
padding-left: 40px; // Or whatever padding your font size needs
}
This gives the same result as the accepted answer: https://jsfiddle.net/5wxf2ayu/
Screenshot:
One option is, you can wrap the submit
button with a form
Something like this:
<form action="{% url path.to.request_page %}" method="POST">
<input id="submit" type="button" value="Click" />
</form>
(remove the onclick
and method
)
If you want to load a specific part of the page, without page reload - you can do
<input id="submit" type="button" value="Click" data_url/>
and on a submit
listener
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
success: function(data){ $('#target').html(data) }
});
});
});
I try to
npm cache clean
But npm said newer version on npm (> 5) has self healing Mechanism and every thing i need to do for checking npm is use verify
npm cache verify
npm message :
The npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid.
If you want to make sure everything is consistent, use 'npm cache verify' instead.
but for forcing npm use this:
npm cache clean --force
As stated in 1.7.12 Release Notes, you may use
$ git rebase -i --root
You need to change source to viewmodel object:
myBinding.Source = viewModelObject;
A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.
using System;
using System.Management;
namespace Utils
{
class NetworkManagement
{
/// <summary>
/// Returns a list of all the network interface class names that are currently enabled in the system
/// </summary>
/// <returns>list of nic names</returns>
public static string[] GetAllNicDescriptions()
{
List<string> nics = new List<string>();
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"])
.Select(x=> new NetworkAdapterConfiguration(x)))
{
nics.Add(config.Description);
}
}
}
return nics.ToArray();
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)
{
using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
{
foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
{
// NAC class was generated by opening a developer console and entering:
// mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs
// See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/
using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))
{
if (config.SetDNSServerSearchOrder(dnsServers) == 0)
{
RestartNetworkAdapter(nicDescription);
}
}
}
}
}
return false;
}
/// <summary>
/// Restarts a given Network adapter
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
public static void RestartNetworkAdapter(string nicDescription)
{
using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
{
using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
{
foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)mo["Description"] == nicDescription))
{
// NA class was generated by opening dev console and entering
// mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))
{
adapter.Disable();
adapter.Enable();
Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect
return;
}
}
}
}
}
/// <summary>
/// Get's the DNS Server of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
public static string[] GetNameservers(string nicDescription)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
.Select( x => new NetworkAdapterConfiguration(x)))
{
return config.DNSServerSearchOrder;
}
}
}
return null;
}
/// <summary>
/// Set's a new IP Address and it's Submask of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
/// <param name="ipAddresses">The IP Address</param>
/// <param name="subnetMask">The Submask IP Address</param>
/// <param name="gateway">The gateway.</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
.Select( x=> new NetworkAdapterConfiguration(x)))
{
// Set the new IP and subnet masks if needed
config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask));
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
config.SetGateways(new[] {gateway}, new ushort[] {1});
}
}
}
}
}
}
}
Full source: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs
One way to use pointers over variables is to eliminate duplicate memory required. For example, if you have some large complex object, you can use a pointer to point to that variable for each reference you make. With a variable, you need to duplicate the memory for each copy.
MS doesn't support LIMIT in t-sql. Most of the times i just get MAX(ID) and then subtract.
select * from ORDERS where ID >(select MAX(ID)-10 from ORDERS)
This will return less than 10 records when ID is not sequential.
you need to parse your xml with jquery json parse...i.e
var parsed_json = $.parseJSON(xml);
You can use the jobs -l
command to get to a particular jobL
^Z
[1]+ Stopped guard
my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18 guard
In this case, 46841 is the PID.
From help jobs
:
-l Report the process group ID and working directory of the jobs.
jobs -p
is another option which shows just the PIDs.
To the response of James I will only change the sorting function to make it more universal. This way it will sort text alphabetical and numbers like numbers.
if( $.text([a]) == $.text([b]) )
return 0;
if(isNaN($.text([a])) && isNaN($.text([b]))){
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}
else{
return parseInt($.text([a])) > parseInt($.text([b])) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}
Liam's link looks great, but also check out pandas.Timedelta
- looks like it plays nicely with NumPy's and Python's time deltas.
https://pandas.pydata.org/pandas-docs/stable/timedeltas.html
pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)
Wouldn't a better alternative be to just add a third button ("neither") that will give the same result as none selected?
There was an answer here: Secure distribution of NodeJS applications. Raynos said: V8 allows you to pre-compile JavaScript.
Someone with a requirement where they have to read from bits, lets say you have to read from only 3 bits but you need signed integer then use following:
data is of type: java.util.BitSet
new BigInteger(data.toByteArray).intValue() << 32 - 3 >> 32 - 3
The magic number 3
can be replaced with the number of bits (not bytes) you are using.
Use one of these threee variants:
SOME_PATH="/mnt/someProject/some path"
SOME_PATH='/mnt/someProject/some path'
SOME_PATH=/mnt/someProject/some\ path
Use ViewChild with #localvariable as shown here,
<textarea #someVar id="tasknote"
name="tasknote"
[(ngModel)]="taskNote"
placeholder="{{ notePlaceholder }}"
style="background-color: pink"
(blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }}
</textarea>
In component,
import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
ngAfterViewInit()
{
this.el.nativeElement.focus();
}
import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
constructor(private rd: Renderer) {}
ngAfterViewInit() {
this.rd.invokeElementMethod(this.el.nativeElement,'focus');
}
Please note from Angular v4.0.0-rc.3 (2017-03-10) few things have been changed.
Since Angular team will deprecate invokeElementMethod
, above code no longer can be used.
BREAKING CHANGES
since 4.0 rc.1:
rename RendererV2 to Renderer2
rename RendererTypeV2 to RendererType2
rename RendererFactoryV2 to RendererFactory2
import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
constructor(private rd: Renderer2) {}
ngAfterViewInit() {
console.log(this.rd);
this.el.nativeElement.focus(); //<<<=====same as oldest way
}
console.log(this.rd)
will give you following methods and you can see now invokeElementMethod
is not there. Attaching img as yet it is not documented.
NOTE: You can use following methods of Rendere2
with/without ViewChild variable to do so many things.
You have to add Imports System.Runtime.InteropServices
to the top of your source file.
Alternatively, you can fully qualify attribute name:
<System.Runtime.InteropService.DllImport("user32.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _
There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.
IF you want to install Maven in Eclipse(Java EE) Indigo Then follow these Steps :
Eclipse -> Help -> Install New Software.
Type " http://download.eclipse.org/releases/indigo/ " & Hit Enter.
Expand " Collaboration " tag.
Select Maven plugin from there.
Click on next .
Accept the agreement & click finish.
After installing the maven it will ask for restarting the Eclipse,So restart the eclipse again to see the changes.
Use display:none/block
, instead of visibility
, and add a margin-top/bottom
for the space you want to see ONLY when the inputs are shown
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
} else {
document.getElementById('ifYes').style.display = 'none';
}
}
and your HTML line for the ifYes
tag
<div id="ifYes" style="display:none;margin-top:3%;">If yes, explain:
Just load the image in a hidden <img>
tag (style = "display none"
), listen to the load event firing with jQuery, create a new Image()
with JavaScript, set the source to the invisible image, and get the size like above.
You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(
If you don't wrap the text node in a <span>
like @Jacob suggests, you could instead give the surrounding element padding
as opposed to margin
:
<p id="theParagraph">The text node!</p>
p#theParagraph
{
border: 1px solid red;
padding-bottom: 10px;
}
You can use below code for multiple select:
<select asp-for="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
You can also use:
<select id="EmployeeId" name="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
If you remove the href
attribute the anchor will be not focusable and it will look like simple text, but it will still be clickable.
The inflect package can do this.
https://pypi.python.org/pypi/inflect
$ pip install inflect
and then:
>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine
@ikis, firstly as @Devolus said these are not multiple aruements passed to print()
. Indeed all these arguments passed get
concatenated to form a single String. So print()
does not teakes multiple arguements (a. k. a. var-args). Now the concept that remains to discuss is how print()
prints any type of the arguement passed
to it.
To explain this - toString()
is the secret:
System
is a class, with a static field out
, of type PrintStream
. So you're calling the println(Object x)
method of a
PrintStream
.
It is implemented like this:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
As wee see, it's calling the String.valueOf(Object) method. This is implemented as follows:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And here you see, that toString()
is called.
So whatever is returned from the toString()
method of that class, same gets printed.
And as we know the toString()
is in Object
class and thus inherits a default iplementation from Object.
ex: Remember when we have a class whose toString()
we override and then we pass that ref variable to print
, what do you see printed? - It's what we return from the toString()
.
Have a look at the class
org.joda.time.DateTime
This allows you to do things like:
old = new DateTime();
new = old.plusSeconds(500000);
System.out.println("Hours: " + (new.Hours() - old.Hours()));
However, your solution probably can be simpler:
You need to work out how many seconds in a day, divide your input by the result to get the days, and subtract it from the input to keep the remainder. You then need to work out how many hours in the remainder, followed by the minutes, and the final remainder is the seconds.
This is the analysis done for you, now you can focus on the code.
You need to ask what s/he means by "no hard coding", generally it means pass parameters, rather than fixing the input values. There are many ways to do this, depending on how you run your code. Properties are a common way in java.
You're almost here, you're just missing a few things:
PUT /test
{
"mappings": {
"type_name": { <--- add the type name
"properties": { <--- enclose all field definitions in "properties"
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4,": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
}
},
"settings": {
...
}
}
UPDATE
If your index already exists, you can also modify your mappings like this:
PUT test/_mapping/type_name
{
"properties": { <--- enclose all field definitions in "properties"
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4,": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
}
UPDATE:
As of ES 7, mapping types have been removed. You can read more details here
Simply change the text
property
TextField(
controller: txt,
),
RaisedButton(onPressed: () {
txt.text = "My Stringt";
}),
while txt
is just a TextEditingController
var txt = TextEditingController();
Yes by using source filter you can accomplish this, here is the doc source-filtering
Example Request
POST index_name/_search
{
"_source":["field1","filed2".....]
}
Output will be
{
"took": 57,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "index_name",
"_type": "index1",
"_id": "1",
"_score": 1,
"_source": {
"field1": "a",
"field2": "b"
},
{
"field1": "c",
"field2": "d"
},....
}
]
}
}
If someone is looking for analogy , this answer might be helpful.
WSDL is like 'SHOW TABLE STATUS' command in mysql. It defines all the elements(request type, response type, format of URL to hit request,etc.,) which should be part of XML. By definition I mean: 1) Names of request or response 2) What should be treated as input , what should be treated as output.
XSD is like DESCRIBE command in mysql. It tells what all variables and their types, a request and response contains.
Try this:
CREATE TABLE `test_table` (
`id` INT( 10 ) NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT 0,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE = INNODB;