It worked for me.
Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.
You can't have this discussion without bringing up type systems.
The main features of functional programming include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.
That's because these features don't address the same issues that OOP does... they are alternatives to imperative programming. The FP answer to OOP lies in the type systems of ML and Haskell... specifically sum types, abstract data types, ML modules, and Haskell typeclasses.
But of course there are still design patterns which are not solved by FP languages. What is the FP equivalent of a singleton? (Disregarding for a moment that singletons are generally a terrible pattern to use)
The first thing typeclasses do is eliminate the need for singletons.
You could go through the list of 23 and eliminate more, but I don't have time to right now.
State in programming simply means remembering things.
Example
var a = 0;
a = a + 1; // => 1
a = a + 1; // => 2
a = a + 1; // => 3
In the case above, state is stored in the variable "a". We follow by adding 1 to "a" several times. We can only do that because we are able to "remember" the value. The state holder, "a", holds that value in memory.
Often, in programming languages, you want to keep track of things, remember information and access it at a later time.
This, in other languages, is commonly accomplished through the use of classes. A class, just like variables, keeps track of its state. And instances of that class, in turns, also have state within them. State simply means information that you can store and retrieve later.
Example
class Bread {
constructor (weight) {
this.weight = weight;
}
render () {
return `My weight is ${this.weight}!`;
}
}
How can we access "weight" from within the "render" method? Well, thanks to state. Each instance of the class Bread can render its own weight by reading it from the "state", a place in memory where we could store that information.
Now, JavaScript is a very unique language which historically does not have classes (it now does, but under the hood there's only functions and variables) so Closures provide a way for JavaScript to remember things and access them later.
Example
var n = 0;
var count = function () {
n = n + 1;
return n;
};
count(); // # 1
count(); // # 2
count(); // # 3
The example above achieved the goal of "keeping state" with a variable. This is great! However, this has the disadvantage that the variable (the "state" holder) is now exposed. We can do better. We can use Closures.
Example
var countGenerator = function () {
var n = 0;
var count = function () {
n = n + 1;
return n;
};
return count;
};
var count = countGenerator();
count(); // # 1
count(); // # 2
count(); // # 3
Now our "count" function can count. It is only able to do so because it can "hold" state. The state in this case is the variable "n". This variable is now closed. Closed in time and space. In time because you won't ever be able to recover it, change it, assign it a value or interact directly with it. In space because it's geographically nested within the "countGenerator" function.
Why is this fantastic? Because without involving any other sophisticated and complicated tool (e.g. classes, methods, instances, etc) we are able to 1. conceal 2. control from a distance
We conceal the state, the variable "n", which makes it a private variable! We also have created an API that can control this variable in a pre-defined way. In particular, we can call the API like so "count()" and that adds 1 to "n" from a "distance". In no way, shape or form anyone will ever be able to access "n" except through the API.
Closures are a big part of why this is.
If you understand partial
you're halfway there. The idea of partial
is to preapply arguments to a function and give back a new function that wants only the remaining arguments. When this new function is called it includes the preloaded arguments along with whatever arguments were supplied to it.
In Clojure +
is a function but to make things starkly clear:
(defn add [a b] (+ a b))
You may be aware that the inc
function simply adds 1 to whatever number it's passed.
(inc 7) # => 8
Let's build it ourselves using partial
:
(def inc (partial add 1))
Here we return another function that has 1 loaded into the first argument of add
. As add
takes two arguments the new inc
function wants only the b
argument -- not 2 arguments as before since 1 has already been partially applied. Thus partial
is a tool from which to create new functions with default values presupplied. That is why in a functional language functions often order arguments from general to specific. This makes it easier to reuse such functions from which to construct other functions.
Now imagine if the language were smart enough to understand introspectively that add
wanted two arguments. When we passed it one argument, rather than balking, what if the function partially applied the argument we passed it on our behalf understanding that we probably meant to provide the other argument later? We could then define inc
without explicitly using partial
.
(def inc (add 1)) #partial is implied
This is the way some languages behave. It is exceptionally useful when one wishes to compose functions into larger transformations. This would lead one to transducers.
Prefer the MsBuild "Copy" task in an AfterBuild target over a post-build event.
Append this Target into your project file and remove the PostBuildEvent.
<Target Name="AfterBuild">
<Copy SourceFiles="C:\Users\scogan\Documents\Visual Studio 2012\Projects\Organizr\Server\bin\Debug\Organizr.Services.*"
DestinationFolder="C:\inetpub\wwwroot\AppServer\bin\"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
</Target>
I've dumped nodemon
and ts-node
in favor of a much better alternative, ts-node-dev
https://github.com/whitecolor/ts-node-dev
Just run ts-node-dev src/index.ts
The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.
Example:
<div class="editor-field">
<%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
<%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>
Here's a more specific example:
I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).
I made the following model:
namespace DeleteMeQuestion.Models
{
public class QuizModel
{
public int ParentQuestionId { get; set; }
public int QuestionId { get; set; }
public string QuestionDisplayText { get; set; }
public List<Response> Responses { get; set; }
[Range(1,999, ErrorMessage = "Please choose a response.")]
public int SelectedResponse { get; set; }
}
public class Response
{
public int ResponseId { get; set; }
public int ChildQuestionId { get; set; }
public string ResponseDisplayText { get; set; }
}
}
There's a simple range validator in the model, just for fun. Next up, I made the following controller:
namespace DeleteMeQuestion.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index(int? id)
{
// TODO: get question to show based on method parameter
var model = GetModel(id);
return View(model);
}
[HttpPost]
public ActionResult Index(int? id, QuizModel model)
{
if (!ModelState.IsValid)
{
var freshModel = GetModel(id);
return View(freshModel);
}
// TODO: save selected answer in database
// TODO: get next question based on selected answer (hard coded to 999 for now)
var nextQuestionId = 999;
return RedirectToAction("Index", "Home", new {id = nextQuestionId});
}
private QuizModel GetModel(int? questionId)
{
// just a stub, in lieu of a database
var model = new QuizModel
{
QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
QuestionId = 1,
Responses = new List<Response>
{
new Response
{
ChildQuestionId = 2,
ResponseId = 1,
ResponseDisplayText = "Red"
},
new Response
{
ChildQuestionId = 3,
ResponseId = 2,
ResponseDisplayText = "Blue"
},
new Response
{
ChildQuestionId = 4,
ResponseId = 3,
ResponseDisplayText = "Green"
},
}
};
return model;
}
}
}
Finally, I made the following view that makes use of the model:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<div>
<h1><%: Model.QuestionDisplayText %></h1>
<div>
<ul>
<% foreach (var item in Model.Responses) { %>
<li>
<%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
<label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
</li>
<% } %>
</ul>
<%= Html.ValidationMessageFor(m => m.SelectedResponse) %>
</div>
<input type="submit" value="Submit" />
<% } %>
</asp:Content>
As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.
This gives you the radio buttons with the same name attribute, but different ID attributes.
As an alternative to $dollarsign
notation, use a within
block:
breast <- within(breast, {
class <- as.numeric(as.character(class))
})
Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class)
will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.
If you aren't sure how to run a rake task, first find out first what tasks you have and it will also list the commands to run the tasks.
Run rake --tasks
on the terminal.
It will list the tasks like the following:
rake gobble:dev:prime
rake gobble:dev:reset_number_of_kits
rake gobble:dev:scrub_prod_data
You can then run your task with: rake gobble:dev:prime
as listed.
Forking creates an entirely new repository from existing repository (simply doing git clone on gitHub/bitbucket)
Forks are best used: when the intent of the ‘split’ is to create a logically independent project, which may never reunite with its parent.
Branch strategy creates a new branch over the existing/working repository
Branches are best used: when they are created as temporary places to work through a feature, with the intent to merge the branch with the origin.
More Specific :- In open source projects it is the owner of the repository who decides who can push to the repository. However, the idea of open source is that everybody can contribute to the project.
This problem is solved by forks: any time a developer wants to change something in an open source project, they don’t clone the official repository directly. Instead, they fork it to create a copy. When the work is finished, they make a pull request so that the owner of the repository can review the changes and decide whether to merge them to his project.
At its core forking is similar to feature branching, but instead of creating branches a fork of the repository is made, and instead of doing a merge request you create a pull request.
The below links provide the difference in a well-explained manner :
https://blog.gitprime.com/the-definitive-guide-to-forks-and-branches-in-git/
Look for an installation subdirectory, likely named eclipse. Under that subdirectory, if you see files like eclipse.ini, icon.xpm and subdirectories like plugins and dropins, remove the subdirectory parent (the one named eclipse).
That will remove your installation except for anything you've set up yourself (like workspaces, projects, etc.).
Hope this helps.
Finaly I got it!!!
import csv
def select_index(index):
csv_file = open('oscar_age_female.csv', 'r')
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
l = line['Index']
if l == index:
print(line[' "Name"'])
select_index('11')
"Bette Davis"
#include <tr1/unordered_map>
will get you next-standard C++ unique hash container. Usage:
std::tr1::unordered_map<std::string,int> my_map;
my_map["answer"] = 42;
printf( "The answer to life and everything is: %d\n", my_map["answer"] );
I've been using Oracle SQL Developer since the Microsoft software for SQL Server is not currently available on Mac OS X. It works wonders. I would also recommend RazorSQL or SQLGrinder.
I really like:
[date] = CONVERT(VARCHAR(10), GETDATE(), 120)
The 120
format code will coerce the date into the ISO 8601 standard:
'YYYY-MM-DD' or '2017-01-09'
Super easy to use in dplyr (R
) and pandas (Python
)!
Since version 5.7 TCPDF includes support for CSS borders. Margins, padding and float are not yet supported. Check the TCPDF website at http://www.tcpdf.org and consult the official forum for further information.
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
string directoryPath = Path.GetDirectoryName(destinationFileName);
// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
File.Copy(sourceFileName, destinationFileName);
I used start /b for this instead of just start and it ran without a window for each command, so there was no waiting.
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
input[type=text] { text-align:right }
_x000D_
<form>_x000D_
<input type="text" name="name" value="">_x000D_
</form>
_x000D_
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
I finally found the reason,its becuse of the library can't find a CA bundle on your system. PHP >= v5.6 automatically sets verify_peer to true by default. However, not all systems have a known CA bundle on disk .
You can try one of these procedures:
1.If you have a CA file on your system, set openssl.cafile
or curl.cainfo
in your php.ini
to the path of your CA file.
2.Manually specify your SSL CA file location
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($cHandler, CURLOPT_CAINFO, $path-of-your-ca-file);
3.disabled verify_peer
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
There's also the iScroll project which allows you to style the scrollbars plus get it to work with touch devices. http://cubiq.org/iscroll-4
ByteArrayInputStream
extends InputStream
:
InputStream myInputStream = new ByteArrayInputStream(myBytes);
If the passwords are more or less "random" you are out of luck, you will not be able to get a significant reduction in size.
But: Why do you need to compress the passwords? Maybe what you need is not a compression, but some sort of hash value? If you just need to check if a name matches a given password, you don't need do save the password, but can save the hash of a password. To check if a typed in password matches a given name, you can build the hash value the same way and compare it to the saved hash. As a hash (Object.hashCode()) is an int you will be able to store all 20 password-hashes in 80 bytes).
Solved :
After trying everything else, this solves my issue.
After updating to Xcode 8.3.2 i had the same error with a Cordova project. I needed to upgrade Cordova (v7.0.0) and the iOS platform (v4.4.0) for code signing to work.
Yes, there are no classes built into .NET to edit query strings. You'll have to either use Regex or some other method of altering the string itself.
Requires a little javascript.
But, your div
would be clickable.
<div onclick="location.href='http://www.example.com';" style="cursor:pointer;"></div>
As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)
| YOUR_DT | SQL2008 |
|-----------------------------|---------------------|
| 2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
| 2013-08-29 13:55:48 blah | (null) |
| 2013-08-29 13:55:48 rubbish | (null) |
SELECT
[Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
THEN convert(datetime,[Your_Dt])
ELSE NULL
END
) AS ca1 (dt_converted)
;
Notes:
You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'
For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison
declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'
select
FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008
| SQL2012 | SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 |
I always use Import/Export Feature which seems to be the easiest one among all.
Step 1:
Get the backup from the azure instance as follows, Select the database ? Right click ? Tasks ? Export Data Tier Application.
Step 2: Give a specific name for the backup file and save it in your desired location
Step 3: That's it you have taken a backup of the database from sql instance to your local. Lets restore it to the local. Copy the backed up database to your C drive. Now open the PowerShell with administrator rights and navigate to C drive
Step 4: Lets download the powershell script to remove the master keyRemoveMasterKey.ps1 have the script on the same drive in this case its C.
Step 5 : Run the script as follows, .\RemoveMasterKey.ps1 -bacpacPath "C:\identity.bacpac"
That's it, now you can restore it on MSSQL 2017 in your local environment.
Step 6: Connect to your local server, and click Databases ? Import-Data-Tier-Application
Step 7 : Give a name for your database to restore.
Now you will see everything in green!
Read my blog with diagrams.
My solution...
//Fix modal mobile Boostrap 3
function Show(id){
//Fix CSS
$(".modal-footer").css({"padding":"19px 20px 20px","margin-top":"15px","text-align":"right","border-top":"1px solid #e5e5e5"});
$(".modal-body").css("overflow-y","auto");
//Fix .modal-body height
$('#'+id).on('shown.bs.modal',function(){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").css("height","auto");
h1=$("#"+id+">.modal-dialog").height();
h2=$(window).height();
h3=$("#"+id+">.modal-dialog>.modal-content>.modal-body").height();
h4=h2-(h1-h3);
if($(window).width()>=768){
if(h1>h2){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
}
$("#"+id+">.modal-dialog").css("margin","30px auto");
$("#"+id+">.modal-dialog>.modal-content").css("border","1px solid rgba(0,0,0,0.2)");
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",6);
if($("#"+id+">.modal-dialog").height()+30>h2){
$("#"+id+">.modal-dialog").css("margin-top","0px");
$("#"+id+">.modal-dialog").css("margin-bottom","0px");
}
}
else{
//Fix full-screen in mobiles
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
$("#"+id+">.modal-dialog").css("margin",0);
$("#"+id+">.modal-dialog>.modal-content").css("border",0);
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",0);
}
//Aply changes on screen resize (example: mobile orientation)
window.onresize=function(){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").css("height","auto");
h1=$("#"+id+">.modal-dialog").height();
h2=$(window).height();
h3=$("#"+id+">.modal-dialog>.modal-content>.modal-body").height();
h4=h2-(h1-h3);
if($(window).width()>=768){
if(h1>h2){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
}
$("#"+id+">.modal-dialog").css("margin","30px auto");
$("#"+id+">.modal-dialog>.modal-content").css("border","1px solid rgba(0,0,0,0.2)");
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",6);
if($("#"+id+">.modal-dialog").height()+30>h2){
$("#"+id+">.modal-dialog").css("margin-top","0px");
$("#"+id+">.modal-dialog").css("margin-bottom","0px");
}
}
else{
//Fix full-screen in mobiles
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
$("#"+id+">.modal-dialog").css("margin",0);
$("#"+id+">.modal-dialog>.modal-content").css("border",0);
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",0);
}
};
});
//Free event listener
$('#'+id).on('hide.bs.modal',function(){
window.onresize=function(){};
});
//Mobile haven't scrollbar, so this is touch event scrollbar implementation
var y1=0;
var y2=0;
var div=$("#"+id+">.modal-dialog>.modal-content>.modal-body")[0];
div.addEventListener("touchstart",function(event){
y1=event.touches[0].clientY;
});
div.addEventListener("touchmove",function(event){
event.preventDefault();
y2=event.touches[0].clientY;
var limite=div.scrollHeight-div.clientHeight;
var diff=div.scrollTop+y1-y2;
if(diff<0)diff=0;
if(diff>limite)diff=limite;
div.scrollTop=diff;
y1=y2;
});
//Fix position modal, scroll to top.
$('html, body').scrollTop(0);
//Show
$("#"+id).modal('show');
}
For compatibility sake it's better to stick to fill_parent, i.e, when supporting below API 8 devices. But if your app targets API 8 and upwards, you should use match_parent instead.
You can check if the constant's already defined using:
<?php
if (!defined('MYCONST'))
define('MYCONST', 'Weeha!');
?>
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
Add keyword static
to class declaration:
// this is a non-generic static class
public static class LinqHelper
{
}
You can use the Time.String()
method to convert a time.Time
to a string
. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST"
.
If you need other custom format, you can use Time.Format()
. For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss
use the format string "2006-01-02 15:04:05"
.
Example:
t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))
Output (try it on the Go Playground):
2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00
Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.
Also note that using Time.Format()
, as the layout string
you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format()
:
Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.
A simple example of O(1)
might be return 23;
-- whatever the input, this will return in a fixed, finite time.
A typical example of O(N log N)
would be sorting an input array with a good algorithm (e.g. mergesort).
A typical example if O(log N)
would be looking up a value in a sorted input array by bisection.
Wait until Powershell is executed and get the result in vbs
This is an improved version of the Omegastripes code Hide command prompt window when using Exec()
Splits the confused responses from cmd.exe into an array instead of putting everything into a hard-to-parse string.
In addition, if an error occurs during the execution of cmd.exe, a message about its occurrence will become known in vbs.
Option Explicit
Sub RunCScriptHidden()
strSignature = Left(CreateObject("Scriptlet.TypeLib").Guid, 38)
GetObject("new:{C08AFD90-F2A1-11D1-8455-00A0C91F3880}").putProperty strSignature, Me
objShell.Run ("""" & Replace(LCase(WScript.FullName), "wscript", "cscript") & """ //nologo """ & WScript.ScriptFullName & """ ""/signature:" & strSignature & """"), 0, True
End Sub
Sub WshShellExecCmd()
For Each objWnd In CreateObject("Shell.Application").Windows
If IsObject(objWnd.getProperty(WScript.Arguments.Named("signature"))) Then Exit For
Next
Set objParent = objWnd.getProperty(WScript.Arguments.Named("signature"))
objWnd.Quit
'objParent.strRes = CreateObject("WScript.Shell").Exec(objParent.strCmd).StdOut.ReadAll() 'simple solution
Set exec = CreateObject("WScript.Shell").Exec(objParent.strCmd)
While exec.Status = WshRunning
WScript.Sleep 20
Wend
Dim err
If exec.ExitCode = WshFailed Then
err = exec.StdErr.ReadAll
Else
output = Split(exec.StdOut.ReadAll,Chr(10))
End If
If err="" Then
objParent.strRes = output(UBound(output)-1) 'array of results, you can: output(0) Join(output) - Usually needed is the last
Else
objParent.wowError = err
End If
WScript.Quit
End Sub
Const WshRunning = 0,WshFailed = 1:Dim i,name,objShell
Dim strCmd, strRes, objWnd, objParent, strSignature, wowError, output, exec
Set objShell = WScript.CreateObject("WScript.Shell"):wowError=False
strCmd = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass Write-Host Hello-World."
If WScript.Arguments.Named.Exists("signature") Then WshShellExecCmd
RunCScriptHidden
If wowError=False Then
objShell.popup(strRes)
Else
objShell.popup("Error=" & wowError)
End If
Java 8 provides the option of using streams which can be used to sort int[] array
as:
int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2
As mentioned in doc for parallelSort
:
The sorting algorithm is a parallel sort-merge that breaks the array into sub-arrays that are themselves sorted and then merged. When the sub-array length reaches a minimum granularity, the sub-array is sorted using the appropriate Arrays.sort method. If the length of the specified array is less than the minimum granularity, then it is sorted using the appropriate Arrays.sort method. The algorithm requires a working space no greater than the size of the original array. The ForkJoin common pool is used to execute any parallel tasks.
So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort
simply calls sequential sort algorithm.
Just in case we want to reverse sort the integer array we can make use of comparator as:
int[] reverseSorted = IntStream.of(array).boxed()
.sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting.
int strLength = 0;
NSString *urlStr = @"http://www";
NSLog(@" urlStr : %@", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@":" withString:@"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
Another one line command I used is:
[ -e file ] && rm file
Unfortunately, no. If you were running the server in default config, go get your backups (you have backups, right?) - generally, a database doesn't keep previous versions of your data, or a revision of changes: only the current state.
(Alternately, if you have deleted the data through a custom frontend, it is quite possible that the frontend doesn't actually issue a DELETE: many tables have a is_deleted
field or similar, and this is simply toggled by the frontend. Note that this is a "soft delete" implemented in the frontend app - the data is not actually deleted in such cases; if you actually issued a DELETE
, TRUNCATE
or a similar SQL command, this is not applicable.)
Following up on farktronix's suggestion, we have been using Jira ticket numbers for similar in mercurial, and I'm planning to continue using them for git branches. But I think the ticket number itself is probably unique enough. While it might be helpful to have a descriptive word in the branch name as farktronix noted, if you are switching between branches often enough, you probably want less to type. Then if you need to know the branch name, look in Jira for the associated keywords in the ticket if you don't know it. In addition, you should include the ticket number in each comment.
If your branch represents a version, it appears that the common convention is to use x.x.x (example: "1.0.0") format for branch names and vx.x.x (example "v1.0.0") for tag names (to avoid conflict). See also: is-there-an-standard-naming-convention-for-git-tags
You can write like below. Check out the syntax guidelines in this thread
AClass[] array;
...
array = new AClass[]{object1, object2};
If you find arrays annoying better use ArrayList.
<Directory /uploads>
Options +Indexes
</Directory>
I am working with a Python code for a REST API, so this is for those who are working on similar projects.
I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I'm able to refer to the nested dictionary keys right away, like this:
datapoint_1 = json1_data['datapoints']['datapoint_1']
where datapoint_1 is inside the datapoints dictionary.
Check out this sample: http://jsfiddle.net/Epgvc/1/
I just floated the title to the left and added a clear:both
div to the bottom..
To find a div
of a certain class that contains a span
at any depth containing certain text, try:
//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')]
That said, this solution looks extremely fragile. If the table happens to contain a span
with the text you're looking for, the div
containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.
array.length
will tell you how many elements are in an array
String formatting using %
is a great way to handle this. Here are some examples.
The formatting code '%s'
converts '12345'
to a string, but it's already a string.
>>> '%s' % '12345'
'12345'
'%.3s'
specifies to use only the first three characters.
>>> '%.3s' % '12345'
'123'
'%.7s'
says to use the first seven characters, but there are only five. No problem.
>>> '%.7s' % '12345'
'12345'
'%7s'
uses up to seven characters, filling missing characters with spaces on the left.
>>> '%7s' % '12345'
' 12345'
'%-7s'
is the same thing, except filling missing characters on the right.
>>> '%-7s' % '12345'
'12345 '
'%5.3'
says use the first three characters, but fill it with spaces on the left to total five characters.
>>> '%5.3s' % '12345'
' 123'
Same thing except filling on the right.
>>> '%-5.3s' % '12345'
'123 '
Can handle multiple arguments too!
>>> 'do u no %-4.3sda%3.2s wae' % ('12345', 6789)
'do u no 123 da 67 wae'
If you require even more flexibility, str.format()
is available too. Here is documentation for both.
In a maven project create a file src/main/resources/application.yml
with the following content:
spring.profiles: integration
# use local or embedded mongodb at localhost:27017
---
spring.profiles: production
spring.data.mongodb.uri: mongodb://<user>:<passwd>@<host>:<port>/<dbname>
Spring Boot will automatically use this file to configure your application. Then you can start your spring boot application either with the integration profile (and use your local MongoDB)
java -jar -Dspring.profiles.active=integration your-app.jar
or with the production profile (and use your production MongoDB)
java -jar -Dspring.profiles.active=production your-app.jar
I know it's been a while since this question was posted, but I was just getting this exact error, and I have a really simple solution that MIGHT work for some. All I did was double click on the folder 'Servers', which then allowed me to start the server with no error message. Sometimes the solution is right in front of your eyes. This might work for some people like me who go straight to google without trying fix the issue themselves!
You could add a calculated column that includes only the date without the time. Between the two options, I'd go with the BETWEEN
operator because it's 'cleaner' to me and should make better use of indexes. Comparing execution plans would seem to indicate that BETWEEN
would be faster; however, in actual testing they performed the same.
Just specify max-width: 100%
alone, that should do it.
If you are using multiple criteria, and want to count the number of non-blank cells in a particular column, you probably want to look at DCOUNTA.
e.g
A B C D E F G
1 Dog Cat Cow Dog Cat
2 x 1 x 1
3 x 2
4 x 1 nb Result:
5 x 2 nb 1
Formula in E5: =DCOUNTA(A1:C5,"Cow",E1:F2)
<div class="container"> _x000D_
<section class="main-content">_x000D_
<center><a href="#"><button id="view-fullscreen">view full size page large</button></a><center>_x000D_
<script>(function () {_x000D_
var viewFullScreen = document.getElementById("view-fullscreen");_x000D_
if (viewFullScreen) {_x000D_
viewFullScreen.addEventListener("click", function () {_x000D_
var docElm = document.documentElement;_x000D_
if (docElm.requestFullscreen) {_x000D_
docElm.requestFullscreen();_x000D_
}_x000D_
else if (docElm.mozRequestFullScreen) {_x000D_
docElm.mozRequestFullScreen();_x000D_
}_x000D_
else if (docElm.webkitRequestFullScreen) {_x000D_
docElm.webkitRequestFullScreen();_x000D_
}_x000D_
}, false);_x000D_
}_x000D_
})();</script>_x000D_
</section>_x000D_
</div>
_x000D_
for view demo clcik here demo of click to open page in fullscreen
I. Plain XSLT 1.0 solution:
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="text()" name="split">
<xsl:param name="pText" select="."/>
<xsl:if test="string-length($pText)">
<xsl:if test="not($pText=.)">
<br />
</xsl:if>
<xsl:value-of select=
"substring-before(concat($pText,';'),';')"/>
<xsl:call-template name="split">
<xsl:with-param name="pText" select=
"substring-after($pText, ';')"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
when applied on this XML document:
<t>123 Elm Street;PO Box 222;c/o James Jones</t>
produces the wanted, corrected result:
123 Elm Street<br />PO Box 222<br />c/o James Jones
II. FXSL 1 (for XSLT 1.0):
Here we just use the FXSL template str-map
(and do not have to write recursive template for the 999th time):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
<xsl:import href="str-dvc-map.xsl"/>
<testmap:testmap/>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
<xsl:call-template name="str-map">
<xsl:with-param name="pFun" select="$vTestMap"/>
<xsl:with-param name="pStr" select=
"'123 Elm Street;PO Box 222;c/o James Jones'"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="replace" mode="f:FXSL"
match="*[namespace-uri() = 'testmap']">
<xsl:param name="arg1"/>
<xsl:choose>
<xsl:when test="not($arg1=';')">
<xsl:value-of select="$arg1"/>
</xsl:when>
<xsl:otherwise><br /></xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:
123 Elm Street<br/>PO Box 222<br/>c/o James Jones
III. Using XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="text()">
<xsl:for-each select="tokenize(.,';')">
<xsl:sequence select="."/>
<xsl:if test="not(position() eq last())"><br /></xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on this XML document:
<t>123 Elm Street;PO Box 222;c/o James Jones</t>
the wanted, correct result is produced:
123 Elm Street<br />PO Box 222<br />c/o James Jones
final ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
}
});
I hope this fixes your problem.
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
It's the ASCII/UTF code for LF
(0A
) - Unix-based systems are using it as the newline character, while Windows uses the CR-LF PAIR (OD0A
).
It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal
.
json: unsupported type: map[int]main.Foo
JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.
You have two options:
1 Use map[string]Foo
and convert the index to string (using fmt.Sprint for example):
datas := make(map[string]Foo, N)
for i := 0; i < 10; i++ {
datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)
2 Simply just use a slice (javascript array):
datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)
To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.
<?php
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
?>
The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.
In .net2.0 you can use the variable Application.UserAppDataPath
You need to load your image as bitmap:
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.your_image);
Then make the bitmap mutable and create a canvas over it:
Canvas canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));
You then can draw on the canvas.
use std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
the following example produces -65538
as its result:
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string
So, the simplest answer for newer code would probably look like this:
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).
It appears that since lexical_cast<>
is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast
and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.
Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
If you don't feel like using boost, here's a light version of lexical cast which does no error checking:
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
which you can use like this:
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
This will add an image to another.
using (Graphics grfx = Graphics.FromImage(image))
{
grfx.DrawImage(newImage, x, y)
}
Graphics is in the namespace System.Drawing
One major difference is that DataSets can hold multiple tables and you can define relationships between those tables.
If you are only returning a single result set though I would think a DataTable would be more optimized. I would think there has to be some overhead (granted small) to offer the functionality a DataSet does and keep track of multiple DataTables.
Try:
public void onclick(View v){
ImageView activity= (ImageView) findViewById(R.id.imageview1);
button1.setImageResource(R.drawable.buttonpressed);}
UPDATED query:
select id from t where id < (select max(id) from t);
It'll select all but the last row from the table t.
reloadRowsAtIndexPaths:
is fine, but still will force UITableViewDelegate
methods to fire.
The simplest approach I can imagine is:
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];
It's important to invoke your configureCell:
implementation on main thread, as it wont work on non-UI thread (the same story with reloadData
/reloadRowsAtIndexPaths:
). Sometimes it might be helpful to add:
dispatch_async(dispatch_get_main_queue(), ^
{
[self configureCell:cell forIndexPath:indexPath];
});
It's also worth to avoid work that would be done outside of the currently visible view:
BOOL cellIsVisible = [[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] != NSNotFound;
if (cellIsVisible)
{
....
}
For symfony 4 users:
$query = $request->query->get('query');
For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.
Just add:
export {};
at the top of your code.
Credit to EUGENE MURAVITSKY
form.onsubmit = function(){
return textarea.value.match(/^\d+(\.\d+)?$/);
}
Is this what you're looking for?
I hope it helps.
EDIT: I edited my example above so that there can only be one period, preceded by at least one digit and followed by at least one digit.
Just put your two textviews host and port in an independant linearlayout horizontal and use android:layout_weight to make the percentage
Use the numpy.corrcoef
function instead of numpy.correlate
to calculate the statistical correlation for a lag of t:
def autocorr(x, t=1):
return numpy.corrcoef(numpy.array([x[:-t], x[t:]]))
Following program describe how bidirectional relation work in hibernate.
When parent will save its list of child object will be auto save.
On Parent side:
@Entity
@Table(name="clients")
public class Clients implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@OneToMany(mappedBy="clients", cascade=CascadeType.ALL)
List<SmsNumbers> smsNumbers;
}
And put the following annotation on the child side:
@Entity
@Table(name="smsnumbers")
public class SmsNumbers implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
String number;
String status;
Date reg_date;
@ManyToOne
@JoinColumn(name = "client_id")
private Clients clients;
// and getter setter.
}
Main class:
public static void main(String arr[])
{
Session session = HibernateUtil.openSession();
//getting transaction object from session object
session.beginTransaction();
Clients cl=new Clients("Murali", "1010101010");
SmsNumbers sms1=new SmsNumbers("99999", "Active", cl);
SmsNumbers sms2=new SmsNumbers("88888", "InActive", cl);
SmsNumbers sms3=new SmsNumbers("77777", "Active", cl);
List<SmsNumbers> lstSmsNumbers=new ArrayList<SmsNumbers>();
lstSmsNumbers.add(sms1);
lstSmsNumbers.add(sms2);
lstSmsNumbers.add(sms3);
cl.setSmsNumbers(lstSmsNumbers);
session.saveOrUpdate(cl);
session.getTransaction().commit();
session.close();
}
I had the same error message in my localhost development with my Visual Studio. Note that everything was working when released with Microsoft Release Management (MRM). I fixed my situation by changing the initial value that was a MRM reference.
My App.config initial value was the following:
<connectionStrings>
<add name="BDORA" connectionString="__token3__" />
</connectionStrings>
Locally, the application execution could not interpret the token3 reference to its real value in Tokens.xml. To make it work on my localhost, I had to force the value from token3 in Tokens.xml into the App.config file.
Yes, you need $(this)
for jQuery functions, but when you want to access basic javascript methods of the element that don't use jQuery, you can just use this
.
This is quite likely the simplest way to achieve what you are looking for.
In order to use this map
function in this instance, we will have to pass a currentValue
(always-required) parameter, as well an index
(optional) parameter.
In the below example, station
is our currentValue
, and x
is our index
.
station
represents the current value of the object within the array as it is iterated over.
x
automatically increments; increasing by one each time a new object is mapped.
render () {
return (
<div>
{stations.map((station, x) => (
<div key={x}> {station} </div>
))}
</div>
);
}
What Thomas Valadez had answered, while it had provided the best/simplest method to render a component from an array of objects, it had failed to properly address the way in which you would assign a key during this process.
I was about to post the head/tail trick, but actually I'd probably just fire up emacs. ;-)
open the new output file, ctl-y save
Let's me see what's happening.
It took a few tries, but I was able to get your jsFiddle to work (for Webkit only).
There's still an issue with the animation speed when the user re-enters the div.
Basically, just set the current rotation value to a variable, then do some calculations on that value (to convert to degrees), then set that value back to the element on mouse move and mouse enter.
Check out the jsFiddle: http://jsfiddle.net/4Vz63/46/
Check out this article for more information, including how to add cross-browser compatibility: http://css-tricks.com/get-value-of-css-rotation-through-javascript/
You can also use a for
loop and tr
to extract the filename from the path...
for x in `echo $path | tr "/" " "`; do filename=$x; done
The tr
replaces all "/" delimiters in path with spaces so making a list of strings, and the for
loop scans through them leaving the last one in the filename
variable.
Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:
SELECT count(DISTINCT concat(id, name, address)) FROM mytable;
var arr = [1, 2, 3];
arr.slice(-1).pop(); // return 3 and arr = [1, 2, 3]
This will return undefined if the array is empty and this will not change the value of the array.
I got the same error when using %
as a percent character in my format string. The solution to this is to double up the %%
.
Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.
Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.
Is there any particular reason that you need to use find
? You can just use ls
to find files that match a pattern in a directory.
ls /dev/abc-*
If you do need to use find
, you can use the -maxdepth 1
switch to only apply to the specified directory.
You can also do this with one query too using a join like so:
UPDATE table1,table2 SET table1.col=a,table2.col2=b
WHERE items.id=month.id;
And then just send this one query, of course. You can read more about joins here: http://dev.mysql.com/doc/refman/5.0/en/join.html. There's also a couple restrictions for ordering and limiting on multiple table updates you can read about here: http://dev.mysql.com/doc/refman/5.0/en/update.html (just ctrl+f "join").
I've tried different solutions. First was:
a_df=np.unique(df[['col1','col2']], axis=0)
and it works well for not object data Another way to do this and to avoid error (for object columns type) is to apply drop_duplicates()
a_df=df.drop_duplicates(['col1','col2'])[['col1','col2']]
You can also use SQL to do this, but it worked very slow in my case:
from pandasql import sqldf
q="""SELECT DISTINCT col1, col2 FROM df;"""
pysqldf = lambda q: sqldf(q, globals())
a_df = pysqldf(q)
To answer your specific question, you cannot have two methods with the same name and the same arguments in a single class; using the HttpGet and HttpPost attributes doesn't distinguish the methods.
To address this, I'd typically include the view model for the form you're posting:
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
public ActionResult Index(formViewModel model)
{
do work on model --
return View();
}
}
There are padding built into various classes.
For example:
A asp.net web forms app:
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
this code above would place the Text of "Show Deleted" too close to the checkbox to what I see at nice to look at.
However with bootstrap
<div class="checkbox-inline">
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
</div>
This created the space, if you don't want the text bold, that class=checkbox
Bootstrap is very flexible, so in this case I don't need a hack, but sometimes you need to.
if you have an array
var subcategories=[{name:"test",desc:"test"}];
function hasCategory(nameStr) {
for(let i=0;i<subcategories.length;i++){
if(subcategories[i].name===nameStr){
return true;
}
}
return false;
}
if you have an object
var category={name:"asd",test:""};
if(category.hasOwnProperty('name')){//or category.name!==undefined
return true;
}else{
return false;
}
I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.
Code:
import os
print(os.path.expanduser("~"))
Output Windows:
PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX
Output Linux (Ubuntu):
rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx
I also tested it on Python 2.7.17 and that works too.
(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3
Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.
You can use the following to get the previous URL.
var oldURL = document.referrer;
alert(oldURL);
As others have mentioned, using an XML library is the easiest way. If you do want to escape yourself, you could look into StringEscapeUtils
from the Apache Commons Lang library.
You can use the shift keyword (operator?) to iterate through them. Example:
#!/bin/bash
function print()
{
while [ $# -gt 0 ]
do
echo $1;
shift 1;
done
}
print $*;
<div id='element_123_wrapper_text'>My sample DIV</div>
The Operator ^ - Match elements that starts with given value
div[id^="element_123"] {
}
The Operator $ - Match elements that ends with given value
div[id$="wrapper_text"] {
}
The Operator * - Match elements that have an attribute containing a given value
div[id*="wrapper_text"] {
}
What I've always done is just wrap the radio button inside the label...
<label for="one">
<input type="radio" id="one" name="first_item" value="1" />
First Item
</label>
Something like that, has always worked for me.
Division is performed using the /
operator:
result = a / b;
Modulo division is done using the %
operator:
result = a % b;
I think the response of aaron can be enhanced for URL that contains variables:
var sdk = require('postman-collection');
const testURL=pm.environment.values.substitute(pm.request.url, null, false);
const objURL=new sdk.Url(testURL);
console.log("clearing cookies for: "+testURL);
const jar = pm.cookies.jar();
jar.clear(objURL, function (error) {
// error - <Error>
if(error)
console.log("Error clearing cookies: "+error);
});
<style type="text/css">
td { word-wrap: break-word;max-width:50px; }
</style>
I think you're almost there.
The thing is, your $(this)
in the "close button" listener is not the clickable div. So you want to search it first. try to replace $(this)
with $(this).closest(".clickable")
. And don't forget the e.stopPropagation()
as Guilherme is suggesting. that should be something like:
$( document ).ready(function() {
$(document).on("click", ".close_button", function () {
alert ("oi");
e.stopPropagation()
$(this).closest(".clickable").addClass("spot");
$(this).closest(".clickable").removeClass("grown");
});
$(document).on("click", ".clickable", function () {
if ($(this).hasClass("spot")){
$(this).addClass("grown");
$(this).removeClass("spot");
}
});
});
Replace
#include "Landing.h"
with
class Landing;
If you still get errors, also post Item.h
, Flight.h
and common.h
EDIT: In response to comment.
You will need to e.g. #include "Landing.h"
from Event.cpp
in order to actually use the class. You just cannot include it from Event.h
No no no… in general these things are possible. It'll just make you feel like a dirty person. If you absolutely must, do this:
Create a category with your own implementation of +imageNamed:(NSString*)imageName
that calls through to the existing implementation and uses the technique identified here (How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?) to permanently associate imageName
with the UIImage object that is returned.
Use Method Swizzling to swap the provided implementation of imageNamed:
for your implementation in the method lookup table of the Objective-C runtime.
Access the name you associated with the UIImage instance (using objc_getAssociatedObject) anytime you want it.
I can verify that this works, with the caveat that you can't get the names of UIImage's loaded in NIBs. It appears that images loaded from NIBs are not created through any standard function calls, so it's really a mystery to me.
I'm leaving the implementation up to you. Copy-pasting code that screws with the Objective-C runtime is a very bad idea, so think carefully about your project's needs and implement this only if you must.
In the html tables, <table>
tag expect <tr>
tag right after itself and <tr>
tag expect <td>
tag right after itself. So if you want to put a div in table, you can put it in between <td>
and </td>
tags as data.
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<div>_x000D_
<p>It works well</p>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
<table>
_x000D_
New, resurrected project site (Win7 compability and more!): http://sshwindows.sourceforge.net
1st January 2012
- OpenSSH for Windows 5.6p1-2 based release created!!
- Happy New Year all! Since COpSSH has started charging I've resurrected this project
- Updated all binaries to current releases
- Added several new supporting DLLs as required by all executables in package
- Renamed switch.exe to bash.exe to remove the need to modify and compile mkpasswd.exe each build
- Please note there is a very minor bug in this release, detailed in the docs. I'm working on fixing this, anyone who can code in C and can offer a bit of help it would be much appreciated
It should also be possible to either extend the listener by prototyping it (if we have a reference to it and its not an anonymous function) -or make the onclick
call a call to a function library (a function calling other functions).
Like:
elm.onclick = myFunctionList;
function myFunctionList(){
myFunc1();
myFunc2();
}
This means we never have to change the onclick
call just alter the function myFunctionList()
to do whatever we want, but this leaves us without control of bubbling/catching phases so should be avoided for newer browsers.
You can use the DATE(Year;Month;Day) to make operations on date:
Examples:
=DATE(2013;3;8 + 30) give the result... 7 april 2013 !
=DATE(2013;3 + 15; 8) give the result... 8 june 2014 !
It's very surprising but it works...
I provided the configuration values to word hosted .nET Compoent as follows.
A .NET Class Library component being called/hosted in MS Word. To provide configuration values to my component, I created winword.exe.config in C:\Program Files\Microsoft Office\OFFICE11 folder. You should be able to read configurations values like You do in Traditional .NET.
string sMsg = System.Configuration.ConfigurationManager.AppSettings["WSURL"];
I had to post key value pairs without form and I could do it easily like below:
var request = require('request');
request({
url: 'http://localhost/test2.php',
method: 'POST',
json: {mes: 'heydude'}
}, function(error, response, body){
console.log(body);
});
For a comma-delineated string listing the keys of a JSON Object, try the following:
function listKeys(jObj){
var keyString = '';
for(var k in jObj){
keyString+=(','+k);
}
return keyString.slice(1);
}
/* listKeys({'a' : 'foo', 'b' : 'foo', 'c' : 'foo'}) -> 'a,b,c' */
rename all the *.csv.err files in the <<bucket>>/landing
dir into *.csv files with s3cmd
export aws_profile='foo-bar-aws-profile'
while read -r f ; do tgt_fle=$(echo $f|perl -ne 's/^(.*).csv.err/$1.csv/g;print'); \
echo s3cmd -c ~/.aws/s3cmd/$aws_profile.s3cfg mv $f $tgt_fle; \
done < <(s3cmd -r -c ~/.aws/s3cmd/$aws_profile.s3cfg ls --acl-public --guess-mime-type \
s3://$bucket | grep -i landing | grep csv.err | cut -d" " -f5)
I'd prefer mapping after making sure the value is available
private String getStringIfObjectIsPresent(Optional<Object> object) {
Object ob = object.orElseThrow(MyCustomException::new);
// do your mapping with ob
String result = your-map-function(ob);
return result;
}
or one liner
private String getStringIfObjectIsPresent(Optional<Object> object) {
return your-map-function(object.orElseThrow(MyCustomException::new));
}
You have two options:
Use a Mark of the Web. This will enable a single html page to load. It See here for details. To do this, add the following to your web page below the doctype and above the html tag:
<!-- saved from url=(0014)about:internet -->
Disable this feature. To do so go to Internet Options->Advanced->Security->Allow Active Content... Then close IE. When you restart IE, it will not give you this error.
Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:
Date firstDate = new Date(ConstructorArgsHere);
Now you have a bit of a choice. If you don't pass in any arguments, and just do this,
Date firstDate = new Date();
it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:
Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);
Here x is a vector. You need to convert it into a dataframe for using $ operator.
x <- as.data.frame(x)
will work for you.
x<-c(1,2)
names(x)<- c("bob","ed")
x <- as.data.frame(x)
will give you output of x as:
bob 1
ed 2
And, will give you output of x$ed as:
NULL
If you want bob and ed as column names then you need to transpose the dataframe like x <- as.data.frame(t(x))
So your code becomes
x<-c(1,2)
x
names(x)<- c("bob","ed")
x$ed
x <- as.data.frame(t(x))
Now the output of x$ed is:
[1] 2
MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.
INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct,
t.inact, t.inadur, t.inadist,
t.smlct, t.smldur, t.smldist,
t.larct, t.lardur, t.lardist,
t.emptyct, t.emptydur
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...
I generally do the same as cx42net, but I don't explicitly create an Entry.
HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for (String key : selects.keySet())
{
HashMap<innerKey, String> boxHolder = selects.get(key);
ComboBox cb = new ComboBox();
for (InnerKey innerKey : boxHolder.keySet())
{
cb.items.add(boxHolder.get(innerKey));
}
}
This just seems the most intuitive to me, I think I'm prejudiced against iterating over the values of a map.
You can do this by displaying a div (if you want to do it in a modal manner you could use blockUI - or one of the many other modal dialog plugins out there) prior to the request then just waiting until the call back succeeds as a quick example you can you $.getJSON as follows (you might want to use .ajax if you want to add proper error handling)
$("#ajaxLoader").show(); //Or whatever you want to do
$.getJSON("/AJson/Call/ThatTakes/Ages", function(result) {
//Process your response
$("#ajaxLoader").hide();
});
If you do this several times in your app and want to centralise the behaviour for all ajax calls you can make use of the global AJAX events:-
$("#ajaxLoader").ajaxStart(function() { $(this).show(); })
.ajaxStop(function() { $(this).hide(); });
Using blockUI is similar for example with mark up like:-
<a href="/Path/ToYourJson/Action" id="jsonLink">Get JSON</a>
<div id="resultContainer" style="display:none">
And the answer is:-
<p id="result"></p>
</div>
<div id="ajaxLoader" style="display:none">
<h2>Please wait</h2>
<p>I'm getting my AJAX on!</p>
</div>
And using jQuery:-
$(function() {
$("#jsonLink").click(function(e) {
$.post(this.href, function(result) {
$("#resultContainer").fadeIn();
$("#result").text(result.Answer);
}, "json");
return false;
});
$("#ajaxLoader").ajaxStart(function() {
$.blockUI({ message: $("#ajaxLoader") });
})
.ajaxStop(function() {
$.unblockUI();
});
});
I wouldn't use Thread.Sleep(). Either use a scheduled task (as others have mentioned), or set up a timer inside your service, which fires periodically (every 10 minutes for example) and check if the date changed since the last run:
private Timer _timer;
private DateTime _lastRun = DateTime.Now.AddDays(-1);
protected override void OnStart(string[] args)
{
_timer = new Timer(10 * 60 * 1000); // every 10 minutes
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
//...
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// ignore the time, just compare the date
if (_lastRun.Date < DateTime.Now.Date)
{
// stop the timer while we are running the cleanup task
_timer.Stop();
//
// do cleanup stuff
//
_lastRun = DateTime.Now;
_timer.Start();
}
}
I've had similar errors when trying to deploy a Gradle artefact to a Nexus Sonatype repository. You will get a 401 Unauthorized error if you supply the wrong credentials (password etc). You also get an error (and off the top of my head is also a 401) if you try to publish something to a releases repository and that version already exists in the repository. So you might find that by publishing from the command line it works, but then when you do it from a script it fails (because it didn't exist in the repository the first time around). Either publish using a different version number, or delete the old artefact on the server and republish.
The SNAPSHOTS repository (as opposed to the releases repository) allows you to overwrite a similarly numbered version, but your version number should have "-SNAPSHOT" at the end of it.
While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:
import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
print str(row)
Based on gkemp answer, On Windows, I found the keystore file path, password, key alias and key password in an earlier log report before I updated Android Studio.
From windows file explorer c:/Users/your pc name/.AndroidStudio1.4 (your android studio version)\system\log\idea.log.1 (or any old log number)
Then I searched for “android.injected.signing.store” and found this from an earlier date:
-Pandroid.injected.signing.store.file= path to your keystore
-Pandroid.injected.signing.store.password=yourstorepassword
-Pandroid.injected.signing.key.alias=yourkeyalias
-Pandroid.injected.signing.key.password=yourkeypassword
sudo dscl . -create /Users/joeadmin
sudo dscl . -create /Users/joeadmin UserShell /bin/bash
sudo dscl . -create /Users/joeadmin RealName "Joe Admin"
sudo dscl . -create /Users/joeadmin UniqueID "510"
sudo dscl . -create /Users/joeadmin PrimaryGroupID 20
sudo dscl . -create /Users/joeadmin NFSHomeDirectory /Users/joeadmin
sudo dscl . -passwd /Users/joeadmin password
sudo dscl . -append /Groups/admin GroupMembership joeadmin
press enter after every sentence
Then do a:
sudo reboot
Change joeadmin to whatever you want, but it has to be the same all the way through. You can also put a password of your choice after password.
If you don't want to use any additional package, you can call the following function before creating your file:
var path = require('path'),
fs = require('fs');
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
Whilst @Didzis has the correct answer, I will expand on a few points
Aesthetics can be set or mapped within a ggplot call.
An aesthetic defined within aes(...) is mapped from the data, and a legend created.
An aesthetic may also be set to a single value, by defining it outside aes().
As far as I can tell, what you want is to set size to a single value, not map within the call to aes()
When you call aes(size = 2)
it creates a variable called `2`
and uses that to create the size, mapping it from a constant value as it is within a call to aes
(thus it appears in your legend).
Using size = 1 (and without reg_labeller
which is perhaps defined somewhere in your script)
Figure29 +
geom_line(aes(group=factor(tradlib)),size=1) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(
colour = 'black', angle = 90, size = 13,
hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
and with size = 2
Figure29 +
geom_line(aes(group=factor(tradlib)),size=2) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90,
size = 13, hjust = 0.5, vjust =
0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
You can now define the size to work appropriately with the final image size and device type.
Convert PPK to OpenSSh
OS X: Install Homebrew, then run
brew install putty
Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search
To generate the private key:
cd ~
puttygen id_dsa.ppk -O private-openssh -o id_dsa
and to generate the public key:
puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub
Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:
mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub
connect with ssh server
ssh -i ~/.ssh/id_dsa username@servername
Port Forwarding to connect mysql remote server
ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName
You should specify the db you are connecting to:
jdbc:mysql://localhost:3306/mydb
Yes, generally the best way to store a file in a database is to save the byte array in a BLOB column. You will probably want a couple of columns to additionally store the file's metadata such as name, extension, and so on.
It is not always a good idea to store files in the database - for instance, the database size will grow fast if you store files in it. But that all depends on your usage scenario.
var template = $( "<li>", { id: "1234", html:
$( "<div>", { class: "bar", text: "bla" } )
});
$('body').append(template);
What about this?
You can use -[NSDictionary allKeys]
to access all the keys and loop through it.
Is there and image in the list view that you are using> then follow the link: http://vikaskanani.wordpress.com/2011/07/20/android-custom-image-gallery-with-checkbox-in-grid-to-select-multiple/
I think when you work out on the link that I have provided first every thing will work fine, I have tried that. If you want a refined answer please elaborate the question with code and description.
A Fibbonacci sequence is one that sums the result of a number then we have added to the previous result, we should started from 1. I was trying to find a solution based on algorithm, so i build the recursive code, noticed that i keep the previous number and i changed the position. I'm searching the Fibbonacci sequence from 1 to 15.
public static void main(String args[]) {
numbers(1,1,15);
}
public static int numbers(int a, int temp, int target)
{
if(target <= a)
{
return a;
}
System.out.print(a + " ");
a = temp + a;
return numbers(temp,a,target);
}
Note that in some cases, you need to loop in reverse order (but then you can use i-- too).
For example somebody wanted to use the new getElementsByClassName
function to loop on elements of a given class and change this class. He found that only one out of two elements was changed (in FF3).
That's because the function returns a live NodeList, which thus reflects the changes in the Dom tree. Walking the list in reverse order avoided this issue.
var menus = document.getElementsByClassName("style2");
for (var i = menus.length - 1; i >= 0; i--)
{
menus[i].className = "style1";
}
In increasing index progression, when we ask the index 1, FF inspects the Dom and skips the first item with style2, which is the 2nd of the original Dom, thus it returns the 3rd initial item!
Actually its very simple to access window object here is my basic component and i tested it its working
import { Component, OnInit,Inject } from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser';
@Component({
selector: 'app-verticalbanners',
templateUrl: './verticalbanners.component.html',
styleUrls: ['./verticalbanners.component.css']
})
export class VerticalbannersComponent implements OnInit {
constructor(){ }
ngOnInit() {
console.log(window.innerHeight );
}
}
You Need to write a custom Deserializer and then loop it and get the values of the hasmap.
Custom Deserializer:-
public class UserDetailsDeserializer implements JsonDeserializer<AllUserDetailsKeyModel> {
/*
bebebejunskjd:{
"email": "[email protected]",
"mobileNum": "12345678",
"password": "1234567",
"username": "akhil"}*/
@Override public AllUserDetailsKeyModel deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
Gson gson = new Gson();
Type AllUserDetailsResponseModel =
new TypeToken<HashMap<String, AllUserDetailsResponseModel>>(){}.getType();
HashMap<String, AllUserDetailsResponseModel> user =
gson.fromJson(jsonObject, AllUserDetailsResponseModel);
AllUserDetailsKeyModel result = new AllUserDetailsKeyModel();
result.setResult(user);
return result;
}
}
The code in comments is my object model and u should replaceAllUserDetailsKeyModel with your model class and add this to the rest client like below:-
private Converter.Factory createGsonConverter() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(AllUserDetailsKeyModel.class, new UserDetailsDeserializer());
Gson gson = gsonBuilder.create();
return GsonConverterFactory.create(gson);
}
This the custom Convertor for Retrofit.
In your onResponse you just loop with hasmaps and get value by key and my model class looks like below:-
public class AllUserDetailsKeyModel {
private Map<String, AllUserDetailsResponseModel> result;
public Map<String, AllUserDetailsResponseModel> getResult() {
return result;
}
public void setResult(Map<String, AllUserDetailsResponseModel> result) {
this.result = result;
}
}
probably you need to give a Type T where T is your data Type and my model consists only of a hashmap and getters and setters for that.
And finally set Custom Convertor to retrofit like below:- .addConverterFactory(createGsonConverter())
Let me know if you need more clarifications.
This is a simple way to extract the date:
import pandas as pd
d='2015-01-08 22:44:09'
date=pd.to_datetime(d).date()
print(date)
Swift 5
If you want to get the navigation bar height, use the maxY
property that considers the safeArea size as well, like this:
let height = navigationController?.navigationBar.frame.maxY
If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.
If you don't want word wrap, assign the CSS style white-space: nowrap
to the cells.
Just use a two color background image:
<div style="width:100%; background:url('images/bkgmid.png');
background-size: cover;">
content
</div>
And, in case you're not sure if the supplied URL text
has a scheme:
NSString* text = @"www.apple.com";
NSURL* url = [[NSURL alloc] initWithString:text];
if (url.scheme.length == 0)
{
text = [@"http://" stringByAppendingString:text];
url = [[NSURL alloc] initWithString:text];
}
[[UIApplication sharedApplication] openURL:url];
This is because you select not a theme of your project. Try to do next:
The use of the package \usepackage{fancyvrb}
allows the definition of the fontsize argument inside Verbatim:
\begin{Verbatim}[fontsize=\small]
print "Hello, World"
\end{Verbatim}
The fontsize that you can specify are the common
\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge
I know this is almost 1.5 years old, but I hope I can help someone with what I found.
I had built both a console app and a UWP app and my console connnected fine, but not my UWP. After hours of banging my head against the desk - if it's a intranet server hosting the SQL database you must enable "Private Networks (Client & Server)". It's under Package.appxmanifest and the Capabilities tab.Screenshot
What others said is correct but for those who still face the same problem:
In my case it happened because I copied another project n renamed it to something else BUT previous output files in bin
folder were still there... And unfortunately, hitting Build -> Clean Solution
after renaming the project and its Namespaces
doesn't remove them... so deleting them manually solved my problem!
We all know that Java does not provide anything like the unsigned keyword. Moreover, a byte
primitive according to the Java's spec represents a value between -128
and 127
. For instance, if a byte
is cast
to an int
Java will interpret the first bit
as the sign
and use sign extension.
127
to its binary string representation ??Nothing prevents you from viewing a byte
simply as 8-bits and interpret those bits as a value between 0
and 255
. Also, you need to keep in mind that there's nothing you can do to force your interpretation upon someone else's method. If a method accepts a byte
, then that method accepts a value between -128
and 127
unless explicitly stated otherwise.
So the best way to solve this is convert the byte
value to an int
value by calling the Byte.toUnsignedInt()
method or casting it as a int
primitive (int) signedByte & 0xFF
. Here you have an example:
public class BinaryOperations
{
public static void main(String[] args)
{
byte forbiddenZeroBit = (byte) 0x80;
buffer[0] = (byte) (forbiddenZeroBit & 0xFF);
buffer[1] = (byte) ((forbiddenZeroBit | (49 << 1)) & 0xFF);
buffer[2] = (byte) 96;
buffer[3] = (byte) 234;
System.out.println("8-bit header:");
printBynary(buffer);
}
public static void printBuffer(byte[] buffer)
{
for (byte num : buffer) {
printBynary(num);
}
}
public static void printBynary(byte num)
{
int aux = Byte.toUnsignedInt(num);
// int aux = (int) num & 0xFF;
String binary = String.format("%8s', Integer.toBinaryString(aux)).replace(' ', '0');
System.out.println(binary);
}
}
8-bit header:
10000000
11100010
01100000
11101010
You can use ng-change instead of ng-click:
<!doctype html>
<html>
<head>
<script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
<script>
var app = angular.module('myapp', []);
app.controller('mainController', function($scope) {
$scope.vm = {};
$scope.vm.myClick = function($event) {
alert($event);
}
});
</script>
</head>
<body ng-app="myapp">
<div ng-controller="mainController">
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
</div>
</body>
</html>
Should work:
.attr({
target:"nw",
title:"Opens in a new window",
"data-value":"internal link" // attributes which contain dash(-) should be covered in quotes.
});
Note:
" When setting multiple attributes, the quotes around attribute names are optional.
WARNING: When setting the 'class' attribute, you must always use quotes!
From the jQuery documentation (Sep 2016) for .attr:
Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.
Edit:
For future reference...
To get a single attribute you would use
var strAttribute = $(".something").attr("title");
To set a single attribute you would use
$(".something").attr("title","Test");
To set multiple attributes you need to wrap everything in { ... }
$(".something").attr( { title:"Test", alt:"Test2" } );
You will need to use prop()
as of jQuery 1.6+
the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does
So to get the checked status of a checkbox, you should use:
$('#checkbox1').prop('checked'); // Returns true/false
Or to set the checkbox as checked or unchecked you should use:
$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it
You can take database back-up of SQL server instance using C#, as below
Step 1: Install Nuget package "Install-Package Microsoft.SqlServer.SqlManagementObjects
"
Step 2: Use the below C# Command to take backup using Custom function
public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
{
//Define a Backup object variable.
Backup sqlBackup = new Backup();
//Specify the type of backup, the description, the name, and the database to be backed up.
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "FullBackUp";
sqlBackup.Database = databaseName;
//Declare a BackupDeviceItem
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "FullBackUp.bak", DeviceType.File);
//Define Server connection
ServerConnection connection = new ServerConnection(serverName, userName, password); //To Avoid TimeOut Exception
Server sqlServer = new Server(connection);
sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
Database db = sqlServer.Databases[databaseName];
(Reference Database As microsoft.sqlserver.management.smo.database, not as System.entity.database)
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
//Add the device to the Backup object.
sqlBackup.Devices.Add(deviceItem);
//Set the Incremental property to False to specify that this is a full database backup.
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
//Specify that the log must be truncated after the backup is complete.
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
//Run SqlBackup to perform the full database backup on the instance of SQL Server.
sqlBackup.SqlBackup(sqlServer);
//Remove the backup device from the Backup object.
sqlBackup.Devices.Remove(deviceItem);
}
Add References
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SmoExtended
Microsoft.SqlServer.SqlEnum
That's it, you are done, it will take backup of specified database at specified location passed to the function.
Source: Various ways to back up SQL server database
Note: User must have proper rights to write backup data on specified disk location.
You may want to add offsetTop and scrollTop value in case You are animating not the whole page , but rather some nested content.
e.g :
var itemTop= $('.letter[name="'+id+'"]').offset().top;
var offsetTop = $someWrapper.offset().top;
var scrollTop = $someWrapper.scrollTop();
var y = scrollTop + letterTop - offsetTop
this.manage_list_wrap.animate({
scrollTop: y
}, 1000);
You can use Mockito.isA()
for that:
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;
verify(bar).doStuff(isA(Foo[].class));
http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)
For Swift 4.2 and above
let supportEmail = "[email protected]"
if let emailURL = URL(string: "mailto:\(supportEmail)"), UIApplication.shared.canOpenURL(emailURL)
{
UIApplication.shared.open(emailURL, options: [:], completionHandler: nil)
}
Give the user to choose many mail options(like iCloud, google, yahoo, Outlook.com - if no mail is pre-configured in his phone) to send email.
while not any( x in ('AND','OR','NOT') for x in list)
EDIT:
thank you for the upvotes , but etarion's solution is better since it tests if the words AND, OR, NOT are in the list, that is to say 3 tests.
Mine does as many tests as there are words in list.
EDIT2:
Also there is
while not ('AND' in list,'OR' in list,'NOT' in list)==(False,False,False)
After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts
subdirectory.
In CSS code:
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font.woff") format('woff');
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-bold.woff") format('woff');
font-weight: bold;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-boldoblique.woff") format('woff');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-oblique.woff") format('woff');
font-style: italic;
}
After having that definitions, you can just write, for example,
In HTML code:
<div class="mydiv">
<b>this will be written with awesome-font-bold.woff</b>
<br/>
<b><i>this will be written with awesome-font-boldoblique.woff</i></b>
<br/>
<i>this will be written with awesome-font-oblique.woff</i>
<br/>
this will be written with awesome-font.woff
</div>
In CSS code:
.mydiv {
font-family: myfont
}
The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.
The second option is much quicker if you have multiple items.
Any()
returns as soon as 1 item is found.Count()
has to keep going through the entire list.For instance suppose the enumeration had 1000 items.
Any()
would check the first one, then return true.Count()
would return 1000 after traversing the entire enumeration.This is potentially worse if you use one of the predicate overrides - Count() still has to check every single item, even it there is only one match.
You get used to using the Any one - it does make sense and is readable.
One caveat - if you have a List, rather than just an IEnumerable then use that list's Count property.
DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
DataRow AddNewRow = dataTable.AddNewRow();
AddNewRow.ItemArray = dr.ItemArray;
dataTable.Rows.Add(AddNewRow);
}
Well you can achieve this using Color State Resource. If you notice inside your NavigationView
you're using
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
Here instead of using @color/black
or @color/primary_test
, use a Color State List Resource
. For that, first create a new xml
(e.g drawer_item.xml) inside color
directory (which should be inside res
directory.) If you don't have a directory named color
already, create one.
Now inside drawer_item.xml
do something like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="checked state color" android:state_checked="true" />
<item android:color="your default color" />
</selector>
Final step would be to change your NavigationView
<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/drawer_item" // notice here
app:itemTextColor="@color/drawer_item" // and here
app:itemBackground="@android:color/transparent"// and here for setting the background color to tranparent
app:menu="@menu/menu_drawer">
Like this you can use separate Color State List Resources for IconTint
, ItemTextColor
, ItemBackground
.
Now when you set an item as checked (either in xml
or programmatically), the particular item will have different color than the unchecked ones.
.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.
If you have an oracle client intalled on your machine, you can executed the command
imp help=y
to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.
You can use the _getexif()
protected method of a PIL Image.
import PIL.Image
img = PIL.Image.open('img.jpg')
exif_data = img._getexif()
This should give you a dictionary indexed by EXIF numeric tags. If you want the dictionary indexed by the actual EXIF tag name strings, try something like:
import PIL.ExifTags
exif = {
PIL.ExifTags.TAGS[k]: v
for k, v in img._getexif().items()
if k in PIL.ExifTags.TAGS
}
I was having this error w/Citect.
Microsoft Visual C++ 2005 Service Pack 1 Redistributable Package MFC Security Update has the missing files.
(?<![^d])\d+(?:\.\d+)?(?![^d])
clean and simple.
This uses Suffix and Prefix, RegEx features.
It directly returns true - false for IsMatch condition
@Howard Hinnant's answer is both correct and comprehensive. But it might be misunderstood if it's read too quickly, because std::terminate()
(whole process) happens to have the same name as the "terminating" that @Alexander V had in mind (1 thread).
Summary: "terminate 1 thread + forcefully (target thread doesn't cooperate) + pure C++11 = No way."
You have probably defined $name
, $date
, $text
or $date2
to be a string, like:
$name = 'String';
Then if you treat it like an array it will give that fatal error:
$name[] = 'new value'; // fatal error
To solve your problem just add the following code at the beginning of the loop:
$name = array();
$date = array();
$text = array();
$date2 = array();
This will reset their value to array and then you'll able to use them as arrays.
\n
is used for Unix systems (including Linux, and OSX).
\r\n
is mainly used on Windows.
\r
is used on really old Macs.
PHP_EOL
constant is used instead of these characters for portability between platforms.
An alternative way to order a List is using the Collections framework;
in this case using the SortedSet (the bean in the list should implement Comparable, so Double is ok):
List<Double> testList;
...
SortedSet<Double> sortedSet= new TreeSet<Double>();
for(Double number: testList) {
sortedSet.add(number);
}
orderedList=new ArrayList(sortedSet);
In general, to order by an attribute of a bean in the list,put all the elements of the list in a SortedMap, using as a key the attribute, then get the values() from the SortedMap (the attribute should implement Comparable):
List<Bean> testList;
...
SortedMap<AttributeType,Bean> sortedMap= new TreeMap<AttributeType, Bean>();
for(Bean bean : testList) {
sortedMap.put(bean.getAttribute(),bean);
}
orderedList=new ArrayList(sortedMap.values());
I have done this in the past with android:singleLine="true"
and then adding a listener for the "enter" key:
((EditText)this.findViewById(R.id.mytext)).setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
//if the enter key was pressed, then hide the keyboard and do whatever needs doing.
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getApplicationWindowToken(), 0);
//do what you need on your enter key press here
return true;
}
return false;
}
});
In addition to what was already said - in order to avoid this error from interfering (stopping) other Javascript code on your page, you could try forcing the YouTube iframe to load last - after all other Javascript code is loaded.
Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.
If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.
If by chance this error happens when working with SharePoint 2010: Rename your .json file extensions and be sure to update your restService path. No additional "track by $index" was required.
Luckily I was forwarded this link to this rationale:
.json becomes an important file type in SP2010. SP2010 includes certains webservice endpoints. The location of these files is 14hive\isapi folder. The extension of these files are .json. That is the reason it gives such a error.
"cares only that the contents of a json file is json - not its file extension"
Once the file extensions are changed, should be all set.
One possible reason is JAVA_HOME is not set because java is not installed.
I encountered the same issue. It says
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/spark/launcher/Main : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:643)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:296)
at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:406)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/spark/python/pyspark/conf.py", line 104, in __init__
SparkContext._ensure_initialized()
File "/opt/spark/python/pyspark/context.py", line 243, in _ensure_initialized
SparkContext._gateway = gateway or launch_gateway()
File "/opt/spark/python/pyspark/java_gateway.py", line 94, in launch_gateway
raise Exception("Java gateway process exited before sending the driver its port number")
Exception: Java gateway process exited before sending the driver its port number
at sc = pyspark.SparkConf()
. I solved it by running
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
which is from https://www.digitalocean.com/community/tutorials/how-to-install-java-with-apt-get-on-ubuntu-16-04
You're missing an ending anchor.
if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
// ...
}
EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:
if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
// ...
}
Just some bits addition from my side to all available answers
Need of AndroidX
With the current naming convention, it isn’t clear which packages are bundled with the Android operating system, and which are packaged with your application’s APK (Android Package Kit). To clear up this confusion, all the unbundled libraries will be moved to AndroidX’s androidx.* namespace, while the android.* package hierarchy will be reserved for packages that ship with the Android operating system.
Other than this,
Initially, the name of each package indicated the minimum API level supported by that package, for example support-v4. However, version 26.0.0 of the Support Library increased the minimum API to 14, so today many of the package names have nothing to do with the minimum supported API level. When support-v4 and the support-v7 packages both have a minimum API of 14, it’s easy to see why people get confused!. So now with AndroidX, there is no dependence on the API level.
Another important change is that the AndroidX artifacts will update independently, so you’ll be able to update individual AndroidX libraries in your project, rather than having to change every dependency at once. Those frustrating “All com.android.support libraries must use the exact same version specification” messages should become a thing of the past!
I guess a better option is to put $("#idname").autocomplete( "search", "" ); into the onclick paramter of the text box . Since on select, a focus is put in by jquery , this can be a workaround . Dont know if it should be an acceptable solution.
Unions are often used to convert between the binary representations of integers and floats:
union
{
int i;
float f;
} u;
// Convert floating-point bits to integer:
u.f = 3.14159f;
printf("As integer: %08x\n", u.i);
Although this is technically undefined behavior according to the C standard (you're only supposed to read the field which was most recently written), it will act in a well-defined manner in virtually any compiler.
Unions are also sometimes used to implement pseudo-polymorphism in C, by giving a structure some tag indicating what type of object it contains, and then unioning the possible types together:
enum Type { INTS, FLOATS, DOUBLE };
struct S
{
Type s_type;
union
{
int s_ints[2];
float s_floats[2];
double s_double;
};
};
void do_something(struct S *s)
{
switch(s->s_type)
{
case INTS: // do something with s->s_ints
break;
case FLOATS: // do something with s->s_floats
break;
case DOUBLE: // do something with s->s_double
break;
}
}
This allows the size of struct S
to be only 12 bytes, instead of 28.
I had two methods:
in the <script>
, goes to show, that you can spend hours looking for something that was such a simple mistake.
Images have display: inline
by default.
You might want to put the image inside the paragraph.
<p><img /></p>
To avoid common mistakes when using exclude
, remember:
You can not add multiple conditions into an exclude() block like filter
.
To exclude multiple conditions, you must use multiple exclude()
Example
Incorrect:
User.objects.filter(email='[email protected]').exclude(profile__nick_name='', profile__avt='')
Correct:
User.objects.filter(email='[email protected]').exclude(profile__nick_name='').exclude(profile__avt='')
One of the most promising approaches seems to be opening a second communication channel back to the server to ask it how much of the transfer has been completed.
Click on: 1. Your project 2. Signing & Capabilities 3. Select your Team.
Open the project file and not the solution. The project will be converted by the Wizard, and after converted, when you build the project, a new Solution will be generated as a VS2010 one.
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
The main purpose of the primary key is to provide a means to identify each record in the table.
The primary key provides a means to identity the row, using data within the row. A primary key can be based on one or more columns, such as first and last name; however, in many designs, the primary key is an auto-generated number from an identity column.
A primary key has the following characteristics:
A unique key is also called a unique constraint. A unique constraint can be used to ensure rows are unique within the database.
Don’t we already do that with the primary key? Yep, we do, but a table may have several sets of columns which you want unique.
In SQL Server the unique key has the following characteristics:
source : here
Quick and easy forms.
Scala 2.10 and older:
import com.typesafe.scalalogging.slf4j.Logger
import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("TheLoggerName"))
logger.debug("Useful message....")
And build.sbt:
libraryDependencies += "com.typesafe" %% "scalalogging-slf4j" % "1.1.0"
Scala 2.11+ and newer:
import import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("TheLoggerName"))
logger.debug("Useful message....")
And build.sbt:
libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0"
2020 Sep
launch xamp control panel
press admin in mysql row
in opened phpmyadmin press house icon on top left corner
in the top middle you will see user accounts tab and tap it
see in 'new' panel under the table to add a new user for your dbs and set access permissions
I made a plugin called "noswapsuck" that only enables the swapfile when the buffer contains unsaved changes. Once changes have been saved, the swapfile is cleared. Hence, swapfiles which contain the same content as the file on disk will be removed.
Get it here: noswapsuck.vim
It has been working well for me, but I have never publicised it before, so I would welcome feedback.
Advantages:
Disadvantages:
If the buffer has a swapfile, it will not be detected when the file is first opened. It will only be detected when (Solved: We now check for a pre-existing swapfile when a buffer is opened, by temporarily turning the swapfile
is enabled, which is when you start to edit the buffer. That is annoyingly late, and will interrupt you.swapfile
option on again.)
If you are working in an environment where you want to minimise disk-writes (e.g. low power, or files mounted over a network, or editing a huge file) then it is not ideal to keep removing and re-creating the swap file on every save and edit. In such situations, you can do:
:let g:NoSwapSuck_CloseSwapfileOnWrite = 0
which will keep the swapfile after a write, but will still remove it when the buffer loses focus.
By the way, I have another little plugin :DiffAgainstFileOnDisk
which can be pretty useful after hitting (r)ecover
, to check if the buffer you recovered is newer or older than the existing file, or identical to it.
Why is 21 the default port for FTP? Or 80 the default for HTTP? It is a convention.
Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer
by create a Message
object, putting it on a particular Queue
, and moving forward.
There would be a set of Consumer
s who would subscribe to the Queue
in question, and would take care handling the Message
sent across. Note that during the course of this transaction, the Producer
s are decoupled from the logic of how a given Message
would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message
transactions by providing MessageBroker
s.
This solution gives correct results over the entire range [0,UINT_MAX] without requiring digits to be buffered.
It also works for wider types or signed types (with positive values) with appropriate type changes.
This kind of approach is particularly useful on tiny environments (e.g. Arduino bootloader) because it doesn't end up pulling in all the printf() bloat (when printf() isn't used for demo output) and uses very little RAM. You can get a look at value just by blinking a single led :)
#include <limits.h>
#include <stdio.h>
int
main (void)
{
unsigned int score = 42; // Works for score in [0, UINT_MAX]
printf ("score via printf: %u\n", score); // For validation
printf ("score digit by digit: ");
unsigned int div = 1;
unsigned int digit_count = 1;
while ( div <= score / 10 ) {
digit_count++;
div *= 10;
}
while ( digit_count > 0 ) {
printf ("%d", score / div);
score %= div;
div /= 10;
digit_count--;
}
printf ("\n");
return 0;
}
I was searching for solution to the very same problem and un-ticking "Sign the assembly" option works for me:
(as you may notice screenshot comes from VS2010 but hopefully it will help someone)
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
Or using lambda function, like
>>> vec = np.arange(0,27,3).reshape(3,3)
>>> import numpy as np
>>> norm_vec = map(lambda row: row/np.linalg.norm(row), vec)
each vector of vec will have a unit norm.
I'm slightly confused. You should be able to call sqlplus from within the bash script. This may be what you were doing with your first statement
Try Executing the following within your bash script:
#!/bin/bash
echo Start Executing SQL commands
sqlplus <user>/<password> @file-with-sql-1.sql
sqlplus <user>/<password> @file-with-sql-2.sql
If you want to be able to pass data into your scripts you can do it via SQLPlus by passing arguments into the script:
Contents of file-with-sql-1.sql
select * from users where username='&1';
Then change the bash script to call sqlplus passing in the value
#!/bin/bash
MY_USER=bob
sqlplus <user>/<password> @file-with-sql-1.sql $MY_USER
Install ejs if it is not.
npm install ejs
Then after just paste below two lines in your main file. (like app.js, main.js)
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
Try:
if (record.has("problemkey") && !record.isNull("problemkey")) {
// Do something with object.
}
I would suggest checking the drivers and updating them if required.
class foo(object):
def __str__(self):
return "representation"
def __unicode__(self):
return u"representation"
The following solution is specifically for wamp environments:
This foxed me for a little while, tried all the other suggestions, $PATH etc even searched the windows registry looking for clues:
The GUI (wampmanager) indicates I have version 7 selected and yes if I phpinfo() in a page in the browser it will tell me its version 7.x.x yet php -v in the command prompt reports a 5.x.x
If you right click on the wampmanager head to icon->tools->delete unused versions and remove the old version, let it restart the services then the command prompt will return a 7.x.x
This solution means you no longer have the old version if you want to switch between php versions but there is a configuration file in C:\wamp64\wampmanager.conf which appears to specify the version to use with CLI (the parameter is called phpCliVersion). I changed it, restarted the server ... thought I had solved it but no effect perhaps I was a little impatient so I have a feeling there may be some mileage in that.
Hope that helps someone